HookCodeFactory.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class HookCodeFactory {
  7. constructor(config) {
  8. this.config = config;
  9. this.options = undefined;
  10. }
  11. create(options) {
  12. this.init(options);
  13. switch(this.options.type) {
  14. case "sync":
  15. return new Function(this.args(), "\"use strict\";\n" + this.header() + this.content({
  16. onError: err => `throw ${err};\n`,
  17. onResult: result => `return ${result};\n`,
  18. onDone: () => "",
  19. rethrowIfPossible: true
  20. }));
  21. case "async":
  22. return new Function(this.args({
  23. after: "_callback"
  24. }), "\"use strict\";\n" + this.header() + this.content({
  25. onError: err => `_callback(${err});\n`,
  26. onResult: result => `_callback(null, ${result});\n`,
  27. onDone: () => "_callback();\n"
  28. }));
  29. case "promise":
  30. let code = "";
  31. code += "\"use strict\";\n";
  32. code += "return new Promise((_resolve, _reject) => {\n";
  33. code += "var _sync = true;\n";
  34. code += this.header();
  35. code += this.content({
  36. onError: err => {
  37. let code = "";
  38. code += "if(_sync)\n";
  39. code += `_resolve(Promise.resolve().then(() => { throw ${err}; }));\n`;
  40. code += "else\n";
  41. code += `_reject(${err});\n`;
  42. return code;
  43. },
  44. onResult: result => `_resolve(${result});\n`,
  45. onDone: () => "_resolve();\n"
  46. });
  47. code += "_sync = false;\n";
  48. code += "});\n";
  49. return new Function(this.args(), code);
  50. }
  51. }
  52. setup(instance, options) {
  53. instance._x = options.taps.map(t => t.fn);
  54. }
  55. /**
  56. * @param {{ type: "sync" | "promise" | "async", taps: Array<Tap>, interceptors: Array<Interceptor> }} options
  57. */
  58. init(options) {
  59. this.options = options;
  60. this._args = options.args.slice();
  61. }
  62. header() {
  63. let code = "";
  64. if(this.needContext()) {
  65. code += "var _context = {};\n";
  66. } else {
  67. code += "var _context;\n";
  68. }
  69. code += "var _x = this._x;\n";
  70. if(this.options.interceptors.length > 0) {
  71. code += "var _taps = this.taps;\n";
  72. code += "var _interceptors = this.interceptors;\n";
  73. }
  74. for(let i = 0; i < this.options.interceptors.length; i++) {
  75. const interceptor = this.options.interceptors[i];
  76. if(interceptor.call) {
  77. code += `${this.getInterceptor(i)}.call(${this.args({
  78. before: interceptor.context ? "_context" : undefined
  79. })});\n`;
  80. }
  81. }
  82. return code;
  83. }
  84. needContext() {
  85. for(const tap of this.options.taps)
  86. if(tap.context) return true;
  87. return false;
  88. }
  89. callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) {
  90. let code = "";
  91. let hasTapCached = false;
  92. for(let i = 0; i < this.options.interceptors.length; i++) {
  93. const interceptor = this.options.interceptors[i];
  94. if(interceptor.tap) {
  95. if(!hasTapCached) {
  96. code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`;
  97. hasTapCached = true;
  98. }
  99. code += `${this.getInterceptor(i)}.tap(${interceptor.context ? "_context, " : ""}_tap${tapIndex});\n`;
  100. }
  101. }
  102. code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`;
  103. const tap = this.options.taps[tapIndex];
  104. switch(tap.type) {
  105. case "sync":
  106. if(!rethrowIfPossible) {
  107. code += `var _hasError${tapIndex} = false;\n`;
  108. code += "try {\n";
  109. }
  110. if(onResult) {
  111. code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
  112. before: tap.context ? "_context" : undefined
  113. })});\n`;
  114. } else {
  115. code += `_fn${tapIndex}(${this.args({
  116. before: tap.context ? "_context" : undefined
  117. })});\n`;
  118. }
  119. if(!rethrowIfPossible) {
  120. code += "} catch(_err) {\n";
  121. code += `_hasError${tapIndex} = true;\n`;
  122. code += onError("_err");
  123. code += "}\n";
  124. code += `if(!_hasError${tapIndex}) {\n`;
  125. }
  126. if(onResult) {
  127. code += onResult(`_result${tapIndex}`);
  128. }
  129. if(onDone) {
  130. code += onDone();
  131. }
  132. if(!rethrowIfPossible) {
  133. code += "}\n";
  134. }
  135. break;
  136. case "async":
  137. let cbCode = "";
  138. if(onResult)
  139. cbCode += `(_err${tapIndex}, _result${tapIndex}) => {\n`;
  140. else
  141. cbCode += `_err${tapIndex} => {\n`;
  142. cbCode += `if(_err${tapIndex}) {\n`;
  143. cbCode += onError(`_err${tapIndex}`);
  144. cbCode += "} else {\n";
  145. if(onResult) {
  146. cbCode += onResult(`_result${tapIndex}`);
  147. }
  148. if(onDone) {
  149. cbCode += onDone();
  150. }
  151. cbCode += "}\n";
  152. cbCode += "}";
  153. code += `_fn${tapIndex}(${this.args({
  154. before: tap.context ? "_context" : undefined,
  155. after: cbCode
  156. })});\n`;
  157. break;
  158. case "promise":
  159. code += `var _hasResult${tapIndex} = false;\n`;
  160. code += `_fn${tapIndex}(${this.args({
  161. before: tap.context ? "_context" : undefined
  162. })}).then(_result${tapIndex} => {\n`;
  163. code += `_hasResult${tapIndex} = true;\n`;
  164. if(onResult) {
  165. code += onResult(`_result${tapIndex}`);
  166. }
  167. if(onDone) {
  168. code += onDone();
  169. }
  170. code += `}, _err${tapIndex} => {\n`;
  171. code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`;
  172. code += onError(`_err${tapIndex}`);
  173. code += "});\n";
  174. break;
  175. }
  176. return code;
  177. }
  178. callTapsSeries({ onError, onResult, onDone, rethrowIfPossible }) {
  179. if(this.options.taps.length === 0)
  180. return onDone();
  181. const firstAsync = this.options.taps.findIndex(t => t.type !== "sync");
  182. const next = i => {
  183. if(i >= this.options.taps.length) {
  184. return onDone();
  185. }
  186. const done = () => next(i + 1);
  187. const doneBreak = (skipDone) => {
  188. if(skipDone) return "";
  189. return onDone();
  190. }
  191. return this.callTap(i, {
  192. onError: error => onError(i, error, done, doneBreak),
  193. onResult: onResult && ((result) => {
  194. return onResult(i, result, done, doneBreak);
  195. }),
  196. onDone: !onResult && (() => {
  197. return done();
  198. }),
  199. rethrowIfPossible: rethrowIfPossible && (firstAsync < 0 || i < firstAsync)
  200. });
  201. };
  202. return next(0);
  203. }
  204. callTapsLooping({ onError, onDone, rethrowIfPossible }) {
  205. if(this.options.taps.length === 0)
  206. return onDone();
  207. const syncOnly = this.options.taps.every(t => t.type === "sync");
  208. let code = "";
  209. if(!syncOnly) {
  210. code += "var _looper = () => {\n";
  211. code += "var _loopAsync = false;\n";
  212. }
  213. code += "var _loop;\n";
  214. code += "do {\n";
  215. code += "_loop = false;\n";
  216. for(let i = 0; i < this.options.interceptors.length; i++) {
  217. const interceptor = this.options.interceptors[i];
  218. if(interceptor.loop) {
  219. code += `${this.getInterceptor(i)}.loop(${this.args({
  220. before: interceptor.context ? "_context" : undefined
  221. })});\n`;
  222. }
  223. }
  224. code += this.callTapsSeries({
  225. onError,
  226. onResult: (i, result, next, doneBreak) => {
  227. let code = "";
  228. code += `if(${result} !== undefined) {\n`;
  229. code += "_loop = true;\n";
  230. if(!syncOnly)
  231. code += "if(_loopAsync) _looper();\n";
  232. code += doneBreak(true);
  233. code += `} else {\n`;
  234. code += next();
  235. code += `}\n`;
  236. return code;
  237. },
  238. onDone: onDone && (() => {
  239. let code = "";
  240. code += "if(!_loop) {\n";
  241. code += onDone();
  242. code += "}\n";
  243. return code;
  244. }),
  245. rethrowIfPossible: rethrowIfPossible && syncOnly
  246. })
  247. code += "} while(_loop);\n";
  248. if(!syncOnly) {
  249. code += "_loopAsync = true;\n";
  250. code += "};\n";
  251. code += "_looper();\n";
  252. }
  253. return code;
  254. }
  255. callTapsParallel({ onError, onResult, onDone, rethrowIfPossible, onTap = (i, run) => run() }) {
  256. if(this.options.taps.length <= 1) {
  257. return this.callTapsSeries({ onError, onResult, onDone, rethrowIfPossible })
  258. }
  259. let code = "";
  260. code += "do {\n";
  261. code += `var _counter = ${this.options.taps.length};\n`;
  262. if(onDone) {
  263. code += "var _done = () => {\n";
  264. code += onDone();
  265. code += "};\n";
  266. }
  267. for(let i = 0; i < this.options.taps.length; i++) {
  268. const done = () => {
  269. if(onDone)
  270. return "if(--_counter === 0) _done();\n";
  271. else
  272. return "--_counter;";
  273. };
  274. const doneBreak = (skipDone) => {
  275. if(skipDone || !onDone)
  276. return "_counter = 0;\n";
  277. else
  278. return "_counter = 0;\n_done();\n";
  279. }
  280. code += "if(_counter <= 0) break;\n";
  281. code += onTap(i, () => this.callTap(i, {
  282. onError: error => {
  283. let code = "";
  284. code += "if(_counter > 0) {\n";
  285. code += onError(i, error, done, doneBreak);
  286. code += "}\n";
  287. return code;
  288. },
  289. onResult: onResult && ((result) => {
  290. let code = "";
  291. code += "if(_counter > 0) {\n";
  292. code += onResult(i, result, done, doneBreak);
  293. code += "}\n";
  294. return code;
  295. }),
  296. onDone: !onResult && (() => {
  297. return done();
  298. }),
  299. rethrowIfPossible
  300. }), done, doneBreak);
  301. }
  302. code += "} while(false);\n";
  303. return code;
  304. }
  305. args({ before, after } = {}) {
  306. let allArgs = this._args;
  307. if(before) allArgs = [before].concat(allArgs);
  308. if(after) allArgs = allArgs.concat(after);
  309. if(allArgs.length === 0) {
  310. return "";
  311. } else {
  312. return allArgs.join(", ");
  313. }
  314. }
  315. getTapFn(idx) {
  316. return `_x[${idx}]`;
  317. }
  318. getTap(idx) {
  319. return `_taps[${idx}]`;
  320. }
  321. getInterceptor(idx) {
  322. return `_interceptors[${idx}]`;
  323. }
  324. }
  325. module.exports = HookCodeFactory;