async.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. 'use strict';
  2. module.exports = {
  3. setup: setupAsync,
  4. compile: compileAsync
  5. };
  6. var util = require('./compile/util');
  7. var ASYNC = {
  8. '*': checkGenerators,
  9. 'co*': checkGenerators,
  10. 'es7': checkAsyncFunction
  11. };
  12. var TRANSPILE = {
  13. 'nodent': getNodent,
  14. 'regenerator': getRegenerator
  15. };
  16. var MODES = [
  17. { async: 'co*' },
  18. { async: 'es7', transpile: 'nodent' },
  19. { async: 'co*', transpile: 'regenerator' }
  20. ];
  21. var regenerator, nodent;
  22. function setupAsync(opts, required) {
  23. if (required !== false) required = true;
  24. var async = opts.async
  25. , transpile = opts.transpile
  26. , check;
  27. switch (typeof transpile) {
  28. case 'string':
  29. var get = TRANSPILE[transpile];
  30. if (!get) throw new Error('bad transpiler: ' + transpile);
  31. return (opts._transpileFunc = get(opts, required));
  32. case 'undefined':
  33. case 'boolean':
  34. if (typeof async == 'string') {
  35. check = ASYNC[async];
  36. if (!check) throw new Error('bad async mode: ' + async);
  37. return (opts.transpile = check(opts, required));
  38. }
  39. for (var i=0; i<MODES.length; i++) {
  40. var _opts = MODES[i];
  41. if (setupAsync(_opts, false)) {
  42. util.copy(_opts, opts);
  43. return opts.transpile;
  44. }
  45. }
  46. /* istanbul ignore next */
  47. throw new Error('generators, nodent and regenerator are not available');
  48. case 'function':
  49. return (opts._transpileFunc = opts.transpile);
  50. default:
  51. throw new Error('bad transpiler: ' + transpile);
  52. }
  53. }
  54. function checkGenerators(opts, required) {
  55. /* jshint evil: true */
  56. try {
  57. (new Function('(function*(){})()'))();
  58. return true;
  59. } catch(e) {
  60. /* istanbul ignore next */
  61. if (required) throw new Error('generators not supported');
  62. }
  63. }
  64. function checkAsyncFunction(opts, required) {
  65. /* jshint evil: true */
  66. try {
  67. (new Function('(async function(){})()'))();
  68. /* istanbul ignore next */
  69. return true;
  70. } catch(e) {
  71. if (required) throw new Error('es7 async functions not supported');
  72. }
  73. }
  74. function getRegenerator(opts, required) {
  75. try {
  76. if (!regenerator) {
  77. var name = 'regenerator';
  78. regenerator = require(name);
  79. regenerator.runtime();
  80. }
  81. if (!opts.async || opts.async === true)
  82. opts.async = 'es7';
  83. return regeneratorTranspile;
  84. } catch(e) {
  85. /* istanbul ignore next */
  86. if (required) throw new Error('regenerator not available');
  87. }
  88. }
  89. function regeneratorTranspile(code) {
  90. return regenerator.compile(code).code;
  91. }
  92. function getNodent(opts, required) {
  93. /* jshint evil: true */
  94. try {
  95. if (!nodent) {
  96. var name = 'nodent';
  97. nodent = require(name)({ log: false, dontInstallRequireHook: true });
  98. }
  99. if (opts.async != 'es7') {
  100. if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions');
  101. opts.async = 'es7';
  102. }
  103. return nodentTranspile;
  104. } catch(e) {
  105. /* istanbul ignore next */
  106. if (required) throw new Error('nodent not available');
  107. }
  108. }
  109. function nodentTranspile(code) {
  110. return nodent.compile(code, '', { promises: true, sourcemap: false }).code;
  111. }
  112. /**
  113. * Creates validating function for passed schema with asynchronous loading of missing schemas.
  114. * `loadSchema` option should be a function that accepts schema uri and node-style callback.
  115. * @this Ajv
  116. * @param {Object} schema schema object
  117. * @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function.
  118. */
  119. function compileAsync(schema, callback) {
  120. /* eslint no-shadow: 0 */
  121. /* jshint validthis: true */
  122. var schemaObj;
  123. var self = this;
  124. try {
  125. schemaObj = this._addSchema(schema);
  126. } catch(e) {
  127. setTimeout(function() { callback(e); });
  128. return;
  129. }
  130. if (schemaObj.validate) {
  131. setTimeout(function() { callback(null, schemaObj.validate); });
  132. } else {
  133. if (typeof this._opts.loadSchema != 'function')
  134. throw new Error('options.loadSchema should be a function');
  135. _compileAsync(schema, callback, true);
  136. }
  137. function _compileAsync(schema, callback, firstCall) {
  138. var validate;
  139. try { validate = self.compile(schema); }
  140. catch(e) {
  141. if (e.missingSchema) loadMissingSchema(e);
  142. else deferCallback(e);
  143. return;
  144. }
  145. deferCallback(null, validate);
  146. function loadMissingSchema(e) {
  147. var ref = e.missingSchema;
  148. if (self._refs[ref] || self._schemas[ref])
  149. return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'));
  150. var _callbacks = self._loadingSchemas[ref];
  151. if (_callbacks) {
  152. if (typeof _callbacks == 'function')
  153. self._loadingSchemas[ref] = [_callbacks, schemaLoaded];
  154. else
  155. _callbacks[_callbacks.length] = schemaLoaded;
  156. } else {
  157. self._loadingSchemas[ref] = schemaLoaded;
  158. self._opts.loadSchema(ref, function (err, sch) {
  159. var _callbacks = self._loadingSchemas[ref];
  160. delete self._loadingSchemas[ref];
  161. if (typeof _callbacks == 'function') {
  162. _callbacks(err, sch);
  163. } else {
  164. for (var i=0; i<_callbacks.length; i++)
  165. _callbacks[i](err, sch);
  166. }
  167. });
  168. }
  169. function schemaLoaded(err, sch) {
  170. if (err) return callback(err);
  171. if (!(self._refs[ref] || self._schemas[ref])) {
  172. try {
  173. self.addSchema(sch, ref);
  174. } catch(e) {
  175. callback(e);
  176. return;
  177. }
  178. }
  179. _compileAsync(schema, callback);
  180. }
  181. }
  182. function deferCallback(err, validate) {
  183. if (firstCall) setTimeout(function() { callback(err, validate); });
  184. else return callback(err, validate);
  185. }
  186. }
  187. }