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
//! Serialize [`serde::Serialize`] values to JavaScript using [`serde_json`].
//!
//! # Serialization
//!
//! The [`Serialized`] item can help you create a valid JavaScript value out of a
//! [`serde_json::value::RawValue`], along with some helpful options. It implements [`fmt::Display`]
//! for direct use, but you can also manually remove it from the [new-type] with
//! [`Serialized::into_string()`].
//!
//! ```rust
//! use serialize_to_javascript::{Options, Serialized};
//!
//! fn main() -> serialize_to_javascript::Result<()> {
//! let raw_value = serde_json::value::to_raw_value("foo'bar")?;
//! let serialized = Serialized::new(&raw_value, &Options::default());
//! assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')");
//! Ok(())
//! }
//! ```
//!
//! # Templating
//!
//! Because of the very common case of wanting to include your JavaScript values into existing
//! JavaScript code, this crate also provides some templating features. [`Template`] helps you map
//! struct fields into template values, while [`DefaultTemplate`] lets you attach it to a specific
//! JavaScript file. See their documentation for more details on how to create and use them.
//!
//! Templated names that are replaced inside templates are `__TEMPLATE_my_field__` where `my_field`
//! is a field on a struct implementing [`Template`]. Raw (`#[raw]` field annotation) value template
//! names use `__RAW_my_field__`. Raw values are inserted directly **without ANY** serialization
//! whatsoever, so being extra careful where it is used is highly recommended.
//!
//! ```rust
//! use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template};
//!
//! #[derive(Template)]
//! #[default_template("../tests/keygen.js")]
//! struct Keygen<'a> {
//! key: &'a str,
//! length: usize,
//!
//! #[raw]
//! optional_script: &'static str,
//! }
//!
//! fn main() -> serialize_to_javascript::Result<()> {
//! let keygen = Keygen {
//! key: "asdf",
//! length: 4,
//! optional_script: "console.log('hello, from my optional script')",
//! };
//!
//! let output: Serialized = keygen.render_default(&Options::default())?;
//!
//! Ok(())
//! }
//! ```
//!
//! [new-type]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#using-the-newtype-pattern-for-type-safety-and-abstraction
pub use ;
pub use ;
use fmt;
/// JavaScript code (in the form of a function parameter) for the JSON.parse() reviver.
const FREEZE_REVIVER: &str = ",(_,v)=>Object.freeze(v)";
/// Serialized JavaScript output.
;
/// Optional settings to pass to the templating system.
/// A struct that contains [`serde::Serialize`] data to insert into a template.
///
/// Create this automatically with a `#[derive(Template)]` attribute. All fields not marked `#[raw]`
/// will be compile-time checked that they implement [`serde::Serialize`].
///
/// Due to the nature of templating variables, [tuple structs] are not allowed as their fields
/// have no names. [Unit structs] have no fields and are a valid target of this trait.
///
/// Template variables are generated as `__TEMPLATE_my_field__` where the serialized value of the
/// `my_field` field replaces all instances of the template variable.
///
/// # Raw Values
///
/// If you have raw values you would like to inject into the template that is not serializable
/// through JSON, such as a string of JavaScript code, then you can mark a field with `#[raw]` to
/// make it embedded directly. **Absolutely NO serialization occurs**, the field is just turned into
/// a string using [`Display`]. As such, fields that are marked `#[raw]` _only_ require [`Display`].
///
/// Raw values use `__RAW_my_field__` as the template variable.
///
/// ---
///
/// This trait is sealed.
///
/// [tuple structs]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types
/// [`Display`]: std::fmt::Display
/// A [`Template`] with an attached default template.
///
/// Create this automatically with `#[default_template("myfile.js")` on your [`Template`] struct.
/// Estimated the minimum capacity needed for the serialized string based on inputs.
///
/// This size will include the size of the wrapping JavaScript (`JSON.parse()` and a potential
/// reviver function based on options) and the user supplied `buf_size` from the passed [`Options`].
/// It currently estimates the minimum size of the passed JSON by assuming it does not need escaping
/// and taking the length of the `&str`.
/// Transforms & escapes a JSON String to `JSON.parse('{json}')`
///
/// Single quotes chosen because double quotes are already used in JSON. With single quotes, we only
/// need to escape strings that include backslashes or single quotes. If we used double quotes, then
/// there would be no cases that a string doesn't need escaping.
///
/// # Safety
///
/// The ability to safely escape JSON into a JSON.parse('{json}') relies entirely on 2 things.
///
/// 1. `serde_json`'s ability to correctly escape and format JSON into a [`String`].
/// 2. JavaScript engines not accepting anything except another unescaped, literal single quote
/// character to end a string that was opened with it.
///
/// # Allocations
///
/// A new [`String`] will always be allocated. If `buf_size` is set to `0`, then it will by default
/// allocate to the return value of [`estimated_capacity()`].