├── .gitignore ├── .gitmodules ├── COPYING ├── README.md ├── bin.js ├── clients ├── module-client.js └── test │ └── demo.html ├── demo-server.js ├── module-compiler ├── INSTALL.md ├── bin.js ├── externs.js ├── module-compiler.js ├── package.json └── third-party │ └── closure-compiler │ ├── COPYING │ └── compiler.jar ├── module-graph.js ├── module-server.js ├── package.json └── test ├── fixtures ├── build │ ├── module$app.js │ ├── module$app.js.map │ ├── module$module$bar.js │ ├── module$module$bar.js.map │ ├── module$module$baz$foo.js │ ├── module$module$baz$foo.js.map │ ├── module$module$foo.js │ ├── module$module$foo.js.map │ ├── module$module.js │ ├── module$module.js.map │ ├── module$sub_app.js │ ├── module$sub_app.js.map │ ├── root.js │ └── root.js.map └── sample-module │ ├── app.js │ ├── module-graph.json │ ├── module.js │ ├── module │ ├── bar.js │ ├── baz │ │ └── foo.js │ └── foo.js │ └── sub-app.js ├── test-module-client.js ├── test-module-graph.js └── test-module-server.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "LABjs"] 2 | path = clients/third-party/LABjs 3 | url = git://github.com/getify/LABjs 4 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2012] Google Inc 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Module Server 2 | ============== 3 | 4 | Module server is a system for efficient serving of CommonJS modules to web browsers. The core feature is that it supports *incremental loading* of modules and their dependencies with exactly 1 HTTP request per incremental load. 5 | 6 | This is a *reference implementation* that has not been battle-tested in production use. See our [presentation from JSConf EU 2012](https://docs.google.com/presentation/d/1Q44eWLI2qvZnmCF5oD2jCw-FFql9dYg36FE5CpbMlw4/preview) for more details. 7 | 8 | The serving system implements the following constraints: 9 | 10 | - Requesting a module initiates exactly 1 HTTP request 11 | - This single requests contains the requested module and all its dependencies. 12 | - Incremental loading (every module request after the first one) of additional modules only downloads dependencies that have not been requested already. 13 | - The client does not need to download a dependency tree to decide which additional dependencies to download. 14 | 15 | For many web applications serving all JavaScript in a single compiled binary may be a good enough, simple solution, more complex apps with large JS code bases will profit from only downloading code when it is needed. While AMD loaders such as [require.js](http://requirejs.org/) implement incremental loading as well, they often do so through recursive downloading of dependencies which may significantly degrade latency. 16 | 17 | Closure compiler supports both compilation of CommonJS and AMD modules. It should thus be possible to use this system as a production frontend for projects that use other systems such as require.js or browserify today. 18 | 19 | ## Source Maps 20 | 21 | By default all JS responses support [source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/) for optimal debugging with Chrome Dev Tools (Don't forget to activate source map support in the Dev Tools settings). We recommend to deactivate this for production use, if you only want to provide clients access to obfuscated JS 22 | 23 | ## Setup 24 | 25 | See [demo-server.js](demo-server.js) for an example server. You may want to adapt this to your individual serving stack (such as as for use within express). We recommend doing actual serving through a caching reverse proxy CDN network for minimal latency. 26 | 27 | ### Demo 28 | 29 | Run `node demo-server.js` then drag [clients/test/demo.html](clients/test/demo.html) to a browser window. 30 | 31 | ## Client 32 | 33 | [clients/module-client.js](clients/module-client.js) provides the in-browser module loader. It depends on $LAB.js but should be easily adaptable to most JS loaders. 34 | 35 | This will get you started: 36 | 37 | 38 | 39 | 40 | 43 | 44 | Whenever you want to do an incremental load of a module, replace `require('foo')` with `loadModule('foo', function(foo) { … })` and you are all set. 45 | 46 | ## Compiler 47 | 48 | [module-compiler/bin.js](module-compiler/bin.js) is a wrapper around closure compiler for compiling JS for serving with Module Server. Run with --help for usage. It supports watching a directory tree for automatic compilation when you change your sources and it ships with closure compiler for easy installation. 49 | 50 | Make sure you have the java binary in your path :) 51 | 52 | Example: 53 | 54 | node module-compiler/bin.js --module_path=./test/fixtures/sample-module --entry_module=app --output_path=../build/ 55 | 56 | See the [INSTALL](module-compiler/INSTALL.md) instructions. 57 | 58 | ### Compilation 59 | 60 | Create a file called `app.js` (or whatever you like) and require all of your top-level modules in it (the ones you actually want to request from your application). This will ensure that everything gets compiled in one go. 61 | 62 | ## Fine print 63 | 64 | Pull requests are very much appreciated. Please sign the [Google Code contributor license agreement](http://code.google.com/legal/individual-cla-v1.0.html) (There is a convenient online form) before submitting. 65 | 66 |
67 |
Author
Malte Ubl (Google Inc.)
68 |
Copyright
Copyright © 2012 Google, Inc.
69 |
License
Apache 2.0
70 |
71 | -------------------------------------------------------------------------------- /bin.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | var exec = require('child_process').exec; 3 | var fs = require('fs'); 4 | 5 | fs.exists(__dirname + '/clients/third-party/LABjs/LAB.js', function(exists) { 6 | runServer = function() { 7 | require(__dirname + '/demo-server'); 8 | }; 9 | 10 | if (exists) { 11 | runServer(); 12 | return; 13 | } 14 | 15 | // JIC we haven't run the npm setup script 16 | var child = exec('cd ' + __dirname + ' && git submodule update', 17 | function (error, stdout, stderr) { 18 | console.log('stdout: ' + stdout); 19 | console.log('stderr: ' + stderr); 20 | if (error !== null) { 21 | console.log('exec error: ' + error); 22 | } 23 | } 24 | ); 25 | 26 | child.on('close', runServer); 27 | }); 28 | 29 | 30 | -------------------------------------------------------------------------------- /clients/module-client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Google Inc. All Rights Reserved. 3 | * 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 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 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. 15 | */ 16 | 17 | /** 18 | * Creates a Module loader. 19 | * USAGE: 20 | * window.loadModule = ModuleServer('http://url./of/your/module/server/'); 21 | * loadModule('your/module', function(yourModule) { … }); 22 | * @param {string} urlPrefix URL prefix of your module server. 23 | * @param {function(string,Function)=} load OPTIONAL function to load JS 24 | * from a given URL, that fires a callback when the JS loaded. If 25 | * you do not provide this function, you need to include $LAB.js in the 26 | * current page. If you want to implement your own loader, make sure it 27 | * supports executing JS in load order (ideally without blocking). 28 | * @param {Function=} getUrl OPTIONAL function to create a URL given the 29 | * urlPrefix, the current module name and a list of modules that have 30 | * already been requested. You will need to provide this if your server 31 | * does not follow the conventions of demo-server.js. 32 | * @return {function(string, function(*)=)} Returns a function to load modules 33 | * The first param is the name of the module and the second param is a 34 | * callback that fires when the module loaded. It received the exports 35 | * object of the module as its first param. 36 | */ 37 | function ModuleServer(urlPrefix, load, getUrl) { 38 | if (!urlPrefix) { 39 | urlPrefix = './'; 40 | } 41 | 42 | if (!load) { 43 | // Provide a default load function. This function assumes that $LAB.js is 44 | // present in the current page. 45 | (function() { 46 | var lab = window.$LAB; 47 | load = function(url, cb) { 48 | lab.script(url).wait(cb); 49 | }; 50 | })() 51 | } 52 | 53 | if (!getUrl) { 54 | getUrl = function(urlPrefix, module, requested) { 55 | return urlPrefix.replace(/\/$/, '') + '/' + encodeURIComponent(module) + 56 | (requested.length > 0 ? '/' + encodeURIComponent( 57 | requested.sort().join(',')) : ''); 58 | }; 59 | } 60 | 61 | var Server = function(urlPrefix) { 62 | this.urlPrefix = urlPrefix; 63 | this.requested = {}; 64 | this.requestedList = []; 65 | this.loaded = {}; 66 | }; 67 | 68 | Server.prototype.load = function(module, cb) { 69 | var self = this; 70 | module = 'module$' + module.replace(/\//g, '$'); 71 | if (this.loaded[module] || ModuleServer.m[module]) { 72 | if (cb) { 73 | cb(ModuleServer.m[module]); 74 | } 75 | return; 76 | } 77 | var userCb = cb; 78 | cb = function() { 79 | if (userCb) { 80 | userCb(ModuleServer.m[module]); 81 | } 82 | }; 83 | if (this.requested[module]) { 84 | this.requested[module].push(cb); 85 | return; 86 | } 87 | var before = this.requestedList.slice(); 88 | this.requestedList.push(module); 89 | var cbs = this.requested[module] = [cb]; 90 | load(getUrl(this.urlPrefix, module, before), function() { 91 | self.loaded[module] = true; 92 | self.requested[module] = null; 93 | for (var i = 0; i < cbs.length; i++) { 94 | cbs[i](); 95 | } 96 | }); 97 | }; 98 | 99 | var instance = new Server(urlPrefix); 100 | function loadModule(module, cb) { 101 | instance.load(module, cb); 102 | }; 103 | return loadModule; 104 | } 105 | 106 | // Registry for loaded modules. 107 | ModuleServer.m = {}; 108 | 109 | if (typeof exports != 'undefined') { 110 | exports.ModuleServer = ModuleServer; 111 | } 112 | -------------------------------------------------------------------------------- /clients/test/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

Module Server Demo

5 |

Make sure to start node demo-server.js and then just open this 6 | file in your web browser

7 |

 8 | 
 9 | 
10 | 
11 | 
12 | 
13 | 
14 | 
41 | 
42 | 
43 | 


--------------------------------------------------------------------------------
/demo-server.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | var http = require('http');
 18 | var fs = require('fs');
 19 | 
 20 | var SOURCE_DIR = __dirname + '/test/fixtures/sample-module';
 21 | var SOURCEMAP_PREFIX = '/_sourcemap';
 22 | var SOURCEMAP_PATH_PREFIX_REGEX = /^\/_sourcemap\//;
 23 | var ORIGINAL_SOURCE_PATH_PREFIX = 'http://127.0.0.1:1337/_js';
 24 | var ORIGINAL_SOURCE_PATH_PREFIX_REGEX = /^\/_js\//;
 25 | 
 26 | require('./module-server').from(SOURCE_DIR + '/../build',
 27 |     SOURCE_DIR + '/module-graph.json', run);
 28 | 
 29 | function run(err, moduleServer) {
 30 |   if (err) {
 31 |     throw err;
 32 |   }
 33 |   function jsForPath(path, isSourceMapRequest, onJs) {
 34 |     path = path.replace(/^\//, '');
 35 |     var parts = path.split(/\//);
 36 |     var modules = decodeURIComponent(parts.shift()).split(/,/);
 37 |     var options = {};
 38 |     parts.forEach(function(part) {
 39 |       var pair = part.split(/=/);
 40 |       options[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
 41 |     });
 42 |     var exclude = null;
 43 |     if(options.exm) {
 44 |       exclude = options.exm.split(/,/);
 45 |     }
 46 |     return moduleServer(modules, exclude, onJs, {
 47 |       createSourceMap: isSourceMapRequest,
 48 |       sourceMapSourceRootUrlPrefix: ORIGINAL_SOURCE_PATH_PREFIX,
 49 |       debug: true,
 50 |       onLog: function() {
 51 |         console.log(arguments);
 52 |       }
 53 |     });
 54 |   }
 55 | 
 56 |   http.createServer(function (req, res) {
 57 |     var url = require('url').parse(req.url);
 58 |     // Load static files for demo
 59 |     switch(url.pathname) {
 60 |       case "/demo.html":
 61 |         fs.readFile(__dirname + '/clients/test/demo.html', 'utf8', function (err, html) {
 62 |           if(err) {
 63 |             throw err;
 64 |           } else {
 65 |             res.writeHead(200, {
 66 |               'Content-Type': 'text/html',
 67 |               'Content-Length': html.length
 68 |             });
 69 |             res.end(html, 'utf8');
 70 |           }
 71 |         });
 72 |         return;
 73 |       case "/third-party/LABjs/LAB.src.js":
 74 |         fs.readFile(__dirname + '/clients/third-party/LABjs/LAB.src.js', 'utf8', function (err, js) {
 75 |           if(err) {
 76 |             throw err;
 77 |           } else {
 78 |             res.writeHead(200, {
 79 |               'Content-Type': 'application/javascript',
 80 |             });
 81 |             res.end(js, 'utf8');
 82 |           }
 83 |         });
 84 |         return; 
 85 |       case "/module-client.js":
 86 |         fs.readFile(__dirname + '/clients/module-client.js', 'utf8', function (err, js) {
 87 |           if(err) {
 88 |             throw err;
 89 |           } else {
 90 |             res.writeHead(200, {
 91 |               'Content-Type': 'application/javascript',
 92 |             });
 93 |             res.end(js, 'utf8');
 94 |           }
 95 |         });
 96 |         return;
 97 |     }
 98 |     console.log('Path ' + url.pathname);
 99 |     if (ORIGINAL_SOURCE_PATH_PREFIX_REGEX.test(url.pathname)) {
100 |       var filename = SOURCE_DIR + '/' + url.pathname
101 |           .replace(ORIGINAL_SOURCE_PATH_PREFIX_REGEX, '');
102 |       fs.readFile(filename, 'utf8', function(err, js) {
103 |         if (err) {
104 |           throw err;
105 |         } else {
106 |           res.writeHead(200, {
107 |             'Content-Type': 'application/javascript',
108 |             'Content-Length': js.length,
109 |             'Pragma': 'no-cache'
110 |           });
111 |           res.end(js, 'utf8');
112 |         }
113 |       });
114 |       return;
115 |     }
116 |     var isSourceMapRequest = false;
117 |     if (SOURCEMAP_PATH_PREFIX_REGEX.test(url.pathname)) {
118 |       isSourceMapRequest = true;
119 |       url.pathname = url.pathname.replace(SOURCEMAP_PATH_PREFIX_REGEX, '/');
120 |     }
121 |     jsForPath(url.pathname, isSourceMapRequest, function(err, length, js,
122 |         sourceMap) {
123 |       if (err) {
124 |         console.log('Error', err);
125 |         if (err.statusCode) {
126 |           res.writeHead(err.statusCode, {'Content-Type': 'text/plain'});
127 |           res.end(err.message)
128 |         } else {
129 |           res.writeHead(500, {'Content-Type': 'text/plain'});
130 |           res.end('Internal server error');
131 |         }
132 |       } else {
133 |         if (isSourceMapRequest) {
134 |           var map = JSON.stringify(sourceMap, null, ' ');
135 |           res.writeHead(200, {
136 |             'Content-Type': 'application/json',
137 |             'Content-Length': map.length,
138 |             'Pragma': 'no-cache'
139 |           });
140 |           res.end(map, 'utf8');
141 |         } else {
142 |           var mapUrl = SOURCEMAP_PREFIX + url.pathname;
143 |           res.writeHead(200, {
144 |             'Content-Type': 'application/javascript',
145 |             'Content-Length': length,
146 |             'SourceMap': mapUrl,
147 |             'X-SourceMap': mapUrl
148 |           });
149 |           res.end(js, 'utf8');
150 |         }
151 |       }
152 |     });
153 |   }).listen(1337, '127.0.0.1');
154 |   console.log('Module server running at http://127.0.0.1:1337/');
155 | }
156 | 


--------------------------------------------------------------------------------
/module-compiler/INSTALL.md:
--------------------------------------------------------------------------------
1 | Run `npm install` in this directory.


--------------------------------------------------------------------------------
/module-compiler/bin.js:
--------------------------------------------------------------------------------
 1 | /**
 2 |  * Copyright 2012 Google Inc. All Rights Reserved.
 3 |  *
 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
 7 |  *
 8 |  *      http://www.apache.org/licenses/LICENSE-2.0
 9 |  *
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.
15 |  */
16 | 
17 | var opt = require('opt').create();
18 | var compiler = require('./module-compiler.js')
19 | 
20 | var config = opt.configSync({
21 | 	process_common_js_modules: true,
22 | 	source_map_format: 'V3',
23 |   // Triggers generation of one output file per CJS module.
24 |   module: 'auto',
25 | 	create_source_map: '%outname%.map',
26 |   externs: []
27 | }, []);
28 | 
29 | function usage() {
30 |   console.log('Example: node module-compiler/bin.js  --module_path=' +
31 |       './test/fixtures/sample-module --entry_module=app --output_path=../build/');
32 |   opt.usage();
33 |   process.exit(0);
34 | }
35 | 
36 | var path;
37 | var watch = true;
38 | 
39 | opt.option(['-h', '--help'], usage, 'This help screen.');
40 | 
41 | opt.option(['-p', '--module_path'], function (p) {
42 |   console.log(p);
43 |   path = p.trim();
44 | }, 'The search path for modules.');
45 | 
46 | opt.option(['-e', '--entry_module'], function (entryModule) {
47 |   var filename = entryModule.trim();
48 |   if (filename && !/\.js$/) {
49 |     filename = filename + '.js';
50 |   }
51 | 
52 |   config.common_js_entry_module = filename;
53 | }, 'The file name of the main module from which all dependencies are derived.');
54 | 
55 | opt.option(['-o', '--output_path'], function (path) {
56 |   config.module_output_path_prefix = (path.trim() || '').replace(/\/$/, '') + '/';
57 |   config.output_module_dependencies = './module-graph.json';
58 | }, 'The path to the output directory for compiled modules.');
59 | 
60 | opt.option(['--no-watch'], function () {
61 |   watch = false;
62 | }, 'Do not keep this program alive and watch for changes in input modules.');
63 | 
64 | opt.option(['--externs'], function (extern) {
65 |   externs.push(extern);
66 | }, 'Path to an extern file for closure compiler.');
67 | 
68 | opt.optionWith(process.argv);
69 | if (!path || path.length < 1 || !config.common_js_entry_module ||
70 |     !config.module_output_path_prefix) {
71 |   usage();
72 | }
73 | 
74 | compiler.compile(path, config);
75 | if (watch) {
76 |   compiler.watch(path, config);
77 | }
78 | 
79 | // TODO get rid of the chdir dependency
80 | 


--------------------------------------------------------------------------------
/module-compiler/externs.js:
--------------------------------------------------------------------------------
 1 | /**
 2 |  * Copyright 2012 Google Inc. All Rights Reserved.
 3 |  *
 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
 7 |  *
 8 |  *      http://www.apache.org/licenses/LICENSE-2.0
 9 |  *
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.
15 |  */
16 | 
17 | var window;
18 | // Just making sure, closure compiler by default likes to stomp on jQuery
19 | // which we can lead to bad developer experience.
20 | var $;
21 | var $LAB; // Part of the standard client.
22 | 
23 | /**
24 |  * Default recommended name for the function to load modules with ModuleServer.
25 |  * Loads a module and then calls the callback once the loaded code is
26 |  * available.
27 |  * @param {string} name Name of the module to load. e.g. 'my/app'
28 |  * @param {function(*)} cb Callback to be called when the module loaded.
29 |  *   The callback retrieves the exports object of the loaded module as the 1st
30 |  *   argument.
31 |  */
32 | window.loadModule = function(name, cb) {};
33 | 
34 | // Name of the default client
35 | var ModuleServer;


--------------------------------------------------------------------------------
/module-compiler/module-compiler.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | var exec = require('child_process').exec;
 18 | 
 19 | function compile(userArgs, cb) {
 20 |   var buildDir = userArgs.module_output_path_prefix
 21 |   var jsFiles = require('findit').sync('.').filter(function(filename) {
 22 |     return /\.js$/.test(filename) && !/^module\$/.test(filename);
 23 |   });
 24 |   var args = [
 25 |     '-jar', __dirname + '/third-party/closure-compiler/compiler.jar',
 26 |     // Adds default externs.
 27 |     '--externs', __dirname + '/externs.js',
 28 |   ];
 29 |   for (var key in userArgs) {
 30 |     // If the value is an array the key is appended one time per element in the
 31 |     // array.
 32 |     var vals = userArgs[key];
 33 |     if (!(vals instanceof Array)) {
 34 |       vals = [vals];
 35 |     }
 36 |     vals.forEach(function(val) {
 37 |       args.push('--' + key);
 38 |       // Closure compiler does not file --foo true.
 39 |       if (val !== true) {
 40 |         args.push(val);
 41 |       }
 42 |     })
 43 |   }
 44 |   jsFiles.forEach(function(filename) {
 45 |     args.push('--js', filename);
 46 |   });
 47 |   console.log('Compiling ' + jsFiles.join(', ') + '\n…');
 48 |   run(args);
 49 | 
 50 |   function run(args) {
 51 |     console.log('Running closure compiler: ' + JSON.stringify(args) + '\n…');
 52 |     var compiler = require('child_process').spawn('java', args, {
 53 |       stdio: 'inherit'
 54 |     });
 55 | 
 56 |     compiler.on('exit', function (code) {
 57 |       if (code === 0) {
 58 |         console.log('Compilation successful.');
 59 |         if (cb) {
 60 |           cb(null);
 61 |         }
 62 |       } else {
 63 |         console.log('Compilation failed.');
 64 |         if (cb) {
 65 |           cb(true);
 66 |         }
 67 |       }
 68 |     });
 69 |   }
 70 | }
 71 | 
 72 | var idle = true;
 73 | var count = 0;
 74 | function compileIfIdle(path, args) {
 75 |   if (count++ == 0) {
 76 |     // TODO remove this chdir.
 77 |     process.chdir(path);
 78 |   }
 79 |   if (idle) {
 80 |     idle = false;
 81 |     compile(args, function() {
 82 |       idle = true;
 83 |     });
 84 |   }
 85 | }
 86 | 
 87 | exports.compile = compileIfIdle;
 88 | exports.watch = function(path, args) {
 89 |   function onChange(type, o) {
 90 |     if (o.path !== 'module-graph.json') { // TODO get rid of this.
 91 |       console.log(type + ': ' + o.path + (o.dir === true ? ' [DIR]' : ''))
 92 |       compileIfIdle(path, args);
 93 |     }
 94 |   }
 95 |   var Watcher = require('fs-watcher').watch;
 96 | 
 97 |   var watcher = new Watcher({
 98 |     root: '.'
 99 |   });
100 | 
101 |   watcher.on('create', onChange.bind(null, 'create'));
102 |   watcher.on('change', onChange.bind(null, 'change'));
103 |   watcher.on('delete', onChange.bind(null, 'delete'));
104 |   watcher.on('error', function() {
105 |     console.log('Error watching');
106 |   });
107 | 
108 |   watcher.start();
109 | }
110 | 
111 | 
112 | 


--------------------------------------------------------------------------------
/module-compiler/package.json:
--------------------------------------------------------------------------------
 1 | {
 2 |     "name":"module-compiler",
 3 |     "version":"0.0.1",
 4 |     "description":"Compiles JavaScript for module-server",
 5 |     "keywords":["modules"],
 6 |     "author":"Google Inc.",
 7 |     "repository":{
 8 |         "url":"https://github.com/google/module-server.git",
 9 |         "type":"git"
10 |     },
11 |     "dependencies":{
12 |         "fs-watcher": "0.2.1",
13 |         "findit": "0.1.2",
14 |         "opt": "0.0.9"
15 |     },
16 |     "bin": {
17 |         "module-compiler": "./bin.js"
18 |     },
19 |     "bugs":{
20 |         "url":"https://github.com/google/module-server/issues"
21 |     },
22 |     "main":"index",
23 |     "engines":{
24 |         "node":">= 0.8.0"
25 |     }
26 | }


--------------------------------------------------------------------------------
/module-compiler/third-party/closure-compiler/COPYING:
--------------------------------------------------------------------------------
  1 | 
  2 |                                  Apache License
  3 |                            Version 2.0, January 2004
  4 |                         http://www.apache.org/licenses/
  5 | 
  6 |    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
  7 | 
  8 |    1. Definitions.
  9 | 
 10 |       "License" shall mean the terms and conditions for use, reproduction,
 11 |       and distribution as defined by Sections 1 through 9 of this document.
 12 | 
 13 |       "Licensor" shall mean the copyright owner or entity authorized by
 14 |       the copyright owner that is granting the License.
 15 | 
 16 |       "Legal Entity" shall mean the union of the acting entity and all
 17 |       other entities that control, are controlled by, or are under common
 18 |       control with that entity. For the purposes of this definition,
 19 |       "control" means (i) the power, direct or indirect, to cause the
 20 |       direction or management of such entity, whether by contract or
 21 |       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 22 |       outstanding shares, or (iii) beneficial ownership of such entity.
 23 | 
 24 |       "You" (or "Your") shall mean an individual or Legal Entity
 25 |       exercising permissions granted by this License.
 26 | 
 27 |       "Source" form shall mean the preferred form for making modifications,
 28 |       including but not limited to software source code, documentation
 29 |       source, and configuration files.
 30 | 
 31 |       "Object" form shall mean any form resulting from mechanical
 32 |       transformation or translation of a Source form, including but
 33 |       not limited to compiled object code, generated documentation,
 34 |       and conversions to other media types.
 35 | 
 36 |       "Work" shall mean the work of authorship, whether in Source or
 37 |       Object form, made available under the License, as indicated by a
 38 |       copyright notice that is included in or attached to the work
 39 |       (an example is provided in the Appendix below).
 40 | 
 41 |       "Derivative Works" shall mean any work, whether in Source or Object
 42 |       form, that is based on (or derived from) the Work and for which the
 43 |       editorial revisions, annotations, elaborations, or other modifications
 44 |       represent, as a whole, an original work of authorship. For the purposes
 45 |       of this License, Derivative Works shall not include works that remain
 46 |       separable from, or merely link (or bind by name) to the interfaces of,
 47 |       the Work and Derivative Works thereof.
 48 | 
 49 |       "Contribution" shall mean any work of authorship, including
 50 |       the original version of the Work and any modifications or additions
 51 |       to that Work or Derivative Works thereof, that is intentionally
 52 |       submitted to Licensor for inclusion in the Work by the copyright owner
 53 |       or by an individual or Legal Entity authorized to submit on behalf of
 54 |       the copyright owner. For the purposes of this definition, "submitted"
 55 |       means any form of electronic, verbal, or written communication sent
 56 |       to the Licensor or its representatives, including but not limited to
 57 |       communication on electronic mailing lists, source code control systems,
 58 |       and issue tracking systems that are managed by, or on behalf of, the
 59 |       Licensor for the purpose of discussing and improving the Work, but
 60 |       excluding communication that is conspicuously marked or otherwise
 61 |       designated in writing by the copyright owner as "Not a Contribution."
 62 | 
 63 |       "Contributor" shall mean Licensor and any individual or Legal Entity
 64 |       on behalf of whom a Contribution has been received by Licensor and
 65 |       subsequently incorporated within the Work.
 66 | 
 67 |    2. Grant of Copyright License. Subject to the terms and conditions of
 68 |       this License, each Contributor hereby grants to You a perpetual,
 69 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 70 |       copyright license to reproduce, prepare Derivative Works of,
 71 |       publicly display, publicly perform, sublicense, and distribute the
 72 |       Work and such Derivative Works in Source or Object form.
 73 | 
 74 |    3. Grant of Patent License. Subject to the terms and conditions of
 75 |       this License, each Contributor hereby grants to You a perpetual,
 76 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 77 |       (except as stated in this section) patent license to make, have made,
 78 |       use, offer to sell, sell, import, and otherwise transfer the Work,
 79 |       where such license applies only to those patent claims licensable
 80 |       by such Contributor that are necessarily infringed by their
 81 |       Contribution(s) alone or by combination of their Contribution(s)
 82 |       with the Work to which such Contribution(s) was submitted. If You
 83 |       institute patent litigation against any entity (including a
 84 |       cross-claim or counterclaim in a lawsuit) alleging that the Work
 85 |       or a Contribution incorporated within the Work constitutes direct
 86 |       or contributory patent infringement, then any patent licenses
 87 |       granted to You under this License for that Work shall terminate
 88 |       as of the date such litigation is filed.
 89 | 
 90 |    4. Redistribution. You may reproduce and distribute copies of the
 91 |       Work or Derivative Works thereof in any medium, with or without
 92 |       modifications, and in Source or Object form, provided that You
 93 |       meet the following conditions:
 94 | 
 95 |       (a) You must give any other recipients of the Work or
 96 |           Derivative Works a copy of this License; and
 97 | 
 98 |       (b) You must cause any modified files to carry prominent notices
 99 |           stating that You changed the files; and
100 | 
101 |       (c) You must retain, in the Source form of any Derivative Works
102 |           that You distribute, all copyright, patent, trademark, and
103 |           attribution notices from the Source form of the Work,
104 |           excluding those notices that do not pertain to any part of
105 |           the Derivative Works; and
106 | 
107 |       (d) If the Work includes a "NOTICE" text file as part of its
108 |           distribution, then any Derivative Works that You distribute must
109 |           include a readable copy of the attribution notices contained
110 |           within such NOTICE file, excluding those notices that do not
111 |           pertain to any part of the Derivative Works, in at least one
112 |           of the following places: within a NOTICE text file distributed
113 |           as part of the Derivative Works; within the Source form or
114 |           documentation, if provided along with the Derivative Works; or,
115 |           within a display generated by the Derivative Works, if and
116 |           wherever such third-party notices normally appear. The contents
117 |           of the NOTICE file are for informational purposes only and
118 |           do not modify the License. You may add Your own attribution
119 |           notices within Derivative Works that You distribute, alongside
120 |           or as an addendum to the NOTICE text from the Work, provided
121 |           that such additional attribution notices cannot be construed
122 |           as modifying the License.
123 | 
124 |       You may add Your own copyright statement to Your modifications and
125 |       may provide additional or different license terms and conditions
126 |       for use, reproduction, or distribution of Your modifications, or
127 |       for any such Derivative Works as a whole, provided Your use,
128 |       reproduction, and distribution of the Work otherwise complies with
129 |       the conditions stated in this License.
130 | 
131 |    5. Submission of Contributions. Unless You explicitly state otherwise,
132 |       any Contribution intentionally submitted for inclusion in the Work
133 |       by You to the Licensor shall be under the terms and conditions of
134 |       this License, without any additional terms or conditions.
135 |       Notwithstanding the above, nothing herein shall supersede or modify
136 |       the terms of any separate license agreement you may have executed
137 |       with Licensor regarding such Contributions.
138 | 
139 |    6. Trademarks. This License does not grant permission to use the trade
140 |       names, trademarks, service marks, or product names of the Licensor,
141 |       except as required for reasonable and customary use in describing the
142 |       origin of the Work and reproducing the content of the NOTICE file.
143 | 
144 |    7. Disclaimer of Warranty. Unless required by applicable law or
145 |       agreed to in writing, Licensor provides the Work (and each
146 |       Contributor provides its Contributions) on an "AS IS" BASIS,
147 |       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 |       implied, including, without limitation, any warranties or conditions
149 |       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 |       PARTICULAR PURPOSE. You are solely responsible for determining the
151 |       appropriateness of using or redistributing the Work and assume any
152 |       risks associated with Your exercise of permissions under this License.
153 | 
154 |    8. Limitation of Liability. In no event and under no legal theory,
155 |       whether in tort (including negligence), contract, or otherwise,
156 |       unless required by applicable law (such as deliberate and grossly
157 |       negligent acts) or agreed to in writing, shall any Contributor be
158 |       liable to You for damages, including any direct, indirect, special,
159 |       incidental, or consequential damages of any character arising as a
160 |       result of this License or out of the use or inability to use the
161 |       Work (including but not limited to damages for loss of goodwill,
162 |       work stoppage, computer failure or malfunction, or any and all
163 |       other commercial damages or losses), even if such Contributor
164 |       has been advised of the possibility of such damages.
165 | 
166 |    9. Accepting Warranty or Additional Liability. While redistributing
167 |       the Work or Derivative Works thereof, You may choose to offer,
168 |       and charge a fee for, acceptance of support, warranty, indemnity,
169 |       or other liability obligations and/or rights consistent with this
170 |       License. However, in accepting such obligations, You may act only
171 |       on Your own behalf and on Your sole responsibility, not on behalf
172 |       of any other Contributor, and only if You agree to indemnify,
173 |       defend, and hold each Contributor harmless for any liability
174 |       incurred by, or claims asserted against, such Contributor by reason
175 |       of your accepting any such warranty or additional liability.
176 | 
177 |    END OF TERMS AND CONDITIONS
178 | 
179 |    APPENDIX: How to apply the Apache License to your work.
180 | 
181 |       To apply the Apache License to your work, attach the following
182 |       boilerplate notice, with the fields enclosed by brackets "[]"
183 |       replaced with your own identifying information. (Don't include
184 |       the brackets!)  The text should be enclosed in the appropriate
185 |       comment syntax for the file format. We also recommend that a
186 |       file or class name and description of purpose be included on the
187 |       same "printed page" as the copyright notice for easier
188 |       identification within third-party archives.
189 | 
190 |    Copyright [2012] Google Inc.
191 | 
192 |    Licensed under the Apache License, Version 2.0 (the "License");
193 |    you may not use this file except in compliance with the License.
194 |    You may obtain a copy of the License at
195 | 
196 |        http://www.apache.org/licenses/LICENSE-2.0
197 | 
198 |    Unless required by applicable law or agreed to in writing, software
199 |    distributed under the License is distributed on an "AS IS" BASIS,
200 |    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 |    See the License for the specific language governing permissions and
202 |    limitations under the License.
203 | 


--------------------------------------------------------------------------------
/module-compiler/third-party/closure-compiler/compiler.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/module-server/68c42d7a8621bee645d2e01e8a57d9ef7e7e6d5c/module-compiler/third-party/closure-compiler/compiler.jar


--------------------------------------------------------------------------------
/module-graph.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | 
 18 | /**
 19 |  * Module for module graphs and dependency calculation.
 20 |  */
 21 | 
 22 | var fs = require('fs');
 23 | 
 24 | /**
 25 |  * Make a ModuleGraph from an object as it is output by closure compiler
 26 |  * when passed the TODO compiler flag.
 27 |  * @param {Array.} modules Array of module definitions.
 28 |  * @return {ModuleGraph}
 29 |  */
 30 | exports.fromSerialization = function(modules) {
 31 |   return new ModuleGraph(modules);
 32 | };
 33 | 
 34 | // TODO: Should this exist. Nice for convenience, but there should almost
 35 | // certainly not be more data access methods in this module.
 36 | /**
 37 |  * Make a ModuleGraph from a file as it is output by closure compiler
 38 |  * when passed the TODO compiler flag.
 39 |  * @param {string} filename Filename of the module graph file.
 40 |  * @apram {function(Error, ModuleGraph)}
 41 |  * @return {ModuleGraph}
 42 |  */
 43 | exports.fromFilename = function(filename, cb) {
 44 |   fs.readFile(filename, 'utf8', function(err, str) {
 45 |     if (err) {
 46 |       return cb(err);
 47 |     }
 48 |     cb(null, new ModuleGraph(JSON.parse(str)));
 49 |   });
 50 | };
 51 | 
 52 | function Module(info) {
 53 |   this.name = info.name;
 54 |   this.inputs = info.inputs;
 55 |   this.transitiveDeps = info['transitive-dependencies'].reverse();
 56 | }
 57 | 
 58 | Module.prototype.toString = function() {
 59 |   return '';
 60 | };
 61 | 
 62 | /**
 63 |  * A module graph class.
 64 |  * @constructor
 65 |  */
 66 | function ModuleGraph(moduleData) {
 67 |   var self = this;
 68 |   var modules = {};
 69 |   var moduleNameList = [];
 70 |   moduleData.forEach(function(info) {
 71 |     var m = new Module(info);
 72 |     modules[info.name] = m;
 73 |     moduleNameList.push(info.name);
 74 |   });
 75 | 
 76 |   /**
 77 |    * Get a list of all module names.
 78 |    * @return {Array.} List of module names.
 79 |    */
 80 |   this.getAllModules = function() {
 81 |     return moduleNameList;
 82 |   };
 83 | 
 84 |   /**
 85 |    * Get transitive dependencies for a given module
 86 |    * @param {string} name Name of the module.
 87 |    * @return {Array.} List of module names.
 88 |    */
 89 |   this.getTransitiveDependencies = function(name) {
 90 |     var m = getModule(name);
 91 |     return m.transitiveDeps || [];
 92 |   };
 93 | 
 94 |   function getModule(name) {
 95 |     var m = modules[name];
 96 |     if (!m) {
 97 |       throw new self.NotFoundException(name);
 98 |     }
 99 |     return m;
100 |   }
101 | 
102 |   /**
103 |    * Error object used when a requested module cannot be found.
104 |    * @constructor
105 |    */
106 |   this.NotFoundException = function(name) {
107 |     var msg = 'Unknown module: ' + name;
108 |     this.name = name;
109 |     this.message = msg;
110 |     Error.call(this, msg);
111 |   };
112 |   this.NotFoundException.prototype = new Error();
113 |   this.NotFoundException.prototype.statusCode = 404;
114 | 
115 |   /**
116 |    * Gets the requested module names and their transitive deps minus the
117 |    * transitive deps (and the) of the optional excluded names.
118 |    * @param {Array.} moduleNames List of module names.
119 |    * @apram {Array.} opt_excludeNames List of module names to exclude.
120 |    * @return {Array.} List of module names.
121 |    */
122 |   this.getModules = function(moduleNames, opt_excludeNames) {
123 |     var list = [];
124 |     var seen = {};
125 |     var exclude = {};
126 | 
127 |     if (opt_excludeNames) {
128 |       opt_excludeNames.forEach(function(name) {
129 |         exclude[name] = true;
130 |         var m = getModule(name);
131 |         m.transitiveDeps.forEach(function(name) {
132 |           exclude[name] = true;
133 |         });
134 |       });
135 |     }
136 | 
137 |     function addModule(name) {
138 |       if (!seen[name] && !exclude[name]) {
139 |         seen[name] = true;
140 |         list.push(name)
141 |       }
142 |     }
143 |     moduleNames.forEach(function(name) {
144 |       var m = getModule(name);
145 |       m.transitiveDeps.forEach(addModule);
146 |       addModule(m.name);
147 |     });
148 |     return list;
149 |   };
150 | }


--------------------------------------------------------------------------------
/module-server.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | var path = require('path');
 18 | var fs = require('fs');
 19 | 
 20 | function JsModuleFile(pathPrefix, name, onSource, onSourceMap) {
 21 |   var self = this;
 22 |   self.filename = path.join(pathPrefix, name + '.js');
 23 |   self.js = null;
 24 |   self.map = null;
 25 |   fs.readFile(this.filename, 'utf8', function(err, data) {
 26 |     if (err) {
 27 |       return onSource(err);
 28 |     }
 29 |     self.js = data;
 30 |     onSource(null, self);
 31 |   });
 32 |   fs.readFile(this.filename + '.map', 'utf8', function(err, data) {
 33 |     if (err) {
 34 |       return onSourceMap(err);
 35 |     }
 36 |     self.map = data;
 37 |     onSourceMap(null, self);
 38 |   });
 39 | }
 40 | 
 41 | JsModuleFile.prototype.getNumberOfLines = function() {
 42 |   return this.js.split(/\n/).length;
 43 | };
 44 | 
 45 | JsModuleFile.prototype.getMap = function() {
 46 |   // Return a fresh copy every time.
 47 |   return JSON.parse(this.map);
 48 | };
 49 | 
 50 | function makeServer(graph, modules) {
 51 |   return function(moduleNames, excludeNames, onJs, options) {
 52 |     options = options || {};
 53 |     var debug = options.debug;
 54 |     var log = options.onLog || function() {};
 55 |     var createSourceMap = !!options.createSourceMap;
 56 |     log('Module request', moduleNames, excludeNames);
 57 |     try {
 58 |       var names = graph.getModules(moduleNames, excludeNames);
 59 |     } catch(e) {
 60 |       return onJs(e)
 61 |     }
 62 |     log('Serving modules', names);
 63 |     var js = '';
 64 |     var lineNumber = 1;
 65 |     var sourceMapSections = createSourceMap ? [] : null;
 66 |     for (var i = 0; i < names.length; i++) {
 67 |       var name = names[i];
 68 |       if (debug) {
 69 |         js += '/* Module: ' + name + ' */\n';
 70 |         lineNumber++;
 71 |       }
 72 |       var file = modules[name];
 73 |       js += file.js + '\n';
 74 |       js += 'ModuleServer.m.' + name + '=' + name + ';\n';
 75 |       if (createSourceMap) {
 76 |         var map = file.getMap();
 77 |         map.sourceRoot = options.sourceMapSourceRootUrlPrefix;
 78 |         sourceMapSections.push({
 79 |           offset: {
 80 |             line: lineNumber,
 81 |             column: 0, // That is why we always add an extra line.
 82 |           },
 83 |           map: map
 84 |         });
 85 |         lineNumber = lineNumber + file.getNumberOfLines()
 86 |           + 1  // The ModuleServer.m… line;
 87 |       }
 88 |     }
 89 |     var sourceMap = createSourceMap ? {
 90 |       version: 3,
 91 |       file: "just-the-container.js",
 92 |       sections: sourceMapSections
 93 |     } : null;
 94 |     onJs(null, js.length, js, sourceMap);
 95 |   }
 96 | };
 97 | 
 98 | /**
 99 |  * Make a module server that serves JS from memory and loads it from disk.
100 |  * @param {string} pathPrefix Directory where JS files can be found. JS files
101 |  *     are expected to be pathPrefix + name + '.js'
102 |  * @param {string} graphFilename Filename of a module graph serialization.
103 |  * @param {function(Error,function(Array.,Array.,
104 |  *     function(Error,number,string),Object))} initCompleteCb Callback to be
105 |  *     fired when the server is ready.
106 |  * @return {*}
107 |  */
108 | exports.from = function(pathPrefix, graphFilename, initCompleteCb) {
109 |   require('./module-graph').fromFilename(graphFilename, function(err, graph) {
110 |     if (err) {
111 |       return initCompleteCb(err);
112 |     }
113 |     var modules = {};
114 |     var allModules = graph.getAllModules();
115 |     allModules.forEach(function(name) {
116 |       modules[name] = new JsModuleFile(pathPrefix, name, onFile, onFile);
117 |     });
118 | 
119 |     var fn = makeServer(graph, modules);
120 |     fn.NotFoundException = graph.NotFoundException;
121 | 
122 |     var loaded = 0;
123 |     function onFile(err) {
124 |       if (err) {
125 |         return initCompleteCb(err);
126 |       }
127 |       if (++loaded == allModules.length * 2) {
128 |         initCompleteCb(null, fn);
129 |       }
130 |     }
131 |   });
132 | }


--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "name":"module-server",
 3 |   "version":"0.0.1-alpha",
 4 |   "license":{
 5 |     "type":"Apache 2.0",
 6 |     "url":"http://code.google.com/legal/individual-cla-v1.0.html"
 7 |   },
 8 |   "devDependencies":{
 9 |     "tag":"latest"
10 |   },
11 |   "author":{
12 |     "name":"Google Inc.",
13 |     "url":"https://github.com/google"
14 |   },
15 |   "bugs":"https://github.com/google/module-server/issues",
16 |   "bin":{
17 |     "module-server":"./bin.js"
18 |   },
19 |   "repository":{
20 |     "type":"git",
21 |     "url":"https://github.com/google/module-server.git"
22 |   },
23 |   "scripts":{
24 |     "preinstall":"git clone git://github.com/getify/LABjs clients/third-party/LABjs"
25 |   },
26 |   "main":"module-server.js"
27 | }
28 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$app.js:
--------------------------------------------------------------------------------
1 | var module$app={},module$$module$app=module$module,module$$module$app=module$sub_app;
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$app.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$app",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,WAAA,EAAA,CAAIC,mBAASC,aAAb,CACID,mBAASE;",
6 | "sources":["app.js"],
7 | "names":["module$app","module","module$module","module$sub_app"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$bar.js:
--------------------------------------------------------------------------------
1 | var module$module$bar={bar:function(){return"bar"}};
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$bar.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$module$bar",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,kBAAA,KAAcC,QAAQ,EAAG,CACvB,MAAO,KADgB,CAAzB;",
6 | "sources":["module/bar.js"],
7 | "names":["module$module$bar","module$module$bar.bar"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$baz$foo.js:
--------------------------------------------------------------------------------
1 | var module$module$baz$foo={foo:function(){return"test"},log:function(a){window.log(a)}};
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$baz$foo.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$module$baz$foo",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,sBAAA,KAAcC,QAAQ,EAAG,CACvB,MAAO,MADgB,CAAzB,KAIcC,QAAQ,CAACC,CAAD,CAAM,CAC1BC,MAAAC,IAAA,CAAWF,CAAX,CAD0B,CAJ5B;",
6 | "sources":["module/baz/foo.js"],
7 | "names":["module$module$baz$foo","module$module$baz$foo.foo","module$module$baz$foo.log","msg","window","log"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$foo.js:
--------------------------------------------------------------------------------
1 | var module$module$foo={},impl$$module$module$foo=module$module$baz$foo,bar$$module$module$foo=module$module$bar;
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module$foo.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$module$foo",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,kBAAA,EAAA,CAAIC,wBAAOC,qBAAX,CACIC,uBAAMC;",
6 | "sources":["module/foo.js"],
7 | "names":["module$module$foo","impl","module$module$baz$foo","bar","module$module$bar"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module.js:
--------------------------------------------------------------------------------
1 | var module$module={},module$$module$module=module$module$foo;module$module.test=function(){return module$$module$module};
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$module.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$module",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,cAAA,EAAA,CAAIC,sBAASC,iBAKbC,cAAAC,KAAA,CAAeC,QAAQ,EAAG,CACxB,MAAOJ,sBADiB;",
6 | "sources":["module.js"],
7 | "names":["module$module","module","module$module$foo","exports","test","module$module.test"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$sub_app.js:
--------------------------------------------------------------------------------
1 | var module$sub_app={subApp:function(){return"sub"},testLoad:function(){loadModule("module/baz/foo",function(a){a.log("Logged via foo")})}};
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/module$sub_app.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"module$sub_app",
4 | "lineCount":1,
5 | "mappings":"AAAA,IAAAA,eAAA,QAAiBC,QAAQ,EAAG,CAC1B,MAAO,KADmB,CAA5B,UAImBC,QAAQ,EAAG,CAC5BC,UAAA,CAAW,gBAAX,CAA6B,QAAQ,CAACC,CAAD,CAAM,CACzCA,CAAAC,IAAA,CAAQ,gBAAR,CADyC,CAA3C,CAD4B,CAJ9B;",
6 | "sources":["sub-app.js"],
7 | "names":["module$sub_app","module$sub_app.subApp","module$sub_app.testLoad","loadModule","foo","log"]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/build/root.js:
--------------------------------------------------------------------------------
1 | 
2 | 


--------------------------------------------------------------------------------
/test/fixtures/build/root.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"root",
4 | "lineCount":1,
5 | "mappings":";",
6 | "sources":[],
7 | "names":[]
8 | }
9 | 


--------------------------------------------------------------------------------
/test/fixtures/sample-module/app.js:
--------------------------------------------------------------------------------
1 | var module = require('module');
2 | var module = require('sub-app');
3 | 


--------------------------------------------------------------------------------
/test/fixtures/sample-module/module-graph.json:
--------------------------------------------------------------------------------
1 | [{"transitive-dependencies":[],"inputs":["[root]"],"dependencies":[],"name":"root"},{"transitive-dependencies":["root"],"inputs":["sub-app.js"],"dependencies":["root"],"name":"module$sub_app"},{"transitive-dependencies":["root"],"inputs":["module/bar.js"],"dependencies":["root"],"name":"module$module$bar"},{"transitive-dependencies":["root"],"inputs":["module/baz/foo.js"],"dependencies":["root"],"name":"module$module$baz$foo"},{"transitive-dependencies":["module$module$baz$foo","module$module$bar","root"],"inputs":["module/foo.js"],"dependencies":["module$module$bar","module$module$baz$foo","root"],"name":"module$module$foo"},{"transitive-dependencies":["module$module$foo","module$module$baz$foo","module$module$bar","root"],"inputs":["module.js"],"dependencies":["module$module$foo","root"],"name":"module$module"},{"transitive-dependencies":["module$module","module$module$foo","module$sub_app","module$module$baz$foo","module$module$bar","root"],"inputs":["app.js"],"dependencies":["module$sub_app","module$module","root"],"name":"module$app"}]


--------------------------------------------------------------------------------
/test/fixtures/sample-module/module.js:
--------------------------------------------------------------------------------
1 | var module = require('module/foo');
2 | 
3 | /*!
4 |  * This won't be optimized away */
5 | 
6 | exports.test = function() {
7 |   return module;
8 | };
9 | 


--------------------------------------------------------------------------------
/test/fixtures/sample-module/module/bar.js:
--------------------------------------------------------------------------------
1 | exports.bar = function() {
2 |   return 'bar';
3 | }


--------------------------------------------------------------------------------
/test/fixtures/sample-module/module/baz/foo.js:
--------------------------------------------------------------------------------
1 | exports.foo = function() {
2 |   return 'test';
3 | };
4 | 
5 | exports.log = function(msg) {
6 |   window.log(msg);
7 | };


--------------------------------------------------------------------------------
/test/fixtures/sample-module/module/foo.js:
--------------------------------------------------------------------------------
1 | var impl = require('module/baz/foo');
2 | var bar = require('module/bar');
3 | 


--------------------------------------------------------------------------------
/test/fixtures/sample-module/sub-app.js:
--------------------------------------------------------------------------------
1 | exports.subApp = function() {
2 |   return 'sub';
3 | };
4 | 
5 | exports.testLoad = function() {
6 |   loadModule('module/baz/foo', function(foo) {
7 |     foo.log('Logged via foo');
8 |   });
9 | };


--------------------------------------------------------------------------------
/test/test-module-client.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | var test = require('tap').test;
 18 | 
 19 | var URL_PREFIX = 'https://prefix';
 20 | 
 21 | var ModuleServer = require('../clients/module-client.js').ModuleServer;
 22 | 
 23 | test('loading-modules', function(t) {
 24 |   var loaded = [];
 25 |   var cbs = [];
 26 |   var modules = [];
 27 |   function cb(module) {
 28 |     modules.push(module);
 29 |   }
 30 |   function mockLoad(url, cb) {
 31 |     loaded.push(url);
 32 |     cbs.push(cb);
 33 |   }
 34 | 
 35 |   var loadModule = ModuleServer(URL_PREFIX, mockLoad);
 36 |   loadModule('foo/bar/baz', cb);
 37 |   t.is(loaded.length, 1);
 38 |   t.is(cbs.length, 1);
 39 |   var module0 = 'module$foo$bar$baz'
 40 |   t.is(loaded[0], URL_PREFIX + '/' + encodeURIComponent(module0));
 41 |   ModuleServer.m[module0] = {
 42 |     foo: true
 43 |   };
 44 |   cbs[0]();
 45 |   t.is(modules.length, 1);
 46 |   t.ok(modules[0].foo);
 47 | 
 48 |   // Incremental load
 49 |   loadModule('foo/bar', cb);
 50 |   t.is(loaded.length, 2);
 51 |   t.is(cbs.length, 2);
 52 |   var module1 = 'module$foo$bar'
 53 |   t.is(loaded[1], URL_PREFIX + '/' + encodeURIComponent(module1) + '/' +
 54 |       encodeURIComponent(module0));
 55 |   ModuleServer.m[module1] = {
 56 |     bar: true
 57 |   };
 58 |   cbs[1]();
 59 |   t.is(modules.length, 2);
 60 |   t.ok(modules[1].bar);
 61 | 
 62 |   // Load something again
 63 |   loadModule('foo/bar', cb);
 64 |   t.is(loaded.length, 2);
 65 |   t.is(cbs.length, 2);
 66 |   t.is(modules.length, 3);
 67 |   t.ok(modules[2].bar);
 68 | 
 69 |   // More incremental load
 70 |   loadModule('aaa', cb);
 71 |   t.is(loaded.length, 3);
 72 |   t.is(cbs.length, 3);
 73 |   var module2 = 'module$aaa'
 74 |   t.is(loaded[2], URL_PREFIX + '/' + encodeURIComponent(module2) + '/' +
 75 |       encodeURIComponent(module1 + ',' + module0));
 76 |   ModuleServer.m[module2] = {
 77 |     aaa: true
 78 |   };
 79 |   cbs[2]();
 80 |   t.is(modules.length, 4);
 81 |   t.equivalent(modules[3], ModuleServer.m[module2]);
 82 |   t.end();
 83 | });
 84 | 
 85 | test('default $LAB.js loader', function(t) {
 86 |   var url;
 87 |   var wait;
 88 |   GLOBAL.window = {};
 89 |   GLOBAL.window.$LAB = {
 90 |     script: function(u) {
 91 |       url = u;
 92 |       return {
 93 |         wait: function(cb) {
 94 |           wait = cb;
 95 |         }
 96 |       };
 97 |     }
 98 |   };
 99 | 
100 |   var loadModule = ModuleServer(URL_PREFIX);
101 |   loadModule('foo/bar/lab');
102 |   var module0 = 'module$foo$bar$lab'
103 |   t.ok(typeof wait === 'function');
104 |   t.is(url, URL_PREFIX + '/' + encodeURIComponent(module0));
105 |   t.end();
106 | });
107 | 


--------------------------------------------------------------------------------
/test/test-module-graph.js:
--------------------------------------------------------------------------------
 1 | /**
 2 |  * Copyright 2012 Google Inc. All Rights Reserved.
 3 |  *
 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
 7 |  *
 8 |  *      http://www.apache.org/licenses/LICENSE-2.0
 9 |  *
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.
15 |  */
16 | 
17 | var test = require('tap').test;
18 | 
19 | var moduleGraph = require('../module-graph.js');
20 | 
21 | test('instantiation', function(t) {
22 |   var name = 'foo';
23 |   var deps = ['bar'];
24 |   var data = [{
25 |     name: name,
26 |     'transitive-dependencies': deps
27 |   }];
28 |   var graph = moduleGraph.fromSerialization(data);
29 |   t.is(graph.getAllModules().length, 1);
30 |   t.is(graph.getAllModules()[0], name);
31 |   t.is(graph.getTransitiveDependencies(name), deps);
32 |   t.end();
33 | });
34 | 
35 | test('graph', function(t) {
36 |   var filename = 'fixtures/sample-module/module-graph.json';
37 |   var data = getJson(filename);
38 |   moduleGraph.fromFilename(filename, function(err, graph) {
39 |     t.is(err, null);
40 |     t.is(graph.getAllModules().length, 7);
41 |     t.is(graph.getAllModules()[0], data[0].name);
42 | 
43 |     var modules = graph.getModules(['module$app']);
44 |     t.equivalent(modules, ['root', 'module$module$bar',
45 |         'module$module$baz$foo', 'module$sub_app', 'module$module$foo',
46 |         'module$module', 'module$app']);
47 | 
48 |     var modules = graph.getModules(['module$sub_app']);
49 |     t.equivalent(modules, ['root', 'module$sub_app']);
50 | 
51 |     var modules = graph.getModules(['module$sub_app', 'module$module$bar']);
52 |     t.equivalent(modules, ['root', 'module$sub_app', 'module$module$bar']);
53 | 
54 |     var notFound = 'Does not exist';
55 |     t.throws(function() {
56 |       graph.getModules(['module$sub_app', notFound]);
57 |     }, new graph.NotFoundException(notFound));
58 | 
59 |     var modules = graph.getModules(['module$app'], ['module$sub_app']);
60 |     t.equivalent(modules, ['module$module$bar', 'module$module$baz$foo',
61 |         'module$module$foo', 'module$module', 'module$app']);
62 | 
63 |     var modules = graph.getModules(['module$app'], ['module$module$foo',
64 |         'module$sub_app']);
65 |     t.equivalent(modules, ['module$module', 'module$app']);
66 | 
67 |     var modules = graph.getModules(['module$app'], ['module$app',
68 |         'module$module$foo', 'module$sub_app']);
69 |     t.equivalent(modules, []);
70 | 
71 |     t.throws(function() {
72 |       graph.getModules(['module$app'], ['module$app', notFound]);
73 |       t.equivalent(modules, []);
74 |     }, new graph.NotFoundException(notFound));
75 | 
76 |     var modules = graph.getModules(['module$sub_app'], ['module$app']);
77 |     t.equivalent(modules, []);
78 | 
79 |     moduleGraph.fromFilename('DOESNOTEXISTwefasdfasdfasdfewf', function(err) {
80 |       t.ok(!!err);
81 |       t.end();
82 |     });
83 |   });
84 | });
85 | 
86 | function getJson(filename) {
87 |   return JSON.parse(require('fs').readFileSync(filename, 'utf8'));
88 | }


--------------------------------------------------------------------------------
/test/test-module-server.js:
--------------------------------------------------------------------------------
  1 | /**
  2 |  * Copyright 2012 Google Inc. All Rights Reserved.
  3 |  *
  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
  7 |  *
  8 |  *      http://www.apache.org/licenses/LICENSE-2.0
  9 |  *
 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.
 15 |  */
 16 | 
 17 | var test = require('tap').test;
 18 | 
 19 | // 'root' is a virtual module that all modules depend on.
 20 | var ROOT_MODULE_PREFIX = '\n\nModuleServer.m.root=root;\n';
 21 | 
 22 | require('../module-server').from('./fixtures/build',
 23 |     './fixtures/sample-module/module-graph.json', function(err, server) {
 24 |   test('module server', function(t) {
 25 |     t.plan(11);
 26 | 
 27 |     var subApp = getJs('module$sub_app');
 28 |     var subAppAndRoot = ROOT_MODULE_PREFIX + subApp;
 29 |     server(['module$sub_app'], [], function(err, length, js, sourceMap) {
 30 |       t.is(err, null);
 31 |       t.is(js, subAppAndRoot);
 32 |       t.is(length, subAppAndRoot.length);
 33 |       t.is(sourceMap, null);
 34 |     });
 35 | 
 36 |     var expectedJs = ROOT_MODULE_PREFIX + subApp + getJs(['module$module$bar',
 37 |         'module$module$baz$foo', 'module$module$foo']);
 38 |     server(['module$sub_app', 'module$module$foo'], [],
 39 |         function(err, length, js) {
 40 |       t.is(err, null);
 41 |       t.is(js, expectedJs);
 42 |       t.is(length, expectedJs.length);
 43 |     });
 44 | 
 45 |     var expectedJs = subApp + getJs(['module$module$bar', 'module$module$foo']);
 46 |     server(['module$sub_app', 'module$module$foo'], ['module$module$baz$foo'],
 47 |         function(err, length, js) {
 48 |       t.is(err, null);
 49 |       t.is(js, expectedJs);
 50 |       t.is(length, expectedJs.length);
 51 |     });
 52 | 
 53 |     var notFound = 'not found';
 54 |     server(['not found', 'module$sub_app', 'module$module$foo'],
 55 |         ['module$module$baz$foo'],
 56 |         function(err, length, js) {
 57 |       t.equivalent(err, new server.NotFoundException(notFound));
 58 |     });
 59 |   });
 60 | 
 61 |   test('logging', function(t) {
 62 |     t.plan(5);
 63 |     var expectedJs = getJs(['module$sub_app','module$module$bar',
 64 |         'module$module$foo']);
 65 |     server(['module$sub_app', 'module$module$foo'], ['module$module$baz$foo'],
 66 |         function(err, length, js) {
 67 |       t.is(err, null);
 68 |       t.is(js, expectedJs);
 69 |       t.is(length, expectedJs.length);
 70 |     }, {
 71 |       onLog: function(type, names, excludedNames) {
 72 |         t.pass()
 73 |       }
 74 |     });
 75 |   });
 76 | 
 77 |   test('source maps', function(t) {
 78 |     t.plan(21);
 79 | 
 80 |     var prefix = 'http://prefix';
 81 | 
 82 |     var options = {
 83 |       createSourceMap: true,
 84 |       sourceMapSourceRootUrlPrefix: prefix
 85 |     };
 86 | 
 87 |     var files = ['module$sub_app', 'module$module$bar', 'module$module$foo'];
 88 | 
 89 |     var expectedJs = getJs(files);
 90 |     server(['module$sub_app', 'module$module$foo'], ['module$module$baz$foo'],
 91 |         function(err, length, js, map) {
 92 |       t.is(err, null);
 93 |       t.is(js, expectedJs);
 94 |       t.is(length, expectedJs.length);
 95 |       t.ok(map != null);
 96 |       t.is(map.version, 3);
 97 |       t.ok(typeof map.file === 'string'); // we don't care about the value;
 98 |       var sections = map.sections;
 99 |       t.ok(sections != null);
100 |       t.ok(sections.length, 3);
101 |       var s0 = sections[0];
102 |       t.is(s0.offset.line, 1);
103 |       t.is(s0.offset.column, 0);
104 |       t.ok(s0.map);
105 |       t.ok(s0.map.version, 3);
106 |       t.is(s0.map.file, files[0]);
107 |       t.ok(s0.map.mappings);
108 |       t.is(s0.map.sourceRoot, prefix);
109 | 
110 |       t.is(sections[1].offset.line, 4);
111 |       t.is(sections[1].offset.column, 0);
112 |       t.is(sections[1].map.file, files[1]);
113 |       t.is(sections[2].offset.line, 7);
114 |       t.is(sections[2].offset.column, 0);
115 |       t.is(sections[2].map.file, files[2]);
116 |     }, options);
117 |   });
118 | });
119 | 
120 | function getJs(names) {
121 |   if (typeof names === 'string') {
122 |     names = [names];
123 |   }
124 |   var js = '';
125 |   names.forEach(function(name) {
126 |     var filename = './fixtures/build/' + name + '.js';
127 |     js += require('fs').readFileSync(filename, 'utf8') + '\n';
128 |     js += 'ModuleServer.m.' + name + '=' + name + ';\n';
129 |   });
130 |   return js;
131 | }
132 | 


--------------------------------------------------------------------------------