@chaos-maker/core 0.3.0 → 0.4.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/sw.mjs ADDED
@@ -0,0 +1,720 @@
1
+ var oe = Object.defineProperty;
2
+ var ae = (e, t, n) => t in e ? oe(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var W = (e, t, n) => ae(e, typeof t != "symbol" ? t + "" : t, n);
4
+ class se {
5
+ constructor(t = 2e3) {
6
+ W(this, "listeners", /* @__PURE__ */ new Map());
7
+ W(this, "log", []);
8
+ this.maxLogEntries = t;
9
+ }
10
+ on(t, n) {
11
+ this.listeners.has(t) || this.listeners.set(t, /* @__PURE__ */ new Set()), this.listeners.get(t).add(n);
12
+ }
13
+ off(t, n) {
14
+ var r;
15
+ (r = this.listeners.get(t)) == null || r.delete(n);
16
+ }
17
+ emit(t) {
18
+ this.log.push(t), this.log.length > this.maxLogEntries && this.log.shift(), this.notify(this.listeners.get(t.type), t), this.notify(this.listeners.get("*"), t);
19
+ }
20
+ getLog() {
21
+ return [...this.log];
22
+ }
23
+ clearLog() {
24
+ this.log = [];
25
+ }
26
+ notify(t, n) {
27
+ if (t)
28
+ for (const r of t)
29
+ try {
30
+ r(n);
31
+ } catch {
32
+ }
33
+ }
34
+ }
35
+ function ie(e) {
36
+ let t = e | 0;
37
+ return () => {
38
+ t = t + 1831565813 | 0;
39
+ let n = Math.imul(t ^ t >>> 15, 1 | t);
40
+ return n = n + Math.imul(n ^ n >>> 7, 61 | n) ^ n, ((n ^ n >>> 14) >>> 0) / 4294967296;
41
+ };
42
+ }
43
+ function ue() {
44
+ return Math.random() * 4294967296 >>> 0;
45
+ }
46
+ function Y(e) {
47
+ const t = e ?? ue();
48
+ return {
49
+ random: ie(t),
50
+ seed: t
51
+ };
52
+ }
53
+ function N(e, t) {
54
+ return t() < e;
55
+ }
56
+ function $(e, t) {
57
+ const n = (t.get(e) ?? 0) + 1;
58
+ return t.set(e, n), n;
59
+ }
60
+ function B(e, t) {
61
+ return e.onNth !== void 0 ? t === e.onNth : e.everyNth !== void 0 ? t % e.everyNth === 0 : e.afterN !== void 0 ? t > e.afterN : !0;
62
+ }
63
+ function U(e, t) {
64
+ return t === "*" ? !0 : e.includes(t);
65
+ }
66
+ function le(e, t) {
67
+ switch (t) {
68
+ case "truncate":
69
+ return e.slice(0, Math.max(0, Math.floor(e.length / 2)));
70
+ case "malformed-json":
71
+ return `${e}"}`;
72
+ case "empty":
73
+ return "";
74
+ case "wrong-type":
75
+ return "<html><body>Unexpected HTML</body></html>";
76
+ }
77
+ }
78
+ function ee(e) {
79
+ const t = e.replace(/#[^\r\n]*/g, " "), n = /\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(t);
80
+ return (n == null ? void 0 : n[1]) ?? null;
81
+ }
82
+ function ce(e) {
83
+ try {
84
+ return JSON.parse(e);
85
+ } catch {
86
+ return;
87
+ }
88
+ }
89
+ function te(e) {
90
+ if (!e || typeof e != "object") return { isGraphQL: !1, operationName: null };
91
+ if (Array.isArray(e))
92
+ return e.length === 0 ? { isGraphQL: !1, operationName: null } : te(e[0]);
93
+ const t = e, n = typeof t.query == "string", r = typeof t.operationName == "string";
94
+ return !n && !r ? { isGraphQL: !1, operationName: null } : r && t.operationName.length > 0 ? { isGraphQL: !0, operationName: t.operationName } : n ? { isGraphQL: !0, operationName: ee(t.query) } : { isGraphQL: !0, operationName: null };
95
+ }
96
+ function fe(e) {
97
+ let t;
98
+ try {
99
+ t = new URL(e, "http://_chaos-maker.invalid");
100
+ } catch {
101
+ return { kind: "not-graphql" };
102
+ }
103
+ const n = t.searchParams.get("operationName"), r = t.searchParams.get("query");
104
+ return n && n.length > 0 ? { kind: "extracted", operationName: n } : r && r.length > 0 ? { kind: "extracted", operationName: ee(r) } : { kind: "not-graphql" };
105
+ }
106
+ function de(e, t, n, r) {
107
+ const a = e.toUpperCase();
108
+ if (a === "POST") {
109
+ if (n !== null) {
110
+ const u = ce(n);
111
+ if (u === void 0) return { kind: "not-graphql" };
112
+ const { isGraphQL: p, operationName: c } = te(u);
113
+ return p ? { kind: "extracted", operationName: c } : { kind: "not-graphql" };
114
+ }
115
+ return r ? { kind: "unparseable" } : { kind: "not-graphql" };
116
+ }
117
+ return a === "GET" ? fe(t) : { kind: "not-graphql" };
118
+ }
119
+ function pe(e, t) {
120
+ return t === null ? !1 : typeof e == "string" ? e === t : ((e.global || e.sticky) && (e.lastIndex = 0), e.test(t));
121
+ }
122
+ function ne(e, t) {
123
+ return e ? t.kind === "not-graphql" ? { kind: "no-match" } : t.kind === "unparseable" ? { kind: "unparseable" } : pe(e, t.operationName) ? { kind: "match", operationName: t.operationName } : { kind: "no-match" } : t.kind === "extracted" ? { kind: "skip-no-constraint", operationName: t.operationName } : { kind: "skip-no-constraint", operationName: null };
124
+ }
125
+ function H(e) {
126
+ return typeof Request < "u" && e instanceof Request;
127
+ }
128
+ function he(e) {
129
+ return H(e) ? e.url : e.toString();
130
+ }
131
+ function ye(e, t) {
132
+ return t != null && t.method ? t.method.toUpperCase() : H(e) ? e.method.toUpperCase() : "GET";
133
+ }
134
+ function ge(e, t) {
135
+ if (t != null && t.signal)
136
+ return t.signal;
137
+ if (H(e))
138
+ return e.signal;
139
+ }
140
+ function be() {
141
+ if (typeof DOMException < "u")
142
+ return new DOMException("The user aborted a request.", "AbortError");
143
+ const e = new Error("The user aborted a request.");
144
+ return e.name = "AbortError", e;
145
+ }
146
+ function me(e, t) {
147
+ if (!t)
148
+ return e;
149
+ const n = new AbortController(), r = (c) => {
150
+ p(), n.signal.aborted || n.abort(c.reason);
151
+ }, a = () => r(e), u = () => r(t), p = () => {
152
+ e.removeEventListener("abort", a), t.removeEventListener("abort", u);
153
+ };
154
+ return e.aborted ? (r(e), n.signal) : t.aborted ? (r(t), n.signal) : (e.addEventListener("abort", a, { once: !0 }), t.addEventListener("abort", u, { once: !0 }), n.signal);
155
+ }
156
+ function ke(e, t) {
157
+ return t ? {
158
+ ...e ?? {},
159
+ signal: t
160
+ } : e;
161
+ }
162
+ async function we(e, t) {
163
+ const n = t == null ? void 0 : t.body;
164
+ if (n != null) {
165
+ if (typeof n == "string") return { text: n, unparseable: !1 };
166
+ if (typeof URLSearchParams < "u" && n instanceof URLSearchParams)
167
+ return { text: n.toString(), unparseable: !1 };
168
+ if (typeof Blob < "u" && n instanceof Blob) {
169
+ if (!(n.type === "" || /json|text|graphql/i.test(n.type))) return { text: null, unparseable: !0 };
170
+ try {
171
+ return { text: await n.text(), unparseable: !1 };
172
+ } catch {
173
+ return { text: null, unparseable: !0 };
174
+ }
175
+ }
176
+ return { text: null, unparseable: !0 };
177
+ }
178
+ if (H(e)) {
179
+ if (e.body === null) return { text: null, unparseable: !1 };
180
+ try {
181
+ return { text: await e.clone().text(), unparseable: !1 };
182
+ } catch {
183
+ return { text: null, unparseable: !0 };
184
+ }
185
+ }
186
+ return { text: null, unparseable: !1 };
187
+ }
188
+ function q(e, t, n, r, a) {
189
+ e == null || e.emit({
190
+ type: t,
191
+ timestamp: Date.now(),
192
+ applied: !1,
193
+ detail: { url: n, method: r, ...a, reason: "graphql-body-unparseable" }
194
+ });
195
+ }
196
+ function R(e, t, n, r, a) {
197
+ if (!U(t, e.urlPattern)) return { proceed: !1, outcome: null };
198
+ if (e.methods && !e.methods.includes(n)) return { proceed: !1, outcome: null };
199
+ const u = ne(e.graphqlOperation, r);
200
+ if (u.kind === "no-match" || u.kind === "unparseable")
201
+ return { proceed: !1, outcome: u };
202
+ const p = $(e, a);
203
+ return B(e, p) ? { proceed: !0, outcome: u } : { proceed: !1, outcome: u };
204
+ }
205
+ function P(e) {
206
+ return e ? e.kind === "match" || e.kind === "skip-no-constraint" ? e.operationName ? { operationName: e.operationName } : {} : {} : {};
207
+ }
208
+ function j(e, t, n, r, a, u) {
209
+ e == null || e.emit({
210
+ type: "network:abort",
211
+ timestamp: Date.now(),
212
+ applied: a,
213
+ detail: { url: n, method: r, timeoutMs: t.timeout, ...P(u) }
214
+ });
215
+ }
216
+ function F(e, t, n, r, a, u) {
217
+ e == null || e.emit({
218
+ type: "network:corruption",
219
+ timestamp: Date.now(),
220
+ applied: a,
221
+ detail: { url: n, method: r, strategy: t.strategy, ...P(u) }
222
+ });
223
+ }
224
+ function Se(e) {
225
+ return e.graphqlOperation !== void 0;
226
+ }
227
+ function Me(e, t, n, r, a = /* @__PURE__ */ new Map()) {
228
+ return async (u, p) => {
229
+ var b, m, k, w;
230
+ const c = he(u), d = ye(u, p), C = ge(u, p), L = (() => {
231
+ const o = [t.failures, t.latencies, t.aborts, t.corruptions, t.cors];
232
+ for (const y of o)
233
+ if (y != null && y.some(Se)) return !0;
234
+ return !1;
235
+ })();
236
+ let S = { kind: "not-graphql" };
237
+ if (L) {
238
+ const o = await we(u, p);
239
+ S = de(d, c, o.text, o.unparseable);
240
+ }
241
+ if (t.cors)
242
+ for (const o of t.cors) {
243
+ if (!U(c, o.urlPattern) || o.methods && !o.methods.includes(d)) continue;
244
+ const y = ne(o.graphqlOperation, S);
245
+ if (y.kind === "no-match") continue;
246
+ if (y.kind === "unparseable") {
247
+ q(r, "network:cors", c, d, {});
248
+ continue;
249
+ }
250
+ const E = $(o, a);
251
+ if (!B(o, E)) continue;
252
+ const v = N(o.probability, n);
253
+ if (r == null || r.emit({
254
+ type: "network:cors",
255
+ timestamp: Date.now(),
256
+ applied: v,
257
+ detail: { url: c, method: d, ...P(y) }
258
+ }), v) {
259
+ console.debug(`[chaos-maker] CORS block: ${d} ${c}`);
260
+ const x = new TypeError("Failed to fetch");
261
+ throw x.stack = "", x;
262
+ }
263
+ }
264
+ let M = null, A = null, T, i, s = !1;
265
+ const l = (o) => {
266
+ !M || s || (s = !0, i && (clearTimeout(i), i = void 0), j(r, M, c, d, o, A));
267
+ };
268
+ if (t.aborts)
269
+ for (const o of t.aborts) {
270
+ const y = R(o, c, d, S, a);
271
+ if (!y.proceed) {
272
+ ((b = y.outcome) == null ? void 0 : b.kind) === "unparseable" && q(r, "network:abort", c, d, { timeoutMs: o.timeout });
273
+ continue;
274
+ }
275
+ if (!N(o.probability, n)) {
276
+ j(r, o, c, d, !1, y.outcome);
277
+ continue;
278
+ }
279
+ console.warn(`CHAOS: Aborting ${d} ${c} after ${o.timeout || 0}ms`), M = o, A = y.outcome;
280
+ const v = new AbortController();
281
+ T = me(v.signal, C);
282
+ const x = () => {
283
+ s || (l(!0), v.abort(be()));
284
+ };
285
+ o.timeout ? i = setTimeout(x, o.timeout) : x();
286
+ break;
287
+ }
288
+ if (M)
289
+ try {
290
+ const o = await e(u, ke(p, T));
291
+ return l(!1), o;
292
+ } catch (o) {
293
+ throw l(!1), o;
294
+ }
295
+ if (t.failures)
296
+ for (const o of t.failures) {
297
+ const y = R(o, c, d, S, a);
298
+ if (!y.proceed) {
299
+ ((m = y.outcome) == null ? void 0 : m.kind) === "unparseable" && q(r, "network:failure", c, d, { statusCode: o.statusCode });
300
+ continue;
301
+ }
302
+ const E = N(o.probability, n);
303
+ if (r == null || r.emit({
304
+ type: "network:failure",
305
+ timestamp: Date.now(),
306
+ applied: E,
307
+ detail: { url: c, method: d, statusCode: o.statusCode, ...P(y.outcome) }
308
+ }), E) {
309
+ console.warn(`CHAOS: Forcing ${o.statusCode} for ${d} ${c}`);
310
+ const v = o.body ?? JSON.stringify({ error: "Chaos Maker Attack!" }), x = o.headers ?? {};
311
+ return new Response(v, {
312
+ status: o.statusCode,
313
+ statusText: o.statusText ?? "Service Unavailable (Chaos)",
314
+ headers: x
315
+ });
316
+ }
317
+ }
318
+ if (t.latencies)
319
+ for (const o of t.latencies) {
320
+ const y = R(o, c, d, S, a);
321
+ if (!y.proceed) {
322
+ ((k = y.outcome) == null ? void 0 : k.kind) === "unparseable" && q(r, "network:latency", c, d, { delayMs: o.delayMs });
323
+ continue;
324
+ }
325
+ const E = N(o.probability, n);
326
+ r == null || r.emit({
327
+ type: "network:latency",
328
+ timestamp: Date.now(),
329
+ applied: E,
330
+ detail: { url: c, method: d, delayMs: o.delayMs, ...P(y.outcome) }
331
+ }), E && (console.warn(`CHAOS: Adding ${o.delayMs}ms latency to ${d} ${c}`), await new Promise((v) => setTimeout(v, o.delayMs)));
332
+ }
333
+ let f = null, h = null;
334
+ if (t.corruptions)
335
+ for (const o of t.corruptions) {
336
+ const y = R(o, c, d, S, a);
337
+ if (!y.proceed) {
338
+ ((w = y.outcome) == null ? void 0 : w.kind) === "unparseable" && q(r, "network:corruption", c, d, { strategy: o.strategy });
339
+ continue;
340
+ }
341
+ if (!N(o.probability, n)) {
342
+ F(r, o, c, d, !1, y.outcome);
343
+ continue;
344
+ }
345
+ f = o, h = y.outcome;
346
+ break;
347
+ }
348
+ let g;
349
+ try {
350
+ g = await e(u, p);
351
+ } catch (o) {
352
+ throw f && F(r, f, c, d, !1, h), o;
353
+ }
354
+ if (!f)
355
+ return g;
356
+ try {
357
+ console.warn(`CHAOS: Corrupting response for ${d} ${c} with strategy: ${f.strategy}`);
358
+ const o = await g.text(), y = le(o, f.strategy);
359
+ return F(r, f, c, d, !0, h), new Response(y, {
360
+ status: g.status,
361
+ statusText: g.statusText,
362
+ headers: g.headers
363
+ });
364
+ } catch (o) {
365
+ throw F(r, f, c, d, !1, h), o;
366
+ }
367
+ };
368
+ }
369
+ const J = /* @__PURE__ */ Symbol.for("chaos-maker.websocket.intercepted");
370
+ function Ce(e, t) {
371
+ return e === "both" ? !0 : e === t;
372
+ }
373
+ function z(e) {
374
+ return typeof e == "string" ? "text" : "binary";
375
+ }
376
+ function K(e, t) {
377
+ switch (t) {
378
+ case "truncate":
379
+ return e.slice(0, Math.max(0, Math.floor(e.length / 2)));
380
+ case "malformed-json":
381
+ return `${e}"}`;
382
+ case "empty":
383
+ return "";
384
+ case "wrong-type":
385
+ return "<html><body>Unexpected HTML</body></html>";
386
+ }
387
+ }
388
+ function Z(e, t) {
389
+ if (t === "malformed-json" || t === "wrong-type") return null;
390
+ if (t === "empty")
391
+ return typeof Blob < "u" && e instanceof Blob ? new Blob([]) : e instanceof ArrayBuffer ? new ArrayBuffer(0) : new Uint8Array(0);
392
+ if (typeof Blob < "u" && e instanceof Blob)
393
+ return e.slice(0, Math.max(0, Math.floor(e.size / 2)));
394
+ if (e instanceof ArrayBuffer)
395
+ return e.slice(0, Math.max(0, Math.floor(e.byteLength / 2)));
396
+ const n = e, r = Math.max(0, Math.floor(n.byteLength / 2));
397
+ return new Uint8Array(n.buffer.slice(n.byteOffset, n.byteOffset + r));
398
+ }
399
+ function O(e, t, n, r, a) {
400
+ if (!e) return null;
401
+ for (const u of e) {
402
+ if (!U(t, u.urlPattern) || !Ce(u.direction, n)) continue;
403
+ const p = $(u, a);
404
+ if (B(u, p) && N(u.probability, r))
405
+ return u;
406
+ }
407
+ return null;
408
+ }
409
+ function G(e, t, n, r, a) {
410
+ e.emit({
411
+ type: "websocket:drop",
412
+ timestamp: Date.now(),
413
+ applied: !0,
414
+ detail: { url: t, direction: n, payloadType: r, ...a ? { reason: a } : {} }
415
+ });
416
+ }
417
+ function V(e, t, n, r, a) {
418
+ e.emit({
419
+ type: "websocket:delay",
420
+ timestamp: Date.now(),
421
+ applied: !0,
422
+ detail: { url: t, direction: n, payloadType: r, delayMs: a }
423
+ });
424
+ }
425
+ function _(e, t, n, r, a, u, p) {
426
+ e.emit({
427
+ type: "websocket:corrupt",
428
+ timestamp: Date.now(),
429
+ applied: u,
430
+ detail: { url: t, direction: n, payloadType: r, strategy: a, ...p ? { reason: p } : {} }
431
+ });
432
+ }
433
+ function Le(e, t, n, r) {
434
+ e.emit({
435
+ type: "websocket:close",
436
+ timestamp: Date.now(),
437
+ applied: !0,
438
+ detail: { url: t, closeCode: n, closeReason: r }
439
+ });
440
+ }
441
+ function Ee(e, t, n, r, a) {
442
+ const u = /* @__PURE__ */ new Map();
443
+ let p = !0;
444
+ const c = (i, s) => {
445
+ let l = u.get(i);
446
+ l || (l = /* @__PURE__ */ new Set(), u.set(i, l)), l.add(s);
447
+ }, d = (i, s) => {
448
+ var l;
449
+ (l = u.get(i)) == null || l.delete(s);
450
+ }, C = (i, s) => {
451
+ const l = u.get(i);
452
+ if (l) {
453
+ for (const f of l)
454
+ clearTimeout(f.handle), f.kind === "delay" && G(n, f.url, f.direction, f.payloadType, s);
455
+ u.delete(i);
456
+ }
457
+ }, L = (i, s, l) => {
458
+ const f = new MessageEvent("message", {
459
+ data: l,
460
+ origin: s.origin,
461
+ lastEventId: s.lastEventId,
462
+ source: s.source,
463
+ ports: Array.from(s.ports ?? [])
464
+ });
465
+ f[J] = !0, i.dispatchEvent(f);
466
+ }, S = (i, s, l, f) => {
467
+ if (!p) return { handled: !1, data: l };
468
+ const h = "outbound", g = z(l);
469
+ if (O(t.drops, s, h, r, a))
470
+ return G(n, s, h, g), { handled: !0, data: l };
471
+ let b = l;
472
+ const m = O(t.corruptions, s, h, r, a);
473
+ if (m)
474
+ if (g === "text")
475
+ b = K(b, m.strategy), _(n, s, h, g, m.strategy, !0);
476
+ else {
477
+ const w = Z(b, m.strategy);
478
+ w === null ? _(n, s, h, g, m.strategy, !1, "incompatible-payload-type") : (b = w, _(n, s, h, g, m.strategy, !0));
479
+ }
480
+ const k = O(t.delays, s, h, r, a);
481
+ if (k) {
482
+ V(n, s, h, g, k.delayMs);
483
+ const w = {
484
+ kind: "delay",
485
+ handle: setTimeout(() => {
486
+ d(i, w);
487
+ try {
488
+ f(b);
489
+ } catch {
490
+ }
491
+ }, k.delayMs),
492
+ url: s,
493
+ direction: h,
494
+ payloadType: g
495
+ };
496
+ return c(i, w), { handled: !0, data: b };
497
+ }
498
+ return { handled: !1, data: b };
499
+ }, M = (i, s) => {
500
+ i.addEventListener("message", (l) => {
501
+ const f = l;
502
+ if (f[J] || !p) return;
503
+ const h = "inbound", g = z(f.data);
504
+ if (O(t.drops, s, h, r, a)) {
505
+ f.stopImmediatePropagation(), G(n, s, h, g);
506
+ return;
507
+ }
508
+ let b = f.data, m = !1;
509
+ const k = O(t.corruptions, s, h, r, a);
510
+ if (k)
511
+ if (g === "text")
512
+ b = K(b, k.strategy), m = !0, _(n, s, h, g, k.strategy, !0);
513
+ else {
514
+ const o = Z(b, k.strategy);
515
+ o === null ? _(n, s, h, g, k.strategy, !1, "incompatible-payload-type") : (b = o, m = !0, _(n, s, h, g, k.strategy, !0));
516
+ }
517
+ const w = O(t.delays, s, h, r, a);
518
+ if (w) {
519
+ f.stopImmediatePropagation(), V(n, s, h, g, w.delayMs);
520
+ const o = {
521
+ kind: "delay",
522
+ handle: setTimeout(() => {
523
+ d(i, o), L(i, f, b);
524
+ }, w.delayMs),
525
+ url: s,
526
+ direction: h,
527
+ payloadType: g
528
+ };
529
+ c(i, o);
530
+ return;
531
+ }
532
+ m && (f.stopImmediatePropagation(), L(i, f, b));
533
+ });
534
+ }, A = (i, s) => {
535
+ if (t.closes)
536
+ for (const l of t.closes) {
537
+ if (!U(s, l.urlPattern)) continue;
538
+ const f = $(l, a);
539
+ if (!B(l, f) || !N(l.probability, r)) continue;
540
+ const h = l.code ?? 1e3, g = l.reason ?? "Chaos Maker close", b = l.afterMs ?? 0, m = () => {
541
+ if (p) {
542
+ C(i, "close-interrupt"), Le(n, s, h, g);
543
+ try {
544
+ i.close(h, g);
545
+ } catch {
546
+ try {
547
+ i.close();
548
+ } catch {
549
+ }
550
+ }
551
+ }
552
+ };
553
+ if (b <= 0)
554
+ i.readyState === i.OPEN ? m() : i.addEventListener("open", m, { once: !0 });
555
+ else {
556
+ const k = () => {
557
+ const w = {
558
+ kind: "close",
559
+ handle: setTimeout(m, b)
560
+ };
561
+ c(i, w);
562
+ };
563
+ i.readyState === i.OPEN ? k() : i.addEventListener("open", k, { once: !0 });
564
+ }
565
+ return;
566
+ }
567
+ };
568
+ function T(i, s) {
569
+ const l = new e(i, s), f = typeof i == "string" ? i : i.toString(), h = l.send.bind(l);
570
+ return l.send = function(b) {
571
+ const m = S(l, f, b, h);
572
+ m.handled || h(m.data);
573
+ }, M(l, f), A(l, f), l;
574
+ }
575
+ Object.defineProperty(T, "prototype", {
576
+ value: e.prototype,
577
+ writable: !1
578
+ });
579
+ for (const i of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"])
580
+ T[i] = e[i];
581
+ return {
582
+ Wrapped: T,
583
+ uninstall() {
584
+ p = !1;
585
+ for (const [, i] of u)
586
+ for (const s of i)
587
+ clearTimeout(s.handle), s.kind === "delay" && G(n, s.url, s.direction, s.payloadType, "stop-during-delay");
588
+ u.clear();
589
+ }
590
+ };
591
+ }
592
+ const Q = /* @__PURE__ */ Symbol.for("chaos-maker.sw.installed");
593
+ function ve() {
594
+ return typeof self < "u" ? self : typeof globalThis < "u" ? globalThis : null;
595
+ }
596
+ function re(e, t) {
597
+ const n = e.clients;
598
+ !n || typeof n.matchAll != "function" || n.matchAll({ includeUncontrolled: !0 }).then((r) => {
599
+ for (const a of r)
600
+ try {
601
+ a.postMessage(t);
602
+ } catch {
603
+ }
604
+ }).catch(() => {
605
+ });
606
+ }
607
+ function X(e, t) {
608
+ e.running && I(e);
609
+ const n = Y(t.seed);
610
+ if (e.seed = n.seed, e.random = n.random, e.requestCounters = /* @__PURE__ */ new Map(), t.network) {
611
+ const r = e.target;
612
+ typeof r.fetch == "function" && (e.originalFetch = r.fetch, r.fetch = Me(
613
+ e.originalFetch.bind(r),
614
+ t.network,
615
+ e.random,
616
+ e.emitter,
617
+ e.requestCounters
618
+ ));
619
+ }
620
+ return t.websocket && typeof e.target.WebSocket < "u" && (e.originalWebSocket = e.target.WebSocket, e.webSocketHandle = Ee(
621
+ e.originalWebSocket,
622
+ t.websocket,
623
+ e.emitter,
624
+ e.random,
625
+ e.requestCounters
626
+ ), e.target.WebSocket = e.webSocketHandle.Wrapped), e.running = !0, e.seed;
627
+ }
628
+ function I(e) {
629
+ !e.running && !e.originalFetch && !e.originalWebSocket || (e.originalFetch && (e.target.fetch = e.originalFetch, e.originalFetch = void 0), e.originalWebSocket && (e.target.WebSocket = e.originalWebSocket, e.originalWebSocket = void 0), e.webSocketHandle && (e.webSocketHandle.uninstall(), e.webSocketHandle = void 0), e.running = !1);
630
+ }
631
+ function D(e, t, n) {
632
+ var a;
633
+ const r = (a = t.ports) == null ? void 0 : a[0];
634
+ if (r && typeof r.postMessage == "function")
635
+ try {
636
+ r.postMessage(n);
637
+ return;
638
+ } catch {
639
+ }
640
+ re(e, n);
641
+ }
642
+ function xe(e = {}) {
643
+ const t = ve(), n = {
644
+ isRunning: () => !1,
645
+ getSeed: () => null,
646
+ getLog: () => [],
647
+ clearLog: () => {
648
+ },
649
+ uninstall: () => {
650
+ }
651
+ };
652
+ if (!t || typeof t.fetch != "function" || typeof t.addEventListener != "function")
653
+ return n;
654
+ const r = t[Q];
655
+ if (r) return r;
656
+ const a = new se(e.maxLogEntries ?? 2e3), u = Y(0), p = {
657
+ target: t,
658
+ emitter: a,
659
+ running: !1,
660
+ seed: null,
661
+ random: u.random,
662
+ requestCounters: /* @__PURE__ */ new Map()
663
+ };
664
+ a.on("*", (C) => {
665
+ re(t, { __chaosMakerSWEvent: !0, event: C });
666
+ });
667
+ const c = (C) => {
668
+ const L = C, S = L.data;
669
+ if (!S || typeof S != "object") return;
670
+ const M = S;
671
+ if (M.__chaosMakerConfig) {
672
+ const A = X(p, M.__chaosMakerConfig);
673
+ D(t, L, {
674
+ __chaosMakerAck: !0,
675
+ seed: A,
676
+ running: p.running
677
+ });
678
+ return;
679
+ }
680
+ if (M.__chaosMakerStop) {
681
+ I(p), D(t, L, {
682
+ __chaosMakerAck: !0,
683
+ running: !1
684
+ });
685
+ return;
686
+ }
687
+ if (M.__chaosMakerGetLog) {
688
+ D(t, L, {
689
+ __chaosMakerLog: !0,
690
+ log: a.getLog()
691
+ });
692
+ return;
693
+ }
694
+ if (M.__chaosMakerClearLog) {
695
+ a.clearLog(), D(t, L, {
696
+ __chaosMakerAck: !0,
697
+ running: p.running
698
+ });
699
+ return;
700
+ }
701
+ };
702
+ if (t.addEventListener("message", c), (e.source ?? "message") === "self-global") {
703
+ const C = t.__CHAOS_CONFIG__;
704
+ C && typeof C == "object" && X(p, C);
705
+ }
706
+ const d = {
707
+ isRunning: () => p.running,
708
+ getSeed: () => p.seed,
709
+ getLog: () => a.getLog(),
710
+ clearLog: () => a.clearLog(),
711
+ uninstall: () => {
712
+ t.removeEventListener("message", c), I(p), delete t[Q];
713
+ }
714
+ };
715
+ return t[Q] = d, d;
716
+ }
717
+ typeof self < "u" && typeof importScripts == "function" && xe({ source: "message" });
718
+ export {
719
+ xe as installChaosSW
720
+ };