@perspective-dev/client 5.6.1 → 5.7.0

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 (142) hide show
  1. package/README.md +5 -1
  2. package/dist/cdn/perspective.js +3 -2
  3. package/dist/cdn/perspective.js.map +4 -4
  4. package/dist/esm/perspective.browser.d.ts +71 -17
  5. package/dist/esm/perspective.js +2 -2
  6. package/dist/esm/perspective.js.map +4 -4
  7. package/dist/esm/perspective.node.d.ts +20 -3
  8. package/dist/esm/perspective.node.js +664 -35
  9. package/dist/esm/perspective.node.js.map +4 -4
  10. package/dist/esm/public_types.d.ts +31 -0
  11. package/dist/esm/virtual_servers/clickhouse.d.ts +37 -0
  12. package/dist/esm/virtual_servers/clickhouse.js +1 -1
  13. package/dist/esm/virtual_servers/clickhouse.js.map +3 -3
  14. package/dist/esm/virtual_servers/duckdb.d.ts +14 -9
  15. package/dist/esm/virtual_servers/duckdb.js +1 -1
  16. package/dist/esm/virtual_servers/duckdb.js.map +3 -3
  17. package/dist/esm/wasm/cdn.d.ts +12 -0
  18. package/dist/esm/wasm/migrate.d.ts +40 -0
  19. package/dist/esm/wasm/registry.d.ts +123 -0
  20. package/dist/esm/wasm/registry.js +3 -0
  21. package/dist/esm/wasm/registry.js.map +7 -0
  22. package/{src/ts/ts-rs/AggSpec.ts → dist/ts-rs/AggSpec.d.ts} +1 -1
  23. package/{src/ts/ts-rs/Features.ts → dist/ts-rs/Features.d.ts} +16 -6
  24. package/{src/ts/ts-rs/Filter.ts → dist/ts-rs/Filter.d.ts} +1 -1
  25. package/{src/ts/ts-rs/FilterTerm.ts → dist/ts-rs/FilterTerm.d.ts} +1 -1
  26. package/{src/ts/ts-rs/JoinOptions.ts → dist/ts-rs/JoinOptions.d.ts} +1 -1
  27. package/dist/ts-rs/ListFlatten.d.ts +3 -0
  28. package/dist/ts-rs/MapFlatten.d.ts +3 -0
  29. package/{src/ts/ts-rs/OnRemoveData.ts → dist/ts-rs/OnRemoveData.d.ts} +1 -1
  30. package/{src/ts/ts-rs/OnUpdateData.ts → dist/ts-rs/OnUpdateData.d.ts} +1 -1
  31. package/{src/ts/ts-rs/OnUpdateOptions.ts → dist/ts-rs/OnUpdateOptions.d.ts} +1 -1
  32. package/{src/ts/ts-rs/Sort.ts → dist/ts-rs/Sort.d.ts} +1 -1
  33. package/dist/ts-rs/StructFlatten.d.ts +3 -0
  34. package/dist/ts-rs/TableIndex.d.ts +9 -0
  35. package/dist/ts-rs/TableInitOptions.d.ts +65 -0
  36. package/{src/ts/ts-rs/UpdateOptions.ts → dist/ts-rs/UpdateOptions.d.ts} +1 -1
  37. package/{src/ts/ts-rs/ViewConfig.ts → dist/ts-rs/ViewConfig.d.ts} +8 -8
  38. package/{src/ts/ts-rs/ViewConfigUpdate.ts → dist/ts-rs/ViewConfigUpdate.d.ts} +8 -8
  39. package/{src/ts/ts-rs/WindowAggSpec.ts → dist/ts-rs/WindowAggSpec.d.ts} +1 -1
  40. package/{src/ts/ts-rs/WindowSort.ts → dist/ts-rs/WindowSort.d.ts} +1 -1
  41. package/{src/ts/ts-rs/WindowSpec.ts → dist/ts-rs/WindowSpec.d.ts} +1 -1
  42. package/{src/ts/ts-rs/Windows.ts → dist/ts-rs/Windows.d.ts} +1 -1
  43. package/dist/wasm/perspective-js.d.ts +121 -54
  44. package/dist/wasm/perspective-js.js +123 -20
  45. package/dist/wasm/perspective-js.wasm +0 -0
  46. package/dist/wasm/perspective-js.wasm.d.ts +10 -6
  47. package/dist/wasm/perspective-migrate-js.d.ts +41 -0
  48. package/dist/wasm/perspective-migrate-js.js +524 -0
  49. package/dist/wasm/perspective-migrate-js.wasm +0 -0
  50. package/dist/wasm/perspective-migrate-js.wasm.d.ts +8 -0
  51. package/package.json +30 -15
  52. package/dist/esm/ts-rs/AggSpec.d.ts +0 -8
  53. package/dist/esm/ts-rs/Aggregate.d.ts +0 -1
  54. package/dist/esm/ts-rs/ColumnType.d.ts +0 -4
  55. package/dist/esm/ts-rs/ColumnWindow.d.ts +0 -4
  56. package/dist/esm/ts-rs/DeleteOptions.d.ts +0 -6
  57. package/dist/esm/ts-rs/Expressions.d.ts +0 -3
  58. package/dist/esm/ts-rs/Features.d.ts +0 -71
  59. package/dist/esm/ts-rs/Filter.d.ts +0 -2
  60. package/dist/esm/ts-rs/FilterReducer.d.ts +0 -1
  61. package/dist/esm/ts-rs/FilterTerm.d.ts +0 -2
  62. package/dist/esm/ts-rs/GroupRollupMode.d.ts +0 -1
  63. package/dist/esm/ts-rs/JoinOptions.d.ts +0 -9
  64. package/dist/esm/ts-rs/JoinType.d.ts +0 -1
  65. package/dist/esm/ts-rs/ListFlatten.d.ts +0 -1
  66. package/dist/esm/ts-rs/OnRemoveData.d.ts +0 -6
  67. package/dist/esm/ts-rs/OnUpdateData.d.ts +0 -6
  68. package/dist/esm/ts-rs/OnUpdateMode.d.ts +0 -9
  69. package/dist/esm/ts-rs/OnUpdateOptions.d.ts +0 -7
  70. package/dist/esm/ts-rs/Scalar.d.ts +0 -5
  71. package/dist/esm/ts-rs/Sort.d.ts +0 -2
  72. package/dist/esm/ts-rs/SortDir.d.ts +0 -1
  73. package/dist/esm/ts-rs/SplitRollupMode.d.ts +0 -9
  74. package/dist/esm/ts-rs/SystemInfo.d.ts +0 -40
  75. package/dist/esm/ts-rs/TableInitOptions.d.ts +0 -45
  76. package/dist/esm/ts-rs/TableReadFormat.d.ts +0 -7
  77. package/dist/esm/ts-rs/TypedArrayWindow.d.ts +0 -33
  78. package/dist/esm/ts-rs/UpdateOptions.d.ts +0 -8
  79. package/dist/esm/ts-rs/ViewConfig.d.ts +0 -24
  80. package/dist/esm/ts-rs/ViewConfigUpdate.d.ts +0 -116
  81. package/dist/esm/ts-rs/ViewOnRemoveResp.d.ts +0 -4
  82. package/dist/esm/ts-rs/ViewOnUpdateResp.d.ts +0 -4
  83. package/dist/esm/ts-rs/ViewWindow.d.ts +0 -30
  84. package/dist/esm/ts-rs/WindowAggSpec.d.ts +0 -25
  85. package/dist/esm/ts-rs/WindowSort.d.ts +0 -7
  86. package/dist/esm/ts-rs/WindowSortDir.d.ts +0 -6
  87. package/dist/esm/ts-rs/WindowSpec.d.ts +0 -47
  88. package/dist/esm/ts-rs/Windows.d.ts +0 -10
  89. package/src/rust/client.rs +0 -590
  90. package/src/rust/generic_sql_model.rs +0 -276
  91. package/src/rust/lib.rs +0 -99
  92. package/src/rust/table.rs +0 -397
  93. package/src/rust/table_data.rs +0 -164
  94. package/src/rust/typed_array.rs +0 -386
  95. package/src/rust/utils/browser.rs +0 -35
  96. package/src/rust/utils/console_logger.rs +0 -237
  97. package/src/rust/utils/errors.rs +0 -274
  98. package/src/rust/utils/futures.rs +0 -274
  99. package/src/rust/utils/json.rs +0 -252
  100. package/src/rust/utils/local_poll_loop.rs +0 -63
  101. package/src/rust/utils/mod.rs +0 -32
  102. package/src/rust/utils/serde.rs +0 -46
  103. package/src/rust/utils/trace_allocator.rs +0 -98
  104. package/src/rust/view.rs +0 -463
  105. package/src/rust/virtual_server.rs +0 -991
  106. package/src/ts/perspective-server.worker.ts +0 -74
  107. package/src/ts/perspective.browser.ts +0 -380
  108. package/src/ts/perspective.cdn.ts +0 -28
  109. package/src/ts/perspective.node.ts +0 -556
  110. package/src/ts/ts-rs/ListFlatten.ts +0 -3
  111. package/src/ts/ts-rs/TableInitOptions.ts +0 -42
  112. package/src/ts/virtual_server.ts +0 -83
  113. package/src/ts/virtual_servers/clickhouse.ts +0 -533
  114. package/src/ts/virtual_servers/duckdb.ts +0 -549
  115. package/src/ts/wasm/browser.ts +0 -134
  116. package/src/ts/wasm/cdn.ts +0 -32
  117. package/src/ts/wasm/decompress.ts +0 -83
  118. package/src/ts/wasm/emscripten_api.ts +0 -91
  119. package/src/ts/wasm/engine.ts +0 -309
  120. package/src/ts/wasm/features.ts +0 -31
  121. package/src/ts/wasm/perspective-server.poly.ts +0 -460
  122. package/src/ts/websocket.ts +0 -95
  123. package/tsconfig.json +0 -22
  124. /package/{src/ts/ts-rs/Aggregate.ts → dist/ts-rs/Aggregate.d.ts} +0 -0
  125. /package/{src/ts/ts-rs/ColumnType.ts → dist/ts-rs/ColumnType.d.ts} +0 -0
  126. /package/{src/ts/ts-rs/ColumnWindow.ts → dist/ts-rs/ColumnWindow.d.ts} +0 -0
  127. /package/{src/ts/ts-rs/DeleteOptions.ts → dist/ts-rs/DeleteOptions.d.ts} +0 -0
  128. /package/{src/ts/ts-rs/Expressions.ts → dist/ts-rs/Expressions.d.ts} +0 -0
  129. /package/{src/ts/ts-rs/FilterReducer.ts → dist/ts-rs/FilterReducer.d.ts} +0 -0
  130. /package/{src/ts/ts-rs/GroupRollupMode.ts → dist/ts-rs/GroupRollupMode.d.ts} +0 -0
  131. /package/{src/ts/ts-rs/JoinType.ts → dist/ts-rs/JoinType.d.ts} +0 -0
  132. /package/{src/ts/ts-rs/OnUpdateMode.ts → dist/ts-rs/OnUpdateMode.d.ts} +0 -0
  133. /package/{src/ts/ts-rs/Scalar.ts → dist/ts-rs/Scalar.d.ts} +0 -0
  134. /package/{src/ts/ts-rs/SortDir.ts → dist/ts-rs/SortDir.d.ts} +0 -0
  135. /package/{src/ts/ts-rs/SplitRollupMode.ts → dist/ts-rs/SplitRollupMode.d.ts} +0 -0
  136. /package/{src/ts/ts-rs/SystemInfo.ts → dist/ts-rs/SystemInfo.d.ts} +0 -0
  137. /package/{src/ts/ts-rs/TableReadFormat.ts → dist/ts-rs/TableReadFormat.d.ts} +0 -0
  138. /package/{src/ts/ts-rs/TypedArrayWindow.ts → dist/ts-rs/TypedArrayWindow.d.ts} +0 -0
  139. /package/{src/ts/ts-rs/ViewOnRemoveResp.ts → dist/ts-rs/ViewOnRemoveResp.d.ts} +0 -0
  140. /package/{src/ts/ts-rs/ViewOnUpdateResp.ts → dist/ts-rs/ViewOnUpdateResp.d.ts} +0 -0
  141. /package/{src/ts/ts-rs/ViewWindow.ts → dist/ts-rs/ViewWindow.d.ts} +0 -0
  142. /package/{src/ts/ts-rs/WindowSortDir.ts → dist/ts-rs/WindowSortDir.d.ts} +0 -0
@@ -1,274 +0,0 @@
1
- // ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
- // ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
- // ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
- // ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
- // ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
- // ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
- // ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
- // ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
- // ┃ This file is part of the Perspective library, distributed under the terms ┃
10
- // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
- // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
-
13
- use std::fmt::Display;
14
- use std::rc::Rc;
15
- use std::string::FromUtf8Error;
16
-
17
- use perspective_client::{ClientError, ExprValidationResult};
18
- use thiserror::*;
19
- use wasm_bindgen::intern;
20
- use wasm_bindgen::prelude::*;
21
-
22
- #[macro_export]
23
- macro_rules! apierror {
24
- ($msg:expr) => {{
25
- use $crate::utils::errors::ApiErrorType::*;
26
- let js_err_type = $msg;
27
- let err = js_sys::Error::new(js_err_type.to_string().as_str());
28
- let js_err = $crate::utils::errors::ApiError(
29
- js_err_type,
30
- $crate::utils::errors::JsBackTrace(std::rc::Rc::new(err.clone())),
31
- );
32
- js_err
33
- }};
34
- }
35
-
36
- fn format_js_error(value: &JsValue) -> String {
37
- if let Some(err) = value.dyn_ref::<js_sys::Error>() {
38
- let msg = err.message().as_string().unwrap();
39
- if let Ok(x) = js_sys::Reflect::get(value, &intern("stack").into()) {
40
- format!("{}\n{}", msg, x.as_string().unwrap())
41
- } else {
42
- msg
43
- }
44
- } else {
45
- value
46
- .as_string()
47
- .unwrap_or_else(|| format!("{value:?}"))
48
- .to_string()
49
- }
50
- }
51
-
52
- fn format_valid_exprs(recs: &ExprValidationResult) -> String {
53
- recs.errors
54
- .iter()
55
- .map(|x| format!("\"{}\": {}", x.0, x.1.error_message))
56
- .collect::<Vec<_>>()
57
- .join(", ")
58
- }
59
-
60
- /// A bespoke error class for chaining a litany of error types with the `?`
61
- /// operator.
62
- #[derive(Clone, Debug, Error)]
63
- pub enum ApiErrorType {
64
- #[error("{}", format_js_error(.0))]
65
- JsError(JsValue),
66
-
67
- #[error("{}", format_js_error(.0))]
68
- JsRawError(js_sys::Error),
69
-
70
- #[error("Failed to construct table from {0:?}")]
71
- TableError(JsValue),
72
-
73
- #[error("{}", format_js_error(.0))]
74
- ViewerPluginError(JsValue),
75
-
76
- #[error("{0}")]
77
- ExternalError(Rc<Box<dyn std::error::Error>>),
78
-
79
- #[error("{0}")]
80
- UnknownError(String),
81
-
82
- #[error("{0}")]
83
- ClientError(#[from] ClientError),
84
-
85
- #[error("Cancelled")]
86
- CancelledError(#[from] futures::channel::oneshot::Canceled),
87
-
88
- #[error("{0}")]
89
- SerdeJsonError(Rc<serde_json::Error>),
90
-
91
- #[error("{0}")]
92
- ProstError(#[from] prost::DecodeError),
93
-
94
- #[error("Unknown column \"{1}\" in field `{0}`")]
95
- InvalidViewerConfigError(&'static str, String),
96
-
97
- #[error("Invalid `expressions` {}", format_valid_exprs(.0))]
98
- InvalidViewerConfigExpressionsError(Rc<ExprValidationResult>),
99
-
100
- #[error("Expected a Table or string table name")]
101
- TableRefError,
102
-
103
- #[error("No `Table` attached")]
104
- NoTableError,
105
-
106
- #[error(transparent)]
107
- SerdeWasmBindgenError(Rc<serde_wasm_bindgen::Error>),
108
-
109
- #[error(transparent)]
110
- Utf8Error(#[from] FromUtf8Error),
111
-
112
- #[error(transparent)]
113
- StdIoError(Rc<std::io::Error>),
114
-
115
- #[error(transparent)]
116
- ChronoParseError(#[from] chrono::ParseError),
117
- }
118
-
119
- #[derive(Clone, Debug, Error)]
120
- pub struct ApiError(pub ApiErrorType, pub JsBackTrace);
121
-
122
- impl ApiError {
123
- pub fn new<T: Display>(val: T) -> Self {
124
- apierror!(UnknownError(format!("{val}")))
125
- }
126
-
127
- /// The error category
128
- pub fn kind(&self) -> &'static str {
129
- match self.0 {
130
- ApiErrorType::JsError(..) => "[JsError]",
131
- ApiErrorType::TableError(_) => "[TableError]",
132
- ApiErrorType::ExternalError(_) => "[ExternalError]",
133
- ApiErrorType::UnknownError(..) => "[UnknownError]",
134
- ApiErrorType::ClientError(_) => "[ClientError]",
135
- ApiErrorType::CancelledError(_) => "[CancelledError]",
136
- ApiErrorType::SerdeJsonError(_) => "[SerdeJsonError]",
137
- ApiErrorType::ProstError(_) => "[ProstError]",
138
- ApiErrorType::InvalidViewerConfigError(..) => "[InvalidViewerConfigError]",
139
- ApiErrorType::InvalidViewerConfigExpressionsError(_) => "[InvalidViewerConfigError]",
140
- ApiErrorType::TableRefError => "[TableRefError]",
141
- ApiErrorType::NoTableError => "[NoTableError]",
142
- ApiErrorType::SerdeWasmBindgenError(_) => "[SerdeWasmBindgenError]",
143
- ApiErrorType::Utf8Error(_) => "[FromUtf8Error]",
144
- ApiErrorType::StdIoError(_) => "[StdIoError]",
145
- ApiErrorType::ChronoParseError(_) => "[ChronoParseError]",
146
- ApiErrorType::ViewerPluginError(_) => "[ViewerPluginError]",
147
- ApiErrorType::JsRawError(_) => "[JsRawError]",
148
- }
149
- }
150
-
151
- /// The raw internal enum
152
- pub fn inner(&self) -> &'_ ApiErrorType {
153
- &self.0
154
- }
155
-
156
- /// The `Display` for this error
157
- pub fn message(&self) -> String {
158
- self.0.to_string()
159
- }
160
-
161
- /// This error's stacktrace from when it was constructed.
162
- pub fn stacktrace(&self) -> String {
163
- js_sys::Reflect::get(&self.1.0, &intern("stack").into())
164
- .unwrap()
165
- .as_string()
166
- .unwrap()
167
- .to_string()
168
- }
169
- }
170
-
171
- // This type is not thread safe, but the JavaScript environment does not allow
172
- // threading.
173
- unsafe impl Send for ApiError {}
174
- unsafe impl Sync for ApiError {}
175
-
176
- impl std::fmt::Display for ApiError {
177
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178
- self.0.fmt(f)
179
- }
180
- }
181
-
182
- impl<T: Into<ApiErrorType>> From<T> for ApiError {
183
- fn from(value: T) -> Self {
184
- let value: ApiErrorType = value.into();
185
- let err = js_sys::Error::new(value.to_string().as_str());
186
- ApiError(value, JsBackTrace(Rc::new(err.clone())))
187
- }
188
- }
189
-
190
- impl From<ApiError> for JsValue {
191
- fn from(err: ApiError) -> Self {
192
- err.1.0.unchecked_ref::<JsValue>().clone()
193
- }
194
- }
195
-
196
- impl From<serde_wasm_bindgen::Error> for ApiError {
197
- fn from(value: serde_wasm_bindgen::Error) -> Self {
198
- ApiErrorType::SerdeWasmBindgenError(Rc::new(value)).into()
199
- }
200
- }
201
-
202
- impl From<std::io::Error> for ApiError {
203
- fn from(value: std::io::Error) -> Self {
204
- ApiErrorType::StdIoError(Rc::new(value)).into()
205
- }
206
- }
207
-
208
- impl From<Box<dyn std::error::Error>> for ApiError {
209
- fn from(value: Box<dyn std::error::Error>) -> Self {
210
- ApiErrorType::ExternalError(Rc::new(value)).into()
211
- }
212
- }
213
-
214
- impl From<serde_json::Error> for ApiError {
215
- fn from(value: serde_json::Error) -> Self {
216
- ApiErrorType::SerdeJsonError(Rc::new(value)).into()
217
- }
218
- }
219
-
220
- impl From<JsValue> for ApiError {
221
- fn from(err: JsValue) -> Self {
222
- if err.is_instance_of::<js_sys::Error>() {
223
- ApiError(
224
- ApiErrorType::JsRawError(err.clone().unchecked_into()),
225
- JsBackTrace(Rc::new(err.unchecked_into())),
226
- )
227
- } else {
228
- apierror!(JsError(err))
229
- }
230
- }
231
- }
232
-
233
- impl From<String> for ApiError {
234
- fn from(value: String) -> Self {
235
- apierror!(UnknownError(value.to_owned()))
236
- }
237
- }
238
-
239
- impl From<&str> for ApiError {
240
- fn from(value: &str) -> Self {
241
- apierror!(UnknownError(value.to_owned()))
242
- }
243
- }
244
-
245
- /// `ToApiError` handles complex cases that can't be into-d
246
- pub trait ToApiError<T> {
247
- fn into_apierror(self) -> ApiResult<T>;
248
- }
249
-
250
- impl<T> ToApiError<T> for Option<T> {
251
- fn into_apierror(self) -> ApiResult<T> {
252
- self.ok_or_else(|| intern("Unwrap on None").into())
253
- }
254
- }
255
-
256
- impl ToApiError<JsValue> for Result<(), ApiResult<JsValue>> {
257
- fn into_apierror(self) -> ApiResult<JsValue> {
258
- self.map_or_else(|x| x, |()| Ok(JsValue::UNDEFINED))
259
- }
260
- }
261
-
262
- /// A common Rust error handling idiom (see e.g. `anyhow::Result`)
263
- pub type ApiResult<T> = Result<T, ApiError>;
264
-
265
- // Backtrace
266
-
267
- #[derive(Clone, Debug)]
268
- pub struct JsBackTrace(pub Rc<js_sys::Error>);
269
-
270
- impl std::fmt::Display for JsBackTrace {
271
- fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272
- Ok(())
273
- }
274
- }
@@ -1,274 +0,0 @@
1
- // ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
- // ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
- // ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
- // ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
- // ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
- // ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
- // ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
- // ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
- // ┃ This file is part of the Perspective library, distributed under the terms ┃
10
- // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
- // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
-
13
- use std::cell::RefCell;
14
- use std::future::Future;
15
- use std::pin::Pin;
16
-
17
- use perspective_client::ClientError;
18
- // TODO This is risky to rely on, but it is currently impossible to implement
19
- // this trait locally due to the orphan instance restriction. Using this trait
20
- // removes alow of boilerplate required by `async` when casting to `Promise`.
21
- use wasm_bindgen::__rt::IntoJsResult;
22
- use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi};
23
- use wasm_bindgen::describe::WasmDescribe;
24
- use wasm_bindgen::prelude::*;
25
- use wasm_bindgen_futures::{JsFuture, future_to_promise};
26
-
27
- use super::errors::*;
28
-
29
- #[wasm_bindgen]
30
- extern "C" {
31
- /// A DevTools task handle from `console.createTask` — Chrome's Async
32
- /// Stack Tagging API. Bound manually, as `js_sys` does not expose it.
33
- type JsConsoleTask;
34
-
35
- #[wasm_bindgen(method, catch)]
36
- fn run(this: &JsConsoleTask, f: &js_sys::Function) -> Result<JsValue, JsValue>;
37
- }
38
-
39
- #[wasm_bindgen]
40
- extern "C" {
41
- #[wasm_bindgen(variadic, js_namespace = console , js_name = createTask, catch)]
42
- pub fn createTask(name: JsValue) -> Result<JsValue, JsValue>;
43
- }
44
-
45
- /// Create a DevTools task, or `None` where the API is unavailable (it is
46
- /// Chrome-only).
47
- fn create_task(name: &str) -> Option<JsConsoleTask> {
48
- thread_local! {
49
- static CREATE_TASK: Option<(JsValue, js_sys::Function)> = (|| {
50
- let global = js_sys::global();
51
- let console = js_sys::Reflect::get(&global, &"console".into()).ok()?;
52
- let create = js_sys::Reflect::get(&console, &"createTask".into()).ok()?;
53
- Some((console, create.dyn_into().ok()?))
54
- })();
55
- }
56
-
57
- CREATE_TASK.with(|x| {
58
- let (console, create) = x.as_ref()?;
59
- Some(create.call1(console, &name.into()).ok()?.unchecked_into())
60
- })
61
- }
62
-
63
- thread_local! {
64
- /// Scoped poll thunks for [`TRAMPOLINE`], a stack because tagged polls
65
- /// nest (an `ApiFuture` awaiting another `ApiFuture`).
66
- static POLL_STACK: RefCell<Vec<*mut (dyn FnMut() + 'static)>> = RefCell::new(Vec::new());
67
-
68
- /// The single reusable JS closure handed to [`JsConsoleTask::run`].
69
- static TRAMPOLINE: Closure<dyn Fn()> = Closure::new(|| {
70
- let thunk = POLL_STACK.with(|x| x.borrow().last().copied());
71
- if let Some(thunk) = thunk {
72
- unsafe { (*thunk)() }
73
- }
74
- });
75
- }
76
-
77
- /// A newtype wrapper for a `Future` trait object which supports being
78
- /// marshalled to a `JsPromise`.
79
- ///
80
- /// This avoids implementing an API which requires type casting to
81
- /// and from `JsValue` and the associated loss of type safety.
82
- #[must_use]
83
- pub struct ApiFuture<T>(
84
- Pin<Box<dyn Future<Output = ApiResult<T>>>>,
85
- Option<JsConsoleTask>,
86
- )
87
- where
88
- Result<T, JsValue>: IntoJsResult + 'static;
89
-
90
- impl<T> ApiFuture<T>
91
- where
92
- Result<T, JsValue>: IntoJsResult + 'static,
93
- {
94
- /// Constructor for `ApiFuture`. Note that, like a regular `Future`, the
95
- /// `ApiFuture` created does _not_ execute without being further cast to a
96
- /// `Promise`, either explicitly or implcitly (when exposed via
97
- /// `wasm_bindgen`).
98
- pub fn new<U: Future<Output = ApiResult<T>> + 'static>(x: U) -> Self {
99
- Self::new_named("perspective", x)
100
- }
101
-
102
- /// [`Self::new`] with an explicit DevTools task label, shown at the async
103
- /// gap in tagged stack traces.
104
- pub fn new_named<U: Future<Output = ApiResult<T>> + 'static>(name: &str, x: U) -> Self {
105
- Self(Box::pin(x), create_task(name))
106
- }
107
-
108
- pub fn new_throttled<U: Future<Output = ApiResult<T>> + 'static>(x: U) -> ApiFuture<()> {
109
- ApiFuture::<()>::new(async move { x.await.ignore_view_delete().map(|_| ()) })
110
- }
111
-
112
- pub fn new_pure(t: T) -> ApiFuture<T> {
113
- ApiFuture::<T>::new(async move { Ok(t) })
114
- }
115
-
116
- pub fn new_err<E: Into<ApiError> + 'static>(err: E) -> ApiFuture<T> {
117
- ApiFuture::<T>::new(async move { Err(err.into()) })
118
- }
119
- }
120
-
121
- impl<T> ApiFuture<T>
122
- where
123
- Result<T, JsValue>: IntoJsResult + 'static,
124
- {
125
- /// Construct an `ApiFuture` and execute it immediately. The `Promise`
126
- /// handle created internally is dropped, but since JavaScript `Promise`
127
- /// executes on construction, the async invocation persists.
128
- pub fn spawn<U: Future<Output = ApiResult<T>> + 'static>(x: U) {
129
- drop(js_sys::Promise::from(Self::new(x)))
130
- }
131
-
132
- /// [`Self::spawn`] with an explicit DevTools task label.
133
- pub fn spawn_named<U: Future<Output = ApiResult<T>> + 'static>(name: &str, x: U) {
134
- drop(js_sys::Promise::from(Self::new_named(name, x)))
135
- }
136
-
137
- pub fn spawn_throttled<U: Future<Output = ApiResult<T>> + 'static>(x: U) {
138
- drop(js_sys::Promise::from(Self::new_throttled(x)))
139
- }
140
- }
141
-
142
- impl<T> Default for ApiFuture<T>
143
- where
144
- Result<T, JsValue>: IntoJsResult + 'static,
145
- T: Default,
146
- {
147
- fn default() -> Self {
148
- Self::new(async { Ok(Default::default()) })
149
- }
150
- }
151
-
152
- impl<T> From<ApiFuture<T>> for JsValue
153
- where
154
- Result<T, Self>: IntoJsResult + 'static,
155
- {
156
- fn from(fut: ApiFuture<T>) -> Self {
157
- js_sys::Promise::from(fut).unchecked_into()
158
- }
159
- }
160
-
161
- impl<T> From<ApiFuture<T>> for js_sys::Promise
162
- where
163
- Result<T, JsValue>: IntoJsResult + 'static,
164
- {
165
- fn from(fut: ApiFuture<T>) -> Self {
166
- // Await `fut` NOT `fut.0` or the stack frame is lost in Chrome.
167
- future_to_promise(async move { Ok(fut.await?).into_js_result() })
168
- }
169
- }
170
-
171
- impl<T> WasmDescribe for ApiFuture<T>
172
- where
173
- Result<T, JsValue>: IntoJsResult + 'static,
174
- {
175
- fn describe() {
176
- <js_sys::Promise as WasmDescribe>::describe()
177
- }
178
- }
179
-
180
- impl<T> IntoWasmAbi for ApiFuture<T>
181
- where
182
- Result<T, JsValue>: IntoJsResult + 'static,
183
- {
184
- type Abi = <js_sys::Promise as IntoWasmAbi>::Abi;
185
-
186
- #[inline]
187
- fn into_abi(self) -> Self::Abi {
188
- js_sys::Promise::from(self).into_abi()
189
- }
190
- }
191
-
192
- impl<T> FromWasmAbi for ApiFuture<T>
193
- where
194
- Result<T, JsValue>: IntoJsResult + 'static,
195
- T: From<JsValue> + Into<JsValue>,
196
- {
197
- type Abi = <js_sys::Promise as IntoWasmAbi>::Abi;
198
-
199
- #[inline]
200
- unsafe fn from_abi(js: Self::Abi) -> Self {
201
- Self::new(async move {
202
- let promise = unsafe { js_sys::Promise::from_abi(js) };
203
- Ok(JsFuture::from(promise).await?.into())
204
- })
205
- }
206
- }
207
-
208
- impl<T> Future for ApiFuture<T>
209
- where
210
- Result<T, JsValue>: IntoJsResult + 'static,
211
- {
212
- type Output = ApiResult<T>;
213
-
214
- fn poll(
215
- self: Pin<&mut Self>,
216
- cx: &mut std::task::Context<'_>,
217
- ) -> std::task::Poll<Self::Output> {
218
- // SAFETY: structural projection only — neither field is moved, and
219
- // the inner future stays behind its own `Pin<Box<_>>`.
220
- let Self(inner, task) = unsafe { self.get_unchecked_mut() };
221
- let Some(task) = task else {
222
- return inner.as_mut().poll(cx);
223
- };
224
-
225
- let mut result = None;
226
- let mut thunk = || result = Some(inner.as_mut().poll(cx));
227
-
228
- // SAFETY: the lifetime is erased for storage only. The entry is
229
- // pushed and popped within this scope, and `run` invokes the
230
- // trampoline synchronously, so the pointer never outlives `thunk`.
231
- let short: *mut (dyn FnMut() + '_) = &mut thunk;
232
- let long: *mut (dyn FnMut() + 'static) = unsafe { std::mem::transmute(short) };
233
- POLL_STACK.with(|x| x.borrow_mut().push(long));
234
- let _ = TRAMPOLINE.with(|x| task.run(x.as_ref().unchecked_ref()));
235
- POLL_STACK.with(|x| x.borrow_mut().pop());
236
-
237
- #[allow(clippy::drop_non_drop)]
238
- drop(thunk);
239
-
240
- match result {
241
- Some(result) => result,
242
- // `run` threw without invoking the trampoline.
243
- None => inner.as_mut().poll(cx),
244
- }
245
- }
246
- }
247
-
248
- #[extend::ext]
249
- pub impl<T> Result<T, ApiError> {
250
- /// Wraps an error `JsValue` return from a caught JavaScript exception,
251
- /// checking for the explicit error type indicating that a
252
- /// `JsPerspectiveView` call has been cancelled due to it already being
253
- /// deleted. This is a normal mechanic of the `JsPerspectiveView` to
254
- /// cancel a `View` call that is no longer need be the viewer, e.g. when
255
- /// the user updates the UI before the previous update has finished
256
- /// drawing. Without using exceptions for this, we'd need to wrap every
257
- /// such `JsPerspectiveView` call individually.
258
- ///
259
- /// When `"View method cancelled"` message is received, this call should
260
- /// silently be replaced with `Ok`. The message itself is returned in this
261
- /// case (instead of whatever the `async` returns), which is helpful for
262
- /// detecting this condition when debugging.
263
- fn ignore_view_delete(self) -> Result<Option<T>, ApiError> {
264
- self.map(|x| Some(x)).or_else(|err| match err.inner() {
265
- ApiErrorType::ClientError(ClientError::ViewNotFound) => Ok(None),
266
- ApiErrorType::JsRawError(..) | ApiErrorType::JsError(..)
267
- if format!("{err}").contains("View not found") =>
268
- {
269
- Ok(None)
270
- },
271
- _ => Err(err),
272
- })
273
- }
274
- }