postalworker-es 4.0.8 → 5.0.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/dist/index.js ADDED
@@ -0,0 +1,860 @@
1
+ // src/protocol.ts
2
+ var PROTOCOL = 5;
3
+ var WORKER_ID = "worker";
4
+ var CHANNEL_KINDS = /* @__PURE__ */ new Set([
5
+ "fire",
6
+ "hello",
7
+ "worker-ready",
8
+ "join",
9
+ "leave",
10
+ "box-open",
11
+ "box-post",
12
+ "box-close",
13
+ "box-update",
14
+ "box-closed",
15
+ "package-open",
16
+ "package-pack",
17
+ "package-update",
18
+ "load",
19
+ "error"
20
+ ]);
21
+ var CROSS_KINDS = /* @__PURE__ */ new Set([
22
+ "cross-hello",
23
+ "cross-ack",
24
+ "cross-probe",
25
+ "cross-bye",
26
+ "cross"
27
+ ]);
28
+ function isEnvelope(data) {
29
+ if (typeof data !== "object" || data === null) return false;
30
+ const d = data;
31
+ return d["__postal"] === PROTOCOL && typeof d["from"] === "string" && typeof d["kind"] === "string";
32
+ }
33
+ function isChannelMsg(data) {
34
+ return isEnvelope(data) && CHANNEL_KINDS.has(data.kind);
35
+ }
36
+ function isCrossWindowMsg(data) {
37
+ return isEnvelope(data) && CROSS_KINDS.has(data.kind);
38
+ }
39
+ function envelope(from, body) {
40
+ return { __postal: PROTOCOL, from, ...body };
41
+ }
42
+ function reachesTab(audience, selfId) {
43
+ if (audience === "all" || audience === "others") return true;
44
+ if (audience === "worker") return false;
45
+ return audience.to === selfId;
46
+ }
47
+ function assertNever(x) {
48
+ throw new Error(`PostalWorker: unexpected value ${JSON.stringify(x)}`);
49
+ }
50
+
51
+ // src/cross.ts
52
+ var HANDSHAKE_WAIT_MS = 2e3;
53
+ var CrossWindows = class {
54
+ #opts;
55
+ #targets = /* @__PURE__ */ new Map();
56
+ #opened = /* @__PURE__ */ new Map();
57
+ // window -> expected origin
58
+ #trusted = /* @__PURE__ */ new Set();
59
+ #pending = [];
60
+ #handshakeTimer;
61
+ #listener = (e) => this.#onMessage(e);
62
+ constructor(opts) {
63
+ this.#opts = opts;
64
+ this.#trusted.add(window.location.origin);
65
+ if (opts.allowedOrigins !== "*") for (const o of opts.allowedOrigins) this.#trusted.add(normalizeOrigin(o));
66
+ const parentOrigin = this.isFramed ? guessParentOrigin() : void 0;
67
+ if (parentOrigin) this.#trusted.add(parentOrigin);
68
+ const opener = getOpener();
69
+ const openerOrigin = opener ? referrerOrigin() : void 0;
70
+ if (openerOrigin) this.#trusted.add(openerOrigin);
71
+ window.addEventListener("message", this.#listener);
72
+ let waiting = false;
73
+ if (this.isFramed) {
74
+ this.#post(window.parent, "*", { kind: "cross-hello" });
75
+ waiting = true;
76
+ }
77
+ if (opener) {
78
+ this.#post(opener, "*", { kind: "cross-hello" });
79
+ waiting = true;
80
+ }
81
+ if (waiting) this.#handshakeTimer = setTimeout(() => this.#flushPending(), HANDSHAKE_WAIT_MS);
82
+ this.probeFrames();
83
+ }
84
+ get isFramed() {
85
+ try {
86
+ return window.self !== window.top;
87
+ } catch {
88
+ return true;
89
+ }
90
+ }
91
+ /** Ask every child frame to say hello. */
92
+ probeFrames() {
93
+ for (let i = 0; i < window.frames.length; i++) {
94
+ const frame = window.frames[i];
95
+ if (frame) this.#post(frame, "*", { kind: "cross-probe" });
96
+ }
97
+ }
98
+ /** Open a window and trust it (only that window, only at that url's origin). */
99
+ open(url, name, features) {
100
+ const href = new URL(url, window.location.href);
101
+ const win = window.open(href.href, name, features);
102
+ if (!win) {
103
+ console.warn(
104
+ `PostalWorker: window.open("${href.href}") returned null (popup blocked, or "noopener" was set). That window cannot be messaged.`
105
+ );
106
+ return null;
107
+ }
108
+ this.#opened.set(win, href.origin);
109
+ return win;
110
+ }
111
+ /** Send to every registered window (crossFire). */
112
+ send(msgClass, message) {
113
+ const go = () => {
114
+ this.#prune();
115
+ for (const t of this.#targets.values()) {
116
+ this.#post(t.win, t.origin, { kind: "cross", msgClass, message, back: false });
117
+ }
118
+ };
119
+ this.#whenHandshaken(go);
120
+ }
121
+ /** Send to the parent window only (backFire). Returns false when not framed. */
122
+ sendBack(msgClass, message) {
123
+ if (!this.isFramed) return false;
124
+ this.#whenHandshaken(() => {
125
+ const parent = [...this.#targets.values()].find((t) => t.relation === "parent");
126
+ if (parent) this.#post(parent.win, parent.origin, { kind: "cross", msgClass, message, back: true });
127
+ else console.warn("PostalWorker: backFire dropped, the parent window never answered (is PostalWorker running there, and does it trust this origin?)");
128
+ });
129
+ return true;
130
+ }
131
+ /** Close and forget every window registered at this origin (or url's origin). */
132
+ closeOrigin(urlOrOrigin) {
133
+ const origin = normalizeOrigin(urlOrOrigin);
134
+ for (const [id, t] of this.#targets) {
135
+ if (t.origin !== origin) continue;
136
+ if (t.relation === "opened") {
137
+ try {
138
+ t.win.close();
139
+ } catch {
140
+ }
141
+ }
142
+ this.#targets.delete(id);
143
+ }
144
+ for (const [win, o] of this.#opened) {
145
+ if (o !== origin) continue;
146
+ try {
147
+ win.close();
148
+ } catch {
149
+ }
150
+ this.#opened.delete(win);
151
+ }
152
+ }
153
+ targets() {
154
+ this.#prune();
155
+ return [...this.#targets.values()];
156
+ }
157
+ /** Tell every registered window we are leaving. */
158
+ sayGoodbye() {
159
+ for (const t of this.#targets.values()) this.#post(t.win, t.origin, { kind: "cross-bye" });
160
+ }
161
+ destroy() {
162
+ this.sayGoodbye();
163
+ window.removeEventListener("message", this.#listener);
164
+ clearTimeout(this.#handshakeTimer);
165
+ this.#targets.clear();
166
+ this.#opened.clear();
167
+ this.#pending = [];
168
+ }
169
+ // ---------------------------------------------------------------------------
170
+ #onMessage(e) {
171
+ const data = e.data;
172
+ if (!isCrossWindowMsg(data)) return;
173
+ const source = e.source;
174
+ if (!isWindow(source)) return;
175
+ if (data.from === this.#opts.selfId) return;
176
+ if (!this.#isTrusted(e.origin, source)) {
177
+ console.warn(
178
+ `PostalWorker: ignored a message from untrusted origin ${e.origin}. Add it to "allowedOrigins" to accept it.`
179
+ );
180
+ return;
181
+ }
182
+ switch (data.kind) {
183
+ case "cross-probe":
184
+ this.#post(source, e.origin, { kind: "cross-hello" });
185
+ return;
186
+ case "cross-hello":
187
+ this.#register(data.from, source, e.origin);
188
+ this.#post(source, e.origin, { kind: "cross-ack" });
189
+ return;
190
+ case "cross-ack":
191
+ this.#register(data.from, source, e.origin);
192
+ if (source === window.parent || source === getOpener()) this.#flushPending();
193
+ return;
194
+ case "cross-bye":
195
+ this.#targets.delete(data.from);
196
+ return;
197
+ case "cross":
198
+ if (!this.#targets.has(data.from)) this.#register(data.from, source, e.origin);
199
+ this.#opts.onMessage(data.msgClass, data.message, data.from, e.origin, data.back);
200
+ return;
201
+ }
202
+ }
203
+ #register(id, win, origin) {
204
+ let relation = "peer";
205
+ if (this.isFramed && win === window.parent) relation = "parent";
206
+ else if (win === getOpener()) relation = "opener";
207
+ else if (this.#opened.has(win)) relation = "opened";
208
+ else if (isChildFrame(win)) relation = "child";
209
+ for (const [oldId, t] of this.#targets) if (t.win === win && oldId !== id) this.#targets.delete(oldId);
210
+ this.#targets.set(id, { id, win, origin, relation });
211
+ }
212
+ #isTrusted(origin, source) {
213
+ if (this.#opts.allowedOrigins === "*") return true;
214
+ if (this.#trusted.has(origin)) return true;
215
+ const expected = this.#opened.get(source);
216
+ if (expected && expected === origin) return true;
217
+ return isChildFrameAt(source, origin);
218
+ }
219
+ #whenHandshaken(fn) {
220
+ if (this.#handshakeTimer === void 0) fn();
221
+ else this.#pending.push(fn);
222
+ }
223
+ #flushPending() {
224
+ clearTimeout(this.#handshakeTimer);
225
+ this.#handshakeTimer = void 0;
226
+ const queued = this.#pending;
227
+ this.#pending = [];
228
+ for (const fn of queued) fn();
229
+ }
230
+ #prune() {
231
+ for (const [id, t] of this.#targets) if (t.win.closed) this.#targets.delete(id);
232
+ for (const win of this.#opened.keys()) if (win.closed) this.#opened.delete(win);
233
+ }
234
+ #post(win, targetOrigin, body) {
235
+ try {
236
+ win.postMessage(envelope(this.#opts.selfId, body), targetOrigin);
237
+ } catch (error) {
238
+ console.warn("PostalWorker: cross-window postMessage failed", error);
239
+ }
240
+ }
241
+ };
242
+ function isWindow(source) {
243
+ return source !== null && typeof source.postMessage === "function" && "closed" in source;
244
+ }
245
+ function getOpener() {
246
+ try {
247
+ const o = window.opener;
248
+ return o && o !== window ? o : null;
249
+ } catch {
250
+ return null;
251
+ }
252
+ }
253
+ function normalizeOrigin(urlOrOrigin) {
254
+ try {
255
+ return new URL(urlOrOrigin, window.location.href).origin;
256
+ } catch {
257
+ return String(urlOrOrigin);
258
+ }
259
+ }
260
+ function referrerOrigin() {
261
+ if (!document.referrer) return void 0;
262
+ try {
263
+ return new URL(document.referrer).origin;
264
+ } catch {
265
+ return void 0;
266
+ }
267
+ }
268
+ function guessParentOrigin() {
269
+ const ancestors = window.location.ancestorOrigins;
270
+ if (ancestors && ancestors.length > 0) return ancestors[0];
271
+ return referrerOrigin();
272
+ }
273
+ function frameElements() {
274
+ return Array.from(document.querySelectorAll("iframe"));
275
+ }
276
+ function isChildFrame(win) {
277
+ return frameElements().some((f) => f.contentWindow === win);
278
+ }
279
+ function isChildFrameAt(win, origin) {
280
+ for (const frame of frameElements()) {
281
+ if (frame.contentWindow !== win) continue;
282
+ try {
283
+ return new URL(frame.src, window.location.href).origin === origin;
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
288
+ return false;
289
+ }
290
+ function windowFeatures(features) {
291
+ if (!features) return "";
292
+ if (typeof features === "string") return features;
293
+ return Object.entries(features).map(([k, v]) => `${k}=${v === true ? "yes" : v === false ? "no" : String(v)}`).join(",");
294
+ }
295
+
296
+ // src/emitter.ts
297
+ var Registry = class {
298
+ #handlers = /* @__PURE__ */ new Map();
299
+ add(key, handler) {
300
+ let set = this.#handlers.get(key);
301
+ if (!set) {
302
+ set = /* @__PURE__ */ new Set();
303
+ this.#handlers.set(key, set);
304
+ }
305
+ set.add(handler);
306
+ return () => this.remove(key, handler);
307
+ }
308
+ remove(key, handler) {
309
+ if (!handler) {
310
+ this.#handlers.delete(key);
311
+ return;
312
+ }
313
+ const set = this.#handlers.get(key);
314
+ if (!set) return;
315
+ set.delete(handler);
316
+ if (set.size === 0) this.#handlers.delete(key);
317
+ }
318
+ has(key) {
319
+ return this.#handlers.has(key);
320
+ }
321
+ keys() {
322
+ return [...this.#handlers.keys()];
323
+ }
324
+ clear() {
325
+ this.#handlers.clear();
326
+ }
327
+ emit(key, ...args) {
328
+ const set = this.#handlers.get(key);
329
+ if (!set) return;
330
+ for (const handler of [...set]) {
331
+ try {
332
+ handler(...args);
333
+ } catch (error) {
334
+ reportHandlerError(key, error);
335
+ }
336
+ }
337
+ }
338
+ };
339
+ function reportHandlerError(key, error) {
340
+ queueMicrotask(() => {
341
+ throw error instanceof Error ? Object.assign(error, { message: `PostalWorker handler for "${key}" threw: ${error.message}` }) : error;
342
+ });
343
+ }
344
+
345
+ // src/core.ts
346
+ var DEFAULT_CHANNEL = "PostalWorker";
347
+ function createPostalWorker(config) {
348
+ return new PostalWorkerImpl(config);
349
+ }
350
+ var PostalWorkerImpl = class {
351
+ id;
352
+ #mode = "none";
353
+ #online = false;
354
+ #gaveUp = false;
355
+ #destroyed = false;
356
+ #config;
357
+ #channelName;
358
+ #inert;
359
+ #channel;
360
+ #cross;
361
+ #worker;
362
+ #releaseLeader;
363
+ #workerInstance;
364
+ #readyTimer;
365
+ #queue = [];
366
+ #readyWaiters = [];
367
+ #events = new Registry();
368
+ #crossEvents = new Registry();
369
+ #boxes = /* @__PURE__ */ new Map();
370
+ #packages = /* @__PURE__ */ new Map();
371
+ #loaded = /* @__PURE__ */ new Set();
372
+ #onChannel = (e) => this.#handleChannel(e.data);
373
+ #onPageHide = () => {
374
+ this.#post({ kind: "leave" });
375
+ this.#cross?.sayGoodbye();
376
+ };
377
+ #onPageShow = (e) => {
378
+ if (!e.persisted) return;
379
+ this.#post({ kind: "join" });
380
+ this.#post({ kind: "hello" });
381
+ this.#cross?.probeFrames();
382
+ };
383
+ constructor(config) {
384
+ this.#config = config;
385
+ this.#channelName = config.channelName ?? DEFAULT_CHANNEL;
386
+ this.id = newId();
387
+ this.#inert = typeof window === "undefined" || typeof BroadcastChannel === "undefined";
388
+ if (this.#inert) return;
389
+ this.#channel = new BroadcastChannel(this.#channelName);
390
+ this.#channel.addEventListener("message", this.#onChannel);
391
+ this.#cross = new CrossWindows({
392
+ selfId: this.id,
393
+ allowedOrigins: config.allowedOrigins ?? [],
394
+ onMessage: (msgClass, message, from, origin) => this.#crossEvents.emit(msgClass, message, { from, origin })
395
+ });
396
+ window.addEventListener("pagehide", this.#onPageHide);
397
+ window.addEventListener("pageshow", this.#onPageShow);
398
+ this.#post({ kind: "join" });
399
+ this.#startWorker();
400
+ }
401
+ get mode() {
402
+ return this.#mode;
403
+ }
404
+ get workerOnline() {
405
+ return this.#online;
406
+ }
407
+ get isFramed() {
408
+ return this.#cross?.isFramed ?? false;
409
+ }
410
+ ready() {
411
+ if (this.#online) return Promise.resolve(true);
412
+ if (this.#gaveUp || this.#inert || this.#destroyed) return Promise.resolve(false);
413
+ return new Promise((resolve) => this.#readyWaiters.push(resolve));
414
+ }
415
+ // ---- events -------------------------------------------------------------
416
+ on(msgClass, handler) {
417
+ return this.#events.add(msgClass, handler);
418
+ }
419
+ off(msgClass, handler) {
420
+ this.#events.remove(msgClass, handler);
421
+ }
422
+ fire(msgClass, message, audience = "all") {
423
+ const toSelf = audience === "all" || audience === "local" || typeof audience === "object" && audience.to === this.id;
424
+ if (toSelf) {
425
+ queueMicrotask(() => this.#events.emit(msgClass, message, { from: this.id }));
426
+ }
427
+ if (audience === "local") return;
428
+ if (typeof audience === "object" && audience.to === this.id) return;
429
+ this.#post({ kind: "fire", msgClass, message, audience });
430
+ }
431
+ // ---- cross-window ---------------------------------------------------------
432
+ crossOn(msgClass, handler, url, options = {}) {
433
+ const off = this.#crossEvents.add(msgClass, handler);
434
+ if (url !== void 0 && this.#cross) {
435
+ this.#cross.open(url, options.name ?? "_blank", windowFeatures(options.features));
436
+ }
437
+ return off;
438
+ }
439
+ crossOff(msgClass, handler) {
440
+ this.#crossEvents.remove(msgClass, handler);
441
+ }
442
+ crossFire(msgClass, message) {
443
+ this.#cross?.send(msgClass, message);
444
+ }
445
+ backFire(msgClass, message) {
446
+ if (this.#cross && !this.#cross.sendBack(msgClass, message)) {
447
+ console.warn("PostalWorker: backFire() only works inside an iframe");
448
+ }
449
+ }
450
+ fireAll(msgClass, message) {
451
+ this.fire(msgClass, message, "all");
452
+ this.crossFire(msgClass, message);
453
+ }
454
+ closeWindows(urlOrOrigin) {
455
+ this.#cross?.closeOrigin(urlOrOrigin);
456
+ }
457
+ windows() {
458
+ return (this.#cross?.targets() ?? []).map(({ id, origin, relation }) => ({ id, origin, relation }));
459
+ }
460
+ // ---- worker scripts -------------------------------------------------------
461
+ load(url) {
462
+ const href = this.#inert ? String(url) : new URL(url, window.location.href).href;
463
+ if (!this.#requireWorker("load()")) return;
464
+ this.#loaded.add(href);
465
+ this.#post({ kind: "load", url: href });
466
+ }
467
+ // ---- post boxes -----------------------------------------------------------
468
+ postBox(address, handler) {
469
+ let state = this.#boxes.get(address);
470
+ if (!state || state.closing) {
471
+ state = { handlers: /* @__PURE__ */ new Set(), closing: false };
472
+ this.#boxes.set(address, state);
473
+ state.handlers.add(handler);
474
+ if (this.#requireWorker("postBox()")) this.#post({ kind: "box-open", address });
475
+ } else {
476
+ state.handlers.add(handler);
477
+ const last = state.last;
478
+ if (last) queueMicrotask(() => handler({ address, value: last.value, box: last.box, closed: false }));
479
+ }
480
+ const s = state;
481
+ return () => {
482
+ s.handlers.delete(handler);
483
+ if (s.handlers.size === 0 && this.#boxes.get(address) === s) this.closeBox(address);
484
+ };
485
+ }
486
+ post(address, value) {
487
+ if (!this.#requireWorker("post()")) return;
488
+ this.#post({ kind: "box-post", address, value });
489
+ }
490
+ closeBox(address) {
491
+ const state = this.#boxes.get(address);
492
+ if (!state || state.closing) return;
493
+ state.closing = true;
494
+ if (this.#mode === "none" || this.#gaveUp) {
495
+ this.#finishClose(address, state.last?.box ?? {});
496
+ return;
497
+ }
498
+ this.#post({ kind: "box-close", address });
499
+ }
500
+ // ---- packages -------------------------------------------------------------
501
+ package(address, handler) {
502
+ let state = this.#packages.get(address);
503
+ if (!state) {
504
+ state = { handlers: /* @__PURE__ */ new Set() };
505
+ this.#packages.set(address, state);
506
+ state.handlers.add(handler);
507
+ if (this.#requireWorker("package()")) this.#post({ kind: "package-open", address });
508
+ } else {
509
+ state.handlers.add(handler);
510
+ const last = state.last;
511
+ if (last) queueMicrotask(() => handler({ address, content: last.content }));
512
+ }
513
+ const s = state;
514
+ return () => {
515
+ s.handlers.delete(handler);
516
+ if (s.handlers.size === 0 && this.#packages.get(address) === s) this.#packages.delete(address);
517
+ };
518
+ }
519
+ pack(address, content) {
520
+ if (!this.#requireWorker("pack()")) return;
521
+ this.#post({ kind: "package-pack", address, content });
522
+ }
523
+ // ---- lifecycle ------------------------------------------------------------
524
+ destroy() {
525
+ if (this.#destroyed) return;
526
+ this.#destroyed = true;
527
+ if (this.#inert) return;
528
+ this.#onPageHide();
529
+ this.#flushQueue();
530
+ window.removeEventListener("pagehide", this.#onPageHide);
531
+ window.removeEventListener("pageshow", this.#onPageShow);
532
+ this.#channel?.removeEventListener("message", this.#onChannel);
533
+ this.#channel?.close();
534
+ this.#cross?.destroy();
535
+ if (this.#worker instanceof Worker) this.#worker.terminate();
536
+ this.#worker = void 0;
537
+ this.#releaseLeader?.();
538
+ clearTimeout(this.#readyTimer);
539
+ this.#resolveReady(false);
540
+ this.#events.clear();
541
+ this.#crossEvents.clear();
542
+ this.#boxes.clear();
543
+ this.#packages.clear();
544
+ }
545
+ // ---------------------------------------------------------------------------
546
+ #startWorker() {
547
+ const { workerUrl } = this.#config;
548
+ if (workerUrl === false) {
549
+ this.#mode = "none";
550
+ this.#giveUp();
551
+ return;
552
+ }
553
+ const url = new URL(workerUrl, window.location.href).href;
554
+ const options = { name: this.#channelName };
555
+ if (typeof SharedWorker === "function") {
556
+ try {
557
+ const worker = new SharedWorker(url, options);
558
+ worker.addEventListener("error", () => this.#workerFailed(`could not start SharedWorker ${url}`));
559
+ worker.port.start();
560
+ this.#worker = worker;
561
+ this.#mode = "shared";
562
+ this.#post({ kind: "hello" });
563
+ this.#armReadyTimer();
564
+ return;
565
+ } catch (error) {
566
+ console.warn("PostalWorker: SharedWorker failed to start, trying the fallback", error);
567
+ }
568
+ }
569
+ if ((this.#config.fallback ?? "dedicated") === "none" || typeof Worker !== "function") {
570
+ this.#mode = "none";
571
+ this.#giveUp();
572
+ return;
573
+ }
574
+ if (!navigator.locks) {
575
+ this.#mode = "none";
576
+ this.#reportError(new Error("PostalWorker: no SharedWorker or Web Locks here; running without a worker"));
577
+ this.#giveUp();
578
+ return;
579
+ }
580
+ this.#mode = "dedicated";
581
+ this.#post({ kind: "hello" });
582
+ this.#armReadyTimer();
583
+ void navigator.locks.request(`${this.#channelName}:worker-leader`, () => {
584
+ if (this.#destroyed) return void 0;
585
+ try {
586
+ const worker = new Worker(url, options);
587
+ worker.addEventListener("error", () => this.#workerFailed(`could not start Worker ${url}`));
588
+ this.#worker = worker;
589
+ } catch (error) {
590
+ this.#workerFailed(`could not start Worker ${url}: ${String(error)}`);
591
+ return void 0;
592
+ }
593
+ return new Promise((resolve) => {
594
+ this.#releaseLeader = resolve;
595
+ });
596
+ });
597
+ }
598
+ #armReadyTimer() {
599
+ clearTimeout(this.#readyTimer);
600
+ this.#readyTimer = setTimeout(() => {
601
+ if (this.#online) return;
602
+ this.#reportError(new Error(`PostalWorker: worker did not answer within ${this.#config.readyTimeout ?? 5e3}ms`));
603
+ this.#giveUp();
604
+ }, this.#config.readyTimeout ?? 5e3);
605
+ }
606
+ #workerFailed(reason) {
607
+ if (this.#online) return;
608
+ this.#mode = "none";
609
+ this.#reportError(new Error(`PostalWorker: ${reason}`));
610
+ this.#giveUp();
611
+ }
612
+ /** Stop waiting for the worker: send whatever is queued. */
613
+ #giveUp() {
614
+ if (this.#online) return;
615
+ this.#gaveUp = true;
616
+ clearTimeout(this.#readyTimer);
617
+ this.#flushQueue();
618
+ this.#resolveReady(false);
619
+ }
620
+ #requireWorker(what) {
621
+ if (this.#inert) return false;
622
+ if (this.#mode === "none") {
623
+ this.#reportError(new Error(`PostalWorker: ${what} needs the worker, but this instance has none`));
624
+ return false;
625
+ }
626
+ return true;
627
+ }
628
+ #handleChannel(data) {
629
+ if (!isChannelMsg(data) || data.from === this.id) return;
630
+ switch (data.kind) {
631
+ case "fire":
632
+ if (reachesTab(data.audience, this.id)) this.#events.emit(data.msgClass, data.message, { from: data.from });
633
+ return;
634
+ case "worker-ready":
635
+ this.#workerReady(data.instance);
636
+ return;
637
+ case "box-update": {
638
+ if (data.to !== void 0 && data.to !== this.id) return;
639
+ const state = this.#boxes.get(data.address);
640
+ if (!state || state.closing) return;
641
+ state.last = { value: data.value, box: data.box };
642
+ for (const h of [...state.handlers]) safeCall(() => h({ address: data.address, value: data.value, box: data.box, closed: false }));
643
+ return;
644
+ }
645
+ case "box-closed":
646
+ if (data.to === this.id) this.#finishClose(data.address, data.box);
647
+ return;
648
+ case "package-update": {
649
+ if (data.to !== void 0 && data.to !== this.id) return;
650
+ const state = this.#packages.get(data.address);
651
+ if (!state) return;
652
+ if (data.to !== void 0 && data.content === null && state.last) return;
653
+ state.last = { content: data.content };
654
+ for (const h of [...state.handlers]) safeCall(() => h({ address: data.address, content: data.content }));
655
+ return;
656
+ }
657
+ case "error":
658
+ if (data.to === void 0 || data.to === this.id) this.#reportError(new Error(data.message));
659
+ return;
660
+ // messages meant for the worker
661
+ case "hello":
662
+ case "join":
663
+ case "leave":
664
+ case "box-open":
665
+ case "box-post":
666
+ case "box-close":
667
+ case "package-open":
668
+ case "package-pack":
669
+ case "load":
670
+ return;
671
+ default:
672
+ assertNever(data);
673
+ }
674
+ }
675
+ #workerReady(instance) {
676
+ const previous = this.#workerInstance;
677
+ if (previous === instance) return;
678
+ this.#workerInstance = instance;
679
+ clearTimeout(this.#readyTimer);
680
+ this.#post({ kind: "join" }, true);
681
+ if (previous !== void 0) {
682
+ for (const url of this.#loaded) this.#post({ kind: "load", url }, true);
683
+ for (const [address, state] of this.#boxes) {
684
+ if (state.closing) continue;
685
+ const v = state.last?.value;
686
+ this.#post(v === void 0 || v === null ? { kind: "box-open", address } : { kind: "box-open", address, seed: { value: v } }, true);
687
+ }
688
+ for (const address of this.#packages.keys()) this.#post({ kind: "package-open", address }, true);
689
+ }
690
+ this.#online = true;
691
+ this.#gaveUp = false;
692
+ this.#flushQueue();
693
+ this.#resolveReady(true);
694
+ }
695
+ #finishClose(address, box) {
696
+ const state = this.#boxes.get(address);
697
+ if (!state) return;
698
+ this.#boxes.delete(address);
699
+ for (const h of [...state.handlers]) safeCall(() => h({ address, value: null, box, closed: true }));
700
+ }
701
+ /** Send on the channel; queued until the worker answers (or we stop waiting). */
702
+ #post(body, immediate = false) {
703
+ if (!this.#channel || this.#destroyed && body.kind !== "leave") return;
704
+ const waiting = this.#mode !== "none" && !this.#online && !this.#gaveUp;
705
+ if (waiting && !immediate && body.kind !== "hello" && body.kind !== "join") {
706
+ this.#queue.push(body);
707
+ return;
708
+ }
709
+ this.#channel.postMessage(envelope(this.id, body));
710
+ }
711
+ #flushQueue() {
712
+ const queued = this.#queue;
713
+ this.#queue = [];
714
+ for (const body of queued) this.#channel?.postMessage(envelope(this.id, body));
715
+ }
716
+ #resolveReady(online) {
717
+ for (const resolve of this.#readyWaiters.splice(0)) resolve(online);
718
+ }
719
+ #reportError(error) {
720
+ if (this.#config.onError) safeCall(() => this.#config.onError?.(error));
721
+ else console.error(error);
722
+ }
723
+ };
724
+ function safeCall(fn) {
725
+ try {
726
+ fn();
727
+ } catch (error) {
728
+ queueMicrotask(() => {
729
+ throw error;
730
+ });
731
+ }
732
+ }
733
+ function newId() {
734
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
735
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
736
+ }
737
+
738
+ // src/compat.ts
739
+ var singleton;
740
+ function PostalWorker(configuration) {
741
+ singleton ??= createLegacy(configuration ?? {});
742
+ return singleton;
743
+ }
744
+ function createLegacy(config) {
745
+ const route = config.PostalRoute ?? detectPostalRoute();
746
+ const v5 = createPostalWorker({
747
+ workerUrl: joinRoute(route, "PostalSharedWorker.js"),
748
+ allowedOrigins: config.allowedOrigins ?? "*",
749
+ ...config.channelName !== void 0 && { channelName: config.channelName },
750
+ ...config.onError !== void 0 && { onError: config.onError }
751
+ });
752
+ const legacy = {
753
+ get id() {
754
+ return v5.id;
755
+ },
756
+ get sharedWorkerSupported() {
757
+ return typeof SharedWorker === "function";
758
+ },
759
+ get workerOnline() {
760
+ return v5.workerOnline;
761
+ },
762
+ on(msgClass, action) {
763
+ v5.on(msgClass, (m) => action(m));
764
+ return legacy;
765
+ },
766
+ un(msgClass) {
767
+ v5.off(msgClass);
768
+ return true;
769
+ },
770
+ fire(msgClass, msg, audience) {
771
+ v5.fire(msgClass, msg, toAudience(audience));
772
+ return true;
773
+ },
774
+ crossOn(msgClass, action, subscriber, name, windowparams) {
775
+ v5.crossOn(msgClass, (m) => action(m), subscriber, {
776
+ ...name !== void 0 && { name },
777
+ ...windowparams ? { features: windowparams } : {}
778
+ });
779
+ return legacy;
780
+ },
781
+ unCross(msgClass, subscriber) {
782
+ v5.crossOff(msgClass);
783
+ if (subscriber) v5.closeWindows(subscriber);
784
+ return legacy;
785
+ },
786
+ crossFire(msgClass, msg) {
787
+ v5.crossFire(msgClass, msg);
788
+ return legacy;
789
+ },
790
+ fireAll(msgClass, msg) {
791
+ v5.fireAll(msgClass, msg);
792
+ return legacy;
793
+ },
794
+ backFire(msgClass, msg) {
795
+ v5.backFire(msgClass, msg);
796
+ return legacy;
797
+ },
798
+ load(library) {
799
+ v5.load(library);
800
+ },
801
+ postBox(address, callback) {
802
+ v5.postBox(address, ({ address: a, value, box }) => callback({ address: a, value, box }));
803
+ },
804
+ post(address, value) {
805
+ v5.post(address, value);
806
+ },
807
+ closeBox(address) {
808
+ v5.closeBox(address);
809
+ },
810
+ package(address, handling) {
811
+ v5.package(address, ({ address: a, content }) => handling({ address: a, content }));
812
+ },
813
+ pack(address, url) {
814
+ fetch(url).then((r) => {
815
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
816
+ return r.blob();
817
+ }).then(blobToDataUrl).then((content) => v5.pack(address, content)).catch((error) => console.error(`PostalWorker: pack("${address}", "${url}") failed`, error));
818
+ },
819
+ get v5() {
820
+ return v5;
821
+ }
822
+ };
823
+ return legacy;
824
+ }
825
+ function toAudience(audience) {
826
+ if (audience === void 0 || audience === "ALL") return "all";
827
+ if (audience === "PUBLIC") return "others";
828
+ return audience;
829
+ }
830
+ function joinRoute(route, file) {
831
+ if (!route) return file;
832
+ return route.endsWith("/") ? route + file : `${route}/${file}`;
833
+ }
834
+ function detectPostalRoute() {
835
+ if (typeof document === "undefined") return "";
836
+ const scripts = Array.from(document.querySelectorAll("script[src]")).filter(
837
+ (s) => /PostalWorker[^/]*\.js(\?|#|$)/.test(s.src)
838
+ );
839
+ if (scripts.length > 1) console.warn('PostalWorker: found more than one script tag matching "PostalWorker"; using the first');
840
+ const script = scripts[0];
841
+ if (!script) return "";
842
+ const url = new URL(script.src, window.location.href);
843
+ const fromQuery = url.searchParams.get("PostalRoute");
844
+ if (fromQuery !== null) return fromQuery;
845
+ return url.href.slice(0, url.href.length - url.pathname.length) + url.pathname.replace(/[^/]*$/, "");
846
+ }
847
+ function blobToDataUrl(blob) {
848
+ return new Promise((resolve, reject) => {
849
+ const reader = new FileReader();
850
+ reader.onload = () => resolve(String(reader.result));
851
+ reader.onerror = () => reject(reader.error ?? new Error("FileReader failed"));
852
+ reader.readAsDataURL(blob);
853
+ });
854
+ }
855
+ export {
856
+ WORKER_ID,
857
+ createPostalWorker,
858
+ PostalWorker as default
859
+ };
860
+ //# sourceMappingURL=index.js.map