Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 66 additions & 13 deletions crates/wasm-rquickjs/skeleton/src/builtin/execution.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#[cfg(feature = "typescript-compiler-profiling")]
use crate::internal::runtime_services::{ExecutionProfile, ExecutionProfileSnapshot};
use crate::internal::runtime_services::{
OwnedJsRuntime, RuntimeOutputSink, RuntimeServices, normalize_absolute_path,
};
#[cfg(feature = "typescript-compiler-profiling")]
use crate::internal::runtime_services::{ExecutionProfile, ExecutionProfileSnapshot};

use futures::future::{Either, pending, poll_fn, select};
use futures::task::AtomicWaker;
use rquickjs::{CatchResultExt, Ctx, Module, Promise, async_with};
use rquickjs::{CatchResultExt, Ctx, Function, Module, Promise, Value, async_with};
use serde::Deserialize;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
Expand Down Expand Up @@ -162,23 +162,41 @@ fn execution_control_error(job: &ExecutionJob, deadline: Option<Instant>) -> Opt
}

#[cfg(feature = "typescript-runtime")]
fn transform_typescript_execution_source(source: String, name: &str) -> Result<String, String> {
fn transform_typescript_execution_source(
source: String,
name: &str,
source_map: bool,
) -> Result<String, String> {
crate::internal::typescript::transform(
source,
name,
crate::internal::typescript::runtime_mode(),
false,
source_map,
Some(true),
)
.map(|output| output.code)
.map(|output| output.into_code_with_inline_source_map())
.map_err(|error| error.message)
}

#[cfg(not(feature = "typescript-runtime"))]
fn transform_typescript_execution_source(_source: String, _name: &str) -> Result<String, String> {
fn transform_typescript_execution_source(
_source: String,
_name: &str,
_source_map: bool,
) -> Result<String, String> {
Err("TypeScript runtime support is not enabled".to_string())
}

#[cfg(feature = "typescript-runtime")]
fn execution_source_maps_enabled(ctx: &Ctx<'_>) -> bool {
crate::internal::typescript::source_maps_enabled(ctx)
}

#[cfg(not(feature = "typescript-runtime"))]
fn execution_source_maps_enabled(_ctx: &Ctx<'_>) -> bool {
false
}

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct PollResult {
Expand Down Expand Up @@ -355,7 +373,10 @@ async fn run_job(options: ExecutionOptions, job: Rc<ExecutionJob>) {
let profile = {
let started = Instant::now();
let profile = Rc::new(ExecutionProfile::new(started));
profile.set_duration("queueDelay", started.saturating_duration_since(job.created_at));
profile.set_duration(
"queueDelay",
started.saturating_duration_since(job.created_at),
);
profile
};
#[cfg(feature = "typescript-compiler-profiling")]
Expand Down Expand Up @@ -481,10 +502,11 @@ async fn run_job(options: ExecutionOptions, job: Rc<ExecutionJob>) {
})))
.await;

let wrapper_name = cwd.join(if entry.is_some() {
"__wasm_rquickjs_execution_entry.mjs"
} else {
let is_inline = entry.is_none();
let wrapper_name = cwd.join(if is_inline {
"__wasm_rquickjs_execution_inline.mjs"
} else {
"__wasm_rquickjs_execution_entry.mjs"
});
let name = wrapper_name.to_string_lossy().into_owned();
let mut source = if let Some(entry) = entry {
Expand All @@ -500,16 +522,21 @@ async fn run_job(options: ExecutionOptions, job: Rc<ExecutionJob>) {
)
} else {
format!(
"globalThis.__wasmRquickjsExecutionResult = (async () => __wasmRquickjsSerializeExecutionResult(await (async () => {{ {}\n}})()))();",
"globalThis.__wasmRquickjsExecutionResult = (async () => __wasmRquickjsSerializeExecutionResult(await (async () => {{\n{}\n}})()))();",
options.source.unwrap_or_default()
)
};
let source_maps_enabled = if options.language == ExecutionLanguage::Typescript {
async_with!(runtime.ctx => |ctx| { execution_source_maps_enabled(&ctx) }).await
} else {
false
};
mark_profile!("wrapperPreparation");
if options.language == ExecutionLanguage::Typescript {
if let Some(error) = execution_control_error(&job, deadline) {
complete_job!(Err(error.to_string()));
}
source = match transform_typescript_execution_source(source, &name) {
source = match transform_typescript_execution_source(source, &name, source_maps_enabled) {
Ok(source) => source,
Err(error) => {
complete_job!(Err(error));
Expand All @@ -525,6 +552,32 @@ async fn run_job(options: ExecutionOptions, job: Rc<ExecutionJob>) {
let result = {
let execution = async {
async_with!(runtime.ctx => |ctx| {
if (options.language == ExecutionLanguage::Typescript || is_inline)
&& let Ok(register_source_map) = ctx.globals().get::<_, Function>(
"__wasm_rquickjs_register_transformed_source_map",
)
{
let (line_offset, original_line_offset, force_line_offset) =
if options.language == ExecutionLanguage::Typescript && source_maps_enabled {
(0, usize::from(is_inline), false)
} else if is_inline {
(1, 0, true)
} else {
(0, 0, false)
};
register_source_map
.call::<_, ()>((
name.as_str(),
source.as_str(),
Value::new_null(ctx.clone()),
line_offset,
original_line_offset,
force_line_offset,
))
.map_err(|error| {
format!("failed to register execution source map: {error:?}")
})?;
}
Module::evaluate(ctx.clone(), name, source).catch(&ctx)
.map_err(|e| crate::internal::format_caught_error(e))?.finish::<()>().catch(&ctx)
.map_err(|e| crate::internal::format_caught_error(e))?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,61 +318,6 @@ function findGlobalConstructorNameByPrototype(value) {
return "";
}

const inspectNewCallPattern = /\b(?:[A-Za-z_$][A-Za-z0-9_$]*\.)?inspect\s*\(\s*new\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/;
const stackLocationPattern = /\(?(.+):(\d+):(\d+)\)?\s*$/;

function inferConstructorNameFromCallsite() {
const currentModule = globalThis.__wasm_rquickjs_current_module;
if (
currentModule === undefined ||
currentModule === null ||
typeof currentModule.source !== "string"
) {
return "";
}

let stack;
try {
stack = String(new Error().stack || "");
} catch {
return "";
}

const sourceLines = currentModule.source.split("\n");
const stackLines = stack.split("\n");
for (let i = stackLines.length - 1; i >= 1; i--) {
if (!stackLines[i].includes("anonymous (") && !stackLines[i].includes("<anonymous> (")) {
continue;
}

const locationMatch = stackLocationPattern.exec(stackLines[i]);
if (locationMatch === null) {
continue;
}

const lineNumber = Number(locationMatch[2]);
if (!Number.isInteger(lineNumber) || lineNumber < 1 || lineNumber > sourceLines.length) {
continue;
}

const snippet = [
sourceLines[lineNumber - 4],
sourceLines[lineNumber - 3],
sourceLines[lineNumber - 2],
sourceLines[lineNumber - 1],
]
.filter((line) => typeof line === "string")
.join(" ");

const constructorMatch = inspectNewCallPattern.exec(snippet);
if (constructorMatch !== null) {
return constructorMatch[1];
}
}

return "";
}

function trackNullPrototypeConstructor(target, proto) {
if (!isObjectLike(target)) {
return;
Expand Down Expand Up @@ -420,7 +365,7 @@ Reflect.setPrototypeOf = function setPrototypeOf(target, proto) {
}
};

export function getConstructorName(value, allowCallsiteFallback = false) {
export function getConstructorName(value) {
if (!isObjectLike(value)) {
return "Object";
}
Expand All @@ -445,16 +390,6 @@ export function getConstructorName(value, allowCallsiteFallback = false) {
return globalConstructorName;
}

// QuickJS does not expose V8's hidden-class constructor-name recovery API.
// When inspecting `new Foo()` objects whose prototype was replaced with a
// null-prototype object, infer `Foo` from the user callsite as a fallback.
if (allowCallsiteFallback) {
const callsiteConstructorName = inferConstructorNameFromCallsite();
if (callsiteConstructorName !== "") {
return callsiteConstructorName;
}
}

return "Object";
}

Expand Down
Loading
Loading