@gorgonjs/gorgon 1.5.1 → 1.6.1

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.
@@ -1,196 +0,0 @@
1
- /* eslint-disable */
2
- var addSorting = (function() {
3
- 'use strict';
4
- var cols,
5
- currentSort = {
6
- index: 0,
7
- desc: false
8
- };
9
-
10
- // returns the summary table element
11
- function getTable() {
12
- return document.querySelector('.coverage-summary');
13
- }
14
- // returns the thead element of the summary table
15
- function getTableHeader() {
16
- return getTable().querySelector('thead tr');
17
- }
18
- // returns the tbody element of the summary table
19
- function getTableBody() {
20
- return getTable().querySelector('tbody');
21
- }
22
- // returns the th element for nth column
23
- function getNthColumn(n) {
24
- return getTableHeader().querySelectorAll('th')[n];
25
- }
26
-
27
- function onFilterInput() {
28
- const searchValue = document.getElementById('fileSearch').value;
29
- const rows = document.getElementsByTagName('tbody')[0].children;
30
- for (let i = 0; i < rows.length; i++) {
31
- const row = rows[i];
32
- if (
33
- row.textContent
34
- .toLowerCase()
35
- .includes(searchValue.toLowerCase())
36
- ) {
37
- row.style.display = '';
38
- } else {
39
- row.style.display = 'none';
40
- }
41
- }
42
- }
43
-
44
- // loads the search box
45
- function addSearchBox() {
46
- var template = document.getElementById('filterTemplate');
47
- var templateClone = template.content.cloneNode(true);
48
- templateClone.getElementById('fileSearch').oninput = onFilterInput;
49
- template.parentElement.appendChild(templateClone);
50
- }
51
-
52
- // loads all columns
53
- function loadColumns() {
54
- var colNodes = getTableHeader().querySelectorAll('th'),
55
- colNode,
56
- cols = [],
57
- col,
58
- i;
59
-
60
- for (i = 0; i < colNodes.length; i += 1) {
61
- colNode = colNodes[i];
62
- col = {
63
- key: colNode.getAttribute('data-col'),
64
- sortable: !colNode.getAttribute('data-nosort'),
65
- type: colNode.getAttribute('data-type') || 'string'
66
- };
67
- cols.push(col);
68
- if (col.sortable) {
69
- col.defaultDescSort = col.type === 'number';
70
- colNode.innerHTML =
71
- colNode.innerHTML + '<span class="sorter"></span>';
72
- }
73
- }
74
- return cols;
75
- }
76
- // attaches a data attribute to every tr element with an object
77
- // of data values keyed by column name
78
- function loadRowData(tableRow) {
79
- var tableCols = tableRow.querySelectorAll('td'),
80
- colNode,
81
- col,
82
- data = {},
83
- i,
84
- val;
85
- for (i = 0; i < tableCols.length; i += 1) {
86
- colNode = tableCols[i];
87
- col = cols[i];
88
- val = colNode.getAttribute('data-value');
89
- if (col.type === 'number') {
90
- val = Number(val);
91
- }
92
- data[col.key] = val;
93
- }
94
- return data;
95
- }
96
- // loads all row data
97
- function loadData() {
98
- var rows = getTableBody().querySelectorAll('tr'),
99
- i;
100
-
101
- for (i = 0; i < rows.length; i += 1) {
102
- rows[i].data = loadRowData(rows[i]);
103
- }
104
- }
105
- // sorts the table using the data for the ith column
106
- function sortByIndex(index, desc) {
107
- var key = cols[index].key,
108
- sorter = function(a, b) {
109
- a = a.data[key];
110
- b = b.data[key];
111
- return a < b ? -1 : a > b ? 1 : 0;
112
- },
113
- finalSorter = sorter,
114
- tableBody = document.querySelector('.coverage-summary tbody'),
115
- rowNodes = tableBody.querySelectorAll('tr'),
116
- rows = [],
117
- i;
118
-
119
- if (desc) {
120
- finalSorter = function(a, b) {
121
- return -1 * sorter(a, b);
122
- };
123
- }
124
-
125
- for (i = 0; i < rowNodes.length; i += 1) {
126
- rows.push(rowNodes[i]);
127
- tableBody.removeChild(rowNodes[i]);
128
- }
129
-
130
- rows.sort(finalSorter);
131
-
132
- for (i = 0; i < rows.length; i += 1) {
133
- tableBody.appendChild(rows[i]);
134
- }
135
- }
136
- // removes sort indicators for current column being sorted
137
- function removeSortIndicators() {
138
- var col = getNthColumn(currentSort.index),
139
- cls = col.className;
140
-
141
- cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
142
- col.className = cls;
143
- }
144
- // adds sort indicators for current column being sorted
145
- function addSortIndicators() {
146
- getNthColumn(currentSort.index).className += currentSort.desc
147
- ? ' sorted-desc'
148
- : ' sorted';
149
- }
150
- // adds event listeners for all sorter widgets
151
- function enableUI() {
152
- var i,
153
- el,
154
- ithSorter = function ithSorter(i) {
155
- var col = cols[i];
156
-
157
- return function() {
158
- var desc = col.defaultDescSort;
159
-
160
- if (currentSort.index === i) {
161
- desc = !currentSort.desc;
162
- }
163
- sortByIndex(i, desc);
164
- removeSortIndicators();
165
- currentSort.index = i;
166
- currentSort.desc = desc;
167
- addSortIndicators();
168
- };
169
- };
170
- for (i = 0; i < cols.length; i += 1) {
171
- if (cols[i].sortable) {
172
- // add the click event handler on the th so users
173
- // dont have to click on those tiny arrows
174
- el = getNthColumn(i).querySelector('.sorter').parentElement;
175
- if (el.addEventListener) {
176
- el.addEventListener('click', ithSorter(i));
177
- } else {
178
- el.attachEvent('onclick', ithSorter(i));
179
- }
180
- }
181
- }
182
- }
183
- // adds sorting functionality to the UI
184
- return function() {
185
- if (!getTable()) {
186
- return;
187
- }
188
- cols = loadColumns();
189
- loadData();
190
- addSearchBox();
191
- addSortIndicators();
192
- enableUI();
193
- };
194
- })();
195
-
196
- window.addEventListener('load', addSorting);
package/index.ts DELETED
@@ -1,317 +0,0 @@
1
- import MemoryCache from './provider/memory';
2
-
3
- export type asyncFunction = () => Promise<any> | (() => any);
4
- export type GorgonHookKey =
5
- | 'settings'
6
- | 'addProvider'
7
- | 'put'
8
- | 'clear'
9
- | 'clearAll'
10
- | 'overwrite'
11
- | 'get'
12
- | 'valueError';
13
- export type GorgonHook = (key: GorgonHookKey, input?: any, output?: any) => void;
14
- export type GorgonSettings = {
15
- debug: boolean;
16
- defaultProvider: string;
17
- retry: number;
18
- };
19
- export type GorgonSettingsInput = {
20
- debug?: boolean;
21
- defaultProvider?: string;
22
- retry?: number;
23
- };
24
- export type GorgonPolicy = {
25
- expiry: number | Date | false;
26
- provider: string;
27
- };
28
- export type GorgonPolicyInput = GorgonPolicy | number | Date;
29
- export type GorgonPolicySanitized = {
30
- expiry: number | false;
31
- provider: string;
32
- };
33
- type GorgonCurrentTaskItem = Array<{
34
- res?: any;
35
- rej?: any;
36
- queued: Date;
37
- }>;
38
- export interface IGorgonCacheProvider {
39
- init: () => Promise<void>;
40
- get: (key: string) => Promise<any>;
41
- set: <R>(key: string, value: R, policy: GorgonPolicySanitized) => Promise<R>;
42
- clear: (key?: string) => Promise<boolean>;
43
- keys: () => Promise<string[]>;
44
- }
45
-
46
- const Gorgon = (() => {
47
- const currentTasks = {} as { [key: string]: GorgonCurrentTaskItem };
48
- const hOP = currentTasks.hasOwnProperty;
49
-
50
- const settings = {
51
- debug: false,
52
- defaultProvider: 'memory',
53
- retry: 5000,
54
- } as GorgonSettings;
55
-
56
- const policyMaker = function (incPolicy?: GorgonPolicyInput) {
57
- const outPolicy = {
58
- expiry: false,
59
- provider: settings.defaultProvider,
60
- } as GorgonPolicySanitized;
61
-
62
- // Blank policy, false, or no policy. lets store forever
63
- if (!incPolicy) {
64
- return outPolicy;
65
- }
66
-
67
- // Type is a full policy object
68
- if (incPolicy instanceof Date) {
69
- var d = new Date();
70
-
71
- outPolicy.expiry = Math.ceil((incPolicy.getTime() - d.getTime()) / 1000);
72
- } else if (typeof incPolicy === 'object' && incPolicy.expiry) {
73
- if (incPolicy.expiry instanceof Date) {
74
- outPolicy.expiry = Math.ceil((incPolicy.expiry.getTime() - d.getTime()) / 1000);
75
- } else {
76
- outPolicy.expiry = incPolicy.expiry;
77
- }
78
- outPolicy.provider = incPolicy.provider || outPolicy.provider;
79
- } else if (typeof incPolicy === 'object') {
80
- outPolicy.provider = incPolicy.provider || outPolicy.provider;
81
- } else if (typeof incPolicy === 'number') {
82
- outPolicy.expiry = incPolicy;
83
- }
84
-
85
- // Number is too small, negative or not a number
86
- outPolicy.expiry = outPolicy.expiry && outPolicy.expiry > 0 ? outPolicy.expiry : false;
87
-
88
- return outPolicy;
89
- };
90
-
91
- const gorgonCore = {
92
- // Providers available for use
93
- providers: {} as { [key: string]: IGorgonCacheProvider },
94
-
95
- // Hooks
96
- hooks: {} as { [key: string]: Array<GorgonHook> },
97
-
98
- _callHooks: (key: GorgonHookKey, input?: any, output?: any) => {
99
- if (hOP.call(gorgonCore.hooks, key)) {
100
- for (var i in gorgonCore.hooks[key]) {
101
- if (typeof gorgonCore.hooks[key][i] === 'function') {
102
- try {
103
- gorgonCore.hooks[key][i](key, input, output);
104
- } catch (e) {
105
- console.error('[Gorgon] Hook error for hook: ' + key, e);
106
- }
107
- }
108
- }
109
- }
110
- },
111
-
112
- // Allows for settings on the gorgon cache
113
- settings: (newSettings?: GorgonSettingsInput) => {
114
- if (!newSettings) {
115
- return settings;
116
- }
117
-
118
- Object.assign(settings, newSettings); // only overwrite ones sent in; keep others at existing
119
-
120
- gorgonCore._callHooks('settings', newSettings, settings);
121
-
122
- return settings;
123
- },
124
-
125
- // add a hook or array of hooks
126
- addHook: (key: GorgonHookKey, hook: GorgonHook | Array<GorgonHook>) => {
127
- if (!hOP.call(gorgonCore.hooks, key)) {
128
- gorgonCore.hooks[key] = [];
129
- }
130
-
131
- if (Array.isArray(hook)) {
132
- gorgonCore.hooks[key] = gorgonCore.hooks[key].concat(hook);
133
- } else {
134
- gorgonCore.hooks[key].push(hook);
135
- }
136
- },
137
-
138
- // Add a provider
139
- addProvider: (name: string, provider: IGorgonCacheProvider) => {
140
- provider.init(); // Trigger for provider to clear any old cache items or any other cleanup
141
- gorgonCore.providers[name] = provider;
142
-
143
- gorgonCore._callHooks('addProvider', { name, provider });
144
- },
145
-
146
- // Place an item into the cache
147
- put: async <R>(key: string, value: R, policy?: GorgonPolicyInput): Promise<R> => {
148
- policy = policyMaker(policy);
149
- var prov = gorgonCore.providers[policy.provider];
150
-
151
- gorgonCore._callHooks('put', { key, value, policy }, value);
152
-
153
- return prov.set(key, value, policyMaker(policy));
154
- },
155
-
156
- // Clear one or all items in the cache
157
- clear: async (key: string, provider?: string, hookIdentifier?: string) => {
158
- var prov = gorgonCore.providers[provider || settings.defaultProvider];
159
-
160
- gorgonCore._callHooks('clear', { key, provider, identifier: hookIdentifier });
161
-
162
- // Clear a wildcard search of objects
163
- if (key && key.indexOf('*') > -1) {
164
- return prov.keys().then(function (keys) {
165
- var cacheMatchKeys = keys.filter(function (str) {
166
- return new RegExp('^' + key.split('*').join('.*') + '$').test(str);
167
- });
168
-
169
- var clearPromises = cacheMatchKeys.map(prov.clear);
170
- // Incase someone somehow used a wildcard in their cached key (don't do this)
171
-
172
- clearPromises.push(prov.clear(key));
173
- return Promise.all(clearPromises);
174
- });
175
- }
176
-
177
- // Not a special clear
178
- return prov.clear(key);
179
- },
180
-
181
- // Clear all keys/values in the cache
182
- clearAll: async (provider?: string, hookIdentifier?: string) => {
183
- var prov = gorgonCore.providers[provider || settings.defaultProvider];
184
-
185
- gorgonCore._callHooks('clearAll', { provider, identifier: hookIdentifier });
186
-
187
- return prov.clear();
188
- },
189
-
190
- // Allows you to instantly overwite a cache object
191
- overwrite: async (key: string, asyncFunc: asyncFunction, policy?: GorgonPolicyInput) => {
192
- try {
193
- const resolvedData = await asyncFunc();
194
-
195
- const val = await gorgonCore.put(key, resolvedData, policyMaker(policy));
196
-
197
- gorgonCore._callHooks('overwrite', { key, asyncFunc, policy }, val);
198
-
199
- return val;
200
- } catch (e) {
201
- throw e;
202
- }
203
- },
204
-
205
- // Allows you to get from the cache or pull from the promise
206
- get: async <R>(key: string, asyncFunc: () => R, policy?: GorgonPolicyInput): Promise<R> => {
207
- policy = policyMaker(policy);
208
- const prov = gorgonCore.providers[policy.provider];
209
-
210
- const currentVal = await prov.get(key); // Most providers will only lookup by key and return false on not found
211
-
212
- // If we have a current value sent it out; cache hit!
213
- if (currentVal !== undefined) {
214
- if (settings.debug) {
215
- console.info('[Gorgon] Cache hit for key: ' + key, currentVal);
216
- }
217
-
218
- gorgonCore._callHooks('get', { key, asyncFunc, policy, cacheHit: true, queued: false }, currentVal);
219
-
220
- return currentVal;
221
- }
222
-
223
- // Are we currently already running this cache item?
224
- if (hOP.call(currentTasks, key) && Array.isArray(currentTasks[key]) && currentTasks[key].length > 0) {
225
- // Add to the current task, but ignore if any items is below retry anyway threshold
226
- var oldQueue = false;
227
-
228
- for (var i in currentTasks[key]) {
229
- if (currentTasks[key][i].queued < new Date(Date.now() - settings.retry)) {
230
- oldQueue = true;
231
- }
232
- }
233
-
234
- // Add to the current queue
235
- if (!oldQueue) {
236
- if (settings.debug) {
237
- console.info('[Gorgon] Cache miss, in progress, adding to current queue for key: ' + key);
238
- }
239
-
240
- var concurent = new Promise(function (resolve: (value: R) => void, reject) {
241
- currentTasks[key].push({
242
- res: resolve,
243
- rej: reject,
244
- queued: new Date(),
245
- });
246
- });
247
-
248
- gorgonCore._callHooks('get', { key, asyncFunc, policy, cacheHit: false, queued: true }, concurent);
249
-
250
- return concurent;
251
- }
252
- } else {
253
- // Add current task to list, this is the first one so the primary
254
- currentTasks[key] = [{ queued: new Date() }];
255
- }
256
-
257
- try {
258
- if (settings.debug) {
259
- console.info('[Gorgon] Cache miss, resolving item for: ' + key);
260
- }
261
-
262
- // This is the primary item
263
- const resolver = asyncFunc();
264
-
265
- gorgonCore._callHooks('get', { key, asyncFunc, policy, cacheHit: false, queued: false }, resolver);
266
-
267
- // wait for it to finish then push it out
268
- const resolvedData = await resolver;
269
-
270
- if (settings.debug) {
271
- console.info('[Gorgon] Cache resolved, resolved item for: ' + key, resolvedData);
272
- }
273
-
274
- const val = await gorgonCore.put(key, resolvedData, policyMaker(policy));
275
-
276
- if (hOP.call(currentTasks, key)) {
277
- for (var i in currentTasks[key]) {
278
- if (currentTasks[key][i].res) {
279
- if (settings.debug) {
280
- console.info('[Gorgon] Cache queue resolved for: ' + key, resolvedData);
281
- }
282
-
283
- currentTasks[key][i].res(val);
284
- }
285
- }
286
-
287
- currentTasks[key] = [];
288
- delete currentTasks[key];
289
- }
290
-
291
- return val;
292
- } catch (e) {
293
- if (hOP.call(currentTasks, key)) {
294
- for (var i in currentTasks[key]) {
295
- if (currentTasks[key][i].rej) {
296
- currentTasks[key][i].rej(e);
297
- }
298
- }
299
-
300
- gorgonCore._callHooks('valueError', { key, asyncFunc, policy, cacheHit: false, queued: false }, e);
301
-
302
- currentTasks[key] = [];
303
- delete currentTasks[key];
304
- }
305
-
306
- throw e;
307
- }
308
- },
309
- };
310
-
311
- gorgonCore.addProvider('memory', MemoryCache()); // Default provider, light weight and simple
312
-
313
- return gorgonCore;
314
- })();
315
-
316
- export { MemoryCache };
317
- export default Gorgon;
@@ -1,98 +0,0 @@
1
- import {IGorgonCacheProvider, GorgonPolicySanitized} from '../index';
2
-
3
- interface IGorgonMemoryCacheProvider extends IGorgonCacheProvider {
4
- _clear: (key:string) => boolean;
5
- }
6
-
7
- // Created as a function to allow for multiple instances of the memory cache, if needed
8
- const MemoryCacheCreator = ():IGorgonMemoryCacheProvider =>{
9
-
10
- const cache = {};
11
- const hOP = cache.hasOwnProperty;
12
-
13
- // Memory cache is about the simplist cache possible, use it as an example
14
- const memoryCache = {
15
-
16
- init: async() => {
17
- // This should be used to update the cache on boot,
18
- // memory cache will be blank on boot by default
19
- return;
20
- },
21
-
22
- get: async(key:string) => {
23
-
24
- if (hOP.call(cache, key) && cache[key].val) {
25
- // The cached item exists, return it
26
- return cache[key].val;
27
- } else {
28
- // The cached item does not exist reject
29
- return undefined;
30
- }
31
-
32
- },
33
-
34
- set: async(key:string, value:any, policy: GorgonPolicySanitized) => {
35
-
36
- // Clear in case it exists
37
- await memoryCache.clear(key);
38
-
39
- // Set a timemout to self-remove from the cache if in policy
40
- var to = false as boolean | number;
41
-
42
- if (policy && policy.expiry && policy.expiry > 0) {
43
- to = setTimeout(function() {
44
- memoryCache.clear(key);
45
- }, policy.expiry);
46
- }
47
-
48
- // Store the cached item
49
- cache[key] = {
50
- policy: policy,
51
- val: value,
52
- to: to,
53
- };
54
-
55
- return value;
56
-
57
- },
58
-
59
- keys: async() => {
60
- return Object.keys(cache);
61
- },
62
-
63
- clear: async(key?:string) => {
64
-
65
- // Clears a single key or complete clear on empty
66
- // Clear all items in the cache
67
- if (!key) {
68
- for (var i in cache) {
69
- memoryCache._clear(i);
70
- }
71
- return true;
72
- }
73
-
74
- return memoryCache._clear(key);
75
- },
76
-
77
- _clear: (key:string) => {
78
- // Clear a single item, making sure to remove the extra timeout
79
- if (hOP.call(cache, key)) {
80
- if (cache[key].to) {
81
- clearTimeout(cache[key].to);
82
- }
83
-
84
- cache[key] = null;
85
- delete cache[key];
86
- return true;
87
- }
88
-
89
- return false;
90
- },
91
-
92
- };
93
-
94
- return memoryCache;
95
-
96
- }
97
-
98
- export default MemoryCacheCreator;
package/tsconfig.json DELETED
@@ -1,11 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2020",
4
- "lib": ["es2020", "dom"],
5
- "module": "commonjs",
6
- "outDir": "dist",
7
- "declaration": true,
8
- "esModuleInterop": true
9
- },
10
- "include": ["index.ts", "provider/**/*"]
11
- }
package/vite.config.js DELETED
@@ -1,19 +0,0 @@
1
- // vite.config.ts
2
- const path = require('path');
3
- const {defineConfig} = require('vite');
4
- const dts = require('vite-plugin-dts');
5
-
6
- module.exports = defineConfig({
7
- plugins: [dts({insertTypesEntry: true})],
8
- build: {
9
- sourcemap: true,
10
- lib: {
11
- type: ['es', 'cjs', 'umd'],
12
- entry: path.resolve(__dirname, 'index.ts'),
13
- name: 'Gorgon',
14
- fileName: format => `index.${format}.js`,
15
- },
16
- rollupOptions: {
17
- },
18
- },
19
- });