@statewalker/webrun-http-browser 0.1.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.
@@ -0,0 +1,974 @@
1
+ // @statewalker/webrun-http-browser v0.1.0 https://github.com/statewalker/statewalker-webrun-http-browser Copyright 2023 Mikhail Kotelnikov
2
+ (function (global, factory) {
3
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.statewalker = global.statewalker || {}, global.statewalker["webrun-http-browser"] = global.statewalker["webrun-http-browser"] || {})));
6
+ })(this, (function (exports) { 'use strict';
7
+
8
+ function serializeError(error) {
9
+ return Object.assign({
10
+ message: error,
11
+ stack: error.stack,
12
+ }, error);
13
+ }
14
+
15
+ function deserializeError(error) {
16
+ if (typeof error === "string") {
17
+ error = { message: error };
18
+ }
19
+ return Object.assign(new Error(error.message), error);
20
+ }
21
+
22
+ async function callChannel(mainChannel, callType, params, ...transfers) {
23
+ return new Promise((resolve, reject) => {
24
+ const channel = new MessageChannel();
25
+ channel.port1.onmessage = (ev) => {
26
+ const { result, error } = ev.data;
27
+ if (error) reject(deserializeError(error));
28
+ else resolve(result);
29
+ };
30
+ mainChannel.postMessage({ type: callType, params }, [
31
+ channel.port2,
32
+ ...transfers,
33
+ ]);
34
+ });
35
+ }
36
+
37
+ function handleChannelCalls(mainChannel, callType, handler) {
38
+ const messageListener = async (event) => {
39
+ if (!event.data || event.data.type !== callType) return;
40
+ const [port, ...transfers] = event.ports;
41
+ let response = {};
42
+ try {
43
+ const params = event.data.params;
44
+ response.result = await handler(event, params, ...transfers);
45
+ } catch (error) {
46
+ response.error = serializeError(error);
47
+ }
48
+ port.postMessage(response);
49
+ };
50
+ mainChannel.addEventListener("message", messageListener);
51
+ try {
52
+ mainChannel.start && mainChannel.start();
53
+ } catch (e) {}
54
+ return () => mainChannel.removeEventListener("message", messageListener);
55
+ }
56
+
57
+ // See https://github.com/agenjs/agen-utils/blob/main/src/iterator.js
58
+ async function* iterate(init, queue = []) {
59
+ let promise, notify, push = async (error, value, done) => {
60
+ const slot = { error, value, done };
61
+ slot.promise = new Promise(n => slot.notify = n);
62
+ await queue.push(slot);
63
+ notify && notify();
64
+ notify = null;
65
+ return slot.promise;
66
+ };
67
+ const next = (value) => push(undefined, value, false);
68
+ const complete = () => push(undefined, undefined, true);
69
+ const error = err => push(err, undefined, true);
70
+ const unsubscribe = init(Object.assign([next, complete, error], { next, complete, error }));
71
+ let slot;
72
+ try {
73
+ while (true) {
74
+ slot = await queue.shift();
75
+ if (slot) {
76
+ try {
77
+ if (slot.error) { throw slot.error; }
78
+ else if (slot.done) { break; }
79
+ else { yield slot.value; }
80
+ } finally {
81
+ slot.notify(true);
82
+ }
83
+ } else {
84
+ await (promise = notify ? promise : new Promise(n => notify = n));
85
+ }
86
+ }
87
+ } finally {
88
+ notify && notify();
89
+ push = () => false; // Stop pushing in the queue...
90
+ ((typeof unsubscribe === 'function') && (await unsubscribe()));
91
+ while (slot = await queue.shift()) { slot.notify(false); }
92
+ }
93
+ }
94
+
95
+ function newRegistry(onError = console.error) {
96
+ let counter = 0;
97
+ const registrations = {};
98
+ const register = (action) => {
99
+ const id = counter++;
100
+ return (registrations[id] = Object.assign(
101
+ function (skip) {
102
+ try {
103
+ delete registrations[id];
104
+ return !skip && action && action();
105
+ } catch (error) {
106
+ onError(error);
107
+ }
108
+ },
109
+ { action }
110
+ ));
111
+ };
112
+ const unregister = (action) =>
113
+ Object.values(registrations).forEach((r) => r.action === action && r(true));
114
+ const clear = () => Object.values(registrations).forEach((r) => r());
115
+ return Object.assign([register, clear, unregister], {
116
+ register,
117
+ clear,
118
+ unregister
119
+ });
120
+ }
121
+
122
+ async function* recieveData(onMessage) {
123
+ yield* iterate((iterator) => {
124
+ return onMessage(async ({ done = true, value, error } = {}) => {
125
+ if (error) {
126
+ await iterator.error(error);
127
+ } else if (done) {
128
+ await iterator.complete();
129
+ } else {
130
+ await iterator.next(value);
131
+ }
132
+ });
133
+ });
134
+ }
135
+
136
+ async function sendData(send, it) {
137
+ let error;
138
+ try {
139
+ for await (let value of it) {
140
+ await send({ done: false, value });
141
+ }
142
+ } catch (err) {
143
+ error = err;
144
+ } finally {
145
+ await send({ done: true, error });
146
+ }
147
+ }
148
+
149
+ async function* sendStream(communicationPort, input, params = {}) {
150
+ const messageChannel = new MessageChannel();
151
+ communicationPort.postMessage({ type: "START_CALL", params }, [
152
+ messageChannel.port2,
153
+ ]);
154
+
155
+ const channel = newChannel(messageChannel.port1);
156
+ try {
157
+ await channel.start();
158
+ channel.sendAll(input);
159
+ yield* channel.recieveAll();
160
+ } finally {
161
+ await channel.close();
162
+ }
163
+ }
164
+
165
+ function handleStreams(communicationPort, handler) {
166
+ const listener = async (event) => {
167
+ const { type, params } = event.data || {};
168
+ if (type !== "START_CALL") return;
169
+ const port = event.ports[0];
170
+ const channel = newChannel(port);
171
+ try {
172
+ await channel.start();
173
+ const input = channel.recieveAll();
174
+ const response = await handler(input, params);
175
+ await channel.sendAll(response);
176
+ } finally {
177
+ await channel.close();
178
+ }
179
+ };
180
+ communicationPort.addEventListener("message", listener);
181
+ try {
182
+ communicationPort.start && communicationPort.start();
183
+ } catch (e) {}
184
+ return () => communicationPort.removeEventListener("message", listener);
185
+ }
186
+
187
+ /**
188
+ * This method creates and returns methods allowing to send and recieve data over the specified port.
189
+ * The main characteristics of the returned methods is that they properly manage backpressure - sender
190
+ * iterators are waiting to send the next value until the previous one is consumed on the other side.
191
+ * @param {*} port
192
+ * @returns an object with the following methods:
193
+ * * `start` - starts the connection over the specified port
194
+ * * `close`- stops all iterators and closes the port
195
+ * * `recieveAll() : AsyncIterator` - returns an AsyncIterator over all values send by the peer
196
+ * * `sendAll(it : AsyncIterator) : Promise<any>` - sends all values defined by the given
197
+ * AsyncIterator to the peer
198
+ */
199
+ function newChannel(port) {
200
+ let listeners = [];
201
+ let iterators = [];
202
+
203
+ const notifyAll = async (data) => {
204
+ for (let listener of listeners) {
205
+ await listener(data);
206
+ }
207
+ };
208
+ const channel = newInvokationChannel(port, notifyAll);
209
+
210
+ const start = () => channel.start();
211
+
212
+ const close = async () => {
213
+ await notifyAll({ done: true });
214
+ [...iterators].forEach((it) => it.return && it.return());
215
+ await channel.close();
216
+ };
217
+
218
+ async function* recieveAll() {
219
+ yield* recieveData((listener) => {
220
+ listeners.push(listener);
221
+ return () => listeners = listeners.filter((l) => l !== listener);
222
+ });
223
+ }
224
+
225
+ async function sendAll(it) {
226
+ await sendData(
227
+ channel.invoke,
228
+ (async function* () {
229
+ try {
230
+ iterators.push(it);
231
+ yield* it;
232
+ } finally {
233
+ iterators = iterators.filter((i) => i !== it);
234
+ }
235
+ })(),
236
+ );
237
+ }
238
+ return {
239
+ start,
240
+ close,
241
+ recieveAll,
242
+ sendAll,
243
+ };
244
+ }
245
+
246
+ function newInvokationChannel(port, handler = () => {
247
+ throw new Error("Handler not implemented");
248
+ }) {
249
+ const MESSAGE_TYPE_REQUEST = "REQUEST";
250
+ const MESSAGE_TYPE_RESPONSE = "RESPONSE";
251
+ const EVENT_MESSAGE = "message";
252
+
253
+ const requests = {};
254
+ let requestCounter = 0;
255
+ const listener = async (event) => {
256
+ const data = event.data || {};
257
+ const { type, callId } = data;
258
+ if (type === MESSAGE_TYPE_REQUEST) {
259
+ try {
260
+ const { request } = data;
261
+ let result = await handler(request, ...(event.ports || []));
262
+ const [response, ...transfers] = Array.isArray(result)
263
+ ? result
264
+ : result !== undefined
265
+ ? [result]
266
+ : [];
267
+ port.postMessage(
268
+ { type: MESSAGE_TYPE_RESPONSE, callId, response },
269
+ transfers,
270
+ );
271
+ } catch (error) {
272
+ port.postMessage({
273
+ type: MESSAGE_TYPE_RESPONSE,
274
+ callId,
275
+ error: serializeError(error),
276
+ });
277
+ }
278
+ } else if (type === MESSAGE_TYPE_RESPONSE) {
279
+ const { callId, response, error } = data;
280
+ const request = requests[callId];
281
+ delete requests[callId];
282
+ if (request) {
283
+ error
284
+ ? request.reject(deserializeError(error))
285
+ : request.resolve(response);
286
+ }
287
+ }
288
+ };
289
+
290
+ const start = async () => {
291
+ port.addEventListener(EVENT_MESSAGE, listener);
292
+ await port.start();
293
+ };
294
+
295
+ const close = async () => {
296
+ port.removeEventListener(EVENT_MESSAGE, listener);
297
+ await port.close();
298
+ };
299
+
300
+ const invoke = async function (request = {}, ...transfers) {
301
+ const callId = ++requestCounter;
302
+ return new Promise((resolve, reject) => {
303
+ try {
304
+ requests[callId] = { resolve, reject };
305
+ port.postMessage(
306
+ { type: MESSAGE_TYPE_REQUEST, callId, request },
307
+ transfers,
308
+ );
309
+ } catch (error) {
310
+ reject(error);
311
+ delete request[callId];
312
+ }
313
+ });
314
+ };
315
+
316
+ return {
317
+ start,
318
+ close,
319
+ invoke,
320
+ };
321
+ }
322
+
323
+ function toReadableStream(it) {
324
+ return new ReadableStream({
325
+ type: "bytes",
326
+ async pull(controller) {
327
+ let handled = false;
328
+ try {
329
+ while (true) {
330
+ const slot = await it.next();
331
+ if (!slot || slot.done) {
332
+ break;
333
+ }
334
+ controller.enqueue(await slot.value);
335
+ }
336
+ } catch (error) {
337
+ handled = true;
338
+ controller.error(error);
339
+ } finally {
340
+ !handled && controller.close();
341
+ }
342
+ },
343
+ });
344
+ }
345
+
346
+ async function* fromReadableStream(stream) {
347
+ const reader = await stream.getReader();
348
+ let done, value;
349
+ while (({ done, value } = await reader.read())) {
350
+ if (done) {
351
+ break;
352
+ }
353
+ yield await value;
354
+ }
355
+ }
356
+
357
+ /**
358
+ * This method returns an HTTP handlers transforming
359
+ * HTTP Request instances to binary representations and
360
+ * sending them to a transport layer.
361
+ * Results of these transport ivokations are deserialized
362
+ * as meaningful Response instances and returned back to the caller.
363
+ *
364
+ * The specified `send` method is used to dispatch serialized
365
+ * requests to return the serialized remote results.
366
+ * This transport method accepts and returns objects with
367
+ * the same structure:
368
+ * * `options` - contains serialized request or response parameters
369
+ * * `content` - an async iterator over binary blocks for
370
+ * the request or response
371
+ *
372
+ * @param {*} send transport function accepting serialized requests
373
+ * and returning back serialized responses
374
+ * @returns an async handler accepting standard
375
+ * HTTP `Request` instances and returning `Response` instances
376
+ */
377
+ function newHttpClientStub(send) {
378
+ return async (request) => {
379
+ request = await request;
380
+ const fields = [
381
+ "url",
382
+ "method",
383
+ "mode",
384
+ "credentials",
385
+ "cache",
386
+ "redirect",
387
+ "referrer",
388
+ "referrerPolicy",
389
+ "integrity",
390
+ "keepalive",
391
+ ];
392
+ // request = await request.clone();
393
+ const requestOptions = fields.reduce((options, key) => {
394
+ const val = request[key];
395
+ if (val !== undefined) options[key] = val;
396
+ return options;
397
+ }, {});
398
+ const requestContent = (request.body)
399
+ ? fromReadableStream(request.body)
400
+ : [];
401
+ const result = await send({
402
+ options: requestOptions,
403
+ content: requestContent,
404
+ });
405
+ let responseBody = null;
406
+ let responseOptions = {};
407
+ if (!result) {
408
+ responseOptions = {
409
+ status: 404,
410
+ statusText: "Error 404: Not Found",
411
+ };
412
+ } else {
413
+ responseOptions = result.options;
414
+ const responseContent = result.content;
415
+ if (
416
+ requestOptions.method !== "HEAD" &&
417
+ requestOptions.method !== "OPTIONS"
418
+ ) {
419
+ responseBody = toReadableStream(responseContent);
420
+ } else if (responseContent && responseContent.return) {
421
+ responseContent.return();
422
+ }
423
+ }
424
+ return new Response(responseBody, responseOptions);
425
+ };
426
+ }
427
+
428
+ /**
429
+ * This method returns the server-side call handler transforming
430
+ * serialized requests to HTTP Request instances, delegating
431
+ * their handing to the given `handler` method. This handler
432
+ * should handle the HTTP request and return a valid Response instance.
433
+ * The resulting instance is serialized as an object with the same
434
+ * structure as the initial serialized request:
435
+ * - `options` - contains serialized request or response parameters
436
+ * - `content` - an async iterator over binary blocks for
437
+ * the request or response
438
+ * @param {*} handler this handler method accepts standard HTTP Request
439
+ * and returns back an HTTP Response instance
440
+ * @returns a method deserializing HTTP requests and returning back
441
+ * serialized HTTP responses
442
+ */
443
+ function newHttpServerStub(handler) {
444
+ return async (params) => {
445
+ const {
446
+ options: requestOptions,
447
+ content: requestContent,
448
+ } = await params;
449
+ let requestBody = undefined;
450
+ const { url, mode } = requestOptions;
451
+ delete requestOptions.mode;
452
+ delete requestOptions.url;
453
+ if (
454
+ requestOptions.method !== "GET" &&
455
+ requestOptions.method !== "HEAD" &&
456
+ requestOptions.method !== "OPTIONS"
457
+ ) {
458
+ requestBody = toReadableStream(requestContent);
459
+ requestOptions.duplex = "half";
460
+ } else if (requestContent && requestContent.return) {
461
+ requestContent.return();
462
+ }
463
+ const request = new Request(url, {
464
+ ...requestOptions,
465
+ // duplex: 'full',
466
+ body: requestBody,
467
+ });
468
+ const response = await handler(request);
469
+ const responseOptions = {
470
+ status: response.status,
471
+ statusText: response.statusText,
472
+ headers: Object.fromEntries([...response.headers]),
473
+ };
474
+ const responseContent = await fromReadableStream(await response.body);
475
+ return {
476
+ options: responseOptions,
477
+ content: responseContent,
478
+ };
479
+ };
480
+ }
481
+
482
+ async function* httpToIterator(params) {
483
+ const { options, content } = await params;
484
+ const encoder = new TextEncoder();
485
+ yield encoder.encode(JSON.stringify(options));
486
+ yield* content;
487
+ }
488
+
489
+ async function httpFromIterator(it) {
490
+ it = await it;
491
+ const { done, value } = await it.next();
492
+ let options = {};
493
+ if (!done && value) {
494
+ const decoder = new TextDecoder();
495
+ const str = decoder.decode(value);
496
+ options = JSON.parse(str);
497
+ }
498
+ return {
499
+ options,
500
+ content: it,
501
+ };
502
+ }
503
+
504
+ function handleHttpRequests(communicationPort, handler) {
505
+ const serverStub = newHttpServerStub(handler);
506
+ return handleStreams(communicationPort, (it) => {
507
+ return httpToIterator(serverStub(httpFromIterator(it)));
508
+ });
509
+ }
510
+
511
+ async function sendHttpRequest(communicationPort, request) {
512
+ const clientStub = newHttpClientStub(async (req) => {
513
+ return await httpFromIterator(
514
+ sendStream(communicationPort, httpToIterator(req)),
515
+ );
516
+ });
517
+ return await clientStub(request);
518
+ }
519
+
520
+ function promisifyRequest(request) {
521
+ return new Promise((resolve, reject) => {
522
+ // @ts-ignore - file size hacks
523
+ request.oncomplete = request.onsuccess = () => resolve(request.result);
524
+ // @ts-ignore - file size hacks
525
+ request.onabort = request.onerror = () => reject(request.error);
526
+ });
527
+ }
528
+ function createStore(dbName, storeName) {
529
+ const request = indexedDB.open(dbName);
530
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName);
531
+ const dbp = promisifyRequest(request);
532
+ return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
533
+ }
534
+ let defaultGetStoreFunc;
535
+ function defaultGetStore() {
536
+ if (!defaultGetStoreFunc) {
537
+ defaultGetStoreFunc = createStore('keyval-store', 'keyval');
538
+ }
539
+ return defaultGetStoreFunc;
540
+ }
541
+ /**
542
+ * Get a value by its key.
543
+ *
544
+ * @param key
545
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
546
+ */
547
+ function get(key, customStore = defaultGetStore()) {
548
+ return customStore('readonly', (store) => promisifyRequest(store.get(key)));
549
+ }
550
+ /**
551
+ * Set a value with a key.
552
+ *
553
+ * @param key
554
+ * @param value
555
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
556
+ */
557
+ function set(key, value, customStore = defaultGetStore()) {
558
+ return customStore('readwrite', (store) => {
559
+ store.put(value, key);
560
+ return promisifyRequest(store.transaction);
561
+ });
562
+ }
563
+
564
+ class SwPortHandler {
565
+ constructor(options) {
566
+ this.options = options;
567
+ if (!this.key) throw new Error("Key is not defined.");
568
+ if (!this.scope) throw new Error("Scope is not defined");
569
+ }
570
+
571
+ get key() {
572
+ return this.options.key;
573
+ }
574
+
575
+ get scope() {
576
+ return this.options.scope || new URL("./", this.serviceWorkerUrl).pathname;
577
+ }
578
+
579
+ get rootUrl() {
580
+ return new URL(this.scope, (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('index-umd.js', document.baseURI).href)));
581
+ }
582
+
583
+ get serviceWorkerUrl() {
584
+ if (!this._serviceWorkerUrl) {
585
+ let url = this.options.serviceWorkerUrl
586
+ ? new URL(this.options.serviceWorkerUrl)
587
+ : new URL("./index-sw.js", this.rootUrl);
588
+ this._serviceWorkerUrl = url + "";
589
+ }
590
+ return this._serviceWorkerUrl;
591
+ }
592
+
593
+ async _newCommunicationChannel() {
594
+ const messageChannel = new MessageChannel();
595
+ return [messageChannel.port1, messageChannel.port2];
596
+ }
597
+
598
+ async _setCommunicationPort(port) {
599
+ await this.options.bindPort(port);
600
+ }
601
+
602
+ async _updateCommunicationChannel() {
603
+ // console.log("[_updateCommunicationChannel]", this._serviceWorker);
604
+ if (!this._serviceWorker) return;
605
+ const [port1, port2] = await this._newCommunicationChannel();
606
+ await this._setCommunicationPort(port1);
607
+ await callChannel(
608
+ this._serviceWorker,
609
+ "UPDATE_COMMUNICATION_PORT",
610
+ this._getRegistrationInfo(),
611
+ port2,
612
+ );
613
+ }
614
+
615
+ _getRegistrationInfo() {
616
+ return { key: this.key };
617
+ }
618
+
619
+ /**
620
+ * Starts the server.
621
+ */
622
+ async start() {
623
+ return this._registrationPromise = this._registrationPromise ||
624
+ (async () => {
625
+ const [register, cleanup] = newRegistry();
626
+ this._cleanupRegistrations = cleanup;
627
+ register(() => this._cleanupRegistrations = null);
628
+ const registration = await navigator.serviceWorker.register(
629
+ this.serviceWorkerUrl,
630
+ {
631
+ // type: "module",
632
+ scope: this.scope,
633
+ },
634
+ );
635
+ register(() => registration.unregister());
636
+
637
+ // (example: when the service worker is the same but it is waked up/activated after an idle period)
638
+ register(
639
+ handleChannelCalls(
640
+ navigator.serviceWorker,
641
+ "UPDATE_COMMUNICATION_PORT",
642
+ async (event, params, port) => {
643
+ console.log("[UPDATE_COMMUNICATION_PORT]", port);
644
+ this._setCommunicationPort(port);
645
+ return this._getRegistrationInfo();
646
+ },
647
+ ),
648
+ );
649
+
650
+ this._serviceWorker = await getServiceWorkerController();
651
+ await awaitServiceWorkerActivation(this._serviceWorker);
652
+ await this._updateCommunicationChannel();
653
+
654
+ async function getServiceWorkerController() {
655
+ return await new Promise((resolve) => {
656
+ // Resolve right away if this page is already controlled.
657
+ const serviceWorker = navigator.serviceWorker;
658
+ if (serviceWorker.controller) {
659
+ resolve(serviceWorker.controller);
660
+ } else {
661
+ const onChange = () => {
662
+ resolve(serviceWorker.controller);
663
+ serviceWorker.removeEventListener("controllerchange", onChange);
664
+ serviceWorker.oncontrollerchange = null;
665
+ };
666
+ serviceWorker.addEventListener("controllerchange", onChange);
667
+ serviceWorker.oncontrollerchange = onChange;
668
+ }
669
+ });
670
+ }
671
+
672
+ // ------------------------------
673
+ // Await until the service is ready
674
+ async function awaitServiceWorkerActivation(worker) {
675
+ const isActivated = () => worker.state === "activated";
676
+ await new Promise(async (resolve) => {
677
+ if (isActivated()) resolve();
678
+ else {
679
+ worker.onstatechange = () => {
680
+ if (!isActivated()) return;
681
+ worker.onstatechange = null;
682
+ resolve();
683
+ };
684
+ }
685
+ });
686
+ }
687
+ })();
688
+ }
689
+
690
+ /**
691
+ * Stops the server and removes associated handlers.
692
+ */
693
+ async stop() {
694
+ if (this._cleanupRegistrations) this._cleanupRegistrations();
695
+ const registrations = await navigator.serviceWorker.getRegistrations();
696
+ for (let registration of registrations) {
697
+ try {
698
+ await registration.unregister();
699
+ } catch (error) {
700
+ console.log("Service Worker registration failed: ", error);
701
+ }
702
+ }
703
+ }
704
+ }
705
+
706
+ class SwPortDispatcher {
707
+ constructor({ self, log }) {
708
+ this.self = self;
709
+ this.log = log;
710
+ // Contains mapping between path prefixes and clientIds
711
+ this.handlersIndex = new Map();
712
+ }
713
+
714
+ get scope() {
715
+ return new URL("./", (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('index-umd.js', document.baseURI).href))) + "";
716
+ }
717
+
718
+ async loadChannelInfo(key) {
719
+ await this._checkActivation();
720
+ let result;
721
+ for (let channelInfo of this.handlersIndex.values()) {
722
+ if (channelInfo.key !== key) continue;
723
+ const clientId = channelInfo.clientId;
724
+ const client = await self.clients.get(clientId);
725
+ if (!client) {
726
+ // Client gone. Remove the corresponding handlers from the index.
727
+ this.handlersIndex.delete(clientId);
728
+ throw Object.assign(new Error("Error 410: Resource Gone"), {
729
+ status: 410,
730
+ });
731
+ }
732
+ result = channelInfo;
733
+ break;
734
+ }
735
+ return result;
736
+ }
737
+
738
+ start() {
739
+ this._cleanup = handleChannelCalls(
740
+ this.self,
741
+ "UPDATE_COMMUNICATION_PORT",
742
+ async (event, channelInfo, port) => {
743
+ const clientId = event.source.id;
744
+ this.log("[UPDATE_COMMUNICATION_PORT]", clientId, channelInfo);
745
+ await this._updateChannelInfo({ ...channelInfo, port, clientId });
746
+ return { ...channelInfo };
747
+ },
748
+ );
749
+ this.self.onmessage = () => {};
750
+
751
+ this.self.addEventListener("install", (event) => {
752
+ this.log("Skip waiting on install.", event);
753
+ this.self.skipWaiting();
754
+ });
755
+
756
+ this.self.addEventListener("activate", async (event) => {
757
+ this.log(
758
+ "Claim control over all clients.",
759
+ event,
760
+ clients,
761
+ this.self.clients,
762
+ );
763
+ event.waitUntil((async () => {
764
+ await this.self.clients.claim();
765
+ await this._checkActivation();
766
+ })());
767
+ });
768
+ }
769
+
770
+ async stop() {
771
+ if (this._cleanup) {
772
+ await this._cleanup();
773
+ this._cleanup = undefined;
774
+ }
775
+ }
776
+
777
+ async _checkActivation() {
778
+ return this._activationPromise = this._activationPromise ||
779
+ this._activate();
780
+ }
781
+
782
+ async _activate() {
783
+ this.log("[checkActivation]");
784
+ let clientsIndex = await this._loadClientIds();
785
+ for (let [clientId, client] of clientsIndex.entries()) {
786
+ const messageChannel = new MessageChannel();
787
+ const port = messageChannel.port1;
788
+ const channelInfo = await callChannel(
789
+ client,
790
+ "UPDATE_COMMUNICATION_PORT",
791
+ {},
792
+ messageChannel.port2,
793
+ );
794
+ await this._updateChannelInfo({ ...channelInfo, port, clientId });
795
+ }
796
+ }
797
+
798
+ async _updateChannelInfo(channelInfo) {
799
+ this.log("[updateClientInfo]", channelInfo);
800
+ this.handlersIndex.set(channelInfo.clientId, channelInfo);
801
+ await this._updateClientIds([]);
802
+ }
803
+
804
+ async _loadClientIds() {
805
+ const clientIds = new Set((await get("clientIds")) || []);
806
+ return await this._updateClientIds(clientIds);
807
+ }
808
+
809
+ async _updateClientIds(clientIds) {
810
+ clientIds = new Set(clientIds);
811
+ for (let clientId of this.handlersIndex.keys()) {
812
+ clientIds.add(clientId);
813
+ }
814
+ const index = new Map();
815
+ for (let clientId of clientIds) {
816
+ const client = await this.self.clients.get(clientId);
817
+ if (client) index.set(clientId, client);
818
+ else this.handlersIndex.delete(clientId);
819
+ }
820
+ await set("clientIds", [...index.keys()].sort());
821
+ return index;
822
+ }
823
+ }
824
+
825
+ class SwHttpAdapter extends SwPortHandler {
826
+ constructor(options) {
827
+ super(options);
828
+ this._handlers = new Map();
829
+ }
830
+
831
+ async _setCommunicationPort(port) {
832
+ if (this._cleanupRequestChannel) {
833
+ this._cleanupRequestChannel();
834
+ }
835
+ this._cleanupRequestChannel = handleHttpRequests(
836
+ port,
837
+ this._handleHttpRequest.bind(this),
838
+ );
839
+ }
840
+
841
+ async _handleHttpRequest(request) {
842
+ const requestUrl = request.url;
843
+ let handler;
844
+ for (let entry of this._handlers.entries()) {
845
+ const [urlPrefix] = entry;
846
+ if (requestUrl.indexOf(urlPrefix) === 0) {
847
+ handler = entry[1];
848
+ break;
849
+ }
850
+ }
851
+ return !handler
852
+ ? new Response(null, {
853
+ status: 404,
854
+ statusMessage: "Error 404: Not found",
855
+ })
856
+ : handler(request);
857
+ }
858
+
859
+ /**
860
+ * Registers the given request handler.
861
+ * @param {string} prefix unique base URL prefix used to register the specified handler
862
+ * @param {*} handler the request handler
863
+ * @return {string} full URL of the resulting endpoint
864
+ */
865
+ async register(prefix, handler) {
866
+ prefix = "./" + (prefix || "").replace(/^[\.\/]+/, "");
867
+ const rootUrl = this.rootUrl;
868
+ const baseUrl = new URL(prefix, rootUrl) + "";
869
+ this._handlers.set(baseUrl, handler);
870
+ return {
871
+ baseUrl,
872
+ prefix,
873
+ async remove() {
874
+ this._handlers.delete(baseUrl);
875
+ },
876
+ };
877
+ }
878
+ }
879
+
880
+ class SwHttpDispatcher extends SwPortDispatcher {
881
+ constructor(options) {
882
+ super(options);
883
+ }
884
+
885
+ start() {
886
+ super.start();
887
+ this.self.addEventListener("fetch", this._handleFetchEvent.bind(this));
888
+ }
889
+
890
+ _handleFetchEvent(event) {
891
+ event.respondWith((async () => {
892
+ const request = event.request;
893
+ try {
894
+ const requestUrl = request.url;
895
+ const rootUrl = this.scope;
896
+ let channelInfo;
897
+ if (requestUrl.indexOf(rootUrl) === 0) {
898
+ const key = requestUrl
899
+ .substring(rootUrl.length)
900
+ .replace(/^\/?([^\/]+).*$/, "$1");
901
+ // console.log(`* rootUrl="${rootUrl}" requestUrl="${requestUrl}" key="${key}"`);
902
+ channelInfo = await this.loadChannelInfo(key);
903
+ }
904
+ if (channelInfo && channelInfo.port) {
905
+ return await sendHttpRequest(channelInfo.port, request);
906
+ } else {
907
+ const newRequest = new Request(requestUrl, {
908
+ method: request.method,
909
+ headers: request.headers,
910
+ body: request.body,
911
+ referrer: request.referrer,
912
+ referrerPolicy: request.referrerPolicy,
913
+ // mode: request.mode,
914
+ credentials: request.credentials,
915
+ cache: request.cache,
916
+ redirect: request.redirect,
917
+ integrity: request.integrity,
918
+ });
919
+ return await fetch(newRequest);
920
+ }
921
+
922
+ // const requestUrl = request.url;
923
+ // let url = requestUrl.replace(
924
+ // /^.*\/[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}(.*)$/,
925
+ // "$1",
926
+ // );
927
+ // if (url !== requestUrl) {
928
+ // url = new URL(
929
+ // "/packages/webrun-http-browser/src" + url,
930
+ // self.location.href,
931
+ // );
932
+ // }
933
+ } catch (error) {
934
+ console.error(error);
935
+ return new Response(null, {
936
+ status: 500,
937
+ statusText: "Error 500: Internal error",
938
+ });
939
+ }
940
+ })());
941
+ }
942
+ }
943
+ function startHttpDispatcher({ self, log }) {
944
+ const dispatcher = new SwHttpDispatcher({ self, log });
945
+ dispatcher.start();
946
+ return () => {
947
+ dispatcher.stop();
948
+ };
949
+ }
950
+
951
+ exports.SwHttpAdapter = SwHttpAdapter;
952
+ exports.SwHttpDispatcher = SwHttpDispatcher;
953
+ exports.SwPortDispatcher = SwPortDispatcher;
954
+ exports.SwPortHandler = SwPortHandler;
955
+ exports.callChannel = callChannel;
956
+ exports.deserializeError = deserializeError;
957
+ exports.fromReadableStream = fromReadableStream;
958
+ exports.handleChannelCalls = handleChannelCalls;
959
+ exports.handleHttpRequests = handleHttpRequests;
960
+ exports.handleStreams = handleStreams;
961
+ exports.newChannel = newChannel;
962
+ exports.newHttpClientStub = newHttpClientStub;
963
+ exports.newHttpServerStub = newHttpServerStub;
964
+ exports.newInvokationChannel = newInvokationChannel;
965
+ exports.newRegistry = newRegistry;
966
+ exports.recieveData = recieveData;
967
+ exports.sendData = sendData;
968
+ exports.sendHttpRequest = sendHttpRequest;
969
+ exports.sendStream = sendStream;
970
+ exports.serializeError = serializeError;
971
+ exports.startHttpDispatcher = startHttpDispatcher;
972
+ exports.toReadableStream = toReadableStream;
973
+
974
+ }));