-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathServiceBase.mjs
407 lines (352 loc) · 10.8 KB
/
ServiceBase.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import Base from '../core/Base.mjs';
import Message from './Message.mjs';
import RemoteMethodAccess from './mixin/RemoteMethodAccess.mjs';
/**
* @class Neo.worker.ServiceBase
* @extends Neo.core.Base
* @abstract
*/
class ServiceBase extends Base {
static config = {
/**
* @member {String} className='Neo.worker.ServiceBase'
* @protected
*/
className: 'Neo.worker.ServiceBase',
/**
* @member {String} cacheName_='neo-runtime'
*/
cacheName_: 'neo-runtime',
/**
* @member {String[]|Neo.core.Base[]|null} mixins=[RemoteMethodAccess]
*/
mixins: [RemoteMethodAccess],
/**
* Remote method access for other workers
* @member {Object} remote={app: [//...]}
* @protected
*/
remote: {
app: [
'clearCache',
'clearCaches',
'preloadAssets',
'removeAssets'
]
}
}
/**
* @member {String[]} cachePaths
*/
cachePaths = [
'raw.githubusercontent.com/',
'/dist/production/',
'/fontawesome',
'/resources/'
]
/**
* @member {Object[]|null} channelPorts=null
* @protected
*/
channelPorts = null
/**
* @member {Client|null} lastClient=null
* @protected
*/
lastClient = null
/**
* @member {Object[]} promises=[]
* @protected
*/
promises = []
/**
* @member {String[]} remotes=[]
* @protected
*/
remotes = []
/**
* @member {String|null} workerId=null
* @protected
*/
workerId = null
/**
* @param {Object} config
*/
construct(config) {
super.construct(config);
let me = this,
bind = name => me[name].bind(me);
me.channelPorts = [];
Object.assign(globalThis, {
onactivate: bind('onActivate'),
onfetch : bind('onFetch'),
oninstall : bind('onInstall'),
onmessage : bind('onMessage')
});
Neo.currentWorker = me;
Neo.workerId = me.workerId
}
/**
* Triggered when accessing the cacheName config
* @param {String} value
* @protected
*/
beforeGetCacheName(value) {
return value + '-' + this.version
}
/**
* @param {String} name=this.cacheName
* @returns {Promise<Object>}
*/
async clearCache(name=this.cacheName) {
await caches.delete(name);
return {success: true}
}
/**
* @returns {Promise<Object>}
*/
async clearCaches() {
let keys = await caches.keys();
await Promise.all(keys.map(name => caches.delete(name)));
return {success: true}
}
/**
* @param {Client} client
*/
createMessageChannel(client) {
let me = this,
channel = new MessageChannel(),
{port1, port2} = channel;
port1.onmessage = me.onMessage.bind(me);
me.sendMessage('app', {action: 'registerPort', transfer: port2}, [port2]);
me.channelPorts.push({
clientId : client.id,
destination: 'app',
port : port1
})
}
/**
*
* @param {String} destination
* @param {String} clientId=this.lastClient.id
* @returns {MessagePort|null}
*/
getPort(destination, clientId=this.lastClient?.id) {
for (let port of this.channelPorts) {
if (clientId === port.clientId && destination === port.destination) {
return port.port
}
}
return null
}
/**
* Ignore the call in case there is no connected client in place yet
*/
initRemote() {
let me = this,
lastClientId = me.lastClient?.id;
if (lastClientId && !me.remotes.includes(lastClientId)) {
me.remotes.push(lastClientId);
super.initRemote()
}
}
/**
* @param {ExtendableMessageEvent} event
*/
async onActivate(event) {
console.log('onActivate', event);
let me = this,
keys = await caches.keys(),
key;
for (key of keys) {
// Clear caches for prior SW versions, without touching non-related caches
if (key.startsWith(me._cacheName) && key !== me.cacheName) {
// No need to await the method execution
me.clearCache(key)
}
}
}
/**
* @param {Client} source
*/
async onConnect(source) {
console.log('onConnect', source);
this.createMessageChannel(source);
this.initRemote()
}
/**
* @param {ExtendableMessageEvent} event
*/
onFetch(event) {
let hasMatch = false,
{request} = event,
key;
for (key of this.cachePaths) {
if (request.url.includes(key)) {
hasMatch = true;
break
}
}
hasMatch && request.method === 'GET' && event.respondWith(
caches.match(request)
.then(cachedResponse => cachedResponse || caches.open(this.cacheName)
.then(cache => fetch(request)
.then(response => cache.put(request, response.clone())
.then(() => response)
)))
)
}
/**
* @param {ExtendableMessageEvent} event
*/
onInstall(event) {
console.log('onInstall', event)
}
/**
* For a client based message we receive an ExtendableMessageEvent,
* for a MessageChannel based message a MessageEvent
* @param {ExtendableMessageEvent|MessageEvent} event
*/
onMessage(event) {
let me = this,
{data} = event,
{action, replyId} = data,
promise;
if (event.source) { // ExtendableMessageEvent
me.lastClient = event.source
}
if (!action) {
throw new Error('Message action is missing: ' + data.id)
}
if (action !== 'reply') {
me['on' + Neo.capitalize(action)](data, event);
} else if (promise = action === 'reply' && me.promises[replyId]) {
promise[data.reject ? 'reject' : 'resolve'](data.data);
delete me.promises[replyId]
}
}
/**
* @param {Object} msg
* @param {ExtendableMessageEvent} event
*/
onPing(msg, event) {
this.resolve(msg, {originMsg: msg})
}
/**
* @param {Object} msg
* @param {ExtendableMessageEvent} event
*/
async onRegisterNeoConfig(msg, event) {
this.onConnect(event.source)
}
/**
* @param {Object} msg
* @param {ExtendableMessageEvent} event
*/
async onSkipWaiting(msg, event) {
await globalThis.skipWaiting()
}
/**
* @param {Object} msg
* @param {ExtendableMessageEvent} event
*/
onUnregisterPort(msg, event) {
for (let [index, value] of this.channelPorts.entries()) {
if (value.clientId === event.source.id) {
this.channelPorts.splice(index, 1);
break
}
}
}
/**
* @param {Object} data
* @param {String} [data.cacheName=this.cacheName]
* @param {String[]|String} data.files
* @param {Boolean} [data.foreReload=false]
* @returns {Promise<Object>}
*/
async preloadAssets(data) {
let cacheName = data.cacheName || this.cacheName,
cache = await caches.open(cacheName),
{files} = data,
items = [],
asset, hasMatch, item;
if (!Array.isArray(files)) {
files = [files]
}
for (item of files) {
hasMatch = false;
if (!data.forceReload) {
asset = await cache.match(item);
hasMatch = !!asset
}
!hasMatch && items.push(item)
}
if (items.length > 0) {
await cache.addAll(items)
}
return {success: true}
}
/**
* @param {String} dest app, data, main or vdom (excluding the current worker)
* @param {Object} opts configs for Neo.worker.Message
* @param {Array} [transfer] An optional array of Transferable objects to transfer ownership of.
* If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from
* and becomes available only to the worker it was sent to.
* @returns {Promise<any>}
*/
promiseMessage(dest, opts, transfer) {
let me = this;
return new Promise(function(resolve, reject) {
let message = me.sendMessage(dest, opts, transfer),
msgId = message.id;
me.promises[msgId] = {reject, resolve}
})
}
/**
* You can either pass an url, an array of urls or an object with additional options
* See: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete
* @param {String|String[]|Object} data
* @param {String|String[]} data.assets
* @param {String} data.cacheName=this.cacheName
* @param {Object} data.options
* @param {Boolean} data.options.ignoreMethod=false
* @param {Boolean} data.options.ignoreSearch=false
* @param {Boolean} data.options.ignoreVary=false
* @returns {Promise<Object>}
*/
async removeAssets(data) {
if (!Neo.isObject(data)) {
data = {assets: data}
}
let {assets, options={}} = data,
cacheName = data.cacheName || this.cacheName,
cache = await caches.open(cacheName),
promises = [];
if (!Array.isArray(assets)) {
assets = [assets]
}
assets.forEach(asset => {
promises.push(cache.delete(asset, options))
});
await Promise.all(promises);
return {success: true}
}
/**
* @param {String} dest app, data, main or vdom (excluding the current worker)
* @param {Object} opts configs for Neo.worker.Message
* @param {Array} [transfer] An optional array of Transferable objects to transfer ownership of.
* If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from
* and becomes available only to the worker it was sent to.
* @returns {Neo.worker.Message}
* @protected
*/
sendMessage(dest, opts, transfer) {
opts.destination = dest;
let message = new Message(opts),
port = this.getPort(dest) || this.lastClient;
port.postMessage(message, transfer);
return message
}
}
export default Neo.setupClass(ServiceBase);