v8::Handle<v8::Value> toJson(v8::Handle<v8::Value> value) { HandleScope scope; Handle<Context> context = Context::GetCurrent(); Handle<Object> global = context->Global(); Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject(); Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify"))); // JSON.stringify(values, null, '\t'); Handle<Value> argv[] = { value, Null(), String::New("\t") }; TryCatch exception; Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv); if (exception.HasCaught()) { return exception.ReThrow(); } return scope.Close(stringified); }
Handle<Value> evalScript(const Arguments& args) { if (args.Length() < 2) { return ThrowException(Exception::TypeError(String::New("evalScript takes 2 arguments."))); } TryCatch tc; Local<Script> compiled = Script::Compile(args[0]->ToString(), args[1]->ToString()); if (compiled.IsEmpty()) { return tc.ReThrow(); } Handle<Value> value = compiled->Run(); if (value.IsEmpty()) { return tc.ReThrow(); } return value; }
void BookWrap::Apply(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); Local<Function> fun = Local<Function>::Cast(args[0]); Handle<Value> argv[] = { args.This() }; TryCatch trycatch; Handle<Value> v = fun->Call(Null(isolate), 1, argv); if (trycatch.HasCaught()) { trycatch.ReThrow(); } args.GetReturnValue().Set(v); }
Handle<Value> evalInContext(const Arguments& args) { if (args.Length() < 3) { return ThrowException(Exception::TypeError(String::New("evalInContext takes 3 arguments."))); } if (!args[1]->IsObject()) { return ThrowException(Exception::TypeError(String::New("evalInContext expects an object as second argument."))); } HandleScope scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Local<Object> global = context->Global(); Local<Object> jscontext = args[1]->ToObject()->Clone(); Local<Array> names = jscontext->GetOwnPropertyNames(); for (int i = 0; i < names->Length(); i++) { global->Set(names->Get(i), jscontext->Get(names->Get(i))); } TryCatch tc; Local<Script> compiled = Script::Compile(args[0]->ToString(), args[2]->ToString()); if (compiled.IsEmpty()) { return tc.ReThrow(); } Handle<Value> value = compiled->Run(); if (value.IsEmpty()) { return tc.ReThrow(); } return scope.Close(value); }
void test_rethrow() { HandleScope handle_scope; TryCatch trycatch; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Handle<String> source = String::New("oasdohuasdnlqwoi"); Handle<Script> script = Script::Compile(source); { TryCatch innerCatcher; Handle<Value> result = script->Run(); do_check_true(innerCatcher.HasCaught()); innerCatcher.ReThrow(); } context.Dispose(); do_check_true(trycatch.HasCaught()); }
static Handle<Value> includeJavaScript(string id, string parentFolder, bool* error) { // CommonJS path rules if (id.find("/") == 0) { id.replace(id.find("/"), std::string("/").length(), rootFolder); } else if (id.find("./") == 0) { id.replace(id.find("./"), std::string("./").length(), parentFolder); } else if (id.find("../") == 0) { // count ../../../ in id and strip off back of parentFolder int count = 0; size_t idx = 0; size_t pos = 0; while (true) { idx = id.find("../", pos); if (idx == std::string::npos) { break; } else { pos = idx + 3; count++; } } // strip leading ../../ off module id id = id.substr(pos); // strip paths off the parent folder idx = 0; pos = parentFolder.size(); for (int i = 0; i < count; i++) { idx = parentFolder.find_last_of("/", pos); pos = idx - 1; } if (idx == std::string::npos) { *error = true; return ThrowException(String::New("Unable to find module")); } parentFolder = parentFolder.substr(0, idx + 1); id = parentFolder + id; } else { string tempId = rootFolder + id; ifstream ifs((tempId).c_str()); if (!ifs) { id = parentFolder + id; } else { id = rootFolder + id; } } string filename = id; string javascript; { ifstream ifs((filename).c_str()); if (!ifs) { *error = true; Local<Value> taggedMessage = String::New((string(Ti::Msg::No_such_native_module) + " " + id).c_str()); return ThrowException(taggedMessage); } getline(ifs, javascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } // wrap the module { size_t idx = filename.find_last_of("/"); parentFolder = filename.substr(0, idx + 1); static const string preWrap = "Ti.include = function () { Ti.globalInclude(Array.prototype.slice.call(arguments), '" + parentFolder + "')};\n"; javascript = preWrap + javascript; } TryCatch tryCatch; Handle<Script> compiledScript = Script::Compile(String::New(javascript.c_str()), String::New(filename.c_str())); if (compiledScript.IsEmpty()) { *error = true; std::string err_msg; DisplayExceptionLine(tryCatch, err_msg); return tryCatch.ReThrow(); } Local<Value> result = compiledScript->Run(); if (result.IsEmpty()) { *error = true; return tryCatch.ReThrow(); } return result; }
Handle<Value> TiTitaniumObject::_globalInclude(void*, TiObject*, const Arguments& args) { if (args.Length() < 2) { return ThrowException(String::New(Ti::Msg::Missing_argument)); } string id = *String::Utf8Value(args[0]->ToString()); string parentFolder = *String::Utf8Value(args[1]->ToString()); // CommonJS path rules if (id.find("/") == 0) { id.replace(id.find("/"), std::string("/").length(), rootFolder); } else if (id.find("./") == 0) { id.replace(id.find("./"), std::string("./").length(), parentFolder); } else if (id.find("../") == 0) { // count ../../../ in id and strip off back of parentFolder int count = 0; size_t idx = 0; size_t pos = 0; while (true) { idx = id.find("../", pos); if (idx == std::string::npos) { break; } else { pos = idx + 3; count++; } } // strip leading ../../ off module id id = id.substr(pos); // strip paths off the parent folder idx = 0; pos = parentFolder.size(); for (int i = 0; i < count; i++) { idx = parentFolder.find_last_of("/", pos); pos = idx - 1; } if (idx == std::string::npos) { return ThrowException(String::New("Unable to find module")); } parentFolder = parentFolder.substr(0, idx + 1); id = parentFolder + id; } else { string tempId = rootFolder + id; ifstream ifs((tempId).c_str()); if (!ifs) { id = parentFolder + id; } else { id = rootFolder + id; } } string filename = id; string javascript; { ifstream ifs((filename).c_str()); if (!ifs) { Local<Value> taggedMessage = String::New((string(Ti::Msg::No_such_native_module) + " " + id).c_str()); return ThrowException(taggedMessage); } getline(ifs, javascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } // wrap the module { size_t idx = filename.find_last_of("/"); parentFolder = filename.substr(0, idx + 1); static const string preWrap = "Ti.include = function (id) { Ti.globalInclude(id, '" + parentFolder + "')};\n"; javascript = preWrap + javascript; } TryCatch tryCatch; Handle<Script> compiledScript = Script::Compile(String::New(javascript.c_str()), String::New(filename.c_str())); if (compiledScript.IsEmpty()) { DisplayExceptionLine(tryCatch); return tryCatch.ReThrow(); } Persistent<Value> result = Persistent<Value>::New(compiledScript->Run()); if (result.IsEmpty()) { return tryCatch.ReThrow(); } return Undefined(); }
Handle<Value> TiRootObject::_globalRequire(void*, TiObject*, const Arguments& args) { if (args.Length() < 2) { return ThrowException(String::New(Ti::Msg::Missing_argument)); } string id = *String::Utf8Value(args[0]->ToString()); string parentFolder = *String::Utf8Value(args[1]->ToString()); // CommonJS path rules if (id.find("/") == 0) { id.replace(id.find("/"), std::string("/").length(), rootFolder); } else if (id.find("./") == 0) { id.replace(id.find("./"), std::string("./").length(), parentFolder); } else if (id.find("../") == 0) { // count ../../../ in id and strip off back of parentFolder int count = 0; size_t idx = 0; size_t pos = 0; while (true) { idx = id.find("../", pos); if (idx == std::string::npos) { break; } else { pos = idx + 3; count++; } } // strip leading ../../ off module id id = id.substr(pos); // strip paths off the parent folder idx = 0; pos = parentFolder.size(); for (int i = 0; i < count; i++) { idx = parentFolder.find_last_of("/", pos); pos = idx - 1; } if (idx == std::string::npos) { return ThrowException(String::New("Unable to find module")); } parentFolder = parentFolder.substr(0, idx + 1); id = parentFolder + id; } else { string tempId = rootFolder + id; ifstream ifs((tempId + ".js").c_str()); if (!ifs) { id = parentFolder + id; } else { id = rootFolder + id; } } string filename = id + ".js"; // check if cached static map<string, Persistent<Value> > cache; map<string, Persistent<Value> >::const_iterator cachedValue = cache.find(id); if (cachedValue != cache.end()) { return cachedValue->second; } string javascript; { ifstream ifs((filename).c_str()); if (!ifs) { Local<Value> taggedMessage = String::New((string(Ti::Msg::No_such_native_module) + " " + id).c_str()); return ThrowException(taggedMessage); } getline(ifs, javascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } // wrap the module { size_t idx = filename.find_last_of("/"); parentFolder = filename.substr(0, idx + 1); static const string requireWithParent = "var require = function (id) { return globalRequire(id, '" + parentFolder + "')};\n"; static const string preWrap = "(function () {" + requireWithParent + "\nvar module = { exports: {} }; var exports = module.exports;\n"; static const string postWrap = "\nreturn module.exports; })();"; javascript = preWrap + javascript + postWrap; } TryCatch tryCatch; Handle<Script> compiledScript = Script::Compile(String::New(javascript.c_str()), String::New(filename.c_str())); if (compiledScript.IsEmpty()) { DisplayExceptionLine(tryCatch); return tryCatch.ReThrow(); } Persistent<Value> result = Persistent<Value>::New(compiledScript->Run()); if (result.IsEmpty()) { return tryCatch.ReThrow(); } // cache result cache.insert(pair<string, Persistent<Value> >(id, result)); return result; }
void NativeScriptRuntime::CompileAndRun(string modulePath, bool& hasError, Handle<Object>& moduleObj, bool isBootstrapCall) { auto isolate = Isolate::GetCurrent(); Local < Value > exportObj = Object::New(isolate); auto tmpExportObj = new Persistent<Object>(isolate, exportObj.As<Object>()); loadedModules.insert(make_pair(modulePath, tmpExportObj)); TryCatch tc; auto scriptText = Require::LoadModule(modulePath); DEBUG_WRITE("Compiling script (module %s)", modulePath.c_str()); Local < String > fullRequiredModulePath = ConvertToV8String(modulePath); auto script = Script::Compile(scriptText, fullRequiredModulePath); DEBUG_WRITE("Compiled script (module %s)", modulePath.c_str()); if (ExceptionUtil::GetInstance()->HandleTryCatch(tc, "Script " + modulePath + " contains compilation errors!")) { loadedModules.erase(modulePath); tmpExportObj->Reset(); delete tmpExportObj; hasError = true; } else if (script.IsEmpty()) { //think about more descriptive message -> [script_name] was empty DEBUG_WRITE("%s was empty", modulePath.c_str()); } else { DEBUG_WRITE("Running script (module %s)", modulePath.c_str()); TryCatch tcRequire; Local < Function > f = script->Run().As<Function>(); if (ExceptionUtil::GetInstance()->HandleTryCatch(tc)) { DEBUG_WRITE("Exception was handled in java code"); } //this is done so the initial bootstrap function is persistent (and to keep old logic) if(isBootstrapCall) { auto persistentAppModule = new Persistent<Object>(isolate, f); } auto result = f->Call(Object::New(isolate), 1, &exportObj); if(ExceptionUtil::GetInstance()->HandleTryCatch(tc)) { DEBUG_WRITE("Exception was handled in java code"); } else { moduleObj = result.As<Object>(); } // introducing isBootstrapCall in order to save the flow as it was (latter on we can think about including the following code for the bootstrap (initial) call if(!isBootstrapCall) { DEBUG_WRITE("After Running script (module %s)", modulePath.c_str()); if (ExceptionUtil::GetInstance()->HandleTryCatch(tcRequire)) { loadedModules.erase(modulePath); tmpExportObj->Reset(); delete tmpExportObj; hasError = true; tcRequire.ReThrow(); } else { if (moduleObj.IsEmpty()) { auto objectTemplate = ObjectTemplate::New(); moduleObj = objectTemplate->NewInstance(); } DEBUG_WRITE("Script completed (module %s)", modulePath.c_str()); if (!moduleObj->StrictEquals(exportObj)) { loadedModules.erase(modulePath); tmpExportObj->Reset(); delete tmpExportObj; auto persistentModuleObject = new Persistent<Object>(isolate, moduleObj.As<Object>()); loadedModules.insert(make_pair(modulePath, persistentModuleObject)); } } } } if (tc.HasCaught()) { tc.ReThrow(); } }