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( ...@@ -123,14 +123,17 @@ pub async fn get_next_server_transforms_rules(
// optimize_use_state)) // optimize_use_state))
rules.push(get_next_image_rule()); rules.push(get_next_image_rule());
}
if let NextRuntime::Edge = next_runtime { if let NextRuntime::Edge = next_runtime {
rules.push(get_middleware_dynamic_assert_rule(mdx_rs)); rules.push(get_middleware_dynamic_assert_rule(mdx_rs));
if !foreign_code {
rules.push(next_edge_node_api_assert( rules.push(next_edge_node_api_assert(
mdx_rs, mdx_rs,
matches!(context_ty, ServerContextType::Middleware { .. }) matches!(context_ty, ServerContextType::Middleware { .. })
&& matches!(*mode.await?, NextMode::Build), && matches!(*mode.await?, NextMode::Build),
matches!(*mode.await?, NextMode::Build),
)); ));
} }
} }
......
...@@ -14,9 +14,11 @@ use super::module_rule_match_js_no_url; ...@@ -14,9 +14,11 @@ use super::module_rule_match_js_no_url;
pub fn next_edge_node_api_assert( pub fn next_edge_node_api_assert(
enable_mdx_rs: bool, enable_mdx_rs: bool,
should_error_for_node_apis: bool, should_error_for_node_apis: bool,
is_production: bool,
) -> ModuleRule { ) -> ModuleRule {
let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextEdgeNodeApiAssert { let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextEdgeNodeApiAssert {
should_error_for_node_apis, should_error_for_node_apis,
is_production,
}) as _)); }) as _));
ModuleRule::new( ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs), module_rule_match_js_no_url(enable_mdx_rs),
...@@ -30,6 +32,7 @@ pub fn next_edge_node_api_assert( ...@@ -30,6 +32,7 @@ pub fn next_edge_node_api_assert(
#[derive(Debug)] #[derive(Debug)]
struct NextEdgeNodeApiAssert { struct NextEdgeNodeApiAssert {
should_error_for_node_apis: bool, should_error_for_node_apis: bool,
is_production: bool,
} }
#[async_trait] #[async_trait]
...@@ -43,6 +46,7 @@ impl CustomTransformer for NextEdgeNodeApiAssert { ...@@ -43,6 +46,7 @@ impl CustomTransformer for NextEdgeNodeApiAssert {
unresolved_ctxt: SyntaxContext::empty().apply_mark(ctx.unresolved_mark), unresolved_ctxt: SyntaxContext::empty().apply_mark(ctx.unresolved_mark),
}, },
self.should_error_for_node_apis, self.should_error_for_node_apis,
self.is_production,
); );
program.visit_with(&mut visitor); program.visit_with(&mut visitor);
Ok(()) Ok(())
......
...@@ -18,6 +18,7 @@ pub fn warn_for_edge_runtime( ...@@ -18,6 +18,7 @@ pub fn warn_for_edge_runtime(
cm: Arc<SourceMap>, cm: Arc<SourceMap>,
ctx: ExprCtx, ctx: ExprCtx,
should_error_for_node_apis: bool, should_error_for_node_apis: bool,
is_production: bool,
) -> impl Visit { ) -> impl Visit {
WarnForEdgeRuntime { WarnForEdgeRuntime {
cm, cm,
...@@ -26,6 +27,7 @@ pub fn warn_for_edge_runtime( ...@@ -26,6 +27,7 @@ pub fn warn_for_edge_runtime(
should_add_guards: false, should_add_guards: false,
guarded_symbols: Default::default(), guarded_symbols: Default::default(),
guarded_process_props: Default::default(), guarded_process_props: Default::default(),
is_production,
} }
} }
...@@ -39,6 +41,7 @@ struct WarnForEdgeRuntime { ...@@ -39,6 +41,7 @@ struct WarnForEdgeRuntime {
/// `if(typeof clearImmediate !== "function") clearImmediate();` /// `if(typeof clearImmediate !== "function") clearImmediate();`
guarded_symbols: FxHashSet<Atom>, guarded_symbols: FxHashSet<Atom>,
guarded_process_props: FxHashSet<Atom>, guarded_process_props: FxHashSet<Atom>,
is_production: bool,
} }
const EDGE_UNSUPPORTED_NODE_APIS: &[&str] = &[ const EDGE_UNSUPPORTED_NODE_APIS: &[&str] = &[
...@@ -232,6 +235,18 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime", ...@@ -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 { impl Visit for WarnForEdgeRuntime {
...@@ -266,6 +281,11 @@ impl Visit for WarnForEdgeRuntime { ...@@ -266,6 +281,11 @@ impl Visit for WarnForEdgeRuntime {
fn visit_expr(&mut self, n: &Expr) { fn visit_expr(&mut self, n: &Expr) {
if let Expr::Ident(ident) = n { if let Expr::Ident(ident) = n {
if ident.ctxt == self.ctx.unresolved_ctxt { 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 { for api in EDGE_UNSUPPORTED_NODE_APIS {
if self.is_in_middleware_layer() && ident.sym == *api { if self.is_in_middleware_layer() && ident.sym == *api {
self.emit_unsupported_api_error(ident.span, api); self.emit_unsupported_api_error(ident.span, api);
......
...@@ -694,6 +694,7 @@ fn test_edge_assert(input: PathBuf) { ...@@ -694,6 +694,7 @@ fn test_edge_assert(input: PathBuf) {
is_unresolved_ref_safe: false, is_unresolved_ref_safe: false,
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark), unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
}, },
true,
true true
)) ))
) )
......
...@@ -111,13 +111,18 @@ describe('Edge runtime configurable guards', () => { ...@@ -111,13 +111,18 @@ describe('Edge runtime configurable guards', () => {
stderr: true, stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 }, env: { NEXT_TELEMETRY_DEBUG: 1 },
}) })
expect(output.stderr).toContain(`Build failed`)
expect(output.code).toBe(1)
if (!process.env.TURBOPACK) {
expect(output.stderr).toContain(`./pages/api/route.js`) expect(output.stderr).toContain(`./pages/api/route.js`)
}
expect(output.stderr).toContain( expect(output.stderr).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime` `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime`
) )
if (!process.env.TURBOPACK) {
expect(output.stderr).toContain(`Used by default`) expect(output.stderr).toContain(`Used by default`)
expect(output.stderr).toContain(TELEMETRY_EVENT_NAME) expect(output.stderr).toContain(TELEMETRY_EVENT_NAME)
}
}) })
} }
) )
......
...@@ -174,6 +174,9 @@ describe.each([ ...@@ -174,6 +174,9 @@ describe.each([
}) })
it('should have middleware warning during build', () => { it('should have middleware warning during build', () => {
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(`Failed to compile`)
expect(buildResult.stderr).toContain( expect(buildResult.stderr).toContain(
`Used by usingEval, usingEvalSync` `Used by usingEval, usingEvalSync`
...@@ -181,6 +184,8 @@ describe.each([ ...@@ -181,6 +184,8 @@ describe.each([
expect(buildResult.stderr).toContain( expect(buildResult.stderr).toContain(
`Used by usingWebAssemblyCompile` `Used by usingWebAssemblyCompile`
) )
}
expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR) expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR)
}) })
} }
......
...@@ -8975,7 +8975,8 @@ ...@@ -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 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 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 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": [ "failed": [
"Edge runtime configurable guards Edge API using lib with allowed, unused dynamic code production mode build and does not warn at runtime", "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 @@ ...@@ -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 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 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 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 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"
], ],
"pending": [], "pending": [],
"flakey": [], "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