amdefine.js 9.6 KB

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