@merkur/plugin-http-cache 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2020 Vojtěch Šimko SimkoVojta@gmail.com
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ <p align="center">
2
+ <a href="https://merkur.js.org/docs/getting-started" title="Getting started">
3
+ <img src="https://raw.githubusercontent.com/mjancarik/merkur/master/images/merkur-illustration.png" width="100px" height="100px" alt="Merkur illustration"/>
4
+ </a>
5
+ </p>
6
+
7
+ # Merkur
8
+
9
+ [![Build Status](https://github.com/mjancarik/merkur/workflows/CI/badge.svg)](https://github.com/mjancarik/merkur/actions/workflows/ci.yml)
10
+ [![NPM package version](https://img.shields.io/npm/v/@merkur/core/latest.svg)](https://www.npmjs.com/package/@merkur/core)
11
+ ![npm bundle size (scoped version)](https://img.shields.io/bundlephobia/minzip/@merkur/core/latest)
12
+ [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
13
+
14
+ The [Merkur](https://merkur.js.org/) is tiny extensible javascript library for front-end microservices(micro frontends). It allows by default server side rendering for loading performance boost. You can connect it with other frameworks or languages because merkur defines easy API. You can use one of six predefined template's library [React](https://reactjs.org/), [Preact](https://preactjs.com/), [hyperHTML](https://viperhtml.js.org/hyper.html), [µhtml](https://github.com/WebReflection/uhtml#readme), [Svelte](https://svelte.dev/) and [vanilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) but you can easily extend for others.
15
+
16
+ ## Features
17
+ - Flexible templating engine
18
+ - Usable with all tech stacks
19
+ - SSR-ready by default
20
+ - Easy extensible with plugins
21
+ - Tiny - 1 KB minified + gzipped
22
+
23
+ ## Getting started
24
+
25
+ ```bash
26
+ npx @merkur/create-widget <name>
27
+
28
+ cd name
29
+
30
+ npm run dev // Point your browser at http://localhost:4444/
31
+ ```
32
+ ![alt text](https://raw.githubusercontent.com/mjancarik/merkur/master/images/hello-widget.png "Merkur example, hello widget")
33
+ ## Documentation
34
+
35
+ To check out [live demo](https://merkur.js.org/demo) and [docs](https://merkur.js.org/docs), visit [https://merkur.js.org](https://merkur.js.org).
36
+
37
+ ## Contribution
38
+
39
+ Contribute to this project via [Pull-Requests](https://github.com/mjancarik/merkur/pulls).
40
+
41
+ We are following [Conventional Commits Specification](https://www.conventionalcommits.org/en/v1.0.0/#summary). To simplify the commit process, you can use `npm run commit` command. It opens an interactive interface, which should help you with commit message composition.
42
+
43
+ Thank you to all the people who already contributed to Merkur!
44
+
45
+ <a href="https://github.com/mjancarik/merkur/graphs/contributors">
46
+ <img src="https://contrib.rocks/image?repo=mjancarik/merkur" />
47
+ </a>
package/jest.config.js ADDED
@@ -0,0 +1,3 @@
1
+ const defaultConfig = require('../../jest.config.js');
2
+
3
+ module.exports = { ...defaultConfig };
package/lib/index.cjs ADDED
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var core = require('@merkur/core');
6
+ var pluginHttpClient = require('@merkur/plugin-http-client');
7
+
8
+ /**
9
+ * The cache entry is a typed container of cache data used to track the
10
+ * creation and expiration of cache entries.
11
+ */
12
+ class CacheEntry {
13
+ /**
14
+ * Initializes the cache entry.
15
+ *
16
+ * @param {*} value The cache entry value.
17
+ * @param {number} ttl The time to live in milliseconds.
18
+ */
19
+ constructor(value, ttl) {
20
+ this._value = value;
21
+ this._ttl = ttl;
22
+ this._created = Date.now();
23
+ }
24
+
25
+ /**
26
+ * Returns the entry value.
27
+ *
28
+ * @return {*} The entry value.
29
+ */
30
+ get value() {
31
+ return this._value;
32
+ }
33
+
34
+ /**
35
+ * Returns `true` if this entry has expired.
36
+ *
37
+ * @return {boolean} `true` if this entry has expired.
38
+ */
39
+ isExpired() {
40
+ let now = Date.now();
41
+ return now > this._created + this._ttl;
42
+ }
43
+
44
+ /**
45
+ * Exports this cache entry into a JSON-serializable object.
46
+ *
47
+ * @return {{value: *, ttl: number}} This entry exported to a
48
+ * JSON-serializable object.
49
+ */
50
+ serialize() {
51
+ return {
52
+ value: this.value,
53
+ ttl: this._ttl === Infinity ? 'Infinity' : this._ttl,
54
+ };
55
+ }
56
+ }
57
+
58
+ const DEV = 'development';
59
+ const ENV =
60
+ typeof process !== 'undefined' && process && process.env
61
+ ? process.env.NODE_ENV
62
+ : DEV;
63
+
64
+ function getCacheKey({ method, url, body, query }) {
65
+ const data = ~['GET', 'HEAD'].indexOf(method) ? query : body;
66
+ let dataQuery = '';
67
+
68
+ if (data) {
69
+ try {
70
+ dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
71
+ } catch (error) {
72
+ console.warn('The provided data does not have valid JSON format', data);
73
+ }
74
+ }
75
+ return `${method}:${url}?${dataQuery}`;
76
+ }
77
+
78
+ function httpCachePlugin() {
79
+ return {
80
+ async setup(widget) {
81
+ if (ENV === DEV && !widget.$in.httpClient) {
82
+ throw new Error(
83
+ 'You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache'
84
+ );
85
+ }
86
+
87
+ widget = {
88
+ ...httpCacheAPI(),
89
+ ...widget,
90
+ };
91
+
92
+ widget.$in.httpClient.cache = new Map();
93
+
94
+ return widget;
95
+ },
96
+ async create(widget) {
97
+ const { useCache, transferServerCache, ttl } =
98
+ widget.$in.httpClient.defaultConfig;
99
+
100
+ core.bindWidgetToFunctions(widget, widget.httpCache);
101
+
102
+ pluginHttpClient.setDefaultConfig(widget, {
103
+ useCache: useCache ?? true,
104
+ transferServerCache: transferServerCache ?? false,
105
+ ttl: ttl ?? 60000,
106
+ });
107
+
108
+ if (transferServerCache) {
109
+ core.hookMethod(widget, 'info', infoHook);
110
+ if (widget.$httpCache) {
111
+ widget.httpCache.deserialize(widget.$httpCache);
112
+ }
113
+ }
114
+
115
+ return widget;
116
+ },
117
+ };
118
+ }
119
+
120
+ function cacheInTransformer() {
121
+ return {
122
+ async transformResponse(widget, request, response) {
123
+ if (request.useCache && !response.cached) {
124
+ const { cache } = widget.$in.httpClient;
125
+ const cacheEntry = new CacheEntry(pluginHttpClient.copyResponse(response), request.ttl);
126
+ cache.set(getCacheKey(request), cacheEntry);
127
+ }
128
+
129
+ return [request, response];
130
+ },
131
+ };
132
+ }
133
+
134
+ function cacheOutTransformer() {
135
+ return {
136
+ async transformRequest(widget, request, response) {
137
+ if (request.useCache) {
138
+ const cachedResponse = widget.httpCache.get(getCacheKey(request));
139
+
140
+ if (cachedResponse) {
141
+ return [request, { ...cachedResponse, cached: true }];
142
+ }
143
+ }
144
+
145
+ return [request, response];
146
+ },
147
+ };
148
+ }
149
+
150
+ function httpCacheAPI() {
151
+ return {
152
+ httpCache: {
153
+ get(widget, key) {
154
+ const { cache } = widget.$in.httpClient;
155
+ const cacheEntry = cache.get(key);
156
+
157
+ return cacheEntry && !cacheEntry.isExpired()
158
+ ? pluginHttpClient.copyResponse(cacheEntry.value)
159
+ : null;
160
+ },
161
+ serialize(widget) {
162
+ const { cache } = widget.$in.httpClient;
163
+ const serializedData = {};
164
+
165
+ for (const key of cache.keys()) {
166
+ const entry = cache.get(key);
167
+
168
+ if (entry instanceof CacheEntry) {
169
+ serializedData[key] = entry.serialize();
170
+ }
171
+ }
172
+
173
+ return JSON.stringify(serializedData).replace(
174
+ /<\/script/gi,
175
+ '<\\/script'
176
+ );
177
+ },
178
+
179
+ deserialize(widget, serializedData) {
180
+ const { cache } = widget.$in.httpClient;
181
+ let parsedData = {};
182
+
183
+ try {
184
+ parsedData = JSON.parse(serializedData);
185
+ } catch (error) {
186
+ console.warn('Failed to parse http cache data', error);
187
+ }
188
+
189
+ for (const key of Object.keys(parsedData)) {
190
+ let { value, ttl } = parsedData[key];
191
+
192
+ if (ttl === 'Infinity') {
193
+ ttl = Infinity;
194
+ }
195
+
196
+ cache.set(key, new CacheEntry(value, ttl));
197
+ }
198
+ },
199
+ },
200
+ };
201
+ }
202
+
203
+ async function infoHook(widget, originalInfoFn, ...rest) {
204
+ const originalInfo = await originalInfoFn(...rest);
205
+
206
+ return { ...originalInfo, $httpCache: widget.httpCache.serialize() };
207
+ }
208
+
209
+ exports.cacheInTransformer = cacheInTransformer;
210
+ exports.cacheOutTransformer = cacheOutTransformer;
211
+ exports.getCacheKey = getCacheKey;
212
+ exports.httpCachePlugin = httpCachePlugin;
@@ -0,0 +1 @@
1
+ "use strict";function e(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,s=function(){};return{s:s,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,u=!0,a=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return u=e.done,e},e:function(e){a=!0,i=e},f:function(){try{u||null==n.return||n.return()}finally{if(a)throw i}}}}function r(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function t(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function n(e){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?t(Object(n),!0).forEach((function(r){o(e,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))}))}return e}function o(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function s(e,r,t,n,o,s,i){try{var u=e[s](i),a=u.value}catch(e){return void t(e)}u.done?r(a):Promise.resolve(a).then(n,o)}function i(e){return function(){var r=this,t=arguments;return new Promise((function(n,o){var i=e.apply(r,t);function u(e){s(i,n,o,u,a,"next",e)}function a(e){s(i,n,o,u,a,"throw",e)}u(void 0)}))}}function u(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}require("regenerator-runtime/runtime.js"),require("core-js/modules/es.object.define-property.js"),require("core-js/modules/es.date.now.js"),require("core-js/modules/es.date.to-string.js"),require("core-js/modules/es.array.index-of.js"),require("core-js/modules/es.regexp.exec.js"),require("core-js/modules/es.string.replace.js"),require("core-js/modules/es.array.concat.js"),require("core-js/modules/es.array.iterator.js"),require("core-js/modules/es.map.js"),require("core-js/modules/es.object.to-string.js"),require("core-js/modules/es.string.iterator.js"),require("core-js/modules/web.dom-collections.iterator.js"),require("core-js/modules/es.object.keys.js"),require("core-js/modules/es.promise.js"),require("core-js/modules/es.symbol.js"),require("core-js/modules/es.array.filter.js"),require("core-js/modules/es.object.get-own-property-descriptor.js"),require("core-js/modules/es.array.for-each.js"),require("core-js/modules/web.dom-collections.for-each.js"),require("core-js/modules/es.object.get-own-property-descriptors.js"),require("core-js/modules/es.object.define-properties.js"),require("core-js/modules/es.array.slice.js"),require("core-js/modules/es.function.name.js"),require("core-js/modules/es.array.from.js"),require("core-js/modules/es.symbol.description.js"),require("core-js/modules/es.symbol.iterator.js"),require("core-js/modules/es.array.is-array.js"),Object.defineProperty(exports,"__esModule",{value:!0});var a=require("@merkur/core"),c=require("@merkur/plugin-http-client"),l=function(){function e(r,t){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),this._value=r,this._ttl=t,this._created=Date.now()}var r,t,n;return r=e,(t=[{key:"value",get:function(){return this._value}},{key:"isExpired",value:function(){return Date.now()>this._created+this._ttl}},{key:"serialize",value:function(){return{value:this.value,ttl:this._ttl===1/0?"Infinity":this._ttl}}}])&&u(r.prototype,t),n&&u(r,n),Object.defineProperty(r,"prototype",{writable:!1}),e}(),p="development",f="undefined"!=typeof process&&process&&process.env?process.env.NODE_ENV:p;function h(e){var r=e.method,t=e.url,n=e.body,o=e.query,s=~["GET","HEAD"].indexOf(r)?o:n,i="";if(s)try{i=JSON.stringify(s).replace(/<\/script/gi,"<\\/script")}catch(e){console.warn("The provided data does not have valid JSON format",s)}return"".concat(r,":").concat(t,"?").concat(i)}function d(e,r){return m.apply(this,arguments)}function m(){return m=i(regeneratorRuntime.mark((function e(r,t){var o,s,i,u,a=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(o=a.length,s=new Array(o>2?o-2:0),i=2;i<o;i++)s[i-2]=a[i];return e.next=3,t.apply(void 0,s);case 3:return u=e.sent,e.abrupt("return",n(n({},u),{},{$httpCache:r.httpCache.serialize()}));case 5:case"end":return e.stop()}}),e)}))),m.apply(this,arguments)}exports.cacheInTransformer=function(){return{transformResponse:function(e,r,t){return i(regeneratorRuntime.mark((function n(){var o,s;return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return r.useCache&&!t.cached&&(o=e.$in.httpClient.cache,s=new l(c.copyResponse(t),r.ttl),o.set(h(r),s)),n.abrupt("return",[r,t]);case 2:case"end":return n.stop()}}),n)})))()}}},exports.cacheOutTransformer=function(){return{transformRequest:function(e,r,t){return i(regeneratorRuntime.mark((function o(){var s;return regeneratorRuntime.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:if(!r.useCache){o.next=4;break}if(!(s=e.httpCache.get(h(r)))){o.next=4;break}return o.abrupt("return",[r,n(n({},s),{},{cached:!0})]);case 4:return o.abrupt("return",[r,t]);case 5:case"end":return o.stop()}}),o)})))()}}},exports.getCacheKey=h,exports.httpCachePlugin=function(){return{setup:function(r){return i(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(f!==p||r.$in.httpClient){t.next=2;break}throw new Error("You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache");case 2:return(r=n(n({},{httpCache:{get:function(e,r){var t=e.$in.httpClient.cache,n=t.get(r);return n&&!n.isExpired()?c.copyResponse(n.value):null},serialize:function(r){var t,n=r.$in.httpClient.cache,o={},s=e(n.keys());try{for(s.s();!(t=s.n()).done;){var i=t.value,u=n.get(i);u instanceof l&&(o[i]=u.serialize())}}catch(e){s.e(e)}finally{s.f()}return JSON.stringify(o).replace(/<\/script/gi,"<\\/script")},deserialize:function(e,r){var t=e.$in.httpClient.cache,n={};try{n=JSON.parse(r)}catch(e){console.warn("Failed to parse http cache data",e)}for(var o=0,s=Object.keys(n);o<s.length;o++){var i=s[o],u=n[i],a=u.value,c=u.ttl;"Infinity"===c&&(c=1/0),t.set(i,new l(a,c))}}}}),r)).$in.httpClient.cache=new Map,t.abrupt("return",r);case 5:case"end":return t.stop()}}),t)})))()},create:function(e){return i(regeneratorRuntime.mark((function r(){var t,n,o,s;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return t=e.$in.httpClient.defaultConfig,n=t.useCache,o=t.transferServerCache,s=t.ttl,a.bindWidgetToFunctions(e,e.httpCache),c.setDefaultConfig(e,{useCache:null==n||n,transferServerCache:null!=o&&o,ttl:null!=s?s:6e4}),o&&(a.hookMethod(e,"info",d),e.$httpCache&&e.httpCache.deserialize(e.$httpCache)),r.abrupt("return",e);case 5:case"end":return r.stop()}}),r)})))()}}};
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', {
4
+ value: true
5
+ });
6
+
7
+ var core = require('@merkur/core');
8
+
9
+ var pluginHttpClient = require('@merkur/plugin-http-client');
10
+ /**
11
+ * The cache entry is a typed container of cache data used to track the
12
+ * creation and expiration of cache entries.
13
+ */
14
+
15
+
16
+ class CacheEntry {
17
+ /**
18
+ * Initializes the cache entry.
19
+ *
20
+ * @param {*} value The cache entry value.
21
+ * @param {number} ttl The time to live in milliseconds.
22
+ */
23
+ constructor(value, ttl) {
24
+ this._value = value;
25
+ this._ttl = ttl;
26
+ this._created = Date.now();
27
+ }
28
+ /**
29
+ * Returns the entry value.
30
+ *
31
+ * @return {*} The entry value.
32
+ */
33
+
34
+
35
+ get value() {
36
+ return this._value;
37
+ }
38
+ /**
39
+ * Returns `true` if this entry has expired.
40
+ *
41
+ * @return {boolean} `true` if this entry has expired.
42
+ */
43
+
44
+
45
+ isExpired() {
46
+ let now = Date.now();
47
+ return now > this._created + this._ttl;
48
+ }
49
+ /**
50
+ * Exports this cache entry into a JSON-serializable object.
51
+ *
52
+ * @return {{value: *, ttl: number}} This entry exported to a
53
+ * JSON-serializable object.
54
+ */
55
+
56
+
57
+ serialize() {
58
+ return {
59
+ value: this.value,
60
+ ttl: this._ttl === Infinity ? 'Infinity' : this._ttl
61
+ };
62
+ }
63
+
64
+ }
65
+
66
+ const DEV = 'development';
67
+ const ENV = typeof process !== 'undefined' && process && process.env ? process.env.NODE_ENV : DEV;
68
+
69
+ function getCacheKey({
70
+ method,
71
+ url,
72
+ body,
73
+ query
74
+ }) {
75
+ const data = ~['GET', 'HEAD'].indexOf(method) ? query : body;
76
+ let dataQuery = '';
77
+
78
+ if (data) {
79
+ try {
80
+ dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
81
+ } catch (error) {
82
+ console.warn('The provided data does not have valid JSON format', data);
83
+ }
84
+ }
85
+
86
+ return `${method}:${url}?${dataQuery}`;
87
+ }
88
+
89
+ function httpCachePlugin() {
90
+ return {
91
+ async setup(widget) {
92
+ if (ENV === DEV && !widget.$in.httpClient) {
93
+ throw new Error('You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache');
94
+ }
95
+
96
+ widget = { ...httpCacheAPI(),
97
+ ...widget
98
+ };
99
+ widget.$in.httpClient.cache = new Map();
100
+ return widget;
101
+ },
102
+
103
+ async create(widget) {
104
+ const {
105
+ useCache,
106
+ transferServerCache,
107
+ ttl
108
+ } = widget.$in.httpClient.defaultConfig;
109
+ core.bindWidgetToFunctions(widget, widget.httpCache);
110
+ pluginHttpClient.setDefaultConfig(widget, {
111
+ useCache: useCache !== null && useCache !== void 0 ? useCache : true,
112
+ transferServerCache: transferServerCache !== null && transferServerCache !== void 0 ? transferServerCache : false,
113
+ ttl: ttl !== null && ttl !== void 0 ? ttl : 60000
114
+ });
115
+
116
+ if (transferServerCache) {
117
+ core.hookMethod(widget, 'info', infoHook);
118
+
119
+ if (widget.$httpCache) {
120
+ widget.httpCache.deserialize(widget.$httpCache);
121
+ }
122
+ }
123
+
124
+ return widget;
125
+ }
126
+
127
+ };
128
+ }
129
+
130
+ function cacheInTransformer() {
131
+ return {
132
+ async transformResponse(widget, request, response) {
133
+ if (request.useCache && !response.cached) {
134
+ const {
135
+ cache
136
+ } = widget.$in.httpClient;
137
+ const cacheEntry = new CacheEntry(pluginHttpClient.copyResponse(response), request.ttl);
138
+ cache.set(getCacheKey(request), cacheEntry);
139
+ }
140
+
141
+ return [request, response];
142
+ }
143
+
144
+ };
145
+ }
146
+
147
+ function cacheOutTransformer() {
148
+ return {
149
+ async transformRequest(widget, request, response) {
150
+ if (request.useCache) {
151
+ const cachedResponse = widget.httpCache.get(getCacheKey(request));
152
+
153
+ if (cachedResponse) {
154
+ return [request, { ...cachedResponse,
155
+ cached: true
156
+ }];
157
+ }
158
+ }
159
+
160
+ return [request, response];
161
+ }
162
+
163
+ };
164
+ }
165
+
166
+ function httpCacheAPI() {
167
+ return {
168
+ httpCache: {
169
+ get(widget, key) {
170
+ const {
171
+ cache
172
+ } = widget.$in.httpClient;
173
+ const cacheEntry = cache.get(key);
174
+ return cacheEntry && !cacheEntry.isExpired() ? pluginHttpClient.copyResponse(cacheEntry.value) : null;
175
+ },
176
+
177
+ serialize(widget) {
178
+ const {
179
+ cache
180
+ } = widget.$in.httpClient;
181
+ const serializedData = {};
182
+
183
+ for (const key of cache.keys()) {
184
+ const entry = cache.get(key);
185
+
186
+ if (entry instanceof CacheEntry) {
187
+ serializedData[key] = entry.serialize();
188
+ }
189
+ }
190
+
191
+ return JSON.stringify(serializedData).replace(/<\/script/gi, '<\\/script');
192
+ },
193
+
194
+ deserialize(widget, serializedData) {
195
+ const {
196
+ cache
197
+ } = widget.$in.httpClient;
198
+ let parsedData = {};
199
+
200
+ try {
201
+ parsedData = JSON.parse(serializedData);
202
+ } catch (error) {
203
+ console.warn('Failed to parse http cache data', error);
204
+ }
205
+
206
+ for (const key of Object.keys(parsedData)) {
207
+ let {
208
+ value,
209
+ ttl
210
+ } = parsedData[key];
211
+
212
+ if (ttl === 'Infinity') {
213
+ ttl = Infinity;
214
+ }
215
+
216
+ cache.set(key, new CacheEntry(value, ttl));
217
+ }
218
+ }
219
+
220
+ }
221
+ };
222
+ }
223
+
224
+ async function infoHook(widget, originalInfoFn, ...rest) {
225
+ const originalInfo = await originalInfoFn(...rest);
226
+ return { ...originalInfo,
227
+ $httpCache: widget.httpCache.serialize()
228
+ };
229
+ }
230
+
231
+ exports.cacheInTransformer = cacheInTransformer;
232
+ exports.cacheOutTransformer = cacheOutTransformer;
233
+ exports.getCacheKey = getCacheKey;
234
+ exports.httpCachePlugin = httpCachePlugin;
@@ -0,0 +1,223 @@
1
+ import { bindWidgetToFunctions, hookMethod } from '@merkur/core';
2
+ import { copyResponse, setDefaultConfig } from '@merkur/plugin-http-client';
3
+ /**
4
+ * The cache entry is a typed container of cache data used to track the
5
+ * creation and expiration of cache entries.
6
+ */
7
+
8
+ class CacheEntry {
9
+ /**
10
+ * Initializes the cache entry.
11
+ *
12
+ * @param {*} value The cache entry value.
13
+ * @param {number} ttl The time to live in milliseconds.
14
+ */
15
+ constructor(value, ttl) {
16
+ this._value = value;
17
+ this._ttl = ttl;
18
+ this._created = Date.now();
19
+ }
20
+ /**
21
+ * Returns the entry value.
22
+ *
23
+ * @return {*} The entry value.
24
+ */
25
+
26
+
27
+ get value() {
28
+ return this._value;
29
+ }
30
+ /**
31
+ * Returns `true` if this entry has expired.
32
+ *
33
+ * @return {boolean} `true` if this entry has expired.
34
+ */
35
+
36
+
37
+ isExpired() {
38
+ let now = Date.now();
39
+ return now > this._created + this._ttl;
40
+ }
41
+ /**
42
+ * Exports this cache entry into a JSON-serializable object.
43
+ *
44
+ * @return {{value: *, ttl: number}} This entry exported to a
45
+ * JSON-serializable object.
46
+ */
47
+
48
+
49
+ serialize() {
50
+ return {
51
+ value: this.value,
52
+ ttl: this._ttl === Infinity ? 'Infinity' : this._ttl
53
+ };
54
+ }
55
+
56
+ }
57
+
58
+ const DEV = 'development';
59
+ const ENV = typeof process !== 'undefined' && process && process.env ? process.env.NODE_ENV : DEV;
60
+
61
+ function getCacheKey({
62
+ method,
63
+ url,
64
+ body,
65
+ query
66
+ }) {
67
+ const data = ~['GET', 'HEAD'].indexOf(method) ? query : body;
68
+ let dataQuery = '';
69
+
70
+ if (data) {
71
+ try {
72
+ dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
73
+ } catch (error) {
74
+ console.warn('The provided data does not have valid JSON format', data);
75
+ }
76
+ }
77
+
78
+ return `${method}:${url}?${dataQuery}`;
79
+ }
80
+
81
+ function httpCachePlugin() {
82
+ return {
83
+ async setup(widget) {
84
+ if (ENV === DEV && !widget.$in.httpClient) {
85
+ throw new Error('You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache');
86
+ }
87
+
88
+ widget = { ...httpCacheAPI(),
89
+ ...widget
90
+ };
91
+ widget.$in.httpClient.cache = new Map();
92
+ return widget;
93
+ },
94
+
95
+ async create(widget) {
96
+ const {
97
+ useCache,
98
+ transferServerCache,
99
+ ttl
100
+ } = widget.$in.httpClient.defaultConfig;
101
+ bindWidgetToFunctions(widget, widget.httpCache);
102
+ setDefaultConfig(widget, {
103
+ useCache: useCache !== null && useCache !== void 0 ? useCache : true,
104
+ transferServerCache: transferServerCache !== null && transferServerCache !== void 0 ? transferServerCache : false,
105
+ ttl: ttl !== null && ttl !== void 0 ? ttl : 60000
106
+ });
107
+
108
+ if (transferServerCache) {
109
+ hookMethod(widget, 'info', infoHook);
110
+
111
+ if (widget.$httpCache) {
112
+ widget.httpCache.deserialize(widget.$httpCache);
113
+ }
114
+ }
115
+
116
+ return widget;
117
+ }
118
+
119
+ };
120
+ }
121
+
122
+ function cacheInTransformer() {
123
+ return {
124
+ async transformResponse(widget, request, response) {
125
+ if (request.useCache && !response.cached) {
126
+ const {
127
+ cache
128
+ } = widget.$in.httpClient;
129
+ const cacheEntry = new CacheEntry(copyResponse(response), request.ttl);
130
+ cache.set(getCacheKey(request), cacheEntry);
131
+ }
132
+
133
+ return [request, response];
134
+ }
135
+
136
+ };
137
+ }
138
+
139
+ function cacheOutTransformer() {
140
+ return {
141
+ async transformRequest(widget, request, response) {
142
+ if (request.useCache) {
143
+ const cachedResponse = widget.httpCache.get(getCacheKey(request));
144
+
145
+ if (cachedResponse) {
146
+ return [request, { ...cachedResponse,
147
+ cached: true
148
+ }];
149
+ }
150
+ }
151
+
152
+ return [request, response];
153
+ }
154
+
155
+ };
156
+ }
157
+
158
+ function httpCacheAPI() {
159
+ return {
160
+ httpCache: {
161
+ get(widget, key) {
162
+ const {
163
+ cache
164
+ } = widget.$in.httpClient;
165
+ const cacheEntry = cache.get(key);
166
+ return cacheEntry && !cacheEntry.isExpired() ? copyResponse(cacheEntry.value) : null;
167
+ },
168
+
169
+ serialize(widget) {
170
+ const {
171
+ cache
172
+ } = widget.$in.httpClient;
173
+ const serializedData = {};
174
+
175
+ for (const key of cache.keys()) {
176
+ const entry = cache.get(key);
177
+
178
+ if (entry instanceof CacheEntry) {
179
+ serializedData[key] = entry.serialize();
180
+ }
181
+ }
182
+
183
+ return JSON.stringify(serializedData).replace(/<\/script/gi, '<\\/script');
184
+ },
185
+
186
+ deserialize(widget, serializedData) {
187
+ const {
188
+ cache
189
+ } = widget.$in.httpClient;
190
+ let parsedData = {};
191
+
192
+ try {
193
+ parsedData = JSON.parse(serializedData);
194
+ } catch (error) {
195
+ console.warn('Failed to parse http cache data', error);
196
+ }
197
+
198
+ for (const key of Object.keys(parsedData)) {
199
+ let {
200
+ value,
201
+ ttl
202
+ } = parsedData[key];
203
+
204
+ if (ttl === 'Infinity') {
205
+ ttl = Infinity;
206
+ }
207
+
208
+ cache.set(key, new CacheEntry(value, ttl));
209
+ }
210
+ }
211
+
212
+ }
213
+ };
214
+ }
215
+
216
+ async function infoHook(widget, originalInfoFn, ...rest) {
217
+ const originalInfo = await originalInfoFn(...rest);
218
+ return { ...originalInfo,
219
+ $httpCache: widget.httpCache.serialize()
220
+ };
221
+ }
222
+
223
+ export { cacheInTransformer, cacheOutTransformer, getCacheKey, httpCachePlugin };
package/lib/index.js ADDED
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var core = require('@merkur/core');
6
+ var pluginHttpClient = require('@merkur/plugin-http-client');
7
+
8
+ /**
9
+ * The cache entry is a typed container of cache data used to track the
10
+ * creation and expiration of cache entries.
11
+ */
12
+ class CacheEntry {
13
+ /**
14
+ * Initializes the cache entry.
15
+ *
16
+ * @param {*} value The cache entry value.
17
+ * @param {number} ttl The time to live in milliseconds.
18
+ */
19
+ constructor(value, ttl) {
20
+ this._value = value;
21
+ this._ttl = ttl;
22
+ this._created = Date.now();
23
+ }
24
+
25
+ /**
26
+ * Returns the entry value.
27
+ *
28
+ * @return {*} The entry value.
29
+ */
30
+ get value() {
31
+ return this._value;
32
+ }
33
+
34
+ /**
35
+ * Returns `true` if this entry has expired.
36
+ *
37
+ * @return {boolean} `true` if this entry has expired.
38
+ */
39
+ isExpired() {
40
+ let now = Date.now();
41
+ return now > this._created + this._ttl;
42
+ }
43
+
44
+ /**
45
+ * Exports this cache entry into a JSON-serializable object.
46
+ *
47
+ * @return {{value: *, ttl: number}} This entry exported to a
48
+ * JSON-serializable object.
49
+ */
50
+ serialize() {
51
+ return {
52
+ value: this.value,
53
+ ttl: this._ttl === Infinity ? 'Infinity' : this._ttl,
54
+ };
55
+ }
56
+ }
57
+
58
+ const DEV = 'development';
59
+ const ENV =
60
+ typeof process !== 'undefined' && process && process.env
61
+ ? process.env.NODE_ENV
62
+ : DEV;
63
+
64
+ function getCacheKey({ method, url, body, query }) {
65
+ const data = ~['GET', 'HEAD'].indexOf(method) ? query : body;
66
+ let dataQuery = '';
67
+
68
+ if (data) {
69
+ try {
70
+ dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
71
+ } catch (error) {
72
+ console.warn('The provided data does not have valid JSON format', data);
73
+ }
74
+ }
75
+ return `${method}:${url}?${dataQuery}`;
76
+ }
77
+
78
+ function httpCachePlugin() {
79
+ return {
80
+ async setup(widget) {
81
+ if (ENV === DEV && !widget.$in.httpClient) {
82
+ throw new Error(
83
+ 'You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache'
84
+ );
85
+ }
86
+
87
+ widget = {
88
+ ...httpCacheAPI(),
89
+ ...widget,
90
+ };
91
+
92
+ widget.$in.httpClient.cache = new Map();
93
+
94
+ return widget;
95
+ },
96
+ async create(widget) {
97
+ const { useCache, transferServerCache, ttl } =
98
+ widget.$in.httpClient.defaultConfig;
99
+
100
+ core.bindWidgetToFunctions(widget, widget.httpCache);
101
+
102
+ pluginHttpClient.setDefaultConfig(widget, {
103
+ useCache: useCache ?? true,
104
+ transferServerCache: transferServerCache ?? false,
105
+ ttl: ttl ?? 60000,
106
+ });
107
+
108
+ if (transferServerCache) {
109
+ core.hookMethod(widget, 'info', infoHook);
110
+ if (widget.$httpCache) {
111
+ widget.httpCache.deserialize(widget.$httpCache);
112
+ }
113
+ }
114
+
115
+ return widget;
116
+ },
117
+ };
118
+ }
119
+
120
+ function cacheInTransformer() {
121
+ return {
122
+ async transformResponse(widget, request, response) {
123
+ if (request.useCache && !response.cached) {
124
+ const { cache } = widget.$in.httpClient;
125
+ const cacheEntry = new CacheEntry(pluginHttpClient.copyResponse(response), request.ttl);
126
+ cache.set(getCacheKey(request), cacheEntry);
127
+ }
128
+
129
+ return [request, response];
130
+ },
131
+ };
132
+ }
133
+
134
+ function cacheOutTransformer() {
135
+ return {
136
+ async transformRequest(widget, request, response) {
137
+ if (request.useCache) {
138
+ const cachedResponse = widget.httpCache.get(getCacheKey(request));
139
+
140
+ if (cachedResponse) {
141
+ return [request, { ...cachedResponse, cached: true }];
142
+ }
143
+ }
144
+
145
+ return [request, response];
146
+ },
147
+ };
148
+ }
149
+
150
+ function httpCacheAPI() {
151
+ return {
152
+ httpCache: {
153
+ get(widget, key) {
154
+ const { cache } = widget.$in.httpClient;
155
+ const cacheEntry = cache.get(key);
156
+
157
+ return cacheEntry && !cacheEntry.isExpired()
158
+ ? pluginHttpClient.copyResponse(cacheEntry.value)
159
+ : null;
160
+ },
161
+ serialize(widget) {
162
+ const { cache } = widget.$in.httpClient;
163
+ const serializedData = {};
164
+
165
+ for (const key of cache.keys()) {
166
+ const entry = cache.get(key);
167
+
168
+ if (entry instanceof CacheEntry) {
169
+ serializedData[key] = entry.serialize();
170
+ }
171
+ }
172
+
173
+ return JSON.stringify(serializedData).replace(
174
+ /<\/script/gi,
175
+ '<\\/script'
176
+ );
177
+ },
178
+
179
+ deserialize(widget, serializedData) {
180
+ const { cache } = widget.$in.httpClient;
181
+ let parsedData = {};
182
+
183
+ try {
184
+ parsedData = JSON.parse(serializedData);
185
+ } catch (error) {
186
+ console.warn('Failed to parse http cache data', error);
187
+ }
188
+
189
+ for (const key of Object.keys(parsedData)) {
190
+ let { value, ttl } = parsedData[key];
191
+
192
+ if (ttl === 'Infinity') {
193
+ ttl = Infinity;
194
+ }
195
+
196
+ cache.set(key, new CacheEntry(value, ttl));
197
+ }
198
+ },
199
+ },
200
+ };
201
+ }
202
+
203
+ async function infoHook(widget, originalInfoFn, ...rest) {
204
+ const originalInfo = await originalInfoFn(...rest);
205
+
206
+ return { ...originalInfo, $httpCache: widget.httpCache.serialize() };
207
+ }
208
+
209
+ exports.cacheInTransformer = cacheInTransformer;
210
+ exports.cacheOutTransformer = cacheOutTransformer;
211
+ exports.getCacheKey = getCacheKey;
212
+ exports.httpCachePlugin = httpCachePlugin;
package/lib/index.mjs ADDED
@@ -0,0 +1,205 @@
1
+ import { bindWidgetToFunctions, hookMethod } from '@merkur/core';
2
+ import { copyResponse, setDefaultConfig } from '@merkur/plugin-http-client';
3
+
4
+ /**
5
+ * The cache entry is a typed container of cache data used to track the
6
+ * creation and expiration of cache entries.
7
+ */
8
+ class CacheEntry {
9
+ /**
10
+ * Initializes the cache entry.
11
+ *
12
+ * @param {*} value The cache entry value.
13
+ * @param {number} ttl The time to live in milliseconds.
14
+ */
15
+ constructor(value, ttl) {
16
+ this._value = value;
17
+ this._ttl = ttl;
18
+ this._created = Date.now();
19
+ }
20
+
21
+ /**
22
+ * Returns the entry value.
23
+ *
24
+ * @return {*} The entry value.
25
+ */
26
+ get value() {
27
+ return this._value;
28
+ }
29
+
30
+ /**
31
+ * Returns `true` if this entry has expired.
32
+ *
33
+ * @return {boolean} `true` if this entry has expired.
34
+ */
35
+ isExpired() {
36
+ let now = Date.now();
37
+ return now > this._created + this._ttl;
38
+ }
39
+
40
+ /**
41
+ * Exports this cache entry into a JSON-serializable object.
42
+ *
43
+ * @return {{value: *, ttl: number}} This entry exported to a
44
+ * JSON-serializable object.
45
+ */
46
+ serialize() {
47
+ return {
48
+ value: this.value,
49
+ ttl: this._ttl === Infinity ? 'Infinity' : this._ttl,
50
+ };
51
+ }
52
+ }
53
+
54
+ const DEV = 'development';
55
+ const ENV =
56
+ typeof process !== 'undefined' && process && process.env
57
+ ? process.env.NODE_ENV
58
+ : DEV;
59
+
60
+ function getCacheKey({ method, url, body, query }) {
61
+ const data = ~['GET', 'HEAD'].indexOf(method) ? query : body;
62
+ let dataQuery = '';
63
+
64
+ if (data) {
65
+ try {
66
+ dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
67
+ } catch (error) {
68
+ console.warn('The provided data does not have valid JSON format', data);
69
+ }
70
+ }
71
+ return `${method}:${url}?${dataQuery}`;
72
+ }
73
+
74
+ function httpCachePlugin() {
75
+ return {
76
+ async setup(widget) {
77
+ if (ENV === DEV && !widget.$in.httpClient) {
78
+ throw new Error(
79
+ 'You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache'
80
+ );
81
+ }
82
+
83
+ widget = {
84
+ ...httpCacheAPI(),
85
+ ...widget,
86
+ };
87
+
88
+ widget.$in.httpClient.cache = new Map();
89
+
90
+ return widget;
91
+ },
92
+ async create(widget) {
93
+ const { useCache, transferServerCache, ttl } =
94
+ widget.$in.httpClient.defaultConfig;
95
+
96
+ bindWidgetToFunctions(widget, widget.httpCache);
97
+
98
+ setDefaultConfig(widget, {
99
+ useCache: useCache ?? true,
100
+ transferServerCache: transferServerCache ?? false,
101
+ ttl: ttl ?? 60000,
102
+ });
103
+
104
+ if (transferServerCache) {
105
+ hookMethod(widget, 'info', infoHook);
106
+ if (widget.$httpCache) {
107
+ widget.httpCache.deserialize(widget.$httpCache);
108
+ }
109
+ }
110
+
111
+ return widget;
112
+ },
113
+ };
114
+ }
115
+
116
+ function cacheInTransformer() {
117
+ return {
118
+ async transformResponse(widget, request, response) {
119
+ if (request.useCache && !response.cached) {
120
+ const { cache } = widget.$in.httpClient;
121
+ const cacheEntry = new CacheEntry(copyResponse(response), request.ttl);
122
+ cache.set(getCacheKey(request), cacheEntry);
123
+ }
124
+
125
+ return [request, response];
126
+ },
127
+ };
128
+ }
129
+
130
+ function cacheOutTransformer() {
131
+ return {
132
+ async transformRequest(widget, request, response) {
133
+ if (request.useCache) {
134
+ const cachedResponse = widget.httpCache.get(getCacheKey(request));
135
+
136
+ if (cachedResponse) {
137
+ return [request, { ...cachedResponse, cached: true }];
138
+ }
139
+ }
140
+
141
+ return [request, response];
142
+ },
143
+ };
144
+ }
145
+
146
+ function httpCacheAPI() {
147
+ return {
148
+ httpCache: {
149
+ get(widget, key) {
150
+ const { cache } = widget.$in.httpClient;
151
+ const cacheEntry = cache.get(key);
152
+
153
+ return cacheEntry && !cacheEntry.isExpired()
154
+ ? copyResponse(cacheEntry.value)
155
+ : null;
156
+ },
157
+ serialize(widget) {
158
+ const { cache } = widget.$in.httpClient;
159
+ const serializedData = {};
160
+
161
+ for (const key of cache.keys()) {
162
+ const entry = cache.get(key);
163
+
164
+ if (entry instanceof CacheEntry) {
165
+ serializedData[key] = entry.serialize();
166
+ }
167
+ }
168
+
169
+ return JSON.stringify(serializedData).replace(
170
+ /<\/script/gi,
171
+ '<\\/script'
172
+ );
173
+ },
174
+
175
+ deserialize(widget, serializedData) {
176
+ const { cache } = widget.$in.httpClient;
177
+ let parsedData = {};
178
+
179
+ try {
180
+ parsedData = JSON.parse(serializedData);
181
+ } catch (error) {
182
+ console.warn('Failed to parse http cache data', error);
183
+ }
184
+
185
+ for (const key of Object.keys(parsedData)) {
186
+ let { value, ttl } = parsedData[key];
187
+
188
+ if (ttl === 'Infinity') {
189
+ ttl = Infinity;
190
+ }
191
+
192
+ cache.set(key, new CacheEntry(value, ttl));
193
+ }
194
+ },
195
+ },
196
+ };
197
+ }
198
+
199
+ async function infoHook(widget, originalInfoFn, ...rest) {
200
+ const originalInfo = await originalInfoFn(...rest);
201
+
202
+ return { ...originalInfo, $httpCache: widget.httpCache.serialize() };
203
+ }
204
+
205
+ export { cacheInTransformer, cacheOutTransformer, getCacheKey, httpCachePlugin };
@@ -0,0 +1 @@
1
+ !function(e,t){if("function"==typeof define&&define.amd)define("@merkur/plugin-http-cache",["exports","@merkur/core","@merkur/plugin-http-client"],t);else if("undefined"!=typeof exports)t(exports,require("@merkur/core"),require("@merkur/plugin-http-client"));else{var r={exports:{}};t(r.exports,e.Merkur.Core,e.Merkur.Plugin.Httpclient),e.merkurPluginHttpCache=r.exports}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:this,(function(e,t,r){function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach((function(t){c(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function c(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t,r,n,i,o,c){try{var a=e[o](c),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function u(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function c(e){a(o,n,i,c,u,"next",e)}function u(e){a(o,n,i,c,u,"throw",e)}c(void 0)}))}}function l(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}Object.defineProperty(e,"__esModule",{value:!0}),e.cacheInTransformer=function(){return{transformResponse:function(e,t,n){return u((function*(){if(t.useCache&&!n.cached){var i=e.$in.httpClient.cache,o=new f((0,r.copyResponse)(n),t.ttl);i.set(h(t),o)}return[t,n]}))()}}},e.cacheOutTransformer=function(){return{transformRequest:function(e,t,r){return u((function*(){if(t.useCache){var n=e.httpCache.get(h(t));if(n)return[t,o(o({},n),{},{cached:!0})]}return[t,r]}))()}}},e.getCacheKey=h,e.httpCachePlugin=function(){return{setup:function(e){return u((function*(){if(p===s&&!e.$in.httpClient)throw new Error("You must setup plugin @merkur/plugin-http-client before @merkur/plugin-http-cache");return(e=o(o({},{httpCache:{get:function(e,t){var n=e.$in.httpClient.cache.get(t);return n&&!n.isExpired()?(0,r.copyResponse)(n.value):null},serialize:function(e){var t,r=e.$in.httpClient.cache,i={},o=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var c,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,c=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw c}}}}(r.keys());try{for(o.s();!(t=o.n()).done;){var c=t.value,a=r.get(c);a instanceof f&&(i[c]=a.serialize())}}catch(e){o.e(e)}finally{o.f()}return JSON.stringify(i).replace(/<\/script/gi,"<\\/script")},deserialize:function(e,t){var r=e.$in.httpClient.cache,n={};try{n=JSON.parse(t)}catch(e){console.warn("Failed to parse http cache data",e)}for(var i=0,o=Object.keys(n);i<o.length;i++){var c=o[i],a=n[c],u=a.value,l=a.ttl;"Infinity"===l&&(l=1/0),r.set(c,new f(u,l))}}}}),e)).$in.httpClient.cache=new Map,e}))()},create:function(e){return u((function*(){var n=e.$in.httpClient.defaultConfig,i=n.useCache,o=n.transferServerCache,c=n.ttl;return(0,t.bindWidgetToFunctions)(e,e.httpCache),(0,r.setDefaultConfig)(e,{useCache:null==i||i,transferServerCache:null!=o&&o,ttl:null!=c?c:6e4}),o&&((0,t.hookMethod)(e,"info",y),e.$httpCache&&e.httpCache.deserialize(e.$httpCache)),e}))()}}};var f=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._value=t,this._ttl=r,this._created=Date.now()}var t,r,n;return t=e,(r=[{key:"value",get:function(){return this._value}},{key:"isExpired",value:function(){return Date.now()>this._created+this._ttl}},{key:"serialize",value:function(){return{value:this.value,ttl:this._ttl===1/0?"Infinity":this._ttl}}}])&&l(t.prototype,r),n&&l(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}(),s="development",p="undefined"!=typeof process&&process&&process.env?process.env.NODE_ENV:s;function h(e){var t=e.method,r=e.url,n=e.body,i=e.query,o=~["GET","HEAD"].indexOf(t)?i:n,c="";if(o)try{c=JSON.stringify(o).replace(/<\/script/gi,"<\\/script")}catch(e){console.warn("The provided data does not have valid JSON format",o)}return"".concat(t,":").concat(r,"?").concat(c)}function y(e,t){return v.apply(this,arguments)}function v(){return v=u((function*(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];var c=yield t.apply(void 0,n);return o(o({},c),{},{$httpCache:e.httpCache.serialize()})})),v.apply(this,arguments)}}));
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@merkur/plugin-http-cache",
3
+ "version": "0.29.0",
4
+ "description": "Merkur plugin for maintaining http requests cache.",
5
+ "main": "lib/index",
6
+ "module": "lib/index",
7
+ "unpkg": "lib/index.umd.js",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "import": "./lib/index.mjs",
12
+ "require": "./lib/index.cjs"
13
+ },
14
+ "./lib/index.es9.mjs": "./lib/index.es9.mjs",
15
+ "./lib/index.es9.cjs": "./lib/index.es9.cjs"
16
+ },
17
+ "browser": {
18
+ "./lib/index.js": "./lib/index.es5.js",
19
+ "./lib/index.cjs": "./lib/index.es5.js",
20
+ "./lib/index.mjs": "./lib/index.mjs",
21
+ "./lib/index.es9.mjs": "./lib/index.es9.mjs"
22
+ },
23
+ "scripts": {
24
+ "preversion": "npm test",
25
+ "test": "../../node_modules/.bin/jest --no-watchman -c ./jest.config.js",
26
+ "test:es:version": "../../node_modules/.bin/es-check es5 ./lib/index.es5.js && ../../node_modules/.bin/es-check es11 ./lib/index.mjs --module && ../../node_modules/.bin/es-check es9 ./lib/index.es9.mjs --module && ../../node_modules/.bin/es-check es9 ./lib/index.es9.cjs --module",
27
+ "build": "node_modules/.bin/rollup -c",
28
+ "prepare": "npm run build"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/mjancarik/merkur.git"
33
+ },
34
+ "keywords": [
35
+ "merkur",
36
+ "plugin",
37
+ "microservices",
38
+ "microfrontends"
39
+ ],
40
+ "author": "Vojtěch Šimko",
41
+ "license": "ISC",
42
+ "bugs": {
43
+ "url": "https://github.com/mjancarik/merkur/issues"
44
+ },
45
+ "publishConfig": {
46
+ "registry": "https://registry.npmjs.org/",
47
+ "access": "public"
48
+ },
49
+ "homepage": "https://merkur.js.org/",
50
+ "devDependencies": {
51
+ "@merkur/core": "^0.29.0",
52
+ "@merkur/plugin-component": "^0.29.0",
53
+ "@merkur/plugin-http-client": "^0.29.0",
54
+ "rollup": "^2.70.2"
55
+ },
56
+ "peerDependencies": {
57
+ "@merkur/core": "^0.28.0",
58
+ "@merkur/plugin-http-client": "^0.28.1"
59
+ },
60
+ "gitHead": "ddc13f0ef4d1b18a02461011dae5df49d55f03a6"
61
+ }