medium.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createSidecarMedium = exports.createMedium = void 0;
  4. var tslib_1 = require("tslib");
  5. function ItoI(a) {
  6. return a;
  7. }
  8. function innerCreateMedium(defaults, middleware) {
  9. if (middleware === void 0) { middleware = ItoI; }
  10. var buffer = [];
  11. var assigned = false;
  12. var medium = {
  13. read: function () {
  14. if (assigned) {
  15. throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.');
  16. }
  17. if (buffer.length) {
  18. return buffer[buffer.length - 1];
  19. }
  20. return defaults;
  21. },
  22. useMedium: function (data) {
  23. var item = middleware(data, assigned);
  24. buffer.push(item);
  25. return function () {
  26. buffer = buffer.filter(function (x) { return x !== item; });
  27. };
  28. },
  29. assignSyncMedium: function (cb) {
  30. assigned = true;
  31. while (buffer.length) {
  32. var cbs = buffer;
  33. buffer = [];
  34. cbs.forEach(cb);
  35. }
  36. buffer = {
  37. push: function (x) { return cb(x); },
  38. filter: function () { return buffer; },
  39. };
  40. },
  41. assignMedium: function (cb) {
  42. assigned = true;
  43. var pendingQueue = [];
  44. if (buffer.length) {
  45. var cbs = buffer;
  46. buffer = [];
  47. cbs.forEach(cb);
  48. pendingQueue = buffer;
  49. }
  50. var executeQueue = function () {
  51. var cbs = pendingQueue;
  52. pendingQueue = [];
  53. cbs.forEach(cb);
  54. };
  55. var cycle = function () { return Promise.resolve().then(executeQueue); };
  56. cycle();
  57. buffer = {
  58. push: function (x) {
  59. pendingQueue.push(x);
  60. cycle();
  61. },
  62. filter: function (filter) {
  63. pendingQueue = pendingQueue.filter(filter);
  64. return buffer;
  65. },
  66. };
  67. },
  68. };
  69. return medium;
  70. }
  71. function createMedium(defaults, middleware) {
  72. if (middleware === void 0) { middleware = ItoI; }
  73. return innerCreateMedium(defaults, middleware);
  74. }
  75. exports.createMedium = createMedium;
  76. // eslint-disable-next-line @typescript-eslint/ban-types
  77. function createSidecarMedium(options) {
  78. if (options === void 0) { options = {}; }
  79. var medium = innerCreateMedium(null);
  80. medium.options = tslib_1.__assign({ async: true, ssr: false }, options);
  81. return medium;
  82. }
  83. exports.createSidecarMedium = createSidecarMedium;