Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

func-cache

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

func-cache - npm Package Compare versions

Comparing version 2.0.73 to 2.0.74

80

dist/func-cache.cjs.development.js

@@ -366,24 +366,3 @@ 'use strict';

____timeOfCreation: Date.now()
}, options.initialData);
var firstTimeDone = !!options.initialData;
var getData = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _options$getInitialDa;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return (_options$getInitialDa = options.getInitialData()) == null ? void 0 : _options$getInitialDa.then(function (data) {
cached = _extends({}, data, cached);
});
case 2:
case "end":
return _context.stop();
}
}, _callee);
}));
return function getData() {
return _ref.apply(this, arguments);
};
}();
}, options.initialCache);
var updateData = options.onDataUpdate ? debounce(function () {

@@ -411,51 +390,42 @@ try {

var asyncCache = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(getnewval, str) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(getnewval, str) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (firstTimeDone) {
_context2.next = 4;
break;
}
_context2.next = 3;
return getData();
case 3:
firstTimeDone = true;
case 4:
checkExpiry();
if (!(str in cached)) {
_context2.next = 7;
_context.next = 3;
break;
}
return _context2.abrupt("return", cached[str]);
case 7:
_context2.next = 9;
return _context.abrupt("return", cached[str]);
case 3:
_context.next = 5;
return getnewval();
case 9:
cached[str] = _context2.sent;
case 5:
cached[str] = _context.sent;
updateData == null ? void 0 : updateData();
return _context2.abrupt("return", cached[str]);
case 12:
return _context.abrupt("return", cached[str]);
case 8:
case "end":
return _context2.stop();
return _context.stop();
}
}, _callee2);
}, _callee);
}));
return function asyncCache(_x, _x2) {
return _ref2.apply(this, arguments);
return _ref.apply(this, arguments);
};
}();
if (options.async || util.types.isAsyncFunction(func)) {
return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _len,
args,
_key,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
for (_len = _args3.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = _args3[_key];
for (_len = _args2.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = _args2[_key];
}
_context3.next = 3;
_context2.next = 3;
return asyncCache(function () {

@@ -465,8 +435,8 @@ return func.apply(void 0, args);

case 3:
return _context3.abrupt("return", _context3.sent);
return _context2.abrupt("return", _context2.sent);
case 4:
case "end":
return _context3.stop();
return _context2.stop();
}
}, _callee3);
}, _callee2);
}));

@@ -473,0 +443,0 @@ }

@@ -1,2 +0,2 @@

"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("debounce")),r=t(require("util"));function n(){n=function(){return t};var t={},e=Object.prototype,r=e.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function l(t,e,r,n){var i=Object.create((e&&e.prototype instanceof p?e:p).prototype),a=new j(n||[]);return o(i,"_invoke",{value:_(t,r,a)}),i}function s(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=l;var h={};function p(){}function v(){}function d(){}var y={};f(y,a,(function(){return this}));var g=Object.getPrototypeOf,m=g&&g(g(k([])));m&&m!==e&&r.call(m,a)&&(y=m);var w=d.prototype=p.prototype=Object.create(y);function b(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){var n;o(this,"_invoke",{value:function(o,i){function a(){return new e((function(n,a){!function n(o,i,a,c){var u=s(t[o],t,i);if("throw"!==u.type){var f=u.arg,l=f.value;return l&&"object"==typeof l&&r.call(l,"__await")?e.resolve(l.__await).then((function(t){n("next",t,a,c)}),(function(t){n("throw",t,a,c)})):e.resolve(l).then((function(t){f.value=t,a(f)}),(function(t){return n("throw",t,a,c)}))}c(u.arg)}(o,i,n,a)}))}return n=n?n.then(a,a):a()}})}function _(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=L(a,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=s(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===h)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}function L(t,e){var r=e.method,n=t.iterator[r];if(void 0===n)return e.delegate=null,"throw"===r&&t.iterator.return&&(e.method="return",e.arg=void 0,L(t,e),"throw"===e.method)||"return"!==r&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+r+"' method")),h;var o=s(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,h;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function E(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function k(t){if(t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return o.next=o}}return{next:S}}function S(){return{value:void 0,done:!0}}return v.prototype=d,o(w,"constructor",{value:d,configurable:!0}),o(d,"constructor",{value:v,configurable:!0}),v.displayName=f(d,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===v||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,f(t,u,"GeneratorFunction")),t.prototype=Object.create(w),t},t.awrap=function(t){return{__await:t}},b(x.prototype),f(x.prototype,c,(function(){return this})),t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new x(l(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},b(w),f(w,u,"Generator"),f(w,a,(function(){return this})),f(w,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=k,j.prototype={constructor:j,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),u=r.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),E(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;E(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function o(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function i(t){return function(){var e=this,r=arguments;return new Promise((function(n,i){var a=t.apply(e,r);function c(t){o(a,n,i,c,u,"next",t)}function u(t){o(a,n,i,c,u,"throw",t)}c(void 0)}))}}function a(){return(a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}exports.default=function(t,o){void 0===o&&(o={lifeTime:0,debounceTimer:1e3,async:!1});var c=a({____timeOfCreation:Date.now()},o.initialData),u=!!o.initialData,f=function(){var t=i(n().mark((function t(){var e;return n().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,null==(e=o.getInitialData())?void 0:e.then((function(t){c=a({},t,c)}));case 2:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),l=o.onDataUpdate?e((function(){try{null==o.onDataUpdate||o.onDataUpdate(c)}catch(t){o.debug&&console.error(t)}}),o.debounceTimer):void 0,s=function(){0!==o.lifeTime&&Date.now()-c.____timeOfCreation>o.lifeTime&&(c={____timeOfCreation:c.____timeOfCreation})},h=function(t,e){return s(),e in c||(c[e]=t(),null==l||l()),c[e]},p=function(){var t=i(n().mark((function t(e,r){return n().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u){t.next=4;break}return t.next=3,f();case 3:u=!0;case 4:if(s(),!(r in c)){t.next=7;break}return t.abrupt("return",c[r]);case 7:return t.next=9,e();case 9:return c[r]=t.sent,null==l||l(),t.abrupt("return",c[r]);case 12:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}();if(o.async||r.types.isAsyncFunction(t))return i(n().mark((function e(){var r,o,i,a=arguments;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(r=a.length,o=new Array(r),i=0;i<r;i++)o[i]=a[i];return e.next=3,p((function(){return t.apply(void 0,o)}),o.join(","));case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e)})));var v=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return h(t.apply(void 0,r),r.join(","))};return v.clearCache=function(){c={____timeOfCreation:Date.now()}},v.noCache=function(){return t.apply(void 0,arguments)},v},exports.localStorageCacher=function(t,e){var r=(null==e?void 0:e.localStorage)||window.localStorage;return{initialCache:JSON.parse(r.getItem(t)||"{}"),onDataUpdate:function(e){r.setItem(t,JSON.stringify(e))}}};
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("debounce")),r=t(require("util"));function n(){n=function(){return t};var t={},e=Object.prototype,r=e.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function l(t,e,r,n){var i=Object.create((e&&e.prototype instanceof p?e:p).prototype),a=new j(n||[]);return o(i,"_invoke",{value:x(t,r,a)}),i}function s(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=l;var h={};function p(){}function v(){}function d(){}var y={};f(y,a,(function(){return this}));var g=Object.getPrototypeOf,m=g&&g(g(S([])));m&&m!==e&&r.call(m,a)&&(y=m);var w=d.prototype=p.prototype=Object.create(y);function b(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function _(t,e){var n;o(this,"_invoke",{value:function(o,i){function a(){return new e((function(n,a){!function n(o,i,a,c){var u=s(t[o],t,i);if("throw"!==u.type){var f=u.arg,l=f.value;return l&&"object"==typeof l&&r.call(l,"__await")?e.resolve(l.__await).then((function(t){n("next",t,a,c)}),(function(t){n("throw",t,a,c)})):e.resolve(l).then((function(t){f.value=t,a(f)}),(function(t){return n("throw",t,a,c)}))}c(u.arg)}(o,i,n,a)}))}return n=n?n.then(a,a):a()}})}function x(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=L(a,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=s(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===h)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}function L(t,e){var r=e.method,n=t.iterator[r];if(void 0===n)return e.delegate=null,"throw"===r&&t.iterator.return&&(e.method="return",e.arg=void 0,L(t,e),"throw"===e.method)||"return"!==r&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+r+"' method")),h;var o=s(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,h;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function E(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function S(t){if(t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return o.next=o}}return{next:k}}function k(){return{value:void 0,done:!0}}return v.prototype=d,o(w,"constructor",{value:d,configurable:!0}),o(d,"constructor",{value:v,configurable:!0}),v.displayName=f(d,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===v||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,f(t,u,"GeneratorFunction")),t.prototype=Object.create(w),t},t.awrap=function(t){return{__await:t}},b(_.prototype),f(_.prototype,c,(function(){return this})),t.AsyncIterator=_,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new _(l(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},b(w),f(w,u,"Generator"),f(w,a,(function(){return this})),f(w,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=S,j.prototype={constructor:j,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),u=r.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),E(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;E(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:S(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function o(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function i(t){return function(){var e=this,r=arguments;return new Promise((function(n,i){var a=t.apply(e,r);function c(t){o(a,n,i,c,u,"next",t)}function u(t){o(a,n,i,c,u,"throw",t)}c(void 0)}))}}function a(){return(a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}exports.default=function(t,o){void 0===o&&(o={lifeTime:0,debounceTimer:1e3,async:!1});var c=a({____timeOfCreation:Date.now()},o.initialCache),u=o.onDataUpdate?e((function(){try{null==o.onDataUpdate||o.onDataUpdate(c)}catch(t){o.debug&&console.error(t)}}),o.debounceTimer):void 0,f=function(){0!==o.lifeTime&&Date.now()-c.____timeOfCreation>o.lifeTime&&(c={____timeOfCreation:c.____timeOfCreation})},l=function(t,e){return f(),e in c||(c[e]=t(),null==u||u()),c[e]},s=function(){var t=i(n().mark((function t(e,r){return n().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(f(),!(r in c)){t.next=3;break}return t.abrupt("return",c[r]);case 3:return t.next=5,e();case 5:return c[r]=t.sent,null==u||u(),t.abrupt("return",c[r]);case 8:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}();if(o.async||r.types.isAsyncFunction(t))return i(n().mark((function e(){var r,o,i,a=arguments;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(r=a.length,o=new Array(r),i=0;i<r;i++)o[i]=a[i];return e.next=3,s((function(){return t.apply(void 0,o)}),o.join(","));case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e)})));var h=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];return l(t.apply(void 0,r),r.join(","))};return h.clearCache=function(){c={____timeOfCreation:Date.now()}},h.noCache=function(){return t.apply(void 0,arguments)},h},exports.localStorageCacher=function(t,e){var r=(null==e?void 0:e.localStorage)||window.localStorage;return{initialCache:JSON.parse(r.getItem(t)||"{}"),onDataUpdate:function(e){r.setItem(t,JSON.stringify(e))}}};
//# sourceMappingURL=func-cache.cjs.production.min.js.map

@@ -360,24 +360,3 @@ import debounce from 'debounce';

____timeOfCreation: Date.now()
}, options.initialData);
var firstTimeDone = !!options.initialData;
var getData = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _options$getInitialDa;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return (_options$getInitialDa = options.getInitialData()) == null ? void 0 : _options$getInitialDa.then(function (data) {
cached = _extends({}, data, cached);
});
case 2:
case "end":
return _context.stop();
}
}, _callee);
}));
return function getData() {
return _ref.apply(this, arguments);
};
}();
}, options.initialCache);
var updateData = options.onDataUpdate ? debounce(function () {

@@ -405,51 +384,42 @@ try {

var asyncCache = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(getnewval, str) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(getnewval, str) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (firstTimeDone) {
_context2.next = 4;
break;
}
_context2.next = 3;
return getData();
case 3:
firstTimeDone = true;
case 4:
checkExpiry();
if (!(str in cached)) {
_context2.next = 7;
_context.next = 3;
break;
}
return _context2.abrupt("return", cached[str]);
case 7:
_context2.next = 9;
return _context.abrupt("return", cached[str]);
case 3:
_context.next = 5;
return getnewval();
case 9:
cached[str] = _context2.sent;
case 5:
cached[str] = _context.sent;
updateData == null ? void 0 : updateData();
return _context2.abrupt("return", cached[str]);
case 12:
return _context.abrupt("return", cached[str]);
case 8:
case "end":
return _context2.stop();
return _context.stop();
}
}, _callee2);
}, _callee);
}));
return function asyncCache(_x, _x2) {
return _ref2.apply(this, arguments);
return _ref.apply(this, arguments);
};
}();
if (options.async || util.types.isAsyncFunction(func)) {
return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _len,
args,
_key,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
for (_len = _args3.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = _args3[_key];
for (_len = _args2.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = _args2[_key];
}
_context3.next = 3;
_context2.next = 3;
return asyncCache(function () {

@@ -459,8 +429,8 @@ return func.apply(void 0, args);

case 3:
return _context3.abrupt("return", _context3.sent);
return _context2.abrupt("return", _context2.sent);
case 4:
case "end":
return _context3.stop();
return _context2.stop();
}
}, _callee3);
}, _callee2);
}));

@@ -467,0 +437,0 @@ }

@@ -1,1 +0,4 @@

export declare function fSCacher(tmpPath: string): Partial<FCOptions>;
export default function fSCacher(tmpPath: string): {
initialCache: any;
onDataUpdate: (ndata: any) => Promise<void>;
};
import redis from 'redis';
export declare function redisCacher(tmpPath: string, options: {
export default function redisCacher(tmpPath: string, options: {
client: redis.RedisClientType;
}): Partial<FCOptions>;
import redis from '@upstash/redis';
export declare function upstashCacher(tmpPath: string, options: {
export default function upstashCacher(tmpPath: string, options: {
client: redis.Redis;
}): Partial<FCOptions>;
{
"name": "func-cache",
"version": "2.0.73",
"private": false,
"version": "2.0.74",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"description": "TypeScript library for caching static functions",
"keywords": [
"cache",
"function",
"simple",
"redis",
"memory",
"upstash"
"files": [
"dist/**/*",
"src/**/*"
],
"engines": {
"node": ">=10"
},
"repository": {

@@ -18,29 +19,37 @@ "type": "git",

},
"license": "MIT",
"author": "haouarihk",
"sideEffects": false,
"main": "dist/index.js",
"module": "dist/func-cache.esm.js",
"typings": "dist/index.d.ts",
"files": [
"src/*",
"dist/*",
"src/tools/*",
"dist/tools/*",
"LICENSE",
"README.md"
],
"scripts": {
"start": "tsdx watch",
"build": "tsdx build",
"format": "tsdx lint src --fix",
"lint": "tsdx lint src",
"test": "tsdx test",
"lint": "tsdx lint",
"prepare": "tsdx build",
"semantic-release": "semantic-release",
"start": "tsdx watch",
"test": "tsdx test"
"size": "size-limit",
"analyze": "size-limit --why"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"trailingComma": "all"
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"author": "haouarihk",
"module": "dist/funcache.esm.js",
"size-limit": [
{
"path": "dist/funcache.cjs.production.min.js",
"limit": "10 KB"
},
{
"path": "dist/funcache.esm.js",
"limit": "10 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^8.2.4",
"@types/debounce": "^1.2.1",

@@ -51,71 +60,8 @@ "@types/node": "^18.15.10",

"aforwait": "^1.2.0",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jest": "24.3.6",
"prettier-plugin-packagejson": "2.2.11",
"semantic-release": "17.2.4",
"semantic-release-cli": "5.4.3",
"husky": "^8.0.3",
"size-limit": "^8.2.4",
"tsdx": "^0.14.1",
"tslib": "^2.3.1",
"tslib": "^2.5.0",
"typescript": "^5.0.4"
},
"peerDependencies": {},
"engines": {
"node": ">=12"
},
"eslint": {
"env": {
"es6": true,
"jest": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2019,
"sourceType": "module"
},
"extends": [
"eslint:recommended",
"plugin:jest/recommended",
"plugin:import/recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"arrow-body-style": [
"error",
"always"
],
"curly": "error",
"import/order": [
"error",
{
"newlines-between": "always"
}
]
},
"settings": {
"import/extensions": [
".ts"
],
"import/resolver": {
"node": {
"extensions": [
".ts"
]
}
}
}
},
"renovate": {
"extends": [
"config:js-lib",
":automergePatch",
":automergeBranch",
":automergePatch",
":automergeBranch",
":automergeLinters",
":automergeTesters",
":automergeTypes"
]
},
"dependencies": {

@@ -153,2 +99,2 @@ "@upstash/redis": "^1.20.3",

}
}
}

@@ -1,67 +0,103 @@

# Fun cache
# TSDX User Guide
This is the fun and cache.
Congrats! You just saved yourself hours of work by bootstrapping this project with TSDX. Let’s get you oriented with what’s here and how to use it.
# How does it work:
> This TSDX setup is meant for developing libraries (not apps!) that can be published to NPM. If you’re looking to build a Node app, you could use `ts-node-dev`, plain `ts-node`, or simple `tsc`.
It stores a map of results of a function and uses arguments as keys, for faster response,
> If you’re new to TypeScript, checkout [this handy cheatsheet](https://devhints.io/typescript)
Note that if the function result in different results with the same argument, the cache wouldn't work.
## Commands
# How to use:
TSDX scaffolds your new library inside `/src`.
```ts
import funcache from "func-cache";
To run TSDX, use:
const cachedFibonacci = funcache((num: number) => {
// ... your function here
}, options); // about the options, see below
```bash
npm start # or yarn start
```
This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`.
console.log(cachedFibonacci(1000)); //-- viewing the result
To do a one-off build, use `npm run build` or `yarn build`.
console.log(cachedFibonacci.noCache(1000)); //-- run without caching
To run tests, use `npm test` or `yarn test`.
console.log(cachedFibonacci.clearCache()); //-- to clear the cache
## Configuration
Code quality is set up for you with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields in `package.json` accordingly.
### Jest
Jest tests are set up to run with `npm test` or `yarn test`.
### Bundle Analysis
[`size-limit`](https://github.com/ai/size-limit) is set up to calculate the real cost of your library with `npm run size` and visualize the bundle with `npm run analyze`.
#### Setup Files
This is the folder structure we set up for you:
```txt
/src
index.tsx # EDIT THIS
/test
blah.test.tsx # EDIT THIS
.gitignore
package.json
README.md # EDIT THIS
tsconfig.json
```
### Rollup
# Options:
TSDX uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details.
```ts
import fSCacher from "func-cache/tools/fs"; // only for server
import redisCacher from "func-cache/tools/redis"; // only for server
import upstashCacher from "func-cache/tools/upstash"; // only for server
### TypeScript
import funcache, { localStorageCacher } from "func-cache";
`tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your needs.
const options = {
// (1 sec) in miliseconds
lifeTime: 1000,
## Continuous Integration
/** debounce time wait to call onDataUpdate, default 1000ms */
debounceTimer: 200,
### GitHub Actions
/** incase the call is async, (sometimes the script doesn't detect it's async and wont run the await for it) default: false */
async: true,
Two actions are added by default:
- `main` which installs deps w/ cache, lints, tests, and builds on all pushes against a Node and OS matrix
- `size` which comments cost comparison of your library on every pull request using [`size-limit`](https://github.com/ai/size-limit)
// place to store the cache, incase of restarts (browser only)
...localStorageCacher("_cachePlace_for_fibonacci"),
## Optimizations
// place to store the cache, incase of restarts (server only). fs way
...fSCacher("./_cachePlace_for_fibonacci.json"),
Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know that you can take advantage of development-only optimizations:
// place to store the cache, incase of restarts (server only). redis way
...redisCacher("_cachePlace_for_fibonacci", {
client: redisClient,
}),
```js
// ./types/index.d.ts
declare var __DEV__: boolean;
// place to store the cache, incase of restarts (server only). upstash way
...upstashCacher("_cachePlace_for_fibonacci", {
client: upstashClient,
}),
};
// inside your code...
if (__DEV__) {
console.log('foo');
}
```
```
You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant) and [warning](https://github.com/palmerhq/tsdx#warning) functions.
## Module Formats
CJS, ESModules, and UMD module formats are supported.
The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found.
## Named Exports
Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library.
## Including Styles
There are many ways to ship styles, including with CSS-in-JS. TSDX has no opinion on this, configure how you like.
For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so that it can be imported separately by your users and run through their bundler's loader.
## Publishing to NPM
We recommend using [np](https://github.com/sindresorhus/np).
interface FCOptions {
lifeTime: number;
/** incase you want to save the data somewhere else and it's async */
onDataUpdate?: (nData: any) => Promise<void>;
onDataUpdate?: (nData: any) => void;
/** incase you want to get the initial data from somewhere else */
getInitialData?: any;
getCache?: () => Promise<object>;
initialCache?: object;
initialData?: any;
/** debounce time wait to call onDataUpdate, default 1000ms */

@@ -20,2 +17,2 @@ debounceTimer?: number;

debug?: boolean;
}
}

@@ -6,74 +6,62 @@ import debounce from "debounce";

export default function funCache<T extends Function>(func: T, options: FCOptions = { lifeTime: 0, debounceTimer: 1000, async: false }): T & { clearCache: () => void } {
let cached: any = {
____timeOfCreation: Date.now(),
...options.initialData,
};
let cached: any = {
____timeOfCreation: Date.now(),
...options.initialCache
};
let firstTimeDone = !!options.initialData;
const getData = async () => {
await options.getInitialData()?.then((data: any) => {
cached = { ...data, ...cached };
})
const updateData = options.onDataUpdate ? debounce(() => {
try {
options.onDataUpdate?.(cached);
} catch (err) {
if (options.debug) {
console.error(err)
}
}
}, options.debounceTimer) : undefined;
const updateData = options.onDataUpdate ? debounce(() => {
try {
options.onDataUpdate?.(cached);
} catch (err) {
if (options.debug) {
console.error(err)
}
}
}, options.debounceTimer) : undefined;
const checkExpiry = () => {
if (options.lifeTime !== 0 && Date.now() - cached.____timeOfCreation > options.lifeTime)
cached = { ____timeOfCreation: cached.____timeOfCreation }
}
const checkExpiry = () => {
if (options.lifeTime !== 0 && Date.now() - cached.____timeOfCreation > options.lifeTime)
cached = { ____timeOfCreation: cached.____timeOfCreation }
}
const cache = (getnewval: Function, str: any) => {
checkExpiry();
const cache = (getnewval: Function, str: any) => {
checkExpiry();
if (str in cached) return cached[str];
cached[str] = getnewval();
if (str in cached) return cached[str];
cached[str] = getnewval();
updateData?.();
updateData?.();
return cached[str]
}
return cached[str]
}
const asyncCache = async (getnewval: Function, str: any) => {
checkExpiry();
const asyncCache = async (getnewval: Function, str: any) => {
if (!firstTimeDone) {
await getData();
firstTimeDone = true;
}
if (str in cached) return cached[str];
cached[str] = await getnewval();
checkExpiry();
updateData?.();
if (str in cached) return cached[str];
cached[str] = await getnewval();
return cached[str]
}
updateData?.();
if (options.async || util.types.isAsyncFunction(func)) {
return (async (...args: any) =>
await asyncCache(() => func(...args), args.join(","))
) as any
}
return cached[str]
}
const cachedFN = ((...args: any) =>
cache(func(...args), args.join(","))
) as any;
if (options.async || util.types.isAsyncFunction(func)) {
return (async (...args: any) =>
await asyncCache(() => func(...args), args.join(","))
) as any
}
cachedFN.clearCache = () => {
cached = { ____timeOfCreation: Date.now() }
}
const cachedFN = ((...args: any) =>
cache(func(...args), args.join(","))
) as any;
cachedFN.noCache = (...args: any) => func(...args);
cachedFN.clearCache = () => {
cached = { ____timeOfCreation: Date.now() }
}
cachedFN.noCache = (...args: any) => func(...args);
return cachedFN;
return cachedFN;
}

@@ -84,11 +72,11 @@

export function localStorageCacher(tmpPath: string, options?: { localStorage?: Storage }) {
const ls = options?.localStorage || window.localStorage;
return {
initialCache: JSON.parse(
ls.getItem(tmpPath) || "{}"
),
onDataUpdate: (ndata: any) => {
ls.setItem(tmpPath, JSON.stringify(ndata))
},
};
const ls = options?.localStorage || window.localStorage;
return {
initialCache: JSON.parse(
ls.getItem(tmpPath) || "{}"
),
onDataUpdate: (ndata: any) => {
ls.setItem(tmpPath, JSON.stringify(ndata))
},
};
}

@@ -5,6 +5,7 @@ import fs from "fs/promises";

export function fSCacher(tmpPath: string): Partial<FCOptions> {
export default function fSCacher(tmpPath: string) {
return {
initialData: JSON.parse(
initialCache: JSON.parse(
// @ts-ignore
existsSync(tmpPath)

@@ -11,0 +12,0 @@ ? readFileSync(tmpPath, {

import redis from 'redis';
export function redisCacher(tmpPath: string, options: { client: redis.RedisClientType }): Partial<FCOptions> {
export default function redisCacher(tmpPath: string, options: { client: redis.RedisClientType }): Partial<FCOptions> {
const red = options.client;
return {
getInitialData: async () => JSON.parse(
await red.get(tmpPath) || "{}"
),
async getCache() {
return JSON.parse(
await red.get(tmpPath) || "{}"
)
},
onDataUpdate: async (ndata: any) => {

@@ -11,0 +13,0 @@ await red.set(tmpPath, JSON.stringify(ndata))

import redis from '@upstash/redis';
export function upstashCacher(tmpPath: string, options: { client: redis.Redis }): Partial<FCOptions> {
export default function upstashCacher(tmpPath: string, options: { client: redis.Redis }): Partial<FCOptions> {
const red = options.client;
return {
getInitialData: async () => JSON.parse(
await red.get(tmpPath) || "{}"
),
async getCache() {
return JSON.parse(
await red.get(tmpPath) || "{}"
)
},
onDataUpdate: async (ndata: any) => {

@@ -11,0 +13,0 @@ await red.set(tmpPath, JSON.stringify(ndata))

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc