1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use super::Turbine;
use crate::{
errors::*,
i18n::TranslationsManager,
internal::{PageData, PageDataPartial},
path::PathMaybeWithLocale,
plugins::PluginAction,
state::TemplateState,
stores::MutableStore,
utils::get_path_prefix_server,
};
use fs_extra::dir::{copy as copy_dir, CopyOptions};
use futures::future::{try_join, try_join_all};
use serde_json::Value;
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
impl<M: MutableStore, T: TranslationsManager> Turbine<M, T> {
/// Exports your app to a series of static files. If any templates/capsules
/// in your app use request-time-only functionality, this will fail.
pub async fn export(&mut self) -> Result<(), Arc<Error>> {
// Note that this function uses different plugin actions from a pure build
self.plugins
.functional_actions
.export_actions
.before_export
.run((), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
let res = self.build_internal(true).await; // We mark that we will be exporting
if let Err(err) = res {
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_build
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
return Err(err);
} else {
self.plugins
.functional_actions
.export_actions
.after_successful_build
.run((), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
}
// By now, the global states have been written for each locale, along with the
// render configuration (that's all in memory and in the immutable store)
// This won't have any trailing slashes (they're stripped by the immutable store
// initializer)
let dest = format!("{}/exported", self.immutable_store.get_path());
// Turn the build artifacts into self-contained static files
let export_res = self.export_internal().await;
if let Err(err) = export_res {
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_export
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
Err(err)
} else {
self.copy_static_aliases(&dest)?;
self.copy_static_dir(&dest)?;
self.plugins
.functional_actions
.export_actions
.after_successful_export
.run((), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
Ok(())
}
}
// TODO Warnings for render cancellations in exported apps
async fn export_internal(&self) -> Result<(), ServerError> {
// Loop over every pair in the render config
let mut export_futs = Vec::new();
for (path, template_path) in self.render_cfg.iter() {
export_futs.push(self.export_path(path, template_path));
}
// If we're using i18n, loop through the locales to create translations files
let mut translations_futs = Vec::new();
if self.locales.using_i18n {
for locale in self.locales.get_all() {
translations_futs.push(self.create_translation_file(locale));
}
}
// Do *everything* in parallel
try_join(try_join_all(export_futs), try_join_all(translations_futs)).await?;
// Copying in bundles from the filesystem is done externally to this function
Ok(())
}
/// This exports for all locales, or for none if the app doesn't use i18n.
async fn export_path(&self, path: &str, template_path: &str) -> Result<(), ServerError> {
// We assume we've already built the app, which would have populated this
let html_shell = self.html_shell.as_ref().unwrap();
let path_prefix = get_path_prefix_server();
// We need the encoded path to reference flattened build artifacts
// But we don't create a flattened system with exporting, everything is properly
// created in a directory structure
let path_encoded = urlencoding::encode(path).to_string();
// All initial load pages should be written into their own folders, which
// prevents a situation of a template root page outside the directory for the
// rest of that template's pages (see #73). The `.html` file extension is
// added when this variable is used (for contrast to the `.json`s)
let initial_load_path = if path.ends_with("index") {
// However, if it's already an index page, we don't want `index/index.html`
path.to_string()
} else {
format!("{}/index", &path)
};
// Get the template itself
let template = self.entities.get(template_path);
let template = match template {
Some(template) => template,
None => {
return Err(ServeError::PageNotFound {
path: template_path.to_string(),
}
.into())
}
};
// Create a locale detection file for it if we're using i18n
// These just send the app shell, which will perform a redirect as necessary
// Notably, these also include fallback redirectors if either Wasm or JS is
// disabled (or both)
if self.locales.using_i18n && !template.is_capsule {
self.immutable_store
.write(
&format!("exported/{}.html", &initial_load_path),
&html_shell
.clone()
.locale_redirection_fallback(
&format!("{}/{}/{}", path_prefix, self.locales.default, &path),
&self.global_state,
)
.to_string(),
)
.await?;
}
// Check if that template uses build state (in which case it should have a JSON
// file)
let has_state = template.uses_build_state();
if self.locales.using_i18n {
// Loop through all the app's locales
for locale in self.locales.get_all() {
let page_data = self
.get_static_page_data(
&format!("{}-{}", locale, &path_encoded),
has_state,
template.is_capsule,
)
.await?;
// Don't create initial load pages for widgets
if !template.is_capsule {
// Get the translations string for this locale
let translations = self
.translations_manager
.get_translations_str_for_locale(locale.to_string())
.await?;
// Create a full HTML file from those that can be served for initial loads
// The build process writes these with a dummy default locale even though we're
// not using i18n
let full_html = html_shell
.clone()
.page_data(&page_data, &self.global_state, locale, &translations)
.to_string();
self.immutable_store
.write(
&format!("exported/{}/{}.html", locale, initial_load_path),
&full_html,
)
.await?;
}
// Serialize the page data to JSON and write it as a partial (fetched by the app
// shell for subsequent loads)
let partial_page_data = PageDataPartial {
state: page_data.state,
head: page_data.head,
};
let partial = serde_json::to_string(&partial_page_data).unwrap();
self.immutable_store
.write(
&format!("exported/.perseus/page/{}/{}.json", locale, &path),
&partial,
)
.await?;
}
} else {
let page_data = self
.get_static_page_data(
&format!("{}-{}", self.locales.default, &path_encoded),
has_state,
template.is_capsule,
)
.await?;
// Don't create initial load pages for widgets
if !template.is_capsule {
// Create a full HTML file from those that can be served for initial loads
// The build process writes these with a dummy default locale even though we're
// not using i18n
let full_html = html_shell
.clone()
.page_data(&page_data, &self.global_state, "xx-XX", "")
.to_string();
// We don't add an extension because this will be queried directly by the
// browser
self.immutable_store
.write(&format!("exported/{}.html", initial_load_path), &full_html)
.await?;
}
// Serialize the page data to JSON and write it as a partial (fetched by the app
// shell for subsequent loads)
let partial_page_data = PageDataPartial {
state: page_data.state,
head: page_data.head,
};
let partial = serde_json::to_string(&partial_page_data).unwrap();
self.immutable_store
.write(
&format!(
"exported/.perseus/page/{}/{}.json",
self.locales.default, &path
),
&partial,
)
.await?;
}
Ok(())
}
async fn create_translation_file(&self, locale: &str) -> Result<(), ServerError> {
// Get the translations string for that
let translations_str = self
.translations_manager
.get_translations_str_for_locale(locale.to_string())
.await?;
// Write it to an asset so that it can be served directly
self.immutable_store
.write(
&format!("exported/.perseus/translations/{}", locale),
&translations_str,
)
.await?;
Ok(())
}
/// This will work for capsules by just returning empty values
/// for the parts of `PageData` that they can't fulfill. Importantly,
/// capsules will be immediately converted into `PageDataPartial`s by
/// the caller (since initial load pages don't need to be constructed).
async fn get_static_page_data(
&self,
full_path_encoded: &str,
has_state: bool,
is_capsule: bool,
) -> Result<PageData, ServerError> {
// Get the partial HTML content and a state to go with it (if applicable)
let content = if !is_capsule {
self.immutable_store
.read(&format!("static/{}.html", full_path_encoded))
.await?
} else {
String::new()
};
// This maps all the dependencies for any page that has a prerendered fragment
let widget_states = if !is_capsule {
self.immutable_store
.read(&format!("static/{}.widgets.json", full_path_encoded))
.await?
} else {
"{}".to_string()
};
// These are *not* fallible!
let widget_states = match serde_json::from_str::<
HashMap<PathMaybeWithLocale, (String, Value)>,
>(&widget_states)
{
// Same processing as the server does
Ok(widget_states) => widget_states
.into_iter()
.map(|(k, (_, v))| (k, Ok(v)))
.collect::<_>(),
Err(err) => return Err(ServerError::InvalidPageState { source: err }),
};
let head = if !is_capsule {
self.immutable_store
.read(&format!("static/{}.head.html", full_path_encoded))
.await?
} else {
String::new()
};
let mut state = match has_state {
true => serde_json::from_str(
&self
.immutable_store
.read(&format!("static/{}.json", full_path_encoded))
.await?,
)
.map_err(|err| ServerError::InvalidPageState { source: err })?,
false => TemplateState::empty().state,
};
// Widget states are always parsed as fallible on the browser-side
// because initially loaded widgets actually can be. This is a server-side
// workaround that we have to replicate here.
if is_capsule {
state = serde_json::to_value(Ok::<_, ()>(state)).unwrap();
}
// Create an instance of `PageData`
Ok(PageData {
content,
state,
head,
widget_states,
})
}
/// Copies the static aliases into a distribution directory at `dest` (no
/// trailing `/`). This should be the root of the destination directory for
/// the exported files. Because this provides a customizable
/// destination, it is fully engine-agnostic.
///
/// The error type here is a tuple of the location the asset was copied
/// from, the location it was copied to, and the error in that process
/// (which could be from `io` or `fs_extra`).
fn copy_static_aliases(&self, dest: &str) -> Result<(), Arc<Error>> {
// Loop through any static aliases and copy them in too
// Unlike with the server, these could override pages!
// We'll copy from the alias to the path (it could be a directory or a file)
// Remember: `alias` has a leading `/`!
for (alias, path) in &self.static_aliases {
let from = PathBuf::from(path);
let to_str = format!("{}{}", dest, alias);
let to = PathBuf::from(&to_str);
// If the alias is nested, we might need to create directories
if to_str.contains('/') {
// This is guaranteed to be `Some()`, since there is at least the `dist/`
// directory
let parent = to.parent().unwrap();
if !parent.exists() {
if let Err(err) = fs::create_dir(parent) {
let err = EngineError::NestedStaticAliasDirCreationFailed {
source: err,
alias: alias.to_string(),
};
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_nested_static_alias_dir_creation
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
return Err(err);
}
}
}
if from.is_dir() {
if let Err(err) = copy_dir(&from, &to, &CopyOptions::new()) {
let err = EngineError::CopyStaticAliasDirErr {
source: err,
to: to_str,
from: path.to_string(),
};
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_static_alias_dir_copy
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
return Err(err);
}
} else if let Err(err) = fs::copy(&from, &to) {
let err = EngineError::CopyStaticAliasFileError {
source: err,
to: to_str,
from: path.to_string(),
};
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_static_alias_file_copy
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
return Err(err);
}
}
Ok(())
}
/// Copies the directory containing static data to be put in
/// `/.perseus/static/` (URL). This takes in both the location of the
/// static directory and the destination directory for exported files.
fn copy_static_dir(&self, dest: &str) -> Result<(), Arc<Error>> {
// Copy the `static` directory into the export package if it exists
// If the user wants extra, they can use static aliases, plugins are unnecessary
// here
if self.static_dir.exists() {
if let Err(err) = copy_dir(
&self.static_dir,
format!("{}/.perseus/", dest),
&CopyOptions::new(),
) {
let err = EngineError::CopyStaticDirError {
source: err,
path: self.static_dir.to_string_lossy().to_string(),
dest: dest.to_string(),
};
let err: Arc<Error> = Arc::new(err.into());
self.plugins
.functional_actions
.export_actions
.after_failed_static_copy
.run(err.clone(), self.plugins.get_plugin_data())
.map_err(|err| Arc::new(err.into()))?;
return Err(err);
}
}
Ok(())
}
}