2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "module-loader.h"
30 ModuleLoader::ModuleLoader()
35 ModuleLoader::~ModuleLoader()
37 VectorBase::SizeType count = mModules.Count();
38 for( VectorBase::SizeType i = 0; i < count ; ++i)
40 Module* module = mModules[i];
46 bool ModuleLoader::CompileAndRun(v8::Isolate* isolate,
47 const std::string& sourceCode,
48 const std::string& sourceFileName )
51 v8::HandleScope handleScope( isolate );
52 v8::TryCatch tryCatch;
54 // convert from string to v8 string
55 v8::Local<v8::String> source = v8::String::NewFromUtf8( isolate, sourceCode.c_str());
56 v8::Local<v8::String> file = v8::String::NewFromUtf8( isolate, sourceFileName.c_str());
57 v8::ScriptOrigin origin(file);
60 v8::Local<v8::Script> script = v8::Script::Compile( source, &origin);
62 // See if an exception has been thrown
63 if( tryCatch.HasCaught() || script.IsEmpty() )
65 // Print errors that happened during compilation.
66 V8Utils::ReportException( isolate, &tryCatch );
71 v8::Local<v8::Value> result = script->Run();
73 // in V8 test code ( they check for an exception and empty return object )
74 if( tryCatch.HasCaught() || result.IsEmpty() )
76 // Print errors that happened during execution.
77 V8Utils::ReportException( isolate, &tryCatch);
84 bool ModuleLoader::ExecuteScript( v8::Isolate* isolate,
85 const std::string& sourceCode,
86 const std::string& sourceFileName )
88 StoreScriptInfo( sourceFileName );
90 return CompileAndRun(isolate, sourceCode, sourceFileName );
93 bool ModuleLoader::ExecuteScriptFromFile( v8::Isolate* isolate,
94 const std::string& fileName )
98 V8Utils::GetFileContents( fileName, contents );
100 return ExecuteScript( isolate, contents, fileName );
104 * ### var module = require("module-name");
107 * There is no standard for modules or the 'require' keyword in JavaScript.<br />
108 * However CommonJS have this: http://wiki.commonjs.org/wiki/Modules/1.1.1 ( used by Node.js).
111 * The concept behind 'require' keyword is simple, it allows you to include another
112 * JavaScript file, which exports an API / function / constructor / singleton.
115 * // example_module.js
116 * exports.hello = function() { return "hello world" }
121 * var example = require( "example_module.js");
123 * log( example.hello() );
127 * ### Module writers guide:
130 * #### Exporting as a namespace
132 * Example of using a namespace to export functions / objects.
134 * // filesystem-helper.js
135 * exports.version = "FileSystem helper 1.0";
136 * exports.open = function() { }
137 * exports.close = function() { }
138 * exports.read = function() { }
139 * exports.write = function() { ... }
140 * exports.fileSize = function() {...}
145 * var fs = require( "filesystem-helper.js");
149 * var file = fs.open("myfile.txt");
150 * var data = fs.read( file );
154 * #### Exporting as a function
156 * In this example we are using module.exports directly to change it
157 * from an object literal with name-value pairs (exports object) to a function.
159 * // my_first_module.js
160 * module.exports = function() { log("hello-world"); }
165 * var func = require("my_first_module.js");
166 * func(); // prints out hello-world
169 * #### Exporting as a constructor
173 * function ImageActor( position, orientation, image, name )
175 * this = new dali.ImageActor( image );
176 * this.position = position;
177 * this.orientation = orientation;
180 * module.exports = ImageActor;
186 * var ImageActor = require(" ImageActor.js");
188 * var imageActor = new ImageActor( position, orientation, image, "my first image actor");
190 * #### Exporting as a singleton
192 * By exporting a singleton you have an object which has shared state between
193 * any modules using it.
197 * // image-database.js
199 * function ImageDatabase( )
201 * this.addImage = function() { ... };
202 * this.removeImage = function() { ... };
203 * this.getImage = function() { ...};
204 * this.getImageCount = function() { ... };
207 * module.exports = new ImageDatabase();
214 * var database = require('image-database.js');
216 * database.addImage( myImage );
220 * // another-module.js
221 * var database = require('image-database.js');
223 * // gets the same database object as main.js
226 * The first call to require('image-database.js') will create the image database.
227 * Further calls, will return the same instance, because require caches module.exports.
228 * Otherwise it would have to recompile and run the module every time require is called.
232 * #### Automatic wrapping of a module by DALi:
234 * The module is automatically wrapped in a function by DALi before being executed ( similar technique to Node.js). </br>
235 * This is to prevent any functions / variables declared by the module entering the global namespace. </br>
236 * Currently the module will have access to all DALi global functions, like log, require and the DALi API ( actors / stage etc).</br>
239 * // Parameters passed to the internally generated function
240 * // module = reference to current module
241 * // module.exports = defines what the module exports
242 * // exports = reference to module.exports
243 * // __filename = module filename
244 * // __dirname = module directory
246 * function createModuleXYZ( exports ( === module.exports), module, __filename, __dirname )
249 * // Module code automatically inserted here.
251 * log(" my first module ");
252 * var version = "1.3"; // this won't pollute global namespace
253 * exports.version = version;
254 * exports.logActorPosition = function( actorName )
256 * var actor = dali.stage.getRootLayer().findChildByName(actorName );
257 * log( actor.x + "," + actor.y + "," + actor.z );
263 * return module.exports;
267 * Initially module.exports is an object literal with name-value pairs ( exports object).
268 * However it can be re-assigned to a constructor / function / singleton object as shown
269 * in the examples above.
272 * ### Circular dependencies:
274 * DALi JS supports circular dependencies as required by the CommonJS specification.
279 * export.version = "1.3"
280 * export.loaded = false;
281 * var bModule = require('b.js')
282 * export.loaded = true;
286 * var aModule = require('a.js')
287 * log( "aModule version = " + aModule.version + ", aModule loaded = " + aModule.loaded );
289 * //prints aModule = 1.3, aModule loaded = false
293 * var aModule = require("a.js");
296 * When b.js requires a.js, it is given everything that is exported from a.js, up to the point
297 * b.js is required by a.js.
299 * ### 'require' background
301 * There is alternative to module spec in CommonJS called RequireJs ( http://requirejs.org/docs/node.html) <br />
302 * DALi JS tries to follows the CommonJS specification (used by Node.js) as it
303 * is supposed to be better suited to server side development. <br /><br />
309 void ModuleLoader::Require(const v8::FunctionCallbackInfo< v8::Value >& args,
311 v8::Persistent<v8::ObjectTemplate>& globalObjectTemplate )
313 v8::Isolate* isolate = args.GetIsolate();
314 v8::HandleScope handleScope( isolate );
317 std::string fileName = V8Utils::GetStringParameter( PARAMETER_0, found, isolate , args );
320 DALI_SCRIPT_EXCEPTION( isolate, "require missing module name");
324 // strip off any path / .js
325 std::string moduleName;
326 V8Utils::GetModuleName( fileName, moduleName );
328 // see if the module already exists
329 const Module* existingModule = FindModule( moduleName );
332 // printf(" using existing module %s \n",moduleName.c_str() );
333 args.GetReturnValue().Set( existingModule->mExportsObject );
337 std::string path = mCurrentScriptPath; // path of top level script being executed
338 std::string contents;
339 V8Utils::GetFileContents(path + fileName, contents);
341 // wrap the module in a function to protect global namespace.
342 // the create function itself is global so we make it unique for each module
343 // For reference nodeJs does this as an anonymous function, but we're calling it from native side
344 // so need to pass parameters / get a name for it.
345 std::string functionName ="__createModule" + moduleName;
346 std::string source = "function " + functionName + "( exports, module, __filename, __directory) { ";
348 source+=" \n };"; // close the function
350 CompileAndRun( isolate, source, fileName );
352 // We need to create module object, so that the module can read / write properties to it
354 v8::Local<v8::Object> moduleObject = v8::Object::New( isolate );
355 v8::Local<v8::Object> exportsObject = v8::Object::New( isolate );
356 moduleObject->Set( v8::String::NewFromUtf8( isolate, "exports"), exportsObject );
357 moduleObject->Set( v8::String::NewFromUtf8( isolate, "id"), v8::String::NewFromUtf8( isolate ,moduleName.c_str() ) );
359 // store the module exports object now, this is to allow for circular dependencies.
360 // If this-module requires another module, which then requires this module ( creating a circle), it will be given an export object
361 // which contains everything exported so far.
362 Module* module = StoreModule( path, fileName, moduleName, isolate, exportsObject );
364 v8::Local<v8::Context> currentContext = isolate->GetCurrentContext();
366 // get the CreateModule function
367 v8::Local<v8::Function> createModule = v8::Local<v8::Function>::Cast(currentContext->Global()->Get(v8::String::NewFromUtf8( isolate, functionName.c_str() )));
370 std::vector< v8::Local<v8::Value> > arguments;
371 arguments.push_back( exportsObject );
372 arguments.push_back( moduleObject );
373 arguments.push_back( v8::String::NewFromUtf8( isolate, fileName.c_str() ));
374 arguments.push_back( v8::String::NewFromUtf8( isolate, path.c_str() ));
377 // call the CreateModule function
378 createModule->Call( createModule, arguments.size(), &arguments[0]); //[0]
380 // get the module.export object, the module writer may have re-assinged module.exports, so the exports object
381 // no longer references it.
382 v8::Local<v8::Value> moduleExportsValue = moduleObject->Get( v8::String::NewFromUtf8( isolate, "exports"));
383 v8::Local<v8::Object> moduleExports = moduleExportsValue->ToObject();
385 // Re-store the export ( possible nothing happens, because exports hasn't been re-assigned).
386 module->mExportsObject.Reset( isolate, moduleExports);
388 args.GetReturnValue().Set( moduleExports );
391 void ModuleLoader::StoreScriptInfo( const std::string& sourceFileName )
393 V8Utils::GetFileDirectory( sourceFileName, mCurrentScriptPath);
396 Module* ModuleLoader::StoreModule( const std::string& path,
397 const std::string& fileName,
398 const std::string& moduleName,
400 v8::Isolate* isolate,
401 v8::Local<v8::Object>& moduleExportsObject )
403 Module* module = new Module( path, fileName, moduleName, isolate, moduleExportsObject );
404 mModules.PushBack( module );
409 const Module* ModuleLoader::FindModule( const std::string& moduleName )
411 VectorBase::SizeType count = mModules.Count();
412 for( VectorBase::SizeType i = 0; i < count ; ++i)
414 const Module* module = mModules[i];
415 if (module->mModuleName == moduleName )