/
relay.rs
185 lines (165 loc) · 5.75 KB
/
relay.rs
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
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;
use std::path::{Path, PathBuf};
use swc_atoms::JsWord;
use swc_common::errors::HANDLER;
use swc_common::FileName;
use swc_ecmascript::ast::*;
use swc_ecmascript::utils::{quote_ident, ExprFactory};
use swc_ecmascript::visit::{Fold, FoldWith};
#[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RelayLanguageConfig {
TypeScript,
Flow,
}
impl Default for RelayLanguageConfig {
fn default() -> Self {
Self::Flow
}
}
struct Relay<'a> {
root_dir: PathBuf,
pages_dir: PathBuf,
file_name: FileName,
config: &'a Config,
}
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub src: PathBuf,
pub artifact_directory: Option<PathBuf>,
#[serde(default)]
pub language: RelayLanguageConfig,
}
fn pull_first_operation_name_from_tpl(tpl: &TaggedTpl) -> Option<String> {
tpl.tpl.quasis.iter().find_map(|quasis| {
static OPERATION_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(fragment|mutation|query|subscription) (\w+)").unwrap());
let capture_group = OPERATION_REGEX.captures_iter(&quasis.raw).next();
capture_group.map(|capture_group| capture_group[2].to_string())
})
}
fn build_require_expr_from_path(path: &str) -> Expr {
Expr::Call(CallExpr {
span: Default::default(),
callee: quote_ident!("require").as_callee(),
args: vec![Lit::Str(Str {
span: Default::default(),
value: JsWord::from(path),
raw: None,
})
.as_arg()],
type_args: None,
})
}
impl<'a> Fold for Relay<'a> {
fn fold_expr(&mut self, expr: Expr) -> Expr {
let expr = expr.fold_children_with(self);
match &expr {
Expr::TaggedTpl(tpl) => {
if let Some(built_expr) = self.build_call_expr_from_tpl(tpl) {
built_expr
} else {
expr
}
}
_ => expr,
}
}
}
#[derive(Debug)]
enum BuildRequirePathError {
FileNameNotReal,
ArtifactDirectoryExpected { file_name: String },
}
impl<'a> Relay<'a> {
fn path_for_artifact(
&self,
real_file_name: &Path,
definition_name: &str,
) -> Result<PathBuf, BuildRequirePathError> {
let filename = match &self.config.language {
RelayLanguageConfig::Flow => format!("{}.graphql.js", definition_name),
RelayLanguageConfig::TypeScript => {
format!("{}.graphql.ts", definition_name)
}
};
if let Some(artifact_directory) = &self.config.artifact_directory {
Ok(self.root_dir.join(artifact_directory).join(filename))
} else if real_file_name.starts_with(&self.pages_dir) {
Err(BuildRequirePathError::ArtifactDirectoryExpected {
file_name: real_file_name.display().to_string(),
})
} else {
Ok(real_file_name
.parent()
.unwrap()
.join("__generated__")
.join(filename))
}
}
fn build_require_path(
&mut self,
operation_name: &str,
) -> Result<PathBuf, BuildRequirePathError> {
match &self.file_name {
FileName::Real(real_file_name) => {
self.path_for_artifact(real_file_name, operation_name)
}
_ => Err(BuildRequirePathError::FileNameNotReal),
}
}
fn build_call_expr_from_tpl(&mut self, tpl: &TaggedTpl) -> Option<Expr> {
if let Expr::Ident(ident) = &*tpl.tag {
if &*ident.sym != "graphql" {
return None;
}
}
let operation_name = pull_first_operation_name_from_tpl(tpl);
match operation_name {
None => None,
Some(operation_name) => match self.build_require_path(operation_name.as_str()) {
Ok(final_path) => Some(build_require_expr_from_path(final_path.to_str().unwrap())),
Err(err) => {
let base_error = "Could not transform GraphQL template to a Relay import.";
let error_message = match err {
BuildRequirePathError::FileNameNotReal => "Source file was not a real \
file. This is likely a bug and \
should be reported to Next.js"
.to_string(),
BuildRequirePathError::ArtifactDirectoryExpected { file_name } => {
format!(
"The generated file for `{}` will be created in `pages` \
directory, which will break production builds. Try moving the \
file outside of `pages` or set the `artifactDirectory` in the \
Relay config file.",
file_name
)
}
};
HANDLER.with(|handler| {
handler.span_err(
tpl.span,
format!("{} {}", base_error, error_message).as_str(),
);
});
None
}
},
}
}
}
pub fn relay<'a>(
config: &'a Config,
file_name: FileName,
pages_dir: Option<PathBuf>,
) -> impl Fold + '_ {
Relay {
root_dir: std::env::current_dir().unwrap(),
file_name,
pages_dir: pages_dir.unwrap_or_else(|| panic!("pages_dir is expected.")),
config,
}
}