amdefine.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /** vim: et:ts=4:sw=4:sts=4
  2. * @license amdefine 1.0.1 Copyright (c) 2011-2016, 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. if (callback) {
  111. process.nextTick(function () {
  112. callback.apply(null, deps);
  113. });
  114. }
  115. }
  116. }
  117. amdRequire.toUrl = function (filePath) {
  118. if (filePath.indexOf('.') === 0) {
  119. return normalize(filePath, path.dirname(module.filename));
  120. } else {
  121. return filePath;
  122. }
  123. };
  124. return amdRequire;
  125. };
  126. //Favor explicit value, passed in if the module wants to support Node 0.4.
  127. requireFn = requireFn || function req() {
  128. return module.require.apply(module, arguments);
  129. };
  130. function runFactory(id, deps, factory) {
  131. var r, e, m, result;
  132. if (id) {
  133. e = loaderCache[id] = {};
  134. m = {
  135. id: id,
  136. uri: __filename,
  137. exports: e
  138. };
  139. r = makeRequire(requireFn, e, m, id);
  140. } else {
  141. //Only support one define call per file
  142. if (alreadyCalled) {
  143. throw new Error('amdefine with no module ID cannot be called more than once per file.');
  144. }
  145. alreadyCalled = true;
  146. //Use the real variables from node
  147. //Use module.exports for exports, since
  148. //the exports in here is amdefine exports.
  149. e = module.exports;
  150. m = module;
  151. r = makeRequire(requireFn, e, m, module.id);
  152. }
  153. //If there are dependencies, they are strings, so need
  154. //to convert them to dependency values.
  155. if (deps) {
  156. deps = deps.map(function (depName) {
  157. return r(depName);
  158. });
  159. }
  160. //Call the factory with the right dependencies.
  161. if (typeof factory === 'function') {
  162. result = factory.apply(m.exports, deps);
  163. } else {
  164. result = factory;
  165. }
  166. if (result !== undefined) {
  167. m.exports = result;
  168. if (id) {
  169. loaderCache[id] = m.exports;
  170. }
  171. }
  172. }
  173. stringRequire = function (systemRequire, exports, module, id, relId) {
  174. //Split the ID by a ! so that
  175. var index = id.indexOf('!'),
  176. originalId = id,
  177. prefix, plugin;
  178. if (index === -1) {
  179. id = normalize(id, relId);
  180. //Straight module lookup. If it is one of the special dependencies,
  181. //deal with it, otherwise, delegate to node.
  182. if (id === 'require') {
  183. return makeRequire(systemRequire, exports, module, relId);
  184. } else if (id === 'exports') {
  185. return exports;
  186. } else if (id === 'module') {
  187. return module;
  188. } else if (loaderCache.hasOwnProperty(id)) {
  189. return loaderCache[id];
  190. } else if (defineCache[id]) {
  191. runFactory.apply(null, defineCache[id]);
  192. return loaderCache[id];
  193. } else {
  194. if(systemRequire) {
  195. return systemRequire(originalId);
  196. } else {
  197. throw new Error('No module with ID: ' + id);
  198. }
  199. }
  200. } else {
  201. //There is a plugin in play.
  202. prefix = id.substring(0, index);
  203. id = id.substring(index + 1, id.length);
  204. plugin = stringRequire(systemRequire, exports, module, prefix, relId);
  205. if (plugin.normalize) {
  206. id = plugin.normalize(id, makeNormalize(relId));
  207. } else {
  208. //Normalize the ID normally.
  209. id = normalize(id, relId);
  210. }
  211. if (loaderCache[id]) {
  212. return loaderCache[id];
  213. } else {
  214. plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
  215. return loaderCache[id];
  216. }
  217. }
  218. };
  219. //Create a define function specific to the module asking for amdefine.
  220. function define(id, deps, factory) {
  221. if (Array.isArray(id)) {
  222. factory = deps;
  223. deps = id;
  224. id = undefined;
  225. } else if (typeof id !== 'string') {
  226. factory = id;
  227. id = deps = undefined;
  228. }
  229. if (deps && !Array.isArray(deps)) {
  230. factory = deps;
  231. deps = undefined;
  232. }
  233. if (!deps) {
  234. deps = ['require', 'exports', 'module'];
  235. }
  236. //Set up properties for this module. If an ID, then use
  237. //internal cache. If no ID, then use the external variables
  238. //for this node module.
  239. if (id) {
  240. //Put the module in deep freeze until there is a
  241. //require call for it.
  242. defineCache[id] = [id, deps, factory];
  243. } else {
  244. runFactory(id, deps, factory);
  245. }
  246. }
  247. //define.require, which has access to all the values in the
  248. //cache. Useful for AMD modules that all have IDs in the file,
  249. //but need to finally export a value to node based on one of those
  250. //IDs.
  251. define.require = function (id) {
  252. if (loaderCache[id]) {
  253. return loaderCache[id];
  254. }
  255. if (defineCache[id]) {
  256. runFactory.apply(null, defineCache[id]);
  257. return loaderCache[id];
  258. }
  259. };
  260. define.amd = {};
  261. return define;
  262. }
  263. module.exports = amdefine;