@naturalcycles/internal-web-lib 1.1.0 → 1.2.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,1027 @@
1
+ function e(e = 21) {
2
+ let t = "", n = globalThis.crypto.getRandomValues(new Uint8Array(e));
3
+ for (; e--;) t += "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[n[e] & 63];
4
+ return t;
5
+ }
6
+ //#endregion
7
+ //#region src/conversion/conversion.util.ts
8
+ function t() {
9
+ return e();
10
+ }
11
+ //#endregion
12
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/is.util.js
13
+ var n = (e) => !!e;
14
+ function r(e) {
15
+ return typeof e == "object" && !!e && !Array.isArray(e) || !1;
16
+ }
17
+ function i(e) {
18
+ if (e == null) return !0;
19
+ if (typeof e == "string" || Array.isArray(e)) return e.length === 0;
20
+ if (e instanceof Map || e instanceof Set) return e.size === 0;
21
+ if (typeof e == "object") {
22
+ for (let t in e) if (Object.hasOwn(e, t)) return !1;
23
+ return !0;
24
+ }
25
+ return !1;
26
+ }
27
+ //#endregion
28
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/abort.js
29
+ function a(e) {
30
+ return e ? o(e) : void 0;
31
+ }
32
+ function o(e) {
33
+ return typeof AbortSignal.timeout == "function" ? AbortSignal.timeout(e) : s(e);
34
+ }
35
+ function s(e) {
36
+ let t = new AbortController();
37
+ return setTimeout(() => {
38
+ t.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError"));
39
+ }, e), t.signal;
40
+ }
41
+ function c(e) {
42
+ let t = e.filter(n);
43
+ return t.length ? l(t) : void 0;
44
+ }
45
+ function l(e) {
46
+ return e.length === 1 ? e[0] : typeof AbortSignal.any == "function" ? AbortSignal.any(e) : u(e);
47
+ }
48
+ function u(e) {
49
+ let t = new AbortController();
50
+ for (let n of e) if (n.aborted) return t.abort(n.reason), t.signal;
51
+ for (let n of e) n.addEventListener("abort", () => t.abort(n.reason), {
52
+ once: !0,
53
+ signal: t.signal
54
+ });
55
+ return t.signal;
56
+ }
57
+ var d = new class {
58
+ logger = console;
59
+ pendingOps = /* @__PURE__ */ new Set();
60
+ onErrorHooks = [];
61
+ runInBackground(e) {
62
+ let t = e.catch((e) => this.fireOnErrorHooks(e)).finally(() => this.pendingOps.delete(t));
63
+ this.pendingOps.add(t);
64
+ }
65
+ onError(e) {
66
+ this.onErrorHooks.push(e);
67
+ }
68
+ async allDone(e) {
69
+ let { size: t } = this.pendingOps;
70
+ if (!t) return;
71
+ let { logger: n } = this, r = Date.now();
72
+ if (e) {
73
+ if (await Promise.race([Promise.allSettled(this.pendingOps), new Promise((t) => setTimeout(t, e, "timeout"))]) === "timeout") {
74
+ n.warn(`AsyncManager.allDone timed out after ${e} ms with ${this.pendingOps.size} pending op(s)`);
75
+ return;
76
+ }
77
+ } else await Promise.allSettled(this.pendingOps);
78
+ n.log(`AsyncManager.allDone for ${t} op(s) in ${Date.now() - r} ms`);
79
+ }
80
+ reset() {
81
+ this.pendingOps.clear(), this.onErrorHooks = [];
82
+ }
83
+ fireOnErrorHooks(e) {
84
+ this.onErrorHooks.length ? this.onErrorHooks.forEach((t) => t(e)) : this.logger.error("AsyncManager unhandled rejection:", e);
85
+ }
86
+ }(), f = d.runInBackground.bind(d), ee = (...e) => void 0, p = Object.entries;
87
+ //#endregion
88
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/object/object.util.js
89
+ function te(e, t, n = {}) {
90
+ if (n.mutate) {
91
+ for (let n of Object.keys(e)) t.includes(n) || delete e[n];
92
+ return e;
93
+ }
94
+ let r = {};
95
+ for (let n of t) n in e && (r[n] = e[n]);
96
+ return r;
97
+ }
98
+ function m(e, t, n = {}) {
99
+ if (n.mutate) {
100
+ for (let n of t) delete e[n];
101
+ return e;
102
+ }
103
+ let r = {};
104
+ for (let n of Object.keys(e)) t.includes(n) || (r[n] = e[n]);
105
+ return r;
106
+ }
107
+ function ne(e, t = {}) {
108
+ return _(e, (e, t) => !!t, t);
109
+ }
110
+ function h(e, t = {}) {
111
+ return _(e, (e, t) => t != null, t);
112
+ }
113
+ function g(e, t = {}) {
114
+ return _(e, (e, t) => t !== void 0, t);
115
+ }
116
+ function _(e, t, n = {}) {
117
+ if (n.mutate) {
118
+ for (let [n, r] of p(e)) t(n, r, e) || delete e[n];
119
+ return e;
120
+ }
121
+ let r = {};
122
+ for (let [n, i] of p(e)) t(n, i, e) && (r[n] = i);
123
+ return r;
124
+ }
125
+ function v(e, t) {
126
+ let n = {};
127
+ for (let [r, i] of Object.entries(e)) n[t(r, i, e)] = i;
128
+ return n;
129
+ }
130
+ function re(e, t = {}) {
131
+ return _(e, (e, t) => !i(t), t);
132
+ }
133
+ function y(e, ...t) {
134
+ for (let n of t) if (r(n)) for (let t of Object.keys(n)) t !== "__proto__" && t !== "constructor" && t !== "prototype" && (r(n[t]) ? (e[t] ||= {}, y(e[t], n[t])) : e[t] = n[t]);
135
+ return e;
136
+ }
137
+ //#endregion
138
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/env.js
139
+ function b() {
140
+ return !x();
141
+ }
142
+ function x() {
143
+ return typeof window < "u" && !!window?.document;
144
+ }
145
+ //#endregion
146
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/json.util.js
147
+ var S = /^\s*[{["\-\d]/;
148
+ function C(e, t) {
149
+ if (typeof e == "string" && e && S.test(e)) try {
150
+ return JSON.parse(e, t);
151
+ } catch {}
152
+ return e;
153
+ }
154
+ function ie(e, t) {
155
+ try {
156
+ return JSON.parse(e, t);
157
+ } catch {
158
+ throw new F({ text: e });
159
+ }
160
+ }
161
+ //#endregion
162
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/string.util.js
163
+ function w(e, t, n = "...") {
164
+ if (!e || e.length <= t) return e;
165
+ if (t <= n.length) return n;
166
+ let r = Math.round((t - n.length) / 2), i = e.length - Math.floor((t - n.length) / 2);
167
+ return e.slice(0, r) + n + e.slice(i);
168
+ }
169
+ //#endregion
170
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/error/error.util.js
171
+ function T(e, t = Error, n) {
172
+ let r;
173
+ return r = e instanceof t ? e : O(E(e), t), n && (r.data ||= {}, Object.assign(r.data, n)), r;
174
+ }
175
+ function E(e, t) {
176
+ let n;
177
+ return j(e) ? n = D(e) : (e = C(e), n = k(e) ? e.error : A(e) ? e : j(e) ? D(e) : {
178
+ name: "Error",
179
+ message: H(e),
180
+ data: {}
181
+ }), Object.assign(n.data, t), n;
182
+ }
183
+ function D(e) {
184
+ if (!(e instanceof Error) && A(e)) return e;
185
+ let t = {
186
+ name: e.name,
187
+ message: e.message,
188
+ data: { ...e.data }
189
+ };
190
+ return e.stack && (t.stack = e.stack), e.cause && (t.cause = E(e.cause)), t;
191
+ }
192
+ function O(e, t = Error) {
193
+ if (e instanceof t) return e;
194
+ let { name: n, cause: r } = e, i = new t(e.message, e.data, {
195
+ name: n,
196
+ cause: r
197
+ });
198
+ return e.stack && Object.defineProperty(i, "stack", { value: e.stack }), i instanceof N || (Object.defineProperties(i, {
199
+ name: {
200
+ value: n,
201
+ configurable: !0,
202
+ writable: !0
203
+ },
204
+ data: {
205
+ value: e.data,
206
+ writable: !0,
207
+ configurable: !0,
208
+ enumerable: !1
209
+ },
210
+ cause: {
211
+ value: r,
212
+ writable: !0,
213
+ configurable: !0,
214
+ enumerable: !0
215
+ }
216
+ }), Object.defineProperty(i.constructor, "name", {
217
+ value: n,
218
+ configurable: !0,
219
+ writable: !0
220
+ })), i;
221
+ }
222
+ function k(e) {
223
+ try {
224
+ return A(e?.error);
225
+ } catch {
226
+ return !1;
227
+ }
228
+ }
229
+ function A(e) {
230
+ try {
231
+ return !!e && typeof e == "object" && typeof e.name == "string" && typeof e.message == "string" && typeof e.data == "object";
232
+ } catch {
233
+ return !1;
234
+ }
235
+ }
236
+ function j(e) {
237
+ try {
238
+ return !!e && typeof e == "object" && typeof e.name == "string" && typeof e.message == "string";
239
+ } catch {
240
+ return !1;
241
+ }
242
+ }
243
+ function M(e, t) {
244
+ return t ? T(e, void 0, t) : e;
245
+ }
246
+ var N = class e extends Error {
247
+ data;
248
+ cause;
249
+ static of(t) {
250
+ return new e(t.message, t.data, {
251
+ name: t.name,
252
+ cause: t.cause
253
+ });
254
+ }
255
+ constructor(e, t = {}, n = {}) {
256
+ super(e);
257
+ let { name: r = b() ? this.constructor.name : "AppError", cause: i } = n;
258
+ Object.defineProperties(this, {
259
+ name: {
260
+ value: r,
261
+ configurable: !0,
262
+ writable: !0
263
+ },
264
+ data: {
265
+ value: t,
266
+ writable: !0,
267
+ configurable: !0,
268
+ enumerable: !1
269
+ }
270
+ }), i ? Object.defineProperty(this, "cause", {
271
+ value: E(i),
272
+ writable: !0,
273
+ configurable: !0,
274
+ enumerable: !0
275
+ }) : delete this.cause, Object.defineProperty(this.constructor, "name", {
276
+ value: r,
277
+ configurable: !0,
278
+ writable: !0
279
+ });
280
+ }
281
+ }, P = class extends N {
282
+ constructor(e, t, n) {
283
+ t.response && Object.defineProperty(t, "response", { enumerable: !1 }), super(e, t, {
284
+ ...n,
285
+ name: "HttpRequestError"
286
+ });
287
+ }
288
+ }, ae = class extends N {
289
+ constructor(e, t) {
290
+ super(e, t, { name: "AssertionError" });
291
+ }
292
+ }, F = class extends N {
293
+ constructor(e) {
294
+ let t = ["Failed to parse", e.text && w(e.text, 200)].filter(Boolean).join(": ");
295
+ super(t, e, { name: "JsonParseError" });
296
+ }
297
+ }, I = class extends N {
298
+ constructor(e, t, n) {
299
+ super(e, t, {
300
+ ...n,
301
+ name: "TimeoutError"
302
+ });
303
+ }
304
+ }, L = class extends N {
305
+ constructor(e) {
306
+ super(e || "expected error was not thrown", {}, { name: "UnexpectedPassError" });
307
+ }
308
+ };
309
+ //#endregion
310
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/safeJsonStringify.js
311
+ function R(e, t, n, r) {
312
+ try {
313
+ return JSON.stringify(e, t, n);
314
+ } catch {
315
+ return JSON.stringify(e, z(t, r), n);
316
+ }
317
+ }
318
+ function z(e, t) {
319
+ let n = [], r = [];
320
+ return t ??= (e, t) => n[0] === t ? "[Circular ~]" : "[Circular ~." + r.slice(0, n.indexOf(t)).join(".") + "]", function(i, a) {
321
+ if (n.length > 0) {
322
+ let e = n.indexOf(this);
323
+ e === -1 ? (n.push(this), r.push(i)) : (n.splice(e + 1), r.splice(e, Infinity, i)), n.includes(a) && (a = t.call(this, i, a));
324
+ } else n.push(a);
325
+ return e == null ? a : e.call(this, i, a);
326
+ };
327
+ }
328
+ //#endregion
329
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/stringify.js
330
+ var B = typeof globalThis.AggregateError == "function", V = R;
331
+ function H(e, t = {}) {
332
+ if (e === void 0) return "undefined";
333
+ if (e === null) return "null";
334
+ if (typeof e == "function") return "function";
335
+ if (typeof e == "symbol") return e.toString();
336
+ let n;
337
+ if (e = C(e), k(e)) return H(e.error, t);
338
+ if (e instanceof Error || j(e)) n = U(e, t);
339
+ else if (typeof e == "string") n = e.trim() || "empty_string";
340
+ else if (typeof e == "number") n = String(e);
341
+ else {
342
+ e instanceof Map ? e = Object.fromEntries(e) : e instanceof Set && (e = Array.from(e));
343
+ try {
344
+ let { stringifyFn: r = V } = t;
345
+ n = r(e, void 0, 2);
346
+ } catch {
347
+ n = String(e);
348
+ }
349
+ }
350
+ if (n === void 0) return "undefined";
351
+ let { maxLen: r = 1e4 } = t;
352
+ return r && n.length > r ? w(n, r, `\n... ${Math.ceil(n.length / 1024)} Kb message truncated ...\n`) : n;
353
+ }
354
+ function U(e, t) {
355
+ let { includeErrorCause: n = !0 } = t, r = [e.name, e.message].filter(Boolean).join(": ");
356
+ if (typeof e.code == "string" && (r += `\ncode: ${e.code}`), t.includeErrorData && A(e) && Object.keys(e.data).length && (r += "\n" + H(e.data, t)), t.includeErrorStack && e.stack) {
357
+ let t = r.split("\n").length;
358
+ r = [r, ...e.stack.split("\n").slice(t)].join("\n");
359
+ }
360
+ return B && e instanceof AggregateError && e.errors.length && (r = [
361
+ r,
362
+ `${e.errors.length} error(s):`,
363
+ ...e.errors.map((e, n) => `${n + 1}. ${H(e, t)}`)
364
+ ].join("\n")), e.cause && n && (r = r + "\nCaused by: " + H(e.cause, t)), r;
365
+ }
366
+ //#endregion
367
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/error/assert.js
368
+ function W(e, t = Error) {
369
+ if (!(e instanceof t)) throw new ae(`Expected to be instanceof ${t.name}, actual typeof: ${typeof e}`);
370
+ }
371
+ function G(e, t) {
372
+ if (!(e instanceof t)) throw e;
373
+ }
374
+ //#endregion
375
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/promise/pDelay.js
376
+ async function K(e, t) {
377
+ t?.aborted || await new Promise((n) => {
378
+ let r = setTimeout(i, e);
379
+ function i() {
380
+ clearTimeout(r), t?.removeEventListener("abort", i), n();
381
+ }
382
+ t?.addEventListener("abort", i);
383
+ });
384
+ }
385
+ //#endregion
386
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/datetime/time.util.js
387
+ function q(e, t = Date.now()) {
388
+ return J(t - e);
389
+ }
390
+ function J(e) {
391
+ if (e < 1e3) return `${Math.round(e)} ms`;
392
+ if (e < 1e4) return `${(e / 1e3).toFixed(2)} sec`;
393
+ let t = Math.floor(e / 1e3) % 60, n = Math.floor(e / 6e4) % 60, r = Math.floor(e / 36e5);
394
+ return r === 0 ? n === 0 ? `${t} sec` : `${n}m${t}s` : r < 24 ? `${r}h${n}m` : r < 48 ? `${Math.round(r + n / 60)}h` : `${Math.floor(r / 24)} days`;
395
+ }
396
+ //#endregion
397
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/number/number.util.js
398
+ function oe(e, t, n) {
399
+ return e <= t ? t : e >= n ? n : e;
400
+ }
401
+ //#endregion
402
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/promise/pTimeout.js
403
+ async function se(e, t) {
404
+ let n = new AbortController(), { signal: r } = n;
405
+ if (!t.timeout) return await e(r);
406
+ let { timeout: i, name: a = e.name || "pTimeout function", onTimeout: o } = t, s = t.fakeError || /* @__PURE__ */ Error("TimeoutError");
407
+ return await new Promise(async (c, l) => {
408
+ let u = setTimeout(() => {
409
+ let e = new I(`"${a}" timed out after ${i} ms`, t.errorData);
410
+ if (e.stack = s.stack.replace("Error: TimeoutError", "TimeoutError: " + e.message), o) {
411
+ try {
412
+ c(o(e));
413
+ } catch (e) {
414
+ e.stack = s.stack.replace("Error: TimeoutError", e.name + ": " + e.message), l(M(e, t.errorData));
415
+ }
416
+ n.abort(e);
417
+ return;
418
+ }
419
+ l(e), n.abort(e);
420
+ }, i);
421
+ try {
422
+ c(await e(r));
423
+ } catch (e) {
424
+ l(e);
425
+ } finally {
426
+ clearTimeout(u);
427
+ }
428
+ });
429
+ }
430
+ //#endregion
431
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/string/url.util.js
432
+ function ce(e, t) {
433
+ if (typeof e != "string") return null;
434
+ try {
435
+ return new URL(e, t || void 0);
436
+ } catch {
437
+ return null;
438
+ }
439
+ }
440
+ //#endregion
441
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.90.0_undici@8.11.2/node_modules/@naturalcycles/js-lib/dist/http/http.model.js
442
+ var le = [
443
+ "GET",
444
+ "POST",
445
+ "PUT",
446
+ "PATCH",
447
+ "DELETE",
448
+ "HEAD"
449
+ ], ue = class e {
450
+ static VERSION = 5;
451
+ static userAgent = b() ? `fetcher/${this.VERSION}` : void 0;
452
+ constructor(e = {}) {
453
+ if (typeof globalThis.fetch != "function") throw TypeError("globalThis.fetch is not available");
454
+ this.cfg = this.normalizeCfg(e);
455
+ for (let e of le) {
456
+ let t = e.toLowerCase();
457
+ this[`${t}Void`] = async (t, n) => await this.fetch({
458
+ url: t,
459
+ method: e,
460
+ responseType: "void",
461
+ ...n
462
+ }), e !== "HEAD" && (this[`${t}Text`] = async (t, n) => await this.fetch({
463
+ url: t,
464
+ method: e,
465
+ responseType: "text",
466
+ ...n
467
+ }), this[t] = async (t, n) => await this.fetch({
468
+ url: t,
469
+ method: e,
470
+ responseType: "json",
471
+ ...n
472
+ }));
473
+ }
474
+ }
475
+ onBeforeRequest(e) {
476
+ return (this.cfg.hooks.beforeRequest ||= []).push(e), this;
477
+ }
478
+ onAfterResponse(e) {
479
+ return (this.cfg.hooks.afterResponse ||= []).push(e), this;
480
+ }
481
+ onBeforeRetry(e) {
482
+ return (this.cfg.hooks.beforeRetry ||= []).push(e), this;
483
+ }
484
+ onError(e) {
485
+ return (this.cfg.hooks.onError ||= []).push(e), this;
486
+ }
487
+ onInit(e) {
488
+ return (this.cfg.hooks.init ||= []).push(e), this;
489
+ }
490
+ resetInit() {
491
+ this.initPromise = void 0, this.initGeneration++;
492
+ }
493
+ cfg;
494
+ initPromise;
495
+ initGeneration = 0;
496
+ static create(t = {}) {
497
+ return new e(t);
498
+ }
499
+ get;
500
+ post;
501
+ put;
502
+ patch;
503
+ delete;
504
+ getText;
505
+ postText;
506
+ putText;
507
+ patchText;
508
+ deleteText;
509
+ getVoid;
510
+ postVoid;
511
+ putVoid;
512
+ patchVoid;
513
+ deleteVoid;
514
+ headVoid;
515
+ async queryGraphQL(e) {
516
+ e = { ...e }, e.method ||= this.cfg.init.method;
517
+ let t = ne({
518
+ query: e.query,
519
+ variables: e.variables
520
+ });
521
+ e.method === "GET" && e.query.length > 1900 && (e.method = "POST"), e.method === "GET" ? e.searchParams = {
522
+ ...e.searchParams,
523
+ ...t
524
+ } : e.json = t;
525
+ let n = await this.doFetch(e);
526
+ if (n.err) throw n.err;
527
+ if (n.body.errors) {
528
+ let e = n.body.errors[0];
529
+ throw new P(e.message, {
530
+ ...t,
531
+ errors: n.body.errors,
532
+ response: n.fetchResponse,
533
+ responseStatusCode: n.statusCode,
534
+ requestUrl: n.req.fullUrl,
535
+ requestBaseUrl: this.cfg.baseUrl,
536
+ requestMethod: n.req.init.method,
537
+ requestSignature: n.signature,
538
+ requestName: n.req.requestName,
539
+ fetcherName: this.cfg.name,
540
+ requestDuration: Date.now() - n.req.started
541
+ });
542
+ }
543
+ let { data: r } = n.body;
544
+ return e.unwrapObject ? r[e.unwrapObject] : r;
545
+ }
546
+ async getBytes(e, t) {
547
+ return await this.fetch({
548
+ url: e,
549
+ responseType: "bytes",
550
+ ...t
551
+ });
552
+ }
553
+ async getReadableStream(e, t) {
554
+ return await this.fetch({
555
+ url: e,
556
+ responseType: "readableStream",
557
+ ...t
558
+ });
559
+ }
560
+ async fetch(e) {
561
+ let t = await this.doFetch(e);
562
+ if (t.err && (t.req.throwHttpErrors || t.fetchResponse?.ok !== !1)) throw t.err;
563
+ return t.body;
564
+ }
565
+ async fetchWithMeta(e) {
566
+ let t = await this.doFetch(e);
567
+ if (t.err) throw t.err;
568
+ return t;
569
+ }
570
+ async expectError(e) {
571
+ let t = await this.doFetch(e);
572
+ if (!t.err) throw new L("Fetch was expected to error");
573
+ return W(t.err, P), t.err;
574
+ }
575
+ async tryFetch(e) {
576
+ let t = await this.doFetch(e);
577
+ return t.err ? (G(t.err, P), [t.err, null]) : [null, t.body];
578
+ }
579
+ async doFetch(t) {
580
+ let n = 0;
581
+ if (this.cfg.hooks.init) {
582
+ try {
583
+ await (this.initPromise ??= this.runInitHooks());
584
+ } catch (e) {
585
+ throw this.resetInit(), e;
586
+ }
587
+ n = this.initGeneration;
588
+ }
589
+ let r = this.normalizeOptions(t), { logger: i } = this.cfg, { init: { method: o } } = r, s = r.timeoutSeconds ? r.timeoutSeconds * 1e3 : void 0;
590
+ for (let e of this.cfg.hooks.beforeRequest || []) await e(r);
591
+ let l = r.fullUrl.includes("://") ? new URL(r.fullUrl) : void 0, u = [o, l ? this.getShortUrl(l) : r.fullUrl].join(" "), d = {
592
+ req: r,
593
+ retryStatus: {
594
+ retryAttempt: 0,
595
+ retryStopped: !1,
596
+ retryTimeout: r.retry.timeout
597
+ },
598
+ signature: u
599
+ };
600
+ for (; !d.retryStatus.retryStopped;) {
601
+ if (r.started = Date.now(), d.body = void 0, r.init.signal = c([a(s), t.signal]), r.logRequest) {
602
+ let { retryAttempt: e } = d.retryStatus;
603
+ i.log([
604
+ " >>",
605
+ u,
606
+ e && `try#${e + 1}/${r.retry.count + 1}`
607
+ ].filter(Boolean).join(" ")), r.logRequestBody && r.init.body && i.log(r.init.body);
608
+ }
609
+ try {
610
+ d.fetchResponse = await (r.overrideFetchFn || e.callNativeFetch)(r.fullUrl, r.init, r.fetchFn), d.ok = d.fetchResponse.ok, d.err = void 0;
611
+ } catch (e) {
612
+ d.err = T(e), d.ok = !1, d.fetchResponse = void 0;
613
+ }
614
+ if (d.statusFamily = this.getStatusFamily(d), d.statusCode = d.fetchResponse?.status, d.fetchResponse?.ok) try {
615
+ await se(async () => await this.onOkResponse(d), {
616
+ timeout: s ?? 0,
617
+ name: "Fetcher.downloadBody"
618
+ });
619
+ } catch (e) {
620
+ d.err = T(e), d.ok = !1, await this.onNotOkResponse(d);
621
+ }
622
+ else await this.onNotOkResponse(d);
623
+ }
624
+ if (d.err) {
625
+ M(d.err, r.errorData), r.onError?.(d.err);
626
+ for (let e of this.cfg.hooks.onError || []) await e(d.err);
627
+ }
628
+ for (let e of this.cfg.hooks.afterResponse || []) await e(d);
629
+ return d.err && await this.detectStaleInit(t, d, n) ? await this.doFetch({
630
+ ...t,
631
+ [Y]: !0
632
+ }) : d;
633
+ }
634
+ async detectStaleInit(e, t, n) {
635
+ let { shouldReinit: r, init: i } = this.cfg.hooks;
636
+ return !r || !i || e[Y] || !await r(t) ? !1 : (n === this.initGeneration && this.resetInit(), !0);
637
+ }
638
+ async runInitHooks() {
639
+ for (let e of this.cfg.hooks.init || []) await e(this.cfg);
640
+ }
641
+ async onOkResponse(e) {
642
+ let { req: t } = e, { responseType: n } = e.req;
643
+ if (n === "json") {
644
+ if (e.fetchResponse.body) {
645
+ let n = await e.fetchResponse.text();
646
+ n ? (e.body = n, e.body = ie(n, t.jsonReviver)) : e.body = {};
647
+ } else e.body = {};
648
+ } else if (n === "text") e.body = e.fetchResponse.body ? await e.fetchResponse.text() : "";
649
+ else if (n === "arrayBuffer") e.body = e.fetchResponse.body ? await e.fetchResponse.arrayBuffer() : /* @__PURE__ */ new ArrayBuffer(0);
650
+ else if (n === "bytes") e.body = e.fetchResponse.body ? new Uint8Array(await e.fetchResponse.arrayBuffer()) : /* @__PURE__ */ new Uint8Array();
651
+ else if (n === "blob") e.body = e.fetchResponse.body ? await e.fetchResponse.blob() : new Blob();
652
+ else if (n === "void") await e.fetchResponse.body?.cancel();
653
+ else if (n === "readableStream" && (e.body = e.fetchResponse.body, e.body === null)) throw Error("fetchResponse.body is null");
654
+ if (e.retryStatus.retryStopped = !0, t.logResponse) {
655
+ let { retryAttempt: n } = e.retryStatus, { logger: r } = this.cfg;
656
+ r.log([
657
+ " <<",
658
+ e.fetchResponse.status,
659
+ e.signature,
660
+ n && `try#${n + 1}/${t.retry.count + 1}`,
661
+ q(e.req.started)
662
+ ].filter(Boolean).join(" ")), t.logResponseBody && e.body !== void 0 && r.log(e.body);
663
+ }
664
+ }
665
+ static async callNativeFetch(e, t, n) {
666
+ return await (n || globalThis.fetch)(e, t);
667
+ }
668
+ async onNotOkResponse(e) {
669
+ let t;
670
+ if (!e.body && e.fetchResponse) try {
671
+ e.body = C(await e.fetchResponse.text());
672
+ } catch {}
673
+ t = e.err ? D(e.err) : e.body ? E(e.body) : {
674
+ name: "Error",
675
+ message: "Fetch failed",
676
+ data: {}
677
+ };
678
+ let n = e.fetchResponse?.status || 0;
679
+ e.statusFamily === 2 && (e.statusFamily = void 0, e.statusCode = void 0, n = 0), e.err = new P([e.statusCode, e.signature].filter(Boolean).join(" "), h({
680
+ response: e.fetchResponse,
681
+ responseStatusCode: n,
682
+ requestUrl: e.req.fullUrl,
683
+ requestBaseUrl: this.cfg.baseUrl || void 0,
684
+ requestMethod: e.req.init.method,
685
+ requestSignature: e.signature,
686
+ requestName: e.req.requestName,
687
+ fetcherName: this.cfg.name,
688
+ requestDuration: Date.now() - e.req.started
689
+ }), { cause: t }), await this.processRetry(e);
690
+ }
691
+ async processRetry(e) {
692
+ let { retryStatus: t } = e;
693
+ this.shouldRetry(e) || (t.retryStopped = !0);
694
+ for (let t of this.cfg.hooks.beforeRetry || []) await t(e);
695
+ let { count: n, timeoutMultiplier: r, timeoutMax: i } = e.req.retry;
696
+ if (t.retryAttempt >= n && (t.retryStopped = !0), e.err && (!t.retryStopped || e.req.logResponse) && this.cfg.logger.error([
697
+ " <<",
698
+ e.fetchResponse?.status || 0,
699
+ e.signature,
700
+ n && (t.retryAttempt || !t.retryStopped) && `try#${t.retryAttempt + 1}/${n + 1}`,
701
+ q(e.req.started)
702
+ ].filter(Boolean).join(" ") + "\n", H(e.err.cause || e.err)), t.retryStopped) return;
703
+ t.retryAttempt++;
704
+ let a = this.getRetryTimeout(e);
705
+ if (a === null) {
706
+ this.cfg.logger.warn(`${e.signature} server-indicated delay exceeds maxRetryAfter, will not retry`), t.retryStopped = !0;
707
+ return;
708
+ }
709
+ t.retryTimeout = oe(t.retryTimeout * r, 0, i), e.req.debug && this.cfg.logger.log(` .. ${e.signature} waiting ${J(a)}`), await K(a, e.req.signal), e.req.signal?.aborted && (t.retryStopped = !0);
710
+ }
711
+ getRetryTimeout(e) {
712
+ let t = 0;
713
+ if (e.fetchResponse && [429, 503].includes(e.fetchResponse.status)) {
714
+ let n = e.fetchResponse.headers.get("retry-after") ?? e.fetchResponse.headers.get("x-ratelimit-reset");
715
+ if (n) {
716
+ let e = Number(n);
717
+ if (e) t = e > 10 ** 9 ? e * 1e3 - Date.now() : e * 1e3;
718
+ else {
719
+ let e = new Date(n);
720
+ Number.isNaN(e.getTime()) || (t = e.getTime() - Date.now());
721
+ }
722
+ this.cfg.logger.log(`retry-after: ${n}`), t || this.cfg.logger.warn("retry-after could not be parsed");
723
+ }
724
+ }
725
+ if (t) return t > e.req.retry.maxRetryAfter ? null : Math.max(0, t);
726
+ let n = Math.random() * 500;
727
+ return e.retryStatus.retryTimeout + n;
728
+ }
729
+ shouldRetry(e) {
730
+ if (e.req.signal?.aborted) return !1;
731
+ let { retryPost: t, retry3xx: n, retry4xx: r, retry5xx: i } = e.req, { method: a } = e.req.init;
732
+ if (a === "POST" && !t) return !1;
733
+ let { statusFamily: o } = e, s = e.fetchResponse?.status || 0;
734
+ return o === 5 && !i ? !1 : [408, 429].includes(s) ? !0 : !(o === 4 && !r || o === 3 && !n || e.err?.cause?.cause?.message?.includes("unexpected redirect"));
735
+ }
736
+ getStatusFamily(e) {
737
+ let t = e.fetchResponse?.status;
738
+ if (t) {
739
+ if (t >= 500) return 5;
740
+ if (t >= 400) return 4;
741
+ if (t >= 300) return 3;
742
+ if (t >= 200) return 2;
743
+ if (t >= 100) return 1;
744
+ }
745
+ }
746
+ getShortUrl(e) {
747
+ let { baseUrl: t } = this.cfg;
748
+ e.password && (e = new URL(e.toString()), e.password = "[redacted]");
749
+ let n = e.toString();
750
+ return this.cfg.logWithSearchParams || (n = n.split("?")[0]), !this.cfg.logWithBaseUrl && t && n.startsWith(t) && (n = n.slice(t.length)), n;
751
+ }
752
+ normalizeCfg(t) {
753
+ let { debug: n = !1, logger: r = console } = t;
754
+ t.baseUrl?.endsWith("/") && (r.warn(`Fetcher: baseUrl should not end with slash: ${t.baseUrl}`), t.baseUrl = t.baseUrl.slice(0, t.baseUrl.length - 1));
755
+ let i = y({
756
+ baseUrl: "",
757
+ name: this.getFetcherName(t),
758
+ inputUrl: "",
759
+ responseType: "json",
760
+ searchParams: {},
761
+ timeoutSeconds: 30,
762
+ retryPost: !1,
763
+ retry3xx: !1,
764
+ retry4xx: !1,
765
+ retry5xx: !0,
766
+ logger: r,
767
+ debug: n,
768
+ logRequest: n,
769
+ logRequestBody: n,
770
+ logResponse: n,
771
+ logResponseBody: n,
772
+ logWithBaseUrl: b(),
773
+ logWithSearchParams: !0,
774
+ retry: { ...pe },
775
+ init: {
776
+ method: t.method || "GET",
777
+ headers: h({
778
+ "user-agent": e.userAgent,
779
+ ...t.headers
780
+ }),
781
+ credentials: t.credentials,
782
+ redirect: t.redirect,
783
+ dispatcher: t.dispatcher,
784
+ keepalive: t.keepalive
785
+ },
786
+ hooks: {},
787
+ throwHttpErrors: !0,
788
+ errorData: {}
789
+ }, m(t, [
790
+ "method",
791
+ "credentials",
792
+ "headers",
793
+ "redirect",
794
+ "logger",
795
+ "name",
796
+ "keepalive"
797
+ ]));
798
+ return i.init.headers = v(i.init.headers, (e) => e.toLowerCase()), i;
799
+ }
800
+ getFetcherName(e) {
801
+ let { name: t } = e;
802
+ if (!t && e.baseUrl) {
803
+ let n = ce(e.baseUrl);
804
+ n && (t = n.hostname);
805
+ }
806
+ return t;
807
+ }
808
+ normalizeOptions(t) {
809
+ let n = {
810
+ ...te(this.cfg, [
811
+ "timeoutSeconds",
812
+ "retryPost",
813
+ "retry3xx",
814
+ "retry4xx",
815
+ "retry5xx",
816
+ "responseType",
817
+ "jsonReviver",
818
+ "logRequest",
819
+ "logRequestBody",
820
+ "logResponse",
821
+ "logResponseBody",
822
+ "debug",
823
+ "throwHttpErrors",
824
+ "errorData",
825
+ "fetchFn",
826
+ "overrideFetchFn"
827
+ ]),
828
+ started: Date.now(),
829
+ ...m(t, [
830
+ "method",
831
+ "headers",
832
+ "credentials"
833
+ ]),
834
+ inputUrl: t.url || "",
835
+ fullUrl: t.url || "",
836
+ retry: {
837
+ ...this.cfg.retry,
838
+ ...g(t.retry || {})
839
+ },
840
+ init: y({
841
+ ...this.cfg.init,
842
+ headers: {
843
+ ...this.cfg.init.headers,
844
+ "user-agent": e.userAgent
845
+ },
846
+ method: t.method || this.cfg.init.method,
847
+ credentials: t.credentials || this.cfg.init.credentials,
848
+ redirect: t.redirect || this.cfg.init.redirect || "follow",
849
+ keepalive: t.keepalive ?? this.cfg.init.keepalive
850
+ }, { headers: v(t.headers || {}, (e) => e.toLowerCase()) })
851
+ };
852
+ h(n.init.headers, { mutate: !0 });
853
+ let r = t.baseUrl || this.cfg.baseUrl;
854
+ if (r) {
855
+ let { inputUrl: e } = n;
856
+ e.startsWith("/") && (this.cfg.logger.warn("Fetcher: url should not start with / when baseUrl is specified"), e = e.slice(1)), n.fullUrl = `${r}/${e}`;
857
+ }
858
+ let i = g({
859
+ ...this.cfg.searchParams,
860
+ ...t.searchParams
861
+ });
862
+ if (Object.keys(i).length) {
863
+ let e = new URLSearchParams(i).toString();
864
+ n.fullUrl += (n.fullUrl.includes("?") ? "&" : "?") + e;
865
+ }
866
+ return t.json === void 0 ? t.text === void 0 ? t.form ? t.form instanceof URLSearchParams || t.form instanceof FormData ? n.init.body = t.form : (n.init.body = new URLSearchParams(t.form), n.init.headers["content-type"] ||= "application/x-www-form-urlencoded") : t.body !== void 0 && (n.init.body = t.body) : (n.init.body = t.text, n.init.headers["content-type"] ||= "text/plain") : (n.init.body = JSON.stringify(t.json), n.init.headers["content-type"] ||= "application/json"), n.init.headers.accept ||= fe[n.responseType], n;
867
+ }
868
+ };
869
+ function de(e = {}) {
870
+ return ue.create(e);
871
+ }
872
+ var Y = Symbol("reinitAttempted"), fe = {
873
+ text: "text/plain",
874
+ json: "application/json",
875
+ void: "*/*",
876
+ readableStream: "application/octet-stream",
877
+ arrayBuffer: "application/octet-stream",
878
+ bytes: "application/octet-stream",
879
+ blob: "application/octet-stream"
880
+ }, pe = {
881
+ count: 2,
882
+ timeout: 1e3,
883
+ timeoutMax: 3e4,
884
+ timeoutMultiplier: 2,
885
+ maxRetryAfter: 6e5
886
+ }, X;
887
+ (function(e) {
888
+ e.flow = "flow", e.code = "code", e.refId = "refId", e.referral = "referral", e.ignoreConfirmation = "ignoreConfirmation", e.ic = "ic", e.measuringDevice = "measuringDevice", e.irclickid = "irclickid", e.fg = "fg", e.sfg = "sfg", e.sq = "sq", e.cbo = "cbo", e.ip = "ip", e.ipv = "ipv", e.appleAuth = "appleAuth", e.googleAuth = "googleAuth", e.od = "od", e.pl = "pl", e.ScCid = "ScCid", e.fbclid = "fbclid", e.ttclid = "ttclid", e.rdt_cid = "rdt_cid", e.epik = "epik", e.adid = "adid", e.wcf = "wcf", e.we = "we", e.werr = "werr", e.wdpm = "wdpm", e.wsc = "wsc", e.ral = "ral";
889
+ })(X ||= {});
890
+ var me = [
891
+ X.ScCid,
892
+ X.irclickid,
893
+ X.fbclid,
894
+ X.ttclid,
895
+ X.rdt_cid,
896
+ X.epik
897
+ ];
898
+ X.flow, X.code, X.ignoreConfirmation, X.ic, X.fg, X.sfg, X.sq, X.cbo, X.ip, X.ipv, X.od, X.pl, X.wcf, X.we, X.wdpm, X.wsc, X.ral;
899
+ var he;
900
+ (function(e) {
901
+ e[e.OURA = 1] = "OURA", e[e.APPLE_WATCH = 2] = "APPLE_WATCH", e[e.META_LANDING_PAGE = 3] = "META_LANDING_PAGE", e[e.PAYMENT_REDIRECT_FROM_APP = 4] = "PAYMENT_REDIRECT_FROM_APP", e[e.B1 = 5] = "B1", e[e.EMAIL_VERIFICATION_REDIRECT = 6] = "EMAIL_VERIFICATION_REDIRECT", e[e.WHOOP = 7] = "WHOOP";
902
+ })(he ||= {});
903
+ var Z = new class {
904
+ getAllCookies() {
905
+ let e = {}, t = document.cookie.split("; ");
906
+ for (let n of t) {
907
+ let [t, ...r] = n.split("=");
908
+ if (t) {
909
+ let n = r.join("="), i = n ? decodeURIComponent(n) : void 0;
910
+ i && (e[t] = i);
911
+ }
912
+ }
913
+ return e;
914
+ }
915
+ getCookie(e) {
916
+ let t = `${e}=`, n = document.cookie.split("; ");
917
+ for (let e of n) if (e.startsWith(t)) return decodeURIComponent(e.slice(t.length));
918
+ }
919
+ setCookie(e, t, n, r) {
920
+ let i = /* @__PURE__ */ new Date();
921
+ i.setTime(i.getTime() + n * 24 * 60 * 60 * 1e3);
922
+ let a = `${e}=${encodeURIComponent(t)};expires=${i.toUTCString()};path=/`;
923
+ r && (a += `;domain=${r}`), document.cookie = a;
924
+ }
925
+ clearAllCookies() {
926
+ let e = document.cookie.split("; ");
927
+ for (let t of e) {
928
+ let [e] = t.split("=");
929
+ e && (document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`);
930
+ }
931
+ }
932
+ deleteCookie(e) {
933
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
934
+ }
935
+ }();
936
+ //#endregion
937
+ //#region ../shared/dist/util/metaClickId.util.js
938
+ function Q(e) {
939
+ if (e) return e.startsWith("fb.") ? e : `fb.1.${Date.now()}.${e}`;
940
+ }
941
+ function ge(e) {
942
+ if (!e) return;
943
+ e = e.split("?")[0], e.includes("__DOT__") && (e = e.replaceAll("__DOT__", ".")), e = e.split("%")[0], e = e.split("&")[0];
944
+ let t = e.split("."), n = t.lastIndexOf("fb");
945
+ return n > 0 && t.length - n >= 4 && (e = t.slice(n).join(".")), e;
946
+ }
947
+ //#endregion
948
+ //#region src/conversion/conversionClient.ts
949
+ var $ = 30, _e = 200, ve = 20, ye = class {
950
+ constructor(e) {
951
+ this.cfg = {
952
+ ...e,
953
+ enabled: e.enabled ?? !0,
954
+ onError: e.onError ?? ee
955
+ }, this.fetcher = de({ baseUrl: e.url });
956
+ }
957
+ cfg;
958
+ fetcher;
959
+ lastCapturedHref;
960
+ init() {
961
+ this.cfg.enabled && this.tryOrReport(() => this.captureClickIds(), void 0);
962
+ }
963
+ pageView(e, t = {}) {
964
+ this.cfg.enabled && f(this.send("p", e, t));
965
+ }
966
+ purchase(e, t = {}) {
967
+ this.cfg.enabled && f(this.send("purchase", e, t));
968
+ }
969
+ async send(e, t, n) {
970
+ try {
971
+ let r = await this.fetcher.doFetch({
972
+ url: e,
973
+ method: "POST",
974
+ json: t,
975
+ headers: {
976
+ ...this.getHeaders(),
977
+ ...n.extraHeaders
978
+ },
979
+ keepalive: !0,
980
+ responseType: "void"
981
+ });
982
+ r.err && this.cfg.onError(r.err);
983
+ } catch (e) {
984
+ this.cfg.onError(T(e));
985
+ }
986
+ }
987
+ getHeaders() {
988
+ let e = String(this.cfg.clientId);
989
+ return this.tryOrReport(() => (this.cfg.enabled && this.captureClickIds(), re({
990
+ clientId: e,
991
+ fbc: Z.getCookie("_fbc") || Q(Z.getCookie(X.fbclid)),
992
+ fbp: Z.getCookie("_fbp"),
993
+ scCid: Z.getCookie(X.ScCid),
994
+ ttclid: Z.getCookie(X.ttclid),
995
+ rdtCid: Z.getCookie(X.rdt_cid),
996
+ epik: Z.getCookie("_epik") || Z.getCookie(X.epik),
997
+ uuid_c1: Z.getCookie("_scid") || Z.getCookie("uuid_c1")
998
+ })), { clientId: e });
999
+ }
1000
+ tryOrReport(e, t) {
1001
+ try {
1002
+ return e();
1003
+ } catch (e) {
1004
+ return this.cfg.onError(T(e)), t;
1005
+ }
1006
+ }
1007
+ captureClickIds() {
1008
+ let { href: e, search: t } = globalThis.location;
1009
+ if (e === this.lastCapturedHref) return;
1010
+ this.lastCapturedHref = e;
1011
+ let n = new URLSearchParams(t);
1012
+ for (let e of me) {
1013
+ let t = n.get(e) || n.get(e.toLowerCase());
1014
+ if (!t) continue;
1015
+ let r = e === X.fbclid ? this.toFbc(t) : t.slice(0, _e);
1016
+ r && Z.setCookie(e, r, $, this.cfg.cookieDomain);
1017
+ }
1018
+ }
1019
+ toFbc(e) {
1020
+ let t = ge(e);
1021
+ if (!(!t || t.length < ve) && !Z.getCookie(X.fbclid)?.endsWith(`.${t}`)) return Q(t);
1022
+ }
1023
+ };
1024
+ //#endregion
1025
+ export { ye as ConversionClient, t as generateConversionEventId };
1026
+
1027
+ //# sourceMappingURL=conversionClient.js.map