Unverified Commit 1bcf0be9 authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

feat(turbopack): Port more features of webpack middleware plugin (#69856)

### What?

Port more linting features from `webpack/middleware-plugin.ts`.

### Why?


To match the behavior of the default mode.

### How?

Closes PACK-3224
parent 71fba193
......@@ -123,14 +123,17 @@ pub async fn get_next_server_transforms_rules(
// optimize_use_state))
rules.push(get_next_image_rule());
}
if let NextRuntime::Edge = next_runtime {
rules.push(get_middleware_dynamic_assert_rule(mdx_rs));
if let NextRuntime::Edge = next_runtime {
rules.push(get_middleware_dynamic_assert_rule(mdx_rs));
if !foreign_code {
rules.push(next_edge_node_api_assert(
mdx_rs,
matches!(context_ty, ServerContextType::Middleware { .. })
&& matches!(*mode.await?, NextMode::Build),
matches!(*mode.await?, NextMode::Build),
));
}
}
......
......@@ -14,9 +14,11 @@ use super::module_rule_match_js_no_url;
pub fn next_edge_node_api_assert(
enable_mdx_rs: bool,
should_error_for_node_apis: bool,
is_production: bool,
) -> ModuleRule {
let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextEdgeNodeApiAssert {
should_error_for_node_apis,
is_production,
}) as _));
ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs),
......@@ -30,6 +32,7 @@ pub fn next_edge_node_api_assert(
#[derive(Debug)]
struct NextEdgeNodeApiAssert {
should_error_for_node_apis: bool,
is_production: bool,
}
#[async_trait]
......@@ -43,6 +46,7 @@ impl CustomTransformer for NextEdgeNodeApiAssert {
unresolved_ctxt: SyntaxContext::empty().apply_mark(ctx.unresolved_mark),
},
self.should_error_for_node_apis,
self.is_production,
);
program.visit_with(&mut visitor);
Ok(())
......
......@@ -18,6 +18,7 @@ pub fn warn_for_edge_runtime(
cm: Arc<SourceMap>,
ctx: ExprCtx,
should_error_for_node_apis: bool,
is_production: bool,
) -> impl Visit {
WarnForEdgeRuntime {
cm,
......@@ -26,6 +27,7 @@ pub fn warn_for_edge_runtime(
should_add_guards: false,
guarded_symbols: Default::default(),
guarded_process_props: Default::default(),
is_production,
}
}
......@@ -39,6 +41,7 @@ struct WarnForEdgeRuntime {
/// `if(typeof clearImmediate !== "function") clearImmediate();`
guarded_symbols: FxHashSet<Atom>,
guarded_process_props: FxHashSet<Atom>,
is_production: bool,
}
const EDGE_UNSUPPORTED_NODE_APIS: &[&str] = &[
......@@ -232,6 +235,18 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime",
_ => (),
}
}
fn emit_dynamic_not_allowed_error(&self, span: Span) {
if self.is_production {
let msg = "Dynamic Code Evaluation (e. g. 'eval', 'new Function', \
'WebAssembly.compile') not allowed in Edge Runtime"
.to_string();
HANDLER.with(|h| {
h.struct_span_err(span, &msg).emit();
});
}
}
}
impl Visit for WarnForEdgeRuntime {
......@@ -266,6 +281,11 @@ impl Visit for WarnForEdgeRuntime {
fn visit_expr(&mut self, n: &Expr) {
if let Expr::Ident(ident) = n {
if ident.ctxt == self.ctx.unresolved_ctxt {
if ident.sym == "eval" {
self.emit_dynamic_not_allowed_error(ident.span);
return;
}
for api in EDGE_UNSUPPORTED_NODE_APIS {
if self.is_in_middleware_layer() && ident.sym == *api {
self.emit_unsupported_api_error(ident.span, api);
......
......@@ -694,6 +694,7 @@ fn test_edge_assert(input: PathBuf) {
is_unresolved_ref_safe: false,
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
},
true,
true
))
)
......
......@@ -111,13 +111,18 @@ describe('Edge runtime configurable guards', () => {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
})
expect(output.stderr).toContain(`Build failed`)
expect(output.stderr).toContain(`./pages/api/route.js`)
expect(output.code).toBe(1)
if (!process.env.TURBOPACK) {
expect(output.stderr).toContain(`./pages/api/route.js`)
}
expect(output.stderr).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime`
)
expect(output.stderr).toContain(`Used by default`)
expect(output.stderr).toContain(TELEMETRY_EVENT_NAME)
if (!process.env.TURBOPACK) {
expect(output.stderr).toContain(`Used by default`)
expect(output.stderr).toContain(TELEMETRY_EVENT_NAME)
}
})
}
)
......
......@@ -174,13 +174,18 @@ describe.each([
})
it('should have middleware warning during build', () => {
expect(buildResult.stderr).toContain(`Failed to compile`)
expect(buildResult.stderr).toContain(
`Used by usingEval, usingEvalSync`
)
expect(buildResult.stderr).toContain(
`Used by usingWebAssemblyCompile`
)
if (process.env.TURBOPACK) {
expect(buildResult.stderr).toContain(`Ecmascript file had an error`)
} else {
expect(buildResult.stderr).toContain(`Failed to compile`)
expect(buildResult.stderr).toContain(
`Used by usingEval, usingEvalSync`
)
expect(buildResult.stderr).toContain(
`Used by usingWebAssemblyCompile`
)
}
expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR)
})
}
......
......@@ -8975,7 +8975,8 @@
"Edge runtime configurable guards Middleware with use of Function as a type does not warn in dev at runtime",
"Edge runtime configurable guards Middleware with use of Function as a type production mode build and does not warn at runtime",
"Edge runtime configurable guards Multiple functions with different configurations warns in dev for allowed code",
"Edge runtime configurable guards Multiple functions with different configurations warns in dev for unallowed code"
"Edge runtime configurable guards Multiple functions with different configurations warns in dev for unallowed code",
"Edge runtime configurable guards Multiple functions with different configurations production mode fails to build because of unallowed code"
],
"failed": [
"Edge runtime configurable guards Edge API using lib with allowed, unused dynamic code production mode build and does not warn at runtime",
......@@ -8983,8 +8984,7 @@
"Edge runtime configurable guards Edge API with allowed, unused dynamic code production mode build and does not warn at runtime",
"Edge runtime configurable guards Middleware using lib with allowed, unused dynamic code production mode build and does not warn at runtime",
"Edge runtime configurable guards Middleware using lib with unallowed, used dynamic code production mode fails to build because of dynamic code evaluation",
"Edge runtime configurable guards Middleware with allowed, unused dynamic code production mode build and does not warn at runtime",
"Edge runtime configurable guards Multiple functions with different configurations production mode fails to build because of unallowed code"
"Edge runtime configurable guards Middleware with allowed, unused dynamic code production mode build and does not warn at runtime"
],
"pending": [],
"flakey": [],
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment