Skip to content

Commit

Permalink
print js error in console.log
Browse files Browse the repository at this point in the history
  • Loading branch information
ofzo committed Feb 21, 2024
1 parent 2e06f7c commit c4f84e8
Show file tree
Hide file tree
Showing 20 changed files with 711 additions and 1,901 deletions.
2,000 changes: 345 additions & 1,655 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 14 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,24 @@ relative-path = "1.9.2"
reqwest = { version = "0.11.23", features = ["blocking"] }
serde_json = "1.0.111"
serde_v8 = "0.154.0"
swc = "0.270.20"
swc_common = { version = "0.33.12", features = ["tty-emitter"] }
swc_ecma_ast = "0.110.17"
swc_ecma_parser = "0.141.37"
swc_ecma_visit = "0.96.17"
swc_ecma_transforms_module = "0.178.16"
# swc = "0.270.20"
# swc_common = { version = "0.33.12", features = ["tty-emitter"] }
# swc_ecma_ast = "0.110.17"
# swc_ecma_parser = "0.141.37"
# swc_ecma_visit = "0.96.17"
# swc_ecma_transforms_module = "0.178.16"
url = "2.5.0"
v8 = "0.82.0"
anyhow = "1.0.79"
tracing = "0.1.40"
# oxc
oxc_allocator = "^0.6.0"
oxc_codegen = "^0.6.0"
oxc_parser = "^0.6.0"
oxc_transformer = "^0.6.0"
oxc_span= "^0.6.0"
oxc_ast = "^0.6.0"
oxc_semantic = "^0.6.0"

[dependencies.tokio]
features = ["full"]
Expand Down
21 changes: 10 additions & 11 deletions bootstrap/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@ interface RuntimeData {
count: number
}

var runtimeData: RuntimeData = {
asyncHandle: [],
count: 0,
}

export default async function bootstrap(entry: string) {
var runtime: RuntimeData = {
asyncHandle: [],
count: 0,
}
//@ts-ignore
globalThis.setTimeout = (fn: Function, delay: number, ...arg: any[]) => {
runtimeData.asyncHandle[runtimeData.count] = () => {
runtime.asyncHandle[runtime.count] = () => {
fn(...arg)
}
this.timer.send(runtimeData.count, delay)
runtimeData.count++
this.timer.send(runtime.count, delay)
runtime.count++
}
globalThis.exec = (id: number) => {
if (runtimeData.asyncHandle[id]) {
let fn = runtimeData.asyncHandle[id]
delete runtimeData.asyncHandle[id]
if (runtime.asyncHandle[id]) {
let fn = runtime.asyncHandle[id]
delete runtime.asyncHandle[id]
fn()
}
}
Expand Down
19 changes: 13 additions & 6 deletions src/runner/console.rs → src/builtin/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,20 @@ pub fn console_format(
}
if v.is_object() {
let obj = v8::Local::<v8::Object>::try_from(*v).unwrap();

if v.is_native_error() {
let stack = v8::String::new(scope, "stack").unwrap();
let stack = obj
.get(scope, stack.into())
.unwrap()
.to_rust_string_lossy(scope);
return format!("{stack}");
}

let names = obj
.get_own_property_names(scope, Default::default())
.unwrap();
// let prototype = obj.get_prototype(scope).unwrap();

let mut fmt = (0..names.length())
.map(|index| {
let name = names.get_index(scope, index).unwrap();
Expand Down Expand Up @@ -114,7 +124,7 @@ pub fn console_format(
format!("")
}

pub fn console_log(
pub fn log(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut _rv: v8::ReturnValue,
Expand All @@ -128,8 +138,5 @@ pub fn console_log(
.collect::<Vec<_>>()
.join(" ");

println!(
"{} {result}",
format!("{}", Utc::now().format("%Y-%m-%d %H:%M:%S%.3f")).color("gray")
);
println!("{result}");
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
169 changes: 15 additions & 154 deletions src/compile.rs
Original file line number Diff line number Diff line change
@@ -1,68 +1,11 @@
use std::{path::PathBuf, sync::Arc};
use swc::{
config::{Config, JscConfig, ModuleConfig, Options, SourceMapsConfig},
Compiler,
};
use swc_common::{
errors::{ColorConfig, Handler},
FileName, SourceMap, GLOBALS,
};
use swc_ecma_ast::{CallExpr, Callee, EsVersion, Expr, Lit, ModuleDecl};
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax};
use swc_ecma_visit::{Visit, VisitWith};
use v8::Isolate;

use crate::{
compile_oxc,
graph::resolve,
runtime::{ModuleInstance, Runtime},
};

struct ImportParser {
sync_imports: Vec<String>,
async_imports: Vec<String>,
}

impl ImportParser {
pub fn new() -> Self {
Self {
sync_imports: vec![],
async_imports: vec![],
}
}
}

impl Visit for ImportParser {
fn visit_call_expr(&mut self, call_expr: &CallExpr) {
if !matches!(call_expr.callee, Callee::Import(_)) {
return;
}
if !call_expr.args.is_empty() {
let arg = &call_expr.args[0];
if let Expr::Lit(Lit::Str(v)) = &*arg.expr {
self.async_imports.push(v.value.to_string());
}
}
}
fn visit_module_decl(&mut self, module_decl: &ModuleDecl) {
match module_decl {
ModuleDecl::Import(import) => {
if import.type_only {
return;
}
self.sync_imports.push(import.src.value.to_string());
}
ModuleDecl::ExportNamed(export) => {
if let Some(src) = &export.src {
self.sync_imports.push(src.value.to_string());
}
}
ModuleDecl::ExportAll(export) => {
self.sync_imports.push(export.src.value.to_string());
}
_ => {}
}
}
}
use anyhow::anyhow;
use std::{io::Result, path::PathBuf, sync::Arc};
use v8::Isolate;

#[derive(Debug)]
pub struct ModuleDependency {
Expand Down Expand Up @@ -138,7 +81,7 @@ impl ModuleDependency {

let tc_scope = &mut v8::TryCatch::new(scope);
module
.instantiate_module(tc_scope, Runtime::resolve)
.instantiate_module(tc_scope, Runtime::resolve_module_callback)
.unwrap();
let expose = &module.get_module_namespace();
let v8_module = v8::Global::new(tc_scope, module);
Expand All @@ -153,14 +96,18 @@ impl ModuleDependency {
},
);
}

pub fn evaluate(&self, isolate: &mut Isolate) {
let state_rc = Runtime::state(isolate);
let graph_rc = Runtime::graph(isolate);

self.deps.iter().for_each(|url| {
let graph = graph_rc.borrow();
let table = graph.table.borrow();
let dep = table.get(url).unwrap();
let url = resolve(url, &self.filename);
let dep = table
.get(&url)
.expect(&format!("table get failure `{url}`"));
dep.evaluate(isolate);
});

Expand All @@ -187,94 +134,8 @@ impl ModuleDependency {
}
}

pub fn compile(file_name: &str, source: &str) -> ModuleDependency {
let cm = Arc::<SourceMap>::default();
let handler = Arc::new(Handler::with_tty_emitter(
ColorConfig::Auto,
true,
false,
Some(cm.clone()),
));
let compiler = Compiler::new(cm.clone());

let fm = cm.new_source_file(
match url::Url::parse(file_name) {
Ok(url) => FileName::Url(url),
Err(_) => FileName::Real(PathBuf::from(file_name)),
},
source.to_string(),
);

let lexer = Lexer::new(
Syntax::Typescript(Default::default()),
EsVersion::latest(),
StringInput::from(&*fm),
None,
);
let mut parser = Parser::new_from(lexer);

for err in parser.take_errors() {
err.into_diagnostic(&handler).emit();
}

let parsed = parser
.parse_module()
.map_err(|e| e.into_diagnostic(&handler).emit())
.expect(&format!("parse {file_name} fail"));

let mut import_parser = ImportParser::new();
parsed.visit_with(&mut import_parser);

let result = GLOBALS.set(&Default::default(), || {
compiler.run(|| {
compiler
.process_js_file(
fm,
&handler,
&Options {
config: Config {
jsc: JscConfig {
target: Some(EsVersion::Es2022),
syntax: Some(Syntax::Typescript(Default::default())),
..Default::default()
},
module: Some(ModuleConfig::Es6(
swc_ecma_transforms_module::EsModuleConfig {
resolve_fully: true,
},
)),
source_maps: Some(SourceMapsConfig::Bool(false)),
..Default::default()
},
..Default::default()
},
)
.expect("compiler error")
})
});

// let filename = path.file_name().unwrap().to_str().unwrap();
// let mut file = fs::OpenOptions::new()
// .write(true)
// .truncate(true)
// .create(true)
// .open(PathBuf::from(format!("output/{filename}.js")))
// .unwrap();

// if let Some(map) = &result.map {
// fs::write(
// PathBuf::from(format!("output/{filename}.js.map")),
// map.as_bytes(),
// )
// .unwrap();
// }
ModuleDependency {
deps: import_parser.sync_imports,
async_deps: import_parser.async_imports,
specifier: vec![],
source: result.code,
map: result.map,
filename: file_name.to_string(),
is_main: false,
}
}
pub use compile_oxc::compile;
// pub fn compile(file_name: &str, source_text: &str) -> anyhow::Result<ModuleDependency> {
// return compile_oxc::compile(file_name, source_text);
// // return compile_swc::compile(file_name, source_text);
// }
Loading

0 comments on commit c4f84e8

Please sign in to comment.