medium.js 2.5 KB

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