Skip to content

Commit

Permalink
try fix edge: remaining call-sites
Browse files Browse the repository at this point in the history
  • Loading branch information
mischnic committed Nov 6, 2024
1 parent 82d0136 commit 45078fb
Show file tree
Hide file tree
Showing 82 changed files with 374 additions and 306 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('default', () => {
allBundles += output
}
expect(allBundles).toContain(
'__turbopack_external_require__("external-package")'
'__turbopack_external_require__("external-package"'
)
} else {
const output = await fs.readFile(
Expand Down
1 change: 1 addition & 0 deletions turbopack/crates/turbopack-core/src/compile_time_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ pub enum FreeVarReference {
lookup_path: Option<ResolvedVc<FileSystemPath>>,
export: Option<RcStr>,
},
Ident(RcStr),
Value(CompileTimeDefineValue),
Error(RcStr),
}
Expand Down
1 change: 1 addition & 0 deletions turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@ impl From<&FreeVarReference> for JsValue {
fn from(v: &FreeVarReference) -> Self {
match v {
FreeVarReference::Value(v) => v.into(),
FreeVarReference::Ident(v) => JsValue::FreeVar((&**v).into()),
FreeVarReference::EcmaScriptModule { .. } => {
JsValue::unknown_empty(false, "compile time injected free var module")
}
Expand Down
9 changes: 4 additions & 5 deletions turbopack/crates/turbopack-ecmascript/src/chunk/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,9 @@ impl EcmascriptChunkItemContent {
args.push("e: exports");
}
if self.options.stub_require {
args.push("z: require");
} else {
args.push("t: require");
args.push("z: __turbopack_require_stub__");
}
args.push("t: require");
if self.options.wasm {
args.push("w: __turbopack_wasm__");
args.push("u: __turbopack_wasm_module__");
Expand Down Expand Up @@ -193,8 +192,8 @@ pub struct EcmascriptChunkItemOptions {
/// Whether this chunk item's module factory should include an `exports`
/// argument.
pub exports: bool,
/// Whether this chunk item's module factory should include an argument for the real `require`,
/// or just a throwing stub (for ESM)
/// Whether this chunk item's module factory should include an argument for a throwing require
/// stub (for ESM)
pub stub_require: bool,
/// Whether this chunk item's module factory should include a
/// `__turbopack_external_require__` argument.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ impl CodeGenerateable for EsmAssetReference {
)
} else {
quote!(
"var $name = __turbopack_external_require__($id, true);" as Stmt,
"var $name = __turbopack_external_require__($id, () => require($id), true);" as Stmt,
name = Ident::new(ident.clone().into(), DUMMY_SP, Default::default()),
id: Expr = Expr::Lit(request.clone().to_string().into())
)
Expand Down Expand Up @@ -354,7 +354,7 @@ impl CodeGenerateable for EsmAssetReference {
ident.clone().into(),
var_decl_with_span(
quote!(
"var $name = __turbopack_external_require__($id, true);" as Stmt,
"var $name = __turbopack_external_require__($id, () => require($id), true);" as Stmt,
name = Ident::new(ident.clone().into(), DUMMY_SP, Default::default()),
id: Expr = Expr::Lit(request.clone().to_string().into())
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ impl CachedExternalModule {
} else {
writeln!(
code,
"const mod = __turbopack_external_require__({});",
"const mod = __turbopack_external_require__({}, () => require({}));",
StringifyJs(&self.request),
StringifyJs(&self.request)
)?;
}
Expand Down
43 changes: 43 additions & 0 deletions turbopack/crates/turbopack-ecmascript/src/references/ident.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use anyhow::Result;
use swc_core::{ecma::ast::Expr, quote};
use turbo_tasks::{RcStr, Vc};
use turbopack_core::chunk::ChunkingContext;

use super::AstPath;
use crate::{
code_gen::{CodeGenerateable, CodeGeneration},
create_visitor,
};

#[turbo_tasks::value]
pub struct IdentReplacement {
value: RcStr,
path: Vc<AstPath>,
}

#[turbo_tasks::value_impl]
impl IdentReplacement {
#[turbo_tasks::function]
pub fn new(value: RcStr, path: Vc<AstPath>) -> Vc<Self> {
Self::cell(IdentReplacement { value, path })
}
}

#[turbo_tasks::value_impl]
impl CodeGenerateable for IdentReplacement {
#[turbo_tasks::function]
async fn code_generation(
&self,
_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> {
let value = self.value.clone();
let path = &self.path.await?;

let visitor = create_visitor!(path, visit_mut_expr(expr: &mut Expr) {
let id = Expr::Ident((&*value).into());
*expr = quote!("(\"TURBOPACK ident replacement\", $e)" as Expr, e: Expr = id);
});

Ok(CodeGeneration::visitors(vec![visitor]))
}
}
19 changes: 16 additions & 3 deletions turbopack/crates/turbopack-ecmascript/src/references/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod constant_value;
pub mod dynamic_expression;
pub mod esm;
pub mod external_module;
pub mod ident;
pub mod node;
pub mod pattern_mapping;
pub mod raw;
Expand Down Expand Up @@ -134,6 +135,7 @@ use crate::{
cjs::{CjsRequireAssetReference, CjsRequireCacheAccess, CjsRequireResolveAssetReference},
dynamic_expression::DynamicExpression,
esm::{module_id::EsmModuleIdAssetReference, EsmBinding, UrlRewriteBehavior},
ident::IdentReplacement,
node::PackageJsonReference,
require_context::{RequireContextAssetReference, RequireContextMap},
type_issue::SpecifiedModuleTypeIssue,
Expand Down Expand Up @@ -1232,10 +1234,10 @@ async fn compile_time_info_for_module_type(
let free_var_references = compile_time_info.free_var_references;

let mut free_var_references = free_var_references.await?.clone_value();
let (typeof_exports, typeof_module) = if is_esm {
("undefined", "undefined")
let (typeof_exports, typeof_module, require) = if is_esm {
("undefined", "undefined", Some("__turbopack_require_stub__"))
} else {
("object", "object")
("object", "object", None)
};
free_var_references
.entry(vec![
Expand All @@ -1262,6 +1264,11 @@ async fn compile_time_info_for_module_type(
DefineableNameSegment::TypeOf,
])
.or_insert("function".into());
if let Some(require) = require {
free_var_references
.entry(vec![DefineableNameSegment::Name("require".into())])
.or_insert(FreeVarReference::Ident(require.into()));
}

Ok(CompileTimeInfo {
environment: compile_time_info.environment,
Expand Down Expand Up @@ -2192,6 +2199,12 @@ async fn handle_free_var_reference(
Vc::cell(ast_path.to_vec()),
));
}
FreeVarReference::Ident(value) => {
analysis.add_code_gen(IdentReplacement::new(
value.clone(),
Vc::cell(ast_path.to_vec()),
));
}
FreeVarReference::EcmaScriptModule {
request,
lookup_path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,33 +107,15 @@ impl SinglePatternMapping {
match self {
Self::Invalid => self.create_id(key_expr),
Self::Unresolvable(request) => throw_module_not_found_expr(request),
Self::Ignored => {
quote!("{}" as Expr)
}
Self::Module(_) | Self::ModuleLoader(_) => Expr::Call(CallExpr {
callee: Callee::Expr(quote_expr!("__turbopack_require__")),
args: vec![ExprOrSpread {
spread: None,
expr: Box::new(self.create_id(key_expr)),
}],
span: DUMMY_SP,
..Default::default()
}),
Self::External(request, ExternalType::CommonJs) => Expr::Call(CallExpr {
callee: Callee::Expr(quote_expr!("__turbopack_external_require__")),
args: vec![
ExprOrSpread {
spread: None,
expr: request.as_str().into(),
},
ExprOrSpread {
spread: None,
expr: quote_expr!("() => require($arg)"),
},
],
span: DUMMY_SP,
..Default::default()
}),
Self::Ignored => *quote_expr!("{}"),
Self::Module(_) | Self::ModuleLoader(_) => *quote_expr!(
"__turbopack_require__($arg)",
arg: Expr = self.create_id(key_expr)
),
Self::External(request, ExternalType::CommonJs) => *quote_expr!(
"__turbopack_external_require__($arg, () => require($arg))",
arg: Expr = request.as_str().into()
),
Self::External(request, ty) => throw_module_not_found_error_expr(
request,
&format!("Unsupported external type {:?} for commonjs reference", ty),
Expand Down
4 changes: 2 additions & 2 deletions turbopack/crates/turbopack-node/js/src/transforms/postcss.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
declare const __turbopack_external_require__: (id: string) => any;
declare const __turbopack_external_require__: (id: string, thunk: () => any, esm?: boolean) => any;

// @ts-ignore
import postcss from "@vercel/turbopack/postcss";
Expand Down Expand Up @@ -54,7 +54,7 @@ export const init = async (ipc: Ipc<IpcInfoMessage, IpcRequestMessage>) => {
let pluginFactory = arg;

if (typeof pluginFactory === "string") {
pluginFactory = __turbopack_external_require__(pluginFactory);
pluginFactory = __turbopack_external_require__(pluginFactory, () => require(pluginFactory));
}

if (pluginFactory.default) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
declare const __turbopack_external_require__: {
resolve: (name: string, opt: { paths: string[] }) => string;
} & ((id: string) => any);
} & ((id: string, thunk: () => any, esm?: boolean) => any);

import type { Ipc } from "../ipc/evaluate";
import {
Expand Down Expand Up @@ -62,7 +62,7 @@ let runLoaders: typeof import("loader-runner")["runLoaders"];
try {
({ runLoaders } = require("@vercel/turbopack/loader-runner"));
} catch {
({ runLoaders } = __turbopack_external_require__("loader-runner"));
({ runLoaders } = __turbopack_external_require__("loader-runner", () => require("loader-runner")));
}

const contextDir = process.cwd();
Expand Down Expand Up @@ -498,11 +498,13 @@ function makeErrorEmitter(
name: error.name,
message: error.message,
stack: error.stack ? parseStackTrace(error.stack) : [],
cause: undefined,
}
: {
name: "Error",
message: error,
stack: [],
cause: undefined,
},
});
};
Expand Down
5 changes: 3 additions & 2 deletions turbopack/crates/turbopack-tests/js/jest-entry.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/// <reference path="./types.d.ts" />

const jest = __turbopack_external_require__("jest-circus");
const expectMod = __turbopack_external_require__("expect");
const jest = require("jest-circus");
const expectMod = require("expect");

function setupGlobals() {
globalThis.describe = jest.describe;
globalThis.it = jest.it;
globalThis.test = jest.test;
// @ts-ignore Property 'expect' does not exist on type 'typeof globalThis'
globalThis.expect = expectMod.expect;

// From https://github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/test/TestCases.template.js#L422
Expand Down
2 changes: 1 addition & 1 deletion turbopack/crates/turbopack-tests/js/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
declare const __turbopack_external_require__: (id: string) => any;
declare const __turbopack_external_require__: (id: string, thunk: () => any, esm?: boolean) => any;

declare module "TESTS";
10 changes: 10 additions & 0 deletions turbopack/crates/turbopack-tests/tests/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ async fn run_test(prepared_test: Vc<PreparedTest>) -> Result<Vc<RunTestResult>>
)
.resolved_cell(),
);
import_map.insert_exact_alias(
"jest-circus",
ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced, None)
.resolved_cell(),
);
import_map.insert_exact_alias(
"expect",
ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced, None)
.resolved_cell(),
);

let asset_context: Vc<Box<dyn AssetContext>> = Vc::upcast(ModuleAssetContext::new(
Default::default(),
Expand Down
Loading

0 comments on commit 45078fb

Please sign in to comment.