@browsersync/bslive 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/package.json +22 -17
  2. package/Cargo.toml +0 -34
  3. package/bslive/Cargo.toml +0 -35
  4. package/bslive/build.rs +0 -5
  5. package/bslive/src/lib.rs +0 -135
  6. package/bsnext/Cargo.toml +0 -21
  7. package/bsnext/src/main.rs +0 -116
  8. package/crates/bsnext_client/Cargo.toml +0 -8
  9. package/crates/bsnext_client/build.rs +0 -53
  10. package/crates/bsnext_client/generated/dto.ts +0 -147
  11. package/crates/bsnext_client/generated/schema.ts +0 -237
  12. package/crates/bsnext_client/inject/dist/index.js +0 -6540
  13. package/crates/bsnext_client/inject/package.json +0 -12
  14. package/crates/bsnext_client/inject/src/console.ts +0 -25
  15. package/crates/bsnext_client/inject/src/index.ts +0 -73
  16. package/crates/bsnext_client/package-lock.json +0 -2145
  17. package/crates/bsnext_client/package.json +0 -27
  18. package/crates/bsnext_client/src/lib.rs +0 -11
  19. package/crates/bsnext_client/tsconfig.json +0 -22
  20. package/crates/bsnext_client/ui/dist/index.css +0 -78
  21. package/crates/bsnext_client/ui/dist/index.js +0 -997
  22. package/crates/bsnext_client/ui/index.html +0 -18
  23. package/crates/bsnext_client/ui/input.yml +0 -19
  24. package/crates/bsnext_client/ui/package.json +0 -18
  25. package/crates/bsnext_client/ui/src/components/bs-debug.ts +0 -27
  26. package/crates/bsnext_client/ui/src/components/bs-header.ts +0 -33
  27. package/crates/bsnext_client/ui/src/components/bs-icon.ts +0 -101
  28. package/crates/bsnext_client/ui/src/components/bs-server-detail.ts +0 -21
  29. package/crates/bsnext_client/ui/src/components/bs-server-identity.ts +0 -24
  30. package/crates/bsnext_client/ui/src/components/bs-server-list.ts +0 -39
  31. package/crates/bsnext_client/ui/src/index.ts +0 -39
  32. package/crates/bsnext_client/ui/styles/base.css.ts +0 -17
  33. package/crates/bsnext_client/ui/styles/reset.css +0 -52
  34. package/crates/bsnext_client/ui/styles/style.css +0 -29
  35. package/crates/bsnext_client/ui/svg/wordmark-white.svg +0 -38
  36. package/crates/bsnext_core/Cargo.toml +0 -44
  37. package/crates/bsnext_core/src/common_layers.rs +0 -62
  38. package/crates/bsnext_core/src/dir_loader.rs +0 -230
  39. package/crates/bsnext_core/src/dto.rs +0 -341
  40. package/crates/bsnext_core/src/handlers/mod.rs +0 -1
  41. package/crates/bsnext_core/src/handlers/proxy.rs +0 -95
  42. package/crates/bsnext_core/src/lib.rs +0 -12
  43. package/crates/bsnext_core/src/meta/mod.rs +0 -5
  44. package/crates/bsnext_core/src/not_found/mod.rs +0 -1
  45. package/crates/bsnext_core/src/not_found/not_found_service.rs +0 -35
  46. package/crates/bsnext_core/src/panic_handler.rs +0 -32
  47. package/crates/bsnext_core/src/raw_loader.rs +0 -196
  48. package/crates/bsnext_core/src/server/actor.rs +0 -92
  49. package/crates/bsnext_core/src/server/error.rs +0 -41
  50. package/crates/bsnext_core/src/server/handler_change.rs +0 -85
  51. package/crates/bsnext_core/src/server/handler_listen.rs +0 -163
  52. package/crates/bsnext_core/src/server/handler_patch.rs +0 -42
  53. package/crates/bsnext_core/src/server/handler_routes_updated.rs +0 -27
  54. package/crates/bsnext_core/src/server/handler_stop.rs +0 -38
  55. package/crates/bsnext_core/src/server/mod.rs +0 -10
  56. package/crates/bsnext_core/src/server/router/assets.rs +0 -39
  57. package/crates/bsnext_core/src/server/router/mod.rs +0 -123
  58. package/crates/bsnext_core/src/server/router/pub_api.rs +0 -39
  59. package/crates/bsnext_core/src/server/router/snapshots/bsnext_core__server__router__tests__test__handlers.snap +0 -9
  60. package/crates/bsnext_core/src/server/router/tests.rs +0 -209
  61. package/crates/bsnext_core/src/server/signals.rs +0 -11
  62. package/crates/bsnext_core/src/server/state.rs +0 -23
  63. package/crates/bsnext_core/src/servers_supervisor/actor.rs +0 -199
  64. package/crates/bsnext_core/src/servers_supervisor/file_changed_handler.rs +0 -41
  65. package/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs +0 -24
  66. package/crates/bsnext_core/src/servers_supervisor/input_changed_handler.rs +0 -21
  67. package/crates/bsnext_core/src/servers_supervisor/mod.rs +0 -6
  68. package/crates/bsnext_core/src/servers_supervisor/start_handler.rs +0 -86
  69. package/crates/bsnext_core/src/servers_supervisor/stop_handler.rs +0 -26
  70. package/crates/bsnext_core/src/ws/mod.rs +0 -164
  71. package/crates/bsnext_example/Cargo.toml +0 -10
  72. package/crates/bsnext_example/src/basic.rs +0 -51
  73. package/crates/bsnext_example/src/lib.rs +0 -26
  74. package/crates/bsnext_example/src/lit.rs +0 -37
  75. package/crates/bsnext_example/src/md.rs +0 -18
  76. package/crates/bsnext_fs/Cargo.toml +0 -22
  77. package/crates/bsnext_fs/src/actor.rs +0 -123
  78. package/crates/bsnext_fs/src/buffered_debounce.rs +0 -166
  79. package/crates/bsnext_fs/src/filter.rs +0 -39
  80. package/crates/bsnext_fs/src/inner_fs_event_handler.rs +0 -94
  81. package/crates/bsnext_fs/src/lib.rs +0 -141
  82. package/crates/bsnext_fs/src/remove_path_handler.rs +0 -46
  83. package/crates/bsnext_fs/src/stop_handler.rs +0 -15
  84. package/crates/bsnext_fs/src/stream.rs +0 -167
  85. package/crates/bsnext_fs/src/test/mod.rs +0 -213
  86. package/crates/bsnext_fs/src/watch_path_handler.rs +0 -67
  87. package/crates/bsnext_fs/src/watcher.rs +0 -349
  88. package/crates/bsnext_input/Cargo.toml +0 -25
  89. package/crates/bsnext_input/src/input_test/mod.rs +0 -185
  90. package/crates/bsnext_input/src/input_test/snapshots/bsnext_input__input_test__deserialize_3_headers.snap +0 -29
  91. package/crates/bsnext_input/src/input_test/snapshots/bsnext_input__input_test__deserialize_3_headers_control.snap +0 -25
  92. package/crates/bsnext_input/src/lib.rs +0 -153
  93. package/crates/bsnext_input/src/md.rs +0 -541
  94. package/crates/bsnext_input/src/paths.rs +0 -64
  95. package/crates/bsnext_input/src/route.rs +0 -189
  96. package/crates/bsnext_input/src/route_manifest.rs +0 -186
  97. package/crates/bsnext_input/src/server_config.rs +0 -88
  98. package/crates/bsnext_input/src/target.rs +0 -7
  99. package/crates/bsnext_input/src/watch_opt_test/mod.rs +0 -68
  100. package/crates/bsnext_input/src/yml.rs +0 -1
  101. package/crates/bsnext_output/Cargo.toml +0 -16
  102. package/crates/bsnext_output/src/json.rs +0 -11
  103. package/crates/bsnext_output/src/lib.rs +0 -25
  104. package/crates/bsnext_output/src/pretty.rs +0 -147
  105. package/crates/bsnext_resp/Cargo.toml +0 -13
  106. package/crates/bsnext_resp/src/js/snippet.html +0 -1
  107. package/crates/bsnext_resp/src/js/ws.js +0 -1
  108. package/crates/bsnext_resp/src/lib.rs +0 -79
  109. package/crates/bsnext_system/Cargo.toml +0 -29
  110. package/crates/bsnext_system/src/args.rs +0 -46
  111. package/crates/bsnext_system/src/lib.rs +0 -227
  112. package/crates/bsnext_system/src/monitor.rs +0 -241
  113. package/crates/bsnext_system/src/monitor_any_watchables.rs +0 -133
  114. package/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test-2.snap +0 -12
  115. package/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test.snap +0 -30
  116. package/crates/bsnext_system/src/start_kind/start_from_example.rs +0 -49
  117. package/crates/bsnext_system/src/start_kind/start_from_inputs.rs +0 -67
  118. package/crates/bsnext_system/src/start_kind/start_from_paths.rs +0 -51
  119. package/crates/bsnext_system/src/start_kind.rs +0 -56
  120. package/crates/bsnext_system/src/startup.rs +0 -51
  121. package/crates/bsnext_tracing/Cargo.toml +0 -10
  122. package/crates/bsnext_tracing/src/lib.rs +0 -127
  123. package/examples/basic/input.yml +0 -5
  124. package/examples/basic/public/index.html +0 -15
  125. package/examples/basic/public/reset.css +0 -52
  126. package/examples/basic/public/script.js +0 -1
  127. package/examples/basic/public/styles.css +0 -3
  128. package/examples/kitchen-sink/a-file.md +0 -1
  129. package/examples/kitchen-sink/api/1.json +0 -1
  130. package/examples/kitchen-sink/api/2.json +0 -3
  131. package/examples/kitchen-sink/app.js +0 -1
  132. package/examples/kitchen-sink/input.html +0 -185
  133. package/examples/kitchen-sink/input.yml +0 -133
  134. package/examples/kitchen-sink/styles-2.css +0 -3
  135. package/examples/lit/index.html +0 -21
  136. package/examples/lit/input.yml +0 -5
  137. package/examples/lit/lit.js +0 -82
  138. package/examples/lit/package-lock.json +0 -62
  139. package/examples/lit/package.json +0 -15
  140. package/examples/md-single/frontmatter.md +0 -35
  141. package/examples/md-single/md-single.md +0 -35
  142. package/examples/openai/.nvm +0 -1
  143. package/examples/openai/build.mjs +0 -21
  144. package/examples/openai/index.html +0 -13
  145. package/examples/openai/input.yml +0 -59
  146. package/examples/openai/package-lock.json +0 -720
  147. package/examples/openai/package.json +0 -21
  148. package/examples/openai/src/index.js +0 -21
  149. package/examples/openai/sse/01.txt +0 -8
  150. package/examples/proxy-simple/input.yml +0 -9
  151. package/examples/single/input.yaml +0 -26
  152. package/input.yml +0 -8
  153. package/run.sh +0 -6
@@ -1,230 +0,0 @@
1
- #![allow(clippy::redundant_pattern_matching)]
2
- #![allow(clippy::single_match)]
3
- use crate::handlers::proxy::ProxyConfig;
4
- use crate::meta::MetaData;
5
- use axum::body::Body;
6
- use axum::extract::{Request, State};
7
-
8
- use axum::middleware::Next;
9
- use axum::response::{IntoResponse, Response};
10
- use axum::{middleware, Extension, Router};
11
- use bytes::Bytes;
12
- use futures::channel::mpsc::unbounded;
13
- use futures::SinkExt;
14
-
15
- use crate::common_layers::add_route_layers;
16
- use crate::handlers::proxy;
17
- use crate::server::state::ServerState;
18
- use axum::routing::any;
19
- use bsnext_input::route::{DirRoute, ProxyRoute, Route, RouteKind};
20
- use bsnext_resp::{response_modifications_layer, RespMod};
21
- use http::{HeaderValue, StatusCode};
22
- use http_body_util::BodyExt;
23
- use std::collections::HashMap;
24
- use std::convert::Infallible;
25
- use std::sync::Arc;
26
- use std::time::Duration;
27
- use tokio::fs::File;
28
- use tokio::io::{AsyncWriteExt, BufWriter};
29
- use tokio_stream::StreamExt;
30
- use tower::{ServiceBuilder, ServiceExt};
31
- use tower_http::decompression::DecompressionLayer;
32
- use tower_http::services::ServeDir;
33
- use tracing::{span, Instrument, Level};
34
-
35
- pub async fn serve_dir_loader(
36
- State(state): State<Arc<ServerState>>,
37
- req: Request,
38
- _next: Next,
39
- ) -> Response {
40
- let _path = req.uri().path().to_owned();
41
- let span = span!(parent: None, Level::INFO, "serve_dir_loader", path = req.uri().path());
42
- let _guard = span.enter();
43
-
44
- let accepts_html = RespMod::accepts_html(&req);
45
- let routes = state.routes.read().instrument(span.clone()).await;
46
- let mut app = Router::new();
47
- let route_map = routes
48
- .iter()
49
- .filter(|r| matches!(&r.kind, RouteKind::Proxy(_) | RouteKind::Dir(_)))
50
- .fold(HashMap::<&str, Vec<&Route>>::new(), |mut acc, route| {
51
- acc.entry(route.path.as_str())
52
- .and_modify(|acc| acc.push(route))
53
- .or_insert(vec![route]);
54
- acc
55
- });
56
-
57
- for (_, routes) in route_map.iter() {
58
- if routes.len() > 1 {
59
- tracing::error!(
60
- "cannot register duplicate dir or proxy routes, only the first will take effect"
61
- );
62
- }
63
-
64
- let route = routes.first().expect("guarded");
65
- let mut router = match &route.kind {
66
- RouteKind::Proxy(ProxyRoute { proxy }) => {
67
- let response_handling = if accepts_html {
68
- ResponseHandling::Modify
69
- } else {
70
- ResponseHandling::None
71
- };
72
- service_for_proxy(response_handling, route).layer(Extension(ProxyConfig {
73
- target: proxy.to_owned(),
74
- path: route.path.clone(),
75
- }))
76
- }
77
- RouteKind::Dir(DirRoute { dir }) => service_for_dir(route, dir),
78
- _ => unreachable!("{:?}", route.kind),
79
- };
80
- router = add_route_layers(router, route);
81
- app = app.merge(router);
82
- }
83
-
84
- drop(routes);
85
-
86
- let r = app.oneshot(req).await;
87
-
88
- r.into_response()
89
- }
90
-
91
- fn service_for_dir(route: &Route, dir: &str) -> Router {
92
- Router::new()
93
- .nest_service(route.path.as_str(), ServeDir::new(dir))
94
- .layer(middleware::from_fn(tag_file))
95
- .layer(middleware::from_fn(response_modifications_layer))
96
- }
97
-
98
- async fn tag_file(req: Request, next: Next) -> Result<impl IntoResponse, (StatusCode, String)> {
99
- let (mut parts, body) = next.run(req).await.into_parts();
100
- if parts.status.as_u16() == 200 {
101
- parts.extensions.insert(MetaData::ServedFile);
102
- }
103
- Ok(Response::from_parts(parts, body))
104
- }
105
-
106
- enum ResponseHandling {
107
- Modify,
108
- None,
109
- }
110
-
111
- fn service_for_proxy(handling: ResponseHandling, route: &Route) -> Router {
112
- match handling {
113
- ResponseHandling::Modify => Router::new()
114
- .nest_service(route.path.as_str(), any(proxy::proxy_handler))
115
- .layer(
116
- ServiceBuilder::new()
117
- .layer(middleware::from_fn(response_modifications_layer))
118
- .layer(DecompressionLayer::new()),
119
- ),
120
- ResponseHandling::None => Router::new()
121
- .nest_service(route.path.as_str(), any(proxy::proxy_handler))
122
- .layer(middleware::from_fn(response_modifications_layer)),
123
- }
124
- }
125
-
126
- #[allow(dead_code)]
127
- async fn print_request_response(
128
- req: Request,
129
- next: Next,
130
- ) -> Result<impl IntoResponse, (StatusCode, String)> {
131
- let (parts, body) = req.into_parts();
132
- let bytes = buffer_and_print("request", body).await?;
133
- let req = Request::from_parts(parts, Body::from(bytes));
134
-
135
- let res = next.run(req).await;
136
- let (parts, body) = res.into_parts();
137
-
138
- let (mut sender, rec) = unbounded::<Bytes>();
139
- let is_event_stream = parts.headers.get("content-type")
140
- == Some(&HeaderValue::from_str("text/event-stream").unwrap());
141
-
142
- tokio::spawn(async move {
143
- let mut stream = body.into_data_stream();
144
- let mut chunks: Vec<Bytes> = vec![];
145
- while let Some(b) = stream.next().await {
146
- tracing::info!("CHUNK");
147
- match b {
148
- Ok(bytes) => {
149
- if is_event_stream {
150
- // let _written = file.write(&bytes).await;
151
- chunks.push(bytes.to_owned());
152
- match sender.send(bytes.to_owned()).await {
153
- Ok(_) => tracing::trace!("stripped chunk sent"),
154
- Err(_) => tracing::error!("stripped chunk not sent"),
155
- };
156
- } else {
157
- match sender.send(bytes.to_owned()).await {
158
- Ok(_) => tracing::trace!("chunk sent"),
159
- Err(_) => tracing::error!("not sent"),
160
- };
161
- }
162
- }
163
- Err(e) => {
164
- tracing::error!(?e, "error")
165
- }
166
- }
167
- }
168
- if is_event_stream {
169
- let path = std::path::Path::new("record").join("out4.yml");
170
- let mut file = BufWriter::new(File::create(path).await.expect("file"));
171
- let to_str = chunks
172
- .into_iter()
173
- .map(|x| std::str::from_utf8(&x).expect("bytes").to_owned())
174
- .collect::<Vec<_>>();
175
- let yml = serde_yaml::to_string(&to_str).expect("to yaml");
176
- println!("yml={}", yml);
177
- let _r = file.write(yml.as_bytes());
178
-
179
- match file.flush().await {
180
- Ok(_) => {}
181
- Err(_) => {}
182
- }
183
- }
184
- });
185
-
186
- // let res = Response::from_parts(parts, body);
187
- // while let Some(b) = res.body().next().await {
188
- // dbg!(b);
189
- // }
190
-
191
- // let (parts, body) = res.into_parts();
192
- // let bytes = buffer_and_print("response", body).await?;
193
- // let l = lines
194
- // .lines()
195
- // .map(|l| l.to_owned())
196
- // .map(|l| l.strip_prefix("data:").unwrap_or(&l).to_owned())
197
- // .filter(|l| !l.trim().is_empty())
198
- // .collect::<Vec<_>>();
199
-
200
- let stream = rec
201
- .throttle(Duration::from_millis(500))
202
- .map(Ok::<_, Infallible>);
203
-
204
- let res = Response::from_parts(parts, Body::from_stream(stream));
205
-
206
- Ok(res)
207
- }
208
-
209
- #[allow(dead_code)]
210
- async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, (StatusCode, String)>
211
- where
212
- B: axum::body::HttpBody<Data = Bytes>,
213
- B::Error: std::fmt::Display,
214
- {
215
- let bytes = match body.collect().await {
216
- Ok(collected) => collected.to_bytes(),
217
- Err(err) => {
218
- return Err((
219
- StatusCode::BAD_REQUEST,
220
- format!("failed to read {direction} body: {err}"),
221
- ));
222
- }
223
- };
224
-
225
- if let Ok(body) = std::str::from_utf8(&bytes) {
226
- tracing::debug!("{direction} body = {body:?}");
227
- }
228
-
229
- Ok(bytes)
230
- }
@@ -1,341 +0,0 @@
1
- use actix::MessageResponse;
2
- use bsnext_input::server_config::Identity;
3
- use bsnext_input::InputError;
4
- use std::fmt::{Display, Formatter};
5
- use std::path::Path;
6
-
7
- use crate::server::handler_change::{Change, ChangeKind};
8
- use bsnext_fs::Debounce;
9
- use bsnext_input::route::{DirRoute, ProxyRoute, Route, RouteKind};
10
- use typeshare::typeshare;
11
-
12
- #[typeshare]
13
- #[derive(Debug, serde::Serialize)]
14
- pub struct ServerDesc {
15
- pub routes: Vec<RouteDTO>,
16
- pub id: String,
17
- }
18
-
19
- #[typeshare]
20
- #[derive(Debug, serde::Serialize)]
21
- pub struct RouteDTO {
22
- pub path: String,
23
- pub kind: RouteKindDTO,
24
- }
25
-
26
- impl From<Route> for RouteDTO {
27
- fn from(value: Route) -> Self {
28
- Self {
29
- path: value.path.to_owned(),
30
- kind: RouteKindDTO::from(value.kind),
31
- }
32
- }
33
- }
34
- impl From<&Route> for RouteDTO {
35
- fn from(value: &Route) -> Self {
36
- Self {
37
- path: value.path.to_owned(),
38
- kind: RouteKindDTO::from(value.kind.clone()),
39
- }
40
- }
41
- }
42
-
43
- #[typeshare]
44
- #[derive(Debug, serde::Serialize)]
45
- #[serde(tag = "kind", content = "payload")]
46
- pub enum RouteKindDTO {
47
- Html { html: String },
48
- Json { json_str: String },
49
- Raw { raw: String },
50
- Sse { sse: String },
51
- Proxy { proxy: String },
52
- Dir { dir: String },
53
- }
54
-
55
- impl From<RouteKind> for RouteKindDTO {
56
- fn from(value: RouteKind) -> Self {
57
- match value {
58
- RouteKind::Html { html } => RouteKindDTO::Html { html },
59
- RouteKind::Json { json } => RouteKindDTO::Json {
60
- json_str: serde_json::to_string(&json).expect("unreachable"),
61
- },
62
- RouteKind::Raw { raw } => RouteKindDTO::Raw { raw },
63
- RouteKind::Sse { sse } => RouteKindDTO::Sse { sse },
64
- RouteKind::Proxy(ProxyRoute { proxy }) => RouteKindDTO::Proxy { proxy },
65
- RouteKind::Dir(DirRoute { dir }) => RouteKindDTO::Dir { dir },
66
- }
67
- }
68
- }
69
-
70
- #[typeshare]
71
- #[derive(Debug, serde::Serialize)]
72
- pub struct ServersStarted {
73
- pub servers_resp: GetServersMessageResponse,
74
- pub changeset: ServerChangeSet,
75
- }
76
-
77
- #[typeshare]
78
- #[derive(Debug, serde::Serialize)]
79
- pub enum EventLevel {
80
- #[serde(rename = "BSLIVE_EXTERNAL")]
81
- External,
82
- }
83
-
84
- #[typeshare]
85
- #[derive(Debug, serde::Serialize)]
86
- pub struct ExternalEvent {
87
- pub level: EventLevel,
88
- pub fields: ExternalEvents,
89
- }
90
-
91
- #[typeshare]
92
- #[derive(Debug, serde::Serialize)]
93
- #[serde(tag = "kind", content = "payload")]
94
- pub enum ExternalEvents {
95
- ServersStarted(ServersStarted),
96
- Watching(Watching),
97
- WatchingStopped(StoppedWatching),
98
- FileChanged(FileChanged),
99
- FilesChanged(FilesChangedDTO),
100
- InputFileChanged(FileChanged),
101
- InputAccepted(InputAccepted),
102
- StartupFailed(InputErrorDTO),
103
- }
104
-
105
- #[typeshare]
106
- #[derive(Debug, serde::Serialize)]
107
- pub struct InputAccepted {
108
- pub path: String,
109
- }
110
-
111
- #[typeshare]
112
- #[derive(Debug, serde::Serialize)]
113
- pub struct FileChanged {
114
- pub path: String,
115
- }
116
-
117
- #[typeshare]
118
- #[derive(Debug, serde::Serialize)]
119
- pub struct FilesChangedDTO {
120
- pub paths: Vec<String>,
121
- }
122
-
123
- #[typeshare]
124
- #[derive(Debug, serde::Serialize)]
125
- pub struct Watching {
126
- pub paths: Vec<String>,
127
- pub debounce: DebounceDTO,
128
- }
129
-
130
- #[typeshare]
131
- #[derive(Debug, serde::Serialize)]
132
- pub struct StoppedWatching {
133
- pub paths: Vec<String>,
134
- }
135
-
136
- impl StoppedWatching {
137
- pub fn from_path_buf(p: &Path) -> Self {
138
- Self {
139
- paths: vec![p.to_string_lossy().to_string()],
140
- }
141
- }
142
- }
143
-
144
- impl Display for Watching {
145
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
146
- write!(f, "yo")
147
- }
148
- }
149
-
150
- #[typeshare]
151
- #[derive(Debug, serde::Serialize)]
152
- pub struct DebounceDTO {
153
- kind: String,
154
- ms: String,
155
- }
156
-
157
- impl Display for DebounceDTO {
158
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
159
- write!(f, "{}:{}ms", self.kind, self.ms)
160
- }
161
- }
162
-
163
- impl From<Debounce> for DebounceDTO {
164
- fn from(value: Debounce) -> Self {
165
- match value {
166
- Debounce::Trailing { duration } => Self {
167
- kind: "trailing".to_string(),
168
- ms: duration.as_millis().to_string(),
169
- },
170
- Debounce::Buffered { duration } => Self {
171
- kind: "buffered".to_string(),
172
- ms: duration.as_millis().to_string(),
173
- },
174
- }
175
- }
176
- }
177
-
178
- impl FileChanged {
179
- pub fn from_path_buf(p: &Path) -> Self {
180
- Self {
181
- path: p.to_string_lossy().to_string(),
182
- }
183
- }
184
- }
185
-
186
- impl Watching {
187
- pub fn from_path_buf(p: &Path, debounce: Debounce) -> Self {
188
- Self {
189
- paths: vec![p.to_string_lossy().to_string()],
190
- debounce: debounce.into(),
191
- }
192
- }
193
- }
194
-
195
- #[typeshare]
196
- #[derive(Debug, Clone, serde::Serialize)]
197
- #[serde(tag = "kind", content = "payload")]
198
- pub enum ServerChange {
199
- Stopped { bind_address: String },
200
- Started,
201
- Patched,
202
- }
203
-
204
- #[typeshare]
205
- #[derive(Debug, serde::Serialize)]
206
- pub struct ServerChangeSetItem {
207
- pub identity: IdentityDTO,
208
- pub change: ServerChange,
209
- }
210
- #[typeshare]
211
- #[derive(Debug, serde::Serialize)]
212
- pub struct ServerChangeSet {
213
- pub items: Vec<ServerChangeSetItem>,
214
- }
215
-
216
- #[typeshare::typeshare]
217
- #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, MessageResponse)]
218
- pub struct GetServersMessageResponse {
219
- pub servers: Vec<ServerDTO>,
220
- }
221
-
222
- #[typeshare::typeshare]
223
- #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
224
- pub struct ServerDTO {
225
- pub id: String,
226
- pub identity: IdentityDTO,
227
- pub socket_addr: String,
228
- }
229
-
230
- #[typeshare::typeshare]
231
- #[derive(Debug, PartialEq, Hash, Eq, Clone, serde::Deserialize, serde::Serialize)]
232
- #[serde(tag = "kind", content = "payload")]
233
- pub enum IdentityDTO {
234
- Both { name: String, bind_address: String },
235
- Address { bind_address: String },
236
- Named { name: String },
237
- }
238
-
239
- impl From<&Identity> for IdentityDTO {
240
- fn from(value: &Identity) -> Self {
241
- match value {
242
- Identity::Both { name, bind_address } => IdentityDTO::Both {
243
- name: name.to_owned(),
244
- bind_address: bind_address.to_owned(),
245
- },
246
- Identity::Address { bind_address } => IdentityDTO::Address {
247
- bind_address: bind_address.to_owned(),
248
- },
249
- Identity::Named { name } => IdentityDTO::Named {
250
- name: name.to_owned(),
251
- },
252
- }
253
- }
254
- }
255
-
256
- #[typeshare::typeshare]
257
- #[derive(Debug, PartialEq, Hash, Eq, Clone, serde::Deserialize, serde::Serialize)]
258
- #[serde(tag = "kind", content = "payload")]
259
- pub enum InputErrorDTO {
260
- MissingInputs(String),
261
- InvalidInput(String),
262
- NotFound(String),
263
- InputWriteError(String),
264
- PathError(String),
265
- PortError(String),
266
- DirError(String),
267
- }
268
-
269
- impl From<&InputError> for InputErrorDTO {
270
- fn from(value: &InputError) -> Self {
271
- match value {
272
- e @ InputError::MissingInputs => InputErrorDTO::MissingInputs(e.to_string()),
273
- e @ InputError::InvalidInput(_) => InputErrorDTO::InvalidInput(e.to_string()),
274
- e @ InputError::NotFound(_) => InputErrorDTO::NotFound(e.to_string()),
275
- e @ InputError::InputWriteError(_) => InputErrorDTO::InputWriteError(e.to_string()),
276
- e @ InputError::PathError(_) => InputErrorDTO::PathError(e.to_string()),
277
- e @ InputError::PortError(_) => InputErrorDTO::PortError(e.to_string()),
278
- e @ InputError::DirError(_) => InputErrorDTO::DirError(e.to_string()),
279
- }
280
- }
281
- }
282
-
283
- #[typeshare::typeshare]
284
- #[derive(Debug, Clone, serde::Serialize)]
285
- #[serde(tag = "kind", content = "payload")]
286
- pub enum ClientEvent {
287
- Change(ChangeDTO),
288
- }
289
-
290
- #[typeshare::typeshare]
291
- #[derive(Debug, Clone, serde::Serialize)]
292
- #[serde(tag = "kind", content = "payload")]
293
- pub enum ChangeDTO {
294
- Fs {
295
- path: String,
296
- change_kind: ChangeKind,
297
- },
298
- FsMany(Vec<ChangeDTO>),
299
- }
300
-
301
- impl From<&Change> for ChangeDTO {
302
- fn from(value: &Change) -> Self {
303
- match value {
304
- Change::Fs { path, change_kind } => Self::Fs {
305
- path: path.to_string_lossy().to_string(),
306
- change_kind: change_kind.clone(),
307
- },
308
- Change::FsMany(changes) => Self::FsMany(
309
- changes
310
- .iter()
311
- .map(|change| match change {
312
- Change::Fs { path, change_kind } => Self::Fs {
313
- path: path.to_string_lossy().to_string(),
314
- change_kind: change_kind.clone(),
315
- },
316
- Change::FsMany(_) => unreachable!("recursive not supported"),
317
- })
318
- .collect(),
319
- ),
320
- }
321
- }
322
- }
323
-
324
- #[cfg(test)]
325
- mod test {
326
- use super::*;
327
- #[test]
328
- fn test_serialize() -> anyhow::Result<()> {
329
- let fs = Change::fs("./a.js");
330
- let evt = ClientEvent::Change((&fs).into());
331
- let _json = serde_json::to_string(&evt).unwrap();
332
- Ok(())
333
- }
334
- #[test]
335
- fn test_serialize_server_start() -> anyhow::Result<()> {
336
- let fs = Change::fs("./a.js");
337
- let evt = ClientEvent::Change((&fs).into());
338
- let _json = serde_json::to_string(&evt).unwrap();
339
- Ok(())
340
- }
341
- }
@@ -1 +0,0 @@
1
- pub mod proxy;
@@ -1,95 +0,0 @@
1
- use anyhow::Context;
2
- use axum::body::Body;
3
- use axum::extract::Request;
4
- use axum::Extension;
5
-
6
- use axum::response::{IntoResponse, Response};
7
-
8
- use http::{HeaderValue, StatusCode, Uri};
9
- use hyper_tls::HttpsConnector;
10
- use hyper_util::client::legacy::connect::HttpConnector;
11
- use hyper_util::client::legacy::Client;
12
-
13
- #[derive(Debug, Clone)]
14
- pub struct ProxyConfig {
15
- pub target: String,
16
- pub path: String,
17
- }
18
-
19
- // Make our own error that wraps `anyhow::Error`.
20
- pub struct AnyAppError(anyhow::Error);
21
-
22
- // Tell axum how to convert `AppError` into a response.
23
- impl IntoResponse for AnyAppError {
24
- fn into_response(self) -> Response {
25
- (
26
- StatusCode::INTERNAL_SERVER_ERROR,
27
- format!("Something went wrong: {}", self.0),
28
- )
29
- .into_response()
30
- }
31
- }
32
- impl<E> From<E> for AnyAppError
33
- where
34
- E: Into<anyhow::Error>,
35
- {
36
- fn from(err: E) -> Self {
37
- Self(err.into())
38
- }
39
- }
40
-
41
- pub async fn proxy_handler(
42
- Extension(config): Extension<ProxyConfig>,
43
- req: Request,
44
- ) -> Result<Response, AnyAppError> {
45
- let client = {
46
- req.extensions()
47
- .get::<Client<HttpsConnector<HttpConnector>, Body>>()
48
- .expect("must have a client, move this to an extractor?")
49
- };
50
- let client_c = client.clone();
51
-
52
- let target = config.target.clone();
53
-
54
- tracing::trace!(?config);
55
-
56
- let path = req.uri().path();
57
-
58
- tracing::trace!(req.uri = %path, config.path = config.path);
59
- // tracing::trace!(req.headers = ?req.headers());
60
-
61
- let path_query = req
62
- .uri()
63
- .path_and_query()
64
- .map(|v| v.as_str())
65
- .unwrap_or(path);
66
-
67
- let uri = format!("{}{}", target, path_query);
68
- let parsed = Uri::try_from(uri).context("tried to parse")?;
69
-
70
- let target = match (parsed.host(), parsed.port()) {
71
- (Some(host), Some(port)) => format!("{host}:{port}"),
72
- (Some(host), None) => host.to_owned(),
73
- _ => unreachable!("could not extract `host` from url"),
74
- };
75
-
76
- tracing::trace!(outgoing.uri = %parsed);
77
-
78
- let host_header_value = HeaderValue::from_str(&target).unwrap();
79
-
80
- let (parts, body) = req.into_parts();
81
- let mut req = Request::from_parts(parts, body);
82
-
83
- *req.uri_mut() = parsed;
84
-
85
- // todo: Which other headers to mod here?
86
- req.headers_mut().insert("host", host_header_value);
87
-
88
- let res = client_c
89
- .request(req)
90
- .await
91
- .map_err(|_| StatusCode::BAD_REQUEST)
92
- .into_response();
93
-
94
- Ok(res)
95
- }
@@ -1,12 +0,0 @@
1
- pub mod server;
2
- pub mod servers_supervisor;
3
-
4
- pub mod common_layers;
5
- pub mod dir_loader;
6
- pub mod dto;
7
- pub mod handlers;
8
- pub mod meta;
9
- pub mod not_found;
10
- pub mod panic_handler;
11
- pub mod raw_loader;
12
- pub mod ws;
@@ -1,5 +0,0 @@
1
- #[derive(Debug, Clone)]
2
- pub enum MetaData {
3
- ServedFile,
4
- ServedRaw,
5
- }
@@ -1 +0,0 @@
1
- pub mod not_found_service;