amdefine.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /** vim: et:ts=4:sw=4:sts=4
  2. * @license amdefine 0.0.8 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/amdefine for details
  5. */
  6. /*jslint node: true */
  7. /*global module, process */
  8. 'use strict';
  9. /**
  10. * Creates a define for node.
  11. * @param {Object} module the "module" object that is defined by Node for the
  12. * current module.
  13. * @param {Function} [requireFn]. Node's require function for the current module.
  14. * It only needs to be passed in Node versions before 0.5, when module.require
  15. * did not exist.
  16. * @returns {Function} a define function that is usable for the current node
  17. * module.
  18. */
  19. function amdefine(module, requireFn) {
  20. 'use strict';
  21. var defineCache = {},
  22. loaderCache = {},
  23. alreadyCalled = false,
  24. path = require('path'),
  25. makeRequire, stringRequire;
  26. /**
  27. * Trims the . and .. from an array of path segments.
  28. * It will keep a leading path segment if a .. will become
  29. * the first path segment, to help with module name lookups,
  30. * which act like paths, but can be remapped. But the end result,
  31. * all paths that use this function should look normalized.
  32. * NOTE: this method MODIFIES the input array.
  33. * @param {Array} ary the array of path segments.
  34. */
  35. function trimDots(ary) {
  36. var i, part;
  37. for (i = 0; ary[i]; i+= 1) {
  38. part = ary[i];
  39. if (part === '.') {
  40. ary.splice(i, 1);
  41. i -= 1;
  42. } else if (part === '..') {
  43. if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
  44. //End of the line. Keep at least one non-dot
  45. //path segment at the front so it can be mapped
  46. //correctly to disk. Otherwise, there is likely
  47. //no path mapping for a path starting with '..'.
  48. //This can still fail, but catches the most reasonable
  49. //uses of ..
  50. break;
  51. } else if (i > 0) {
  52. ary.splice(i - 1, 2);
  53. i -= 2;
  54. }
  55. }
  56. }
  57. }
  58. function normalize(name, baseName) {
  59. var baseParts;
  60. //Adjust any relative paths.
  61. if (name && name.charAt(0) === '.') {
  62. //If have a base name, try to normalize against it,
  63. //otherwise, assume it is a top-level require that will
  64. //be relative to baseUrl in the end.
  65. if (baseName) {
  66. baseParts = baseName.split('/');
  67. baseParts = baseParts.slice(0, baseParts.length - 1);
  68. baseParts = baseParts.concat(name.split('/'));
  69. trimDots(baseParts);
  70. name = baseParts.join('/');
  71. }
  72. }
  73. return name;
  74. }
  75. /**
  76. * Create the normalize() function passed to a loader plugin's
  77. * normalize method.
  78. */
  79. function makeNormalize(relName) {
  80. return function (name) {
  81. return normalize(name, relName);
  82. };
  83. }
  84. function makeLoad(id) {
  85. function load(value) {
  86. loaderCache[id] = value;
  87. }
  88. load.fromText = function (id, text) {
  89. //This one is difficult because the text can/probably uses
  90. //define, and any relative paths and requires should be relative
  91. //to that id was it would be found on disk. But this would require
  92. //bootstrapping a module/require fairly deeply from node core.
  93. //Not sure how best to go about that yet.
  94. throw new Error('amdefine does not implement load.fromText');
  95. };
  96. return load;
  97. }
  98. makeRequire = function (systemRequire, exports, module, relId) {
  99. function amdRequire(deps, callback) {
  100. if (typeof deps === 'string') {
  101. //Synchronous, single module require('')
  102. return stringRequire(systemRequire, exports, module, deps, relId);
  103. } else {
  104. //Array of dependencies with a callback.
  105. //Convert the dependencies to modules.
  106. deps = deps.map(function (depName) {
  107. return stringRequire(systemRequire, exports, module, depName, relId);
  108. });
  109. //Wait for next tick to call back the require call.
  110. process.nextTick(function () {
  111. callback.apply(null, deps);
  112. });
  113. }
  114. }
  115. amdRequire.toUrl = function (filePath) {
  116. if (filePath.indexOf('.') === 0) {
  117. return normalize(filePath, path.dirname(module.filename));
  118. } else {
  119. return filePath;
  120. }
  121. };
  122. return amdRequire;
  123. };
  124. //Favor explicit value, passed in if the module wants to support Node 0.4.
  125. requireFn = requireFn || function req() {
  126. return module.require.apply(module, arguments);
  127. };
  128. function runFactory(id, deps, factory) {
  129. var r, e, m, result;
  130. if (id) {
  131. e = loaderCache[id] = {};
  132. m = {
  133. id: id,
  134. uri: __filename,
  135. exports: e
  136. };
  137. r = makeRequire(requireFn, e, m, id);
  138. } else {
  139. //Only support one define call per file
  140. if (alreadyCalled) {
  141. throw new Error('amdefine with no module ID cannot be called more than once per file.');
  142. }
  143. alreadyCalled = true;
  144. //Use the real variables from node
  145. //Use module.exports for exports, since
  146. //the exports in here is amdefine exports.
  147. e = module.exports;
  148. m = module;
  149. r = makeRequire(requireFn, e, m, module.id);
  150. }
  151. //If there are dependencies, they are strings, so need
  152. //to convert them to dependency values.
  153. if (deps) {
  154. deps = deps.map(function (depName) {
  155. return r(depName);
  156. });
  157. }
  158. //Call the factory with the right dependencies.
  159. if (typeof factory === 'function') {
  160. result = factory.apply(m.exports, deps);
  161. } else {
  162. result = factory;
  163. }
  164. if (result !== undefined) {
  165. m.exports = result;
  166. if (id) {
  167. loaderCache[id] = m.exports;
  168. }
  169. }
  170. }
  171. stringRequire = function (systemRequire, exports, module, id, relId) {
  172. //Split the ID by a ! so that
  173. var index = id.indexOf('!'),
  174. originalId = id,
  175. prefix, plugin;
  176. if (index === -1) {
  177. id = normalize(id, relId);
  178. //Straight module lookup. If it is one of the special dependencies,
  179. //deal with it, otherwise, delegate to node.
  180. if (id === 'require') {
  181. return makeRequire(systemRequire, exports, module, relId);
  182. } else if (id === 'exports') {
  183. return exports;
  184. } else if (id === 'module') {
  185. return module;
  186. } else if (loaderCache.hasOwnProperty(id)) {
  187. return loaderCache[id];
  188. } else if (defineCache[id]) {
  189. runFactory.apply(null, defineCache[id]);
  190. return loaderCache[id];
  191. } else {
  192. if(systemRequire) {
  193. return systemRequire(originalId);
  194. } else {
  195. throw new Error('No module with ID: ' + id);
  196. }
  197. }
  198. } else {
  199. //There is a plugin in play.
  200. prefix = id.substring(0, index);
  201. id = id.substring(index + 1, id.length);
  202. plugin = stringRequire(systemRequire, exports, module, prefix, relId);
  203. if (plugin.normalize) {
  204. id = plugin.normalize(id, makeNormalize(relId));
  205. } else {
  206. //Normalize the ID normally.
  207. id = normalize(id, relId);
  208. }
  209. if (loaderCache[id]) {
  210. return loaderCache[id];
  211. } else {
  212. plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
  213. return loaderCache[id];
  214. }
  215. }
  216. };
  217. //Create a define function specific to the module asking for amdefine.
  218. function define(id, deps, factory) {
  219. if (Array.isArray(id)) {
  220. factory = deps;
  221. deps = id;
  222. id = undefined;
  223. } else if (typeof id !== 'string') {
  224. factory = id;
  225. id = deps = undefined;
  226. }
  227. if (deps && !Array.isArray(deps)) {
  228. factory = deps;
  229. deps = undefined;
  230. }
  231. if (!deps) {
  232. deps = ['require', 'exports', 'module'];
  233. }
  234. //Set up properties for this module. If an ID, then use
  235. //internal cache. If no ID, then use the external variables
  236. //for this node module.
  237. if (id) {
  238. //Put the module in deep freeze until there is a
  239. //require call for it.
  240. defineCache[id] = [id, deps, factory];
  241. } else {
  242. runFactory(id, deps, factory);
  243. }
  244. }
  245. //define.require, which has access to all the values in the
  246. //cache. Useful for AMD modules that all have IDs in the file,
  247. //but need to finally export a value to node based on one of those
  248. //IDs.
  249. define.require = function (id) {
  250. if (loaderCache[id]) {
  251. return loaderCache[id];
  252. }
  253. if (defineCache[id]) {
  254. runFactory.apply(null, defineCache[id]);
  255. return loaderCache[id];
  256. }
  257. };
  258. define.amd = {};
  259. return define;
  260. }
  261. module.exports = amdefine;