@apify/utilities 1.2.13 → 2.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.
package/index.mjs ADDED
@@ -0,0 +1,1662 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+
5
+ // src/utilities.ts
6
+ import crypto from "crypto";
7
+ import log, { LoggerJson, LogLevel } from "@apify/log";
8
+ import { ANONYMOUS_USERNAME } from "@apify/consts";
9
+ function cryptoRandomObjectId(length = 17) {
10
+ const chars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789";
11
+ const bytes = crypto.randomBytes(length);
12
+ let str = "";
13
+ for (let i = bytes.length - 1; i >= 0; i--) {
14
+ str += chars[(bytes[i] | 0) % chars.length];
15
+ }
16
+ return str;
17
+ }
18
+ __name(cryptoRandomObjectId, "cryptoRandomObjectId");
19
+ function deterministicUniqueId(key, length = 17) {
20
+ return crypto.createHash("sha256").update(key).digest("base64").replace(/(\+|\/|=)/g, "x").substr(0, length);
21
+ }
22
+ __name(deterministicUniqueId, "deterministicUniqueId");
23
+ function getRandomInt(maxExcluded) {
24
+ maxExcluded = Math.floor(maxExcluded);
25
+ return Math.floor(Math.random() * maxExcluded);
26
+ }
27
+ __name(getRandomInt, "getRandomInt");
28
+ function parseDateFromJson(date) {
29
+ if (typeof date === "string") {
30
+ return new Date(Date.parse(date));
31
+ }
32
+ return date;
33
+ }
34
+ __name(parseDateFromJson, "parseDateFromJson");
35
+ function delayPromise(millis) {
36
+ return new Promise((resolve) => {
37
+ if (millis > 0) {
38
+ setTimeout(() => resolve(), millis);
39
+ } else {
40
+ resolve();
41
+ }
42
+ });
43
+ }
44
+ __name(delayPromise, "delayPromise");
45
+ function removeFromArray(array, element) {
46
+ const index = array.indexOf(element);
47
+ if (index >= 0) {
48
+ array.splice(index, 1);
49
+ return true;
50
+ }
51
+ return false;
52
+ }
53
+ __name(removeFromArray, "removeFromArray");
54
+ function http404Route(req, res) {
55
+ res.status(404);
56
+ res.send("Page not found");
57
+ }
58
+ __name(http404Route, "http404Route");
59
+ function expressErrorHandler(err, req, res, next) {
60
+ log.warning("Client HTTP request failed", { url: req.url, errMsg: err.message });
61
+ if (res.headersSent) {
62
+ return next(err);
63
+ }
64
+ res.status(505);
65
+ res.send("Internal server error");
66
+ }
67
+ __name(expressErrorHandler, "expressErrorHandler");
68
+ function betterSetInterval(func, delay) {
69
+ let callback;
70
+ let timeoutId;
71
+ let isRunning = true;
72
+ const funcWrapper = /* @__PURE__ */ __name(function() {
73
+ func(callback);
74
+ }, "funcWrapper");
75
+ callback = /* @__PURE__ */ __name(function() {
76
+ if (isRunning)
77
+ timeoutId = setTimeout(funcWrapper, delay);
78
+ }, "callback");
79
+ funcWrapper();
80
+ return {
81
+ _betterClearInterval() {
82
+ isRunning = false;
83
+ clearTimeout(timeoutId);
84
+ }
85
+ };
86
+ }
87
+ __name(betterSetInterval, "betterSetInterval");
88
+ function betterClearInterval(intervalID) {
89
+ if (intervalID && intervalID._betterClearInterval) {
90
+ try {
91
+ intervalID._betterClearInterval();
92
+ } catch (e) {
93
+ log.exception(e, "_betterClearInterval() threw an exception!?");
94
+ }
95
+ }
96
+ }
97
+ __name(betterClearInterval, "betterClearInterval");
98
+ function escapeRegExp(str) {
99
+ return String(str).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
100
+ }
101
+ __name(escapeRegExp, "escapeRegExp");
102
+ function leftpad(str, len, ch = " ") {
103
+ str = String(str);
104
+ let i = -1;
105
+ if (!ch && ch !== 0)
106
+ ch = " ";
107
+ len -= str.length;
108
+ while (++i < len) {
109
+ str = ch + str;
110
+ }
111
+ return str;
112
+ }
113
+ __name(leftpad, "leftpad");
114
+ function weightedAverage(val1, weight1, val2, weight2) {
115
+ return (val1 * weight1 + val2 * weight2) / (weight1 + weight2);
116
+ }
117
+ __name(weightedAverage, "weightedAverage");
118
+ var FORBIDDEN_USERNAMES_REGEXPS = [
119
+ "page-not-found",
120
+ "docs",
121
+ "terms-of-use",
122
+ "about",
123
+ "pricing",
124
+ "privacy-policy",
125
+ "customers",
126
+ "request-form",
127
+ "request-solution",
128
+ "release-notes",
129
+ "jobs",
130
+ "api-reference",
131
+ "video-tutorials",
132
+ "acts",
133
+ "key-value-stores",
134
+ "schedules",
135
+ "account",
136
+ "sign-up",
137
+ "sign-in-discourse",
138
+ "admin",
139
+ "documentation",
140
+ "change-password",
141
+ "enroll-account",
142
+ "forgot-password",
143
+ "reset-password",
144
+ "sign-in",
145
+ "verify-email",
146
+ "live-status",
147
+ "browser-info",
148
+ "webhooks",
149
+ "health-check",
150
+ "api",
151
+ "change-log",
152
+ "dashboard",
153
+ "community",
154
+ "crawlers",
155
+ "ext",
156
+ "admin",
157
+ "administration",
158
+ "crawler",
159
+ "act",
160
+ "library",
161
+ "lib",
162
+ "apifier",
163
+ "team",
164
+ "contact",
165
+ "doc",
166
+ "documentation",
167
+ "for-business",
168
+ "for-developers",
169
+ "developers",
170
+ "business",
171
+ "integrations",
172
+ "job",
173
+ "setting",
174
+ "settings",
175
+ "privacy",
176
+ "policy",
177
+ "assets",
178
+ "help",
179
+ "config",
180
+ "configuration",
181
+ "terms",
182
+ "hiring",
183
+ "hire",
184
+ "status",
185
+ "status-page",
186
+ "solutions",
187
+ "support",
188
+ "market",
189
+ "marketplace",
190
+ "download",
191
+ "downloads",
192
+ "username",
193
+ "users",
194
+ "user",
195
+ "login",
196
+ "logout",
197
+ "signin",
198
+ "sign",
199
+ "signup",
200
+ "sign-out",
201
+ "signout",
202
+ "plugins",
203
+ "plug-ins",
204
+ "reset",
205
+ "password",
206
+ "passwords",
207
+ "square",
208
+ "profile-photos",
209
+ "profiles",
210
+ "true",
211
+ "false",
212
+ "js",
213
+ "css",
214
+ "img",
215
+ "images",
216
+ "image",
217
+ "partials",
218
+ "fonts",
219
+ "font",
220
+ "dynamic_templates",
221
+ "app",
222
+ "schedules",
223
+ "community",
224
+ "storage",
225
+ "storages",
226
+ "account",
227
+ "node_modules",
228
+ "bower_components",
229
+ "video",
230
+ "knowledgebase",
231
+ "forum",
232
+ "customers",
233
+ "blog",
234
+ "health-check",
235
+ "health",
236
+ "anim",
237
+ "forum_topics.json",
238
+ "forum_categories.json",
239
+ "me",
240
+ "you",
241
+ "him",
242
+ "she",
243
+ "it",
244
+ "external",
245
+ "actor",
246
+ "crawler",
247
+ "scheduler",
248
+ "api",
249
+ "sdk",
250
+ "puppeteer",
251
+ "webdriver",
252
+ "selenium",
253
+ "(selenium.*webdriver)",
254
+ "undefined",
255
+ "page-analyzer",
256
+ "wp-login.php",
257
+ "welcome.action",
258
+ "echo",
259
+ "proxy",
260
+ "super-proxy",
261
+ "gdpr",
262
+ "case-studies",
263
+ "use-cases",
264
+ "how-to",
265
+ "kb",
266
+ "cookies",
267
+ "cookie-policy",
268
+ "cookies-policy",
269
+ "powered-by",
270
+ "run",
271
+ "runs",
272
+ "actor",
273
+ "actors",
274
+ "act",
275
+ "acts",
276
+ "success-stories",
277
+ "roadmap",
278
+ "join-marketplace",
279
+ "presskit",
280
+ "press-kit",
281
+ "covid-19",
282
+ "covid",
283
+ "covid19",
284
+ "matfyz",
285
+ "ideas",
286
+ "public-actors",
287
+ "resources",
288
+ "partners",
289
+ "affiliate",
290
+ "industries",
291
+ "web-scraping",
292
+ "custom-solutions",
293
+ "solution-provider",
294
+ "alternatives",
295
+ "platform",
296
+ "freelancers",
297
+ "freelancer",
298
+ "partner",
299
+ "index",
300
+ "index\\.html",
301
+ "(favicon\\.[a-z]+)",
302
+ "BingSiteAuth.xml",
303
+ "(google.+\\.html)",
304
+ "robots\\.txt",
305
+ "(sitemap\\.[a-z]+)",
306
+ "(apple-touch-icon.*)",
307
+ "security-whitepaper\\.pdf",
308
+ "(\\..*)",
309
+ "(xxx-.*)",
310
+ "([^0-9a-z].*)",
311
+ "(.*[^0-9a-z])",
312
+ "(.*[_.\\-]{2}.*)",
313
+ "0",
314
+ "about",
315
+ "access",
316
+ "account",
317
+ "accounts",
318
+ "activate",
319
+ "activities",
320
+ "activity",
321
+ "ad",
322
+ "add",
323
+ "address",
324
+ "adm",
325
+ "admin",
326
+ "administration",
327
+ "administrator",
328
+ "ads",
329
+ "adult",
330
+ "advertising",
331
+ "affiliate",
332
+ "affiliates",
333
+ "ajax",
334
+ "all",
335
+ "alpha",
336
+ "analysis",
337
+ "analytics",
338
+ "android",
339
+ "anon",
340
+ "anonymous",
341
+ "api",
342
+ "app",
343
+ "apps",
344
+ "archive",
345
+ "archives",
346
+ "article",
347
+ "asct",
348
+ "asset",
349
+ "atom",
350
+ "auth",
351
+ "authentication",
352
+ "avatar",
353
+ "backup",
354
+ "balancer-manager",
355
+ "banner",
356
+ "banners",
357
+ "beta",
358
+ "billing",
359
+ "bin",
360
+ "blog",
361
+ "blogs",
362
+ "board",
363
+ "book",
364
+ "bookmark",
365
+ "bot",
366
+ "bots",
367
+ "bug",
368
+ "business",
369
+ "cache",
370
+ "cadastro",
371
+ "calendar",
372
+ "call",
373
+ "campaign",
374
+ "cancel",
375
+ "captcha",
376
+ "career",
377
+ "careers",
378
+ "cart",
379
+ "categories",
380
+ "category",
381
+ "cgi",
382
+ "cgi-bin",
383
+ "changelog",
384
+ "chat",
385
+ "check",
386
+ "checking",
387
+ "checkout",
388
+ "client",
389
+ "cliente",
390
+ "clients",
391
+ "code",
392
+ "codereview",
393
+ "comercial",
394
+ "comment",
395
+ "comments",
396
+ "communities",
397
+ "community",
398
+ "company",
399
+ "compare",
400
+ "compras",
401
+ "config",
402
+ "configuration",
403
+ "connect",
404
+ "contact",
405
+ "contact-us",
406
+ "contact_us",
407
+ "contactus",
408
+ "contest",
409
+ "contribute",
410
+ "corp",
411
+ "create",
412
+ "css",
413
+ "dashboard",
414
+ "data",
415
+ "db",
416
+ "default",
417
+ "delete",
418
+ "demo",
419
+ "design",
420
+ "designer",
421
+ "destroy",
422
+ "dev",
423
+ "devel",
424
+ "developer",
425
+ "developers",
426
+ "diagram",
427
+ "diary",
428
+ "dict",
429
+ "dictionary",
430
+ "die",
431
+ "dir",
432
+ "direct_messages",
433
+ "directory",
434
+ "dist",
435
+ "doc",
436
+ "docs",
437
+ "documentation",
438
+ "domain",
439
+ "download",
440
+ "downloads",
441
+ "ecommerce",
442
+ "edit",
443
+ "editor",
444
+ "edu",
445
+ "education",
446
+ "email",
447
+ "employment",
448
+ "empty",
449
+ "end",
450
+ "enterprise",
451
+ "entries",
452
+ "entry",
453
+ "error",
454
+ "errors",
455
+ "eval",
456
+ "event",
457
+ "exit",
458
+ "explore",
459
+ "facebook",
460
+ "faq",
461
+ "favorite",
462
+ "favorites",
463
+ "feature",
464
+ "features",
465
+ "feed",
466
+ "feedback",
467
+ "feeds",
468
+ "file",
469
+ "files",
470
+ "first",
471
+ "flash",
472
+ "fleet",
473
+ "fleets",
474
+ "flog",
475
+ "follow",
476
+ "followers",
477
+ "following",
478
+ "forgot",
479
+ "form",
480
+ "forum",
481
+ "forums",
482
+ "founder",
483
+ "free",
484
+ "friend",
485
+ "friends",
486
+ "ftp",
487
+ "gadget",
488
+ "gadgets",
489
+ "game",
490
+ "games",
491
+ "get",
492
+ "gift",
493
+ "gifts",
494
+ "gist",
495
+ "github",
496
+ "graph",
497
+ "group",
498
+ "groups",
499
+ "guest",
500
+ "guests",
501
+ "help",
502
+ "home",
503
+ "homepage",
504
+ "host",
505
+ "hosting",
506
+ "hostmaster",
507
+ "hostname",
508
+ "howto",
509
+ "hpg",
510
+ "html",
511
+ "http",
512
+ "httpd",
513
+ "https",
514
+ "i",
515
+ "iamges",
516
+ "icon",
517
+ "icons",
518
+ "id",
519
+ "idea",
520
+ "ideas",
521
+ "image",
522
+ "images",
523
+ "imap",
524
+ "img",
525
+ "index",
526
+ "indice",
527
+ "info",
528
+ "information",
529
+ "inquiry",
530
+ "instagram",
531
+ "intranet",
532
+ "invitations",
533
+ "invite",
534
+ "ipad",
535
+ "iphone",
536
+ "irc",
537
+ "is",
538
+ "issue",
539
+ "issues",
540
+ "it",
541
+ "item",
542
+ "items",
543
+ "java",
544
+ "javascript",
545
+ "job",
546
+ "jobs",
547
+ "join",
548
+ "js",
549
+ "json",
550
+ "jump",
551
+ "knowledgebase",
552
+ "language",
553
+ "languages",
554
+ "last",
555
+ "ldap-status",
556
+ "legal",
557
+ "license",
558
+ "link",
559
+ "links",
560
+ "linux",
561
+ "list",
562
+ "lists",
563
+ "log",
564
+ "log-in",
565
+ "log-out",
566
+ "log_in",
567
+ "log_out",
568
+ "login",
569
+ "logout",
570
+ "logs",
571
+ "m",
572
+ "mac",
573
+ "mail",
574
+ "mail1",
575
+ "mail2",
576
+ "mail3",
577
+ "mail4",
578
+ "mail5",
579
+ "mailer",
580
+ "mailing",
581
+ "maintenance",
582
+ "manager",
583
+ "manual",
584
+ "map",
585
+ "maps",
586
+ "marketing",
587
+ "master",
588
+ "me",
589
+ "media",
590
+ "member",
591
+ "members",
592
+ "message",
593
+ "messages",
594
+ "messenger",
595
+ "microblog",
596
+ "microblogs",
597
+ "mine",
598
+ "mis",
599
+ "mob",
600
+ "mobile",
601
+ "movie",
602
+ "movies",
603
+ "mp3",
604
+ "msg",
605
+ "msn",
606
+ "music",
607
+ "musicas",
608
+ "mx",
609
+ "my",
610
+ "mysql",
611
+ "name",
612
+ "named",
613
+ "nan",
614
+ "navi",
615
+ "navigation",
616
+ "net",
617
+ "network",
618
+ "new",
619
+ "news",
620
+ "newsletter",
621
+ "nick",
622
+ "nickname",
623
+ "notes",
624
+ "noticias",
625
+ "notification",
626
+ "notifications",
627
+ "notify",
628
+ "ns",
629
+ "ns1",
630
+ "ns10",
631
+ "ns2",
632
+ "ns3",
633
+ "ns4",
634
+ "ns5",
635
+ "ns6",
636
+ "ns7",
637
+ "ns8",
638
+ "ns9",
639
+ "null",
640
+ "oauth",
641
+ "oauth_clients",
642
+ "offer",
643
+ "offers",
644
+ "official",
645
+ "old",
646
+ "online",
647
+ "openid",
648
+ "operator",
649
+ "order",
650
+ "orders",
651
+ "organization",
652
+ "organizations",
653
+ "overview",
654
+ "owner",
655
+ "owners",
656
+ "page",
657
+ "pager",
658
+ "pages",
659
+ "panel",
660
+ "password",
661
+ "payment",
662
+ "perl",
663
+ "phone",
664
+ "photo",
665
+ "photoalbum",
666
+ "photos",
667
+ "php",
668
+ "phpmyadmin",
669
+ "phppgadmin",
670
+ "phpredisadmin",
671
+ "pic",
672
+ "pics",
673
+ "ping",
674
+ "plan",
675
+ "plans",
676
+ "plugin",
677
+ "plugins",
678
+ "policy",
679
+ "pop",
680
+ "pop3",
681
+ "popular",
682
+ "portal",
683
+ "post",
684
+ "postfix",
685
+ "postmaster",
686
+ "posts",
687
+ "pr",
688
+ "premium",
689
+ "press",
690
+ "price",
691
+ "pricing",
692
+ "privacy",
693
+ "privacy-policy",
694
+ "privacy_policy",
695
+ "privacypolicy",
696
+ "private",
697
+ "product",
698
+ "products",
699
+ "profile",
700
+ "project",
701
+ "projects",
702
+ "promo",
703
+ "pub",
704
+ "public",
705
+ "purpose",
706
+ "put",
707
+ "python",
708
+ "query",
709
+ "random",
710
+ "ranking",
711
+ "read",
712
+ "readme",
713
+ "recent",
714
+ "recruit",
715
+ "recruitment",
716
+ "register",
717
+ "registration",
718
+ "release",
719
+ "remove",
720
+ "replies",
721
+ "report",
722
+ "reports",
723
+ "repositories",
724
+ "repository",
725
+ "req",
726
+ "request",
727
+ "requests",
728
+ "reset",
729
+ "roc",
730
+ "root",
731
+ "rss",
732
+ "ruby",
733
+ "rule",
734
+ "sag",
735
+ "sale",
736
+ "sales",
737
+ "sample",
738
+ "samples",
739
+ "save",
740
+ "school",
741
+ "script",
742
+ "scripts",
743
+ "search",
744
+ "secure",
745
+ "security",
746
+ "self",
747
+ "send",
748
+ "server",
749
+ "server-info",
750
+ "server-status",
751
+ "service",
752
+ "services",
753
+ "session",
754
+ "sessions",
755
+ "setting",
756
+ "settings",
757
+ "setup",
758
+ "share",
759
+ "shop",
760
+ "show",
761
+ "sign-in",
762
+ "sign-up",
763
+ "sign_in",
764
+ "sign_up",
765
+ "signin",
766
+ "signout",
767
+ "signup",
768
+ "site",
769
+ "sitemap",
770
+ "sites",
771
+ "smartphone",
772
+ "smtp",
773
+ "soporte",
774
+ "source",
775
+ "spec",
776
+ "special",
777
+ "sql",
778
+ "src",
779
+ "ssh",
780
+ "ssl",
781
+ "ssladmin",
782
+ "ssladministrator",
783
+ "sslwebmaster",
784
+ "staff",
785
+ "stage",
786
+ "staging",
787
+ "start",
788
+ "stat",
789
+ "state",
790
+ "static",
791
+ "stats",
792
+ "status",
793
+ "store",
794
+ "stores",
795
+ "stories",
796
+ "style",
797
+ "styleguide",
798
+ "stylesheet",
799
+ "stylesheets",
800
+ "subdomain",
801
+ "subscribe",
802
+ "subscriptions",
803
+ "suporte",
804
+ "support",
805
+ "svn",
806
+ "swf",
807
+ "sys",
808
+ "sysadmin",
809
+ "sysadministrator",
810
+ "system",
811
+ "tablet",
812
+ "tablets",
813
+ "tag",
814
+ "talk",
815
+ "task",
816
+ "tasks",
817
+ "team",
818
+ "teams",
819
+ "tech",
820
+ "telnet",
821
+ "term",
822
+ "terms",
823
+ "terms-of-service",
824
+ "terms_of_service",
825
+ "termsofservice",
826
+ "test",
827
+ "test1",
828
+ "test2",
829
+ "test3",
830
+ "teste",
831
+ "testing",
832
+ "tests",
833
+ "theme",
834
+ "themes",
835
+ "thread",
836
+ "threads",
837
+ "tmp",
838
+ "todo",
839
+ "tool",
840
+ "tools",
841
+ "top",
842
+ "topic",
843
+ "topics",
844
+ "tos",
845
+ "tour",
846
+ "translations",
847
+ "trends",
848
+ "tutorial",
849
+ "tux",
850
+ "tv",
851
+ "twitter",
852
+ "undef",
853
+ "unfollow",
854
+ "unsubscribe",
855
+ "update",
856
+ "upload",
857
+ "uploads",
858
+ "url",
859
+ "usage",
860
+ "user",
861
+ "username",
862
+ "users",
863
+ "usuario",
864
+ "vendas",
865
+ "ver",
866
+ "version",
867
+ "video",
868
+ "videos",
869
+ "visitor",
870
+ "watch",
871
+ "weather",
872
+ "web",
873
+ "webhook",
874
+ "webhooks",
875
+ "webmail",
876
+ "webmaster",
877
+ "website",
878
+ "websites",
879
+ "welcome",
880
+ "widget",
881
+ "widgets",
882
+ "wiki",
883
+ "win",
884
+ "windows",
885
+ "word",
886
+ "work",
887
+ "works",
888
+ "workshop",
889
+ "ww",
890
+ "wws",
891
+ "www",
892
+ "www1",
893
+ "www2",
894
+ "www3",
895
+ "www4",
896
+ "www5",
897
+ "www6",
898
+ "www7",
899
+ "wwws",
900
+ "wwww",
901
+ "xfn",
902
+ "xml",
903
+ "xmpp",
904
+ "xpg",
905
+ "xxx",
906
+ "yaml",
907
+ "year",
908
+ "yml",
909
+ "you",
910
+ "yourdomain",
911
+ "yourname",
912
+ "yoursite",
913
+ "yourusername"
914
+ ];
915
+ var FORBIDDEN_REGEXP = new RegExp(`^(${ANONYMOUS_USERNAME}|${FORBIDDEN_USERNAMES_REGEXPS.join("|")})$`, "i");
916
+ function isForbiddenUsername(username) {
917
+ return !!username.match(FORBIDDEN_REGEXP);
918
+ }
919
+ __name(isForbiddenUsername, "isForbiddenUsername");
920
+ async function sequentializePromises(promises) {
921
+ if (!promises.length)
922
+ return [];
923
+ const results = [];
924
+ for (const promiseOrFunc of promises) {
925
+ const promise = promiseOrFunc instanceof Function ? promiseOrFunc() : promiseOrFunc;
926
+ results.push(await promise);
927
+ }
928
+ return results;
929
+ }
930
+ __name(sequentializePromises, "sequentializePromises");
931
+ function checkParamPrototypeOrThrow(paramVal, paramName, prototypes, prototypeName, isOptional = false) {
932
+ if (isOptional && (paramVal === void 0 || paramVal === null))
933
+ return;
934
+ const hasCorrectPrototype = prototypes instanceof Array ? prototypes.some((prototype) => paramVal instanceof prototype) : paramVal instanceof prototypes;
935
+ if (!hasCorrectPrototype)
936
+ throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
937
+ }
938
+ __name(checkParamPrototypeOrThrow, "checkParamPrototypeOrThrow");
939
+ function promisifyServerListen(server) {
940
+ return (port) => {
941
+ return new Promise((resolve, reject) => {
942
+ const onError = /* @__PURE__ */ __name((err) => {
943
+ removeListeners();
944
+ reject(err);
945
+ }, "onError");
946
+ const onListening = /* @__PURE__ */ __name(() => {
947
+ removeListeners();
948
+ resolve();
949
+ }, "onListening");
950
+ const removeListeners = /* @__PURE__ */ __name(() => {
951
+ server.removeListener("error", onError);
952
+ server.removeListener("listening", onListening);
953
+ }, "removeListeners");
954
+ server.on("error", onError);
955
+ server.on("listening", onListening);
956
+ server.listen(port);
957
+ });
958
+ };
959
+ }
960
+ __name(promisifyServerListen, "promisifyServerListen");
961
+ function configureLogger(givenLog, isProduction) {
962
+ if (isProduction) {
963
+ givenLog.setOptions({
964
+ level: LogLevel.INFO,
965
+ logger: new LoggerJson()
966
+ });
967
+ } else {
968
+ givenLog.setOptions({ level: LogLevel.DEBUG });
969
+ }
970
+ }
971
+ __name(configureLogger, "configureLogger");
972
+ function timeoutPromise(promise, timeoutMillis, errorMessage = "Promise has timed-out") {
973
+ return new Promise((resolve, reject) => {
974
+ let timeout;
975
+ let hasFulfilled = false;
976
+ const callback = /* @__PURE__ */ __name((err, result) => {
977
+ if (hasFulfilled)
978
+ return;
979
+ clearTimeout(timeout);
980
+ hasFulfilled = true;
981
+ if (err)
982
+ return reject(err);
983
+ resolve(result);
984
+ }, "callback");
985
+ promise.then((result) => callback(null, result), callback);
986
+ timeout = setTimeout(() => callback(new Error(errorMessage)), timeoutMillis);
987
+ });
988
+ }
989
+ __name(timeoutPromise, "timeoutPromise");
990
+
991
+ // src/utilities.client.ts
992
+ import { VERSION_INT_MAJOR_BASE, VERSION_INT_MINOR_BASE, RELATIVE_URL_REGEX } from "@apify/consts";
993
+ function isNullOrUndefined(obj) {
994
+ return obj == null;
995
+ }
996
+ __name(isNullOrUndefined, "isNullOrUndefined");
997
+ function isBuffer(obj) {
998
+ return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
999
+ }
1000
+ __name(isBuffer, "isBuffer");
1001
+ function dateToString(date, middleT) {
1002
+ if (!(date instanceof Date)) {
1003
+ return "";
1004
+ }
1005
+ const year = date.getFullYear();
1006
+ const month = date.getMonth() + 1;
1007
+ const day = date.getDate();
1008
+ const hours = date.getHours();
1009
+ const minutes = date.getMinutes();
1010
+ const seconds = date.getSeconds();
1011
+ const millis = date.getMilliseconds();
1012
+ const pad = /* @__PURE__ */ __name((num) => num < 10 ? `0${num}` : num, "pad");
1013
+ const datePart = `${year}-${pad(month)}-${pad(day)}`;
1014
+ const millisPart = millis < 10 ? `00${millis}` : millis < 100 ? `0${millis}` : millis;
1015
+ const timePart = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${millisPart}`;
1016
+ return `${datePart}${middleT ? "T" : " "}${timePart}`;
1017
+ }
1018
+ __name(dateToString, "dateToString");
1019
+ function truncate(str, maxLength, suffix = "...[truncated]") {
1020
+ maxLength = Math.floor(maxLength);
1021
+ if (suffix.length > maxLength) {
1022
+ throw new Error("suffix string cannot be longer than maxLength");
1023
+ }
1024
+ if (typeof str === "string" && str.length > maxLength) {
1025
+ str = str.substr(0, maxLength - suffix.length) + suffix;
1026
+ }
1027
+ return str;
1028
+ }
1029
+ __name(truncate, "truncate");
1030
+ function getOrdinalSuffix(num) {
1031
+ const s = ["th", "st", "nd", "rd"];
1032
+ const v = num % 100;
1033
+ return s[(v - 20) % 10] || s[v] || s[0];
1034
+ }
1035
+ __name(getOrdinalSuffix, "getOrdinalSuffix");
1036
+ function parseUrl(str) {
1037
+ if (typeof str !== "string")
1038
+ return {};
1039
+ const o = {
1040
+ strictMode: false,
1041
+ key: [
1042
+ "source",
1043
+ "protocol",
1044
+ "authority",
1045
+ "userInfo",
1046
+ "user",
1047
+ "password",
1048
+ "host",
1049
+ "port",
1050
+ "relative",
1051
+ "path",
1052
+ "directory",
1053
+ "file",
1054
+ "query",
1055
+ "fragment"
1056
+ ],
1057
+ q: {
1058
+ name: "queryKey",
1059
+ parser: /(?:^|&)([^&=]*)=?([^&]*)/g
1060
+ },
1061
+ parser: {
1062
+ strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
1063
+ loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
1064
+ }
1065
+ };
1066
+ const m = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
1067
+ const uri = {};
1068
+ let i = o.key.length;
1069
+ while (i--)
1070
+ uri[o.key[i]] = m[i] || "";
1071
+ uri[o.q.name] = {};
1072
+ uri[o.key[12]].replace(o.q.parser, ($0, $1, $2) => {
1073
+ if ($1)
1074
+ uri[o.q.name][$1] = $2;
1075
+ });
1076
+ uri.fragmentKey = {};
1077
+ if (uri.fragment) {
1078
+ uri.fragment.replace(o.q.parser, ($0, $1, $2) => {
1079
+ if ($1)
1080
+ uri.fragmentKey[$1] = $2;
1081
+ });
1082
+ }
1083
+ return uri;
1084
+ }
1085
+ __name(parseUrl, "parseUrl");
1086
+ function normalizeUrl(url, keepFragment) {
1087
+ if (typeof url !== "string" || !url.length) {
1088
+ return null;
1089
+ }
1090
+ const urlObj = parseUrl(url.trim());
1091
+ if (!urlObj.protocol || !urlObj.host) {
1092
+ return null;
1093
+ }
1094
+ const path = urlObj.path.replace(/\/$/, "");
1095
+ const params = urlObj.query ? urlObj.query.split("&").filter((param) => {
1096
+ return !/^utm_/.test(param);
1097
+ }).sort() : [];
1098
+ return `${urlObj.protocol.trim().toLowerCase()}://${urlObj.host.trim().toLowerCase()}${path.trim()}${params.length ? `?${params.join("&").trim()}` : ""}${keepFragment && urlObj.fragment ? `#${urlObj.fragment.trim()}` : ""}`;
1099
+ }
1100
+ __name(normalizeUrl, "normalizeUrl");
1101
+ function markedSetNofollowLinks(href, title, text) {
1102
+ let urlParsed;
1103
+ try {
1104
+ urlParsed = new URL(href);
1105
+ } catch (e) {
1106
+ }
1107
+ const isApifyLink = urlParsed && /(\.|^)apify\.com$/i.test(urlParsed.hostname);
1108
+ return isApifyLink ? `<a href="${href}">${title || text}</a>` : `<a rel="noopener noreferrer nofollow" target="_blank" href="${href}">${title || text}</a>`;
1109
+ }
1110
+ __name(markedSetNofollowLinks, "markedSetNofollowLinks");
1111
+ function markedDecreaseHeadsLevel(text, level) {
1112
+ level += 1;
1113
+ return `<h${level}>${text}</h${level}>`;
1114
+ }
1115
+ __name(markedDecreaseHeadsLevel, "markedDecreaseHeadsLevel");
1116
+ function buildOrVersionNumberIntToStr(int) {
1117
+ if (typeof int !== "number" || !(int >= 0))
1118
+ return null;
1119
+ const major = Math.floor(int / VERSION_INT_MAJOR_BASE);
1120
+ const remainder = int % VERSION_INT_MAJOR_BASE;
1121
+ const minor = Math.floor(remainder / VERSION_INT_MINOR_BASE);
1122
+ const build = remainder % VERSION_INT_MINOR_BASE;
1123
+ let str = `${major}.${minor}`;
1124
+ if (build > 0)
1125
+ str += `.${build}`;
1126
+ return str;
1127
+ }
1128
+ __name(buildOrVersionNumberIntToStr, "buildOrVersionNumberIntToStr");
1129
+ var ESCAPE_DOT = "\uFF0E";
1130
+ var ESCAPE_DOLLAR = "\uFF04";
1131
+ var ESCAPE_TO_BSON = "\uFF54\uFF4F\uFF22\uFF33\uFF2F\uFF2E";
1132
+ var ESCAPE_TO_STRING = "\uFF54\uFF4F\uFF33\uFF54\uFF52\uFF49\uFF4E\uFF47";
1133
+ var ESCAPE_BSON_TYPE = "\uFF3F\uFF42\uFF53\uFF4F\uFF4E\uFF54\uFF59\uFF50\uFF45";
1134
+ var ESCAPE_NULL = "";
1135
+ var REGEXP_IS_ESCAPED = new RegExp(`(${ESCAPE_DOT}|^${ESCAPE_DOLLAR}|^${ESCAPE_TO_BSON}$|^${ESCAPE_BSON_TYPE}|^${ESCAPE_TO_STRING}$)`);
1136
+ var REGEXP_DOT = new RegExp(ESCAPE_DOT, "g");
1137
+ var REGEXP_DOLLAR = new RegExp(`^${ESCAPE_DOLLAR}`);
1138
+ var REGEXP_TO_BSON = new RegExp(`^${ESCAPE_TO_BSON}$`);
1139
+ var REGEXP_TO_STRING = new RegExp(`^${ESCAPE_TO_STRING}$`);
1140
+ var REGEXP_BSON_TYPE = new RegExp(`^${ESCAPE_BSON_TYPE}$`);
1141
+ function escapePropertyName(name) {
1142
+ if (/(\.|^\$|^toBSON$|^_bsontype$|^toString$|\0)/.test(name)) {
1143
+ name = name.replace(/\./g, ESCAPE_DOT);
1144
+ name = name.replace(/^\$/, ESCAPE_DOLLAR);
1145
+ name = name.replace(/^toBSON$/, ESCAPE_TO_BSON);
1146
+ name = name.replace(/^toString$/, ESCAPE_TO_STRING);
1147
+ name = name.replace(/^_bsontype$/, ESCAPE_BSON_TYPE);
1148
+ name = name.replace(/\0/g, ESCAPE_NULL);
1149
+ }
1150
+ return name;
1151
+ }
1152
+ __name(escapePropertyName, "escapePropertyName");
1153
+ function unescapePropertyName(name) {
1154
+ if (REGEXP_IS_ESCAPED.test(name)) {
1155
+ name = name.replace(REGEXP_DOT, ".");
1156
+ name = name.replace(REGEXP_DOLLAR, "$");
1157
+ name = name.replace(REGEXP_TO_BSON, "toBSON");
1158
+ name = name.replace(REGEXP_TO_STRING, "toString");
1159
+ name = name.replace(REGEXP_BSON_TYPE, "_bsontype");
1160
+ }
1161
+ return name;
1162
+ }
1163
+ __name(unescapePropertyName, "unescapePropertyName");
1164
+ function traverseObject(obj, clone, transformFunc) {
1165
+ if (obj === null || typeof obj !== "object" || Object.prototype.toString.call(obj) === "[object Date]" || isBuffer(obj))
1166
+ return obj;
1167
+ let result;
1168
+ if (Array.isArray(obj)) {
1169
+ result = clone ? new Array(obj.length) : obj;
1170
+ for (let i = 0; i < obj.length; i++) {
1171
+ const val = traverseObject(obj[i], clone, transformFunc);
1172
+ if (clone)
1173
+ result[i] = val;
1174
+ }
1175
+ return result;
1176
+ }
1177
+ result = clone ? {} : obj;
1178
+ for (const key in obj) {
1179
+ const val = traverseObject(obj[key], clone, transformFunc);
1180
+ const [transformedKey, transformedVal] = transformFunc(key, val);
1181
+ if (key === transformedKey) {
1182
+ if (clone || val !== transformedVal)
1183
+ result[key] = transformedVal;
1184
+ } else {
1185
+ result[transformedKey] = transformedVal;
1186
+ if (!clone)
1187
+ delete obj[key];
1188
+ }
1189
+ }
1190
+ return result;
1191
+ }
1192
+ __name(traverseObject, "traverseObject");
1193
+ function escapeForBson(obj, clone = false) {
1194
+ return traverseObject(obj, clone, (key, value) => [escapePropertyName(key), value]);
1195
+ }
1196
+ __name(escapeForBson, "escapeForBson");
1197
+ function unescapeFromBson(obj, clone = false) {
1198
+ return traverseObject(obj, clone, (key, value) => [unescapePropertyName(key), value]);
1199
+ }
1200
+ __name(unescapeFromBson, "unescapeFromBson");
1201
+ function isBadForMongo(obj) {
1202
+ let isBad = false;
1203
+ try {
1204
+ traverseObject(obj, false, (key, value) => {
1205
+ const escapedKey = escapePropertyName(key);
1206
+ if (key !== escapedKey) {
1207
+ isBad = true;
1208
+ throw new Error();
1209
+ }
1210
+ return [key, value];
1211
+ });
1212
+ } catch (e) {
1213
+ if (!isBad)
1214
+ throw e;
1215
+ }
1216
+ return isBad;
1217
+ }
1218
+ __name(isBadForMongo, "isBadForMongo");
1219
+ var JsonVariable = class {
1220
+ constructor(name) {
1221
+ this.name = name;
1222
+ }
1223
+ getToken() {
1224
+ return `{{${this.name}}}`;
1225
+ }
1226
+ };
1227
+ __name(JsonVariable, "JsonVariable");
1228
+ function jsonStringifyExtended(value, replacer, space = 0) {
1229
+ if (replacer && !(replacer instanceof Function))
1230
+ throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
1231
+ const replacements = {};
1232
+ const extendedReplacer = /* @__PURE__ */ __name((key, val) => {
1233
+ val = replacer ? replacer(key, val) : val;
1234
+ if (val instanceof Function)
1235
+ return val.toString();
1236
+ if (val instanceof JsonVariable) {
1237
+ const randomToken = `<<<REPLACEMENT_TOKEN::${Math.random()}>>>`;
1238
+ replacements[randomToken] = val.getToken();
1239
+ return randomToken;
1240
+ }
1241
+ return val;
1242
+ }, "extendedReplacer");
1243
+ let stringifiedValue = JSON.stringify(value, extendedReplacer, space);
1244
+ Object.entries(replacements).forEach(([replacementToken, replacementValue]) => {
1245
+ stringifiedValue = stringifiedValue.replace(`"${replacementToken}"`, replacementValue);
1246
+ });
1247
+ return stringifiedValue;
1248
+ }
1249
+ __name(jsonStringifyExtended, "jsonStringifyExtended");
1250
+ function splitFullName(fullName) {
1251
+ if (typeof fullName !== "string")
1252
+ return [null, null];
1253
+ const names = (fullName || "").trim().split(" ");
1254
+ const nonEmptyNames = names.filter((val) => val);
1255
+ if (nonEmptyNames.length === 0) {
1256
+ return [null, null];
1257
+ }
1258
+ if (nonEmptyNames.length === 1) {
1259
+ return [null, nonEmptyNames[0]];
1260
+ }
1261
+ return [names[0], nonEmptyNames.slice(1).join(" ")];
1262
+ }
1263
+ __name(splitFullName, "splitFullName");
1264
+ function isUrlRelative(url) {
1265
+ return RELATIVE_URL_REGEX.test(url);
1266
+ }
1267
+ __name(isUrlRelative, "isUrlRelative");
1268
+
1269
+ // src/exponential_backoff.ts
1270
+ import log2 from "@apify/log";
1271
+ var RetryableError = class extends Error {
1272
+ constructor(error, ...args) {
1273
+ super(...args);
1274
+ this.error = error;
1275
+ }
1276
+ };
1277
+ __name(RetryableError, "RetryableError");
1278
+ async function retryWithExpBackoff(params = {}) {
1279
+ const { func, expBackoffMillis, expBackoffMaxRepeats } = params;
1280
+ if (typeof func !== "function") {
1281
+ throw new Error('Parameter "func" should be a function.');
1282
+ }
1283
+ if (typeof expBackoffMillis !== "number") {
1284
+ throw new Error('Parameter "expBackoffMillis" should be a number.');
1285
+ }
1286
+ if (typeof expBackoffMaxRepeats !== "number") {
1287
+ throw new Error('Parameter "expBackoffMaxRepeats" should be a number.');
1288
+ }
1289
+ for (let i = 0; ; i++) {
1290
+ let error;
1291
+ try {
1292
+ return await func();
1293
+ } catch (e) {
1294
+ error = e;
1295
+ }
1296
+ if (!(error instanceof RetryableError)) {
1297
+ throw error;
1298
+ }
1299
+ if (i >= expBackoffMaxRepeats - 1) {
1300
+ throw error.error;
1301
+ }
1302
+ const waitMillis = expBackoffMillis * 2 ** i;
1303
+ const rand = /* @__PURE__ */ __name((from, to) => from + Math.floor(Math.random() * (to - from + 1)), "rand");
1304
+ const randomizedWaitMillis = rand(waitMillis, waitMillis * 2);
1305
+ if (i === Math.round(expBackoffMaxRepeats / 2)) {
1306
+ log2.warning(`Retry failed ${i} times and will be repeated in ${randomizedWaitMillis}ms`, {
1307
+ originalError: error.error.message,
1308
+ errorDetails: error.error.details
1309
+ });
1310
+ }
1311
+ await delayPromise(randomizedWaitMillis);
1312
+ }
1313
+ }
1314
+ __name(retryWithExpBackoff, "retryWithExpBackoff");
1315
+
1316
+ // src/health_checker.ts
1317
+ var CHECK_TYPES = /* @__PURE__ */ ((CHECK_TYPES2) => {
1318
+ CHECK_TYPES2["MONGODB_READ"] = "MONGODB_READ";
1319
+ CHECK_TYPES2["MONGODB_WRITE"] = "MONGODB_WRITE";
1320
+ CHECK_TYPES2["REDIS"] = "REDIS";
1321
+ return CHECK_TYPES2;
1322
+ })(CHECK_TYPES || {});
1323
+ var HealthChecker = class {
1324
+ constructor(options) {
1325
+ this.options = options;
1326
+ const {
1327
+ checks,
1328
+ redisPrefix = "health-check",
1329
+ redisTtlSecs = 15,
1330
+ checkTimeoutMillis = 15e3,
1331
+ mongoDbWriteTestCollection = "healthCheckPlayground",
1332
+ mongoDbWriteTestRemoveOlderThanSecs = 15
1333
+ } = options;
1334
+ if (!Array.isArray(checks))
1335
+ throw new Error('Parameter "check" must be an array');
1336
+ checks.map((check) => this._validateCheck(check));
1337
+ this.checks = checks;
1338
+ this.redisPrefix = redisPrefix;
1339
+ this.redisTtlSecs = redisTtlSecs;
1340
+ this.checkTimeoutMillis = checkTimeoutMillis;
1341
+ this.mongoDbWriteTestCollection = mongoDbWriteTestCollection;
1342
+ this.mongoDbWriteTestRemoveOlderThanSecs = mongoDbWriteTestRemoveOlderThanSecs;
1343
+ }
1344
+ async ensureIsHealthy() {
1345
+ for (const check of this.checks) {
1346
+ try {
1347
+ const checkPromise = this._performCheck(check);
1348
+ await timeoutPromise(checkPromise, this.checkTimeoutMillis, "Check has timed-out");
1349
+ } catch (_err) {
1350
+ const err = _err;
1351
+ throw new Error(`Health check test "${check.type}" failed with an error: ${err.message}"`);
1352
+ }
1353
+ }
1354
+ }
1355
+ _validateCheck(check) {
1356
+ if (!(check.type in CHECK_TYPES))
1357
+ throw new Error(`Check type "${check.type}" is invalid`);
1358
+ if (typeof check.client !== "object")
1359
+ throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
1360
+ }
1361
+ _performCheck(check) {
1362
+ switch (check.type) {
1363
+ case "MONGODB_READ" /* MONGODB_READ */:
1364
+ return this._testMongoDbRead(check);
1365
+ case "MONGODB_WRITE" /* MONGODB_WRITE */:
1366
+ return this._testMongoDbWrite(check);
1367
+ case "REDIS" /* REDIS */:
1368
+ return this._testRedisWrite(check);
1369
+ default:
1370
+ throw new Error("Unknown check type");
1371
+ }
1372
+ }
1373
+ async _testMongoDbRead({ client }) {
1374
+ const response = await client.listCollections().toArray();
1375
+ if (!Array.isArray(response))
1376
+ throw new Error(`Got ${typeof response} instead of an array!`);
1377
+ }
1378
+ async _testMongoDbWrite({ client }) {
1379
+ const id = cryptoRandomObjectId();
1380
+ const collection = client.collection(this.mongoDbWriteTestCollection);
1381
+ await collection.deleteMany({
1382
+ createdAt: {
1383
+ $lt: new Date(Date.now() - this.mongoDbWriteTestRemoveOlderThanSecs * 1e3)
1384
+ }
1385
+ });
1386
+ await collection.insertOne({
1387
+ _id: id,
1388
+ createdAt: new Date()
1389
+ });
1390
+ const retrieved = await collection.findOne({ _id: id });
1391
+ if (!retrieved)
1392
+ throw new Error(`Item with ID "${id}" not found!`);
1393
+ }
1394
+ async _testRedisWrite({ client }) {
1395
+ const key = `${this.redisPrefix}:${cryptoRandomObjectId()}`;
1396
+ const expected = "OK";
1397
+ await client.set(key, expected, "EX", this.redisTtlSecs);
1398
+ const given = await client.get(key);
1399
+ if (given !== expected)
1400
+ throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
1401
+ }
1402
+ };
1403
+ __name(HealthChecker, "HealthChecker");
1404
+ HealthChecker.CHECK_TYPES = CHECK_TYPES;
1405
+
1406
+ // src/parse_jsonl_stream.ts
1407
+ import { Transform } from "stream";
1408
+ var ParseJsonlStream = class extends Transform {
1409
+ constructor() {
1410
+ super(...arguments);
1411
+ this.pendingChunk = null;
1412
+ }
1413
+ parseLineAndEmitObject(line) {
1414
+ line = line.trim();
1415
+ if (!line) {
1416
+ return;
1417
+ }
1418
+ try {
1419
+ const obj = JSON.parse(line);
1420
+ this.emit("object", obj);
1421
+ } catch (e) {
1422
+ throw new Error(`Cannot parse JSON stream data ('${String(line)}'): ${String(e)}`);
1423
+ }
1424
+ }
1425
+ _transform(chunk, encoding, callback) {
1426
+ let allData;
1427
+ if (this.pendingChunk) {
1428
+ allData = this.pendingChunk + chunk;
1429
+ this.pendingChunk = null;
1430
+ } else {
1431
+ allData = chunk;
1432
+ }
1433
+ const lines = allData.toString().split("\n");
1434
+ if (lines[lines.length - 1] !== "") {
1435
+ this.pendingChunk = lines.pop();
1436
+ }
1437
+ try {
1438
+ for (let i = 0; i < lines.length; i++) {
1439
+ this.parseLineAndEmitObject(lines[i]);
1440
+ }
1441
+ } catch (err) {
1442
+ callback(err, null);
1443
+ return;
1444
+ }
1445
+ callback(null, chunk);
1446
+ }
1447
+ _flush(callback) {
1448
+ if (this.pendingChunk) {
1449
+ try {
1450
+ this.parseLineAndEmitObject(this.pendingChunk);
1451
+ this.pendingChunk = null;
1452
+ } catch (err) {
1453
+ callback(err, null);
1454
+ return;
1455
+ }
1456
+ }
1457
+ callback();
1458
+ }
1459
+ };
1460
+ __name(ParseJsonlStream, "ParseJsonlStream");
1461
+
1462
+ // src/streams_utilities.ts
1463
+ async function concatStreamToBuffer(stream) {
1464
+ return new Promise((resolve, reject) => {
1465
+ const chunks = [];
1466
+ stream.on("data", (chunk) => {
1467
+ chunks.push(chunk);
1468
+ }).on("error", (e) => reject(e)).on("end", () => {
1469
+ const buffer = Buffer.concat(chunks);
1470
+ return resolve(buffer);
1471
+ });
1472
+ });
1473
+ }
1474
+ __name(concatStreamToBuffer, "concatStreamToBuffer");
1475
+ async function readStreamToString(stream, encoding) {
1476
+ const buffer = await concatStreamToBuffer(stream);
1477
+ return buffer.toString(encoding);
1478
+ }
1479
+ __name(readStreamToString, "readStreamToString");
1480
+
1481
+ // src/webhook_payload_template.ts
1482
+ var WebhookPayloadTemplateError = class extends Error {
1483
+ constructor(message) {
1484
+ super(message);
1485
+ this.name = this.constructor.name;
1486
+ if (typeof Error.captureStackTrace === "function") {
1487
+ Error.captureStackTrace(this, this.constructor);
1488
+ }
1489
+ }
1490
+ };
1491
+ __name(WebhookPayloadTemplateError, "WebhookPayloadTemplateError");
1492
+ var InvalidJsonError = class extends WebhookPayloadTemplateError {
1493
+ constructor(originalError) {
1494
+ super(originalError.message);
1495
+ }
1496
+ };
1497
+ __name(InvalidJsonError, "InvalidJsonError");
1498
+ var InvalidVariableError = class extends Error {
1499
+ constructor(variable) {
1500
+ super(`Invalid payload template variable: ${variable}`);
1501
+ }
1502
+ };
1503
+ __name(InvalidVariableError, "InvalidVariableError");
1504
+ var WebhookPayloadTemplate = class {
1505
+ constructor(template, allowedVariables = null, context = {}) {
1506
+ this.template = template;
1507
+ this.allowedVariables = allowedVariables;
1508
+ this.context = context;
1509
+ this.payload = this.template;
1510
+ this.replacedVariables = [];
1511
+ }
1512
+ static parse(payloadTemplate, allowedVariables = null, context = {}) {
1513
+ const type = typeof payloadTemplate;
1514
+ if (type !== "string")
1515
+ throw new Error(`Cannot parse a ${type} payload template.`);
1516
+ const template = new WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);
1517
+ return template._parse();
1518
+ }
1519
+ static stringify(objectTemplate, replacer, indent = 2) {
1520
+ const type = typeof objectTemplate;
1521
+ if (!objectTemplate || type !== "object")
1522
+ throw new Error(`Cannot stringify a ${type} payload template.`);
1523
+ return jsonStringifyExtended(objectTemplate, replacer, indent);
1524
+ }
1525
+ static getVariable(variableName) {
1526
+ return new JsonVariable(variableName);
1527
+ }
1528
+ _parse() {
1529
+ while (true) {
1530
+ try {
1531
+ return JSON.parse(this.payload);
1532
+ } catch (err) {
1533
+ const position = this._findPositionOfNextVariable();
1534
+ if (position) {
1535
+ this._replaceVariable(position);
1536
+ } else {
1537
+ throw new InvalidJsonError(err);
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+ _findPositionOfNextVariable(startIndex = 0) {
1543
+ const openBraceIndex = this.payload.indexOf("{{", startIndex);
1544
+ const closeBraceIndex = this.payload.indexOf("}}", openBraceIndex) + 1;
1545
+ const someVariableMaybeExists = openBraceIndex > -1 && closeBraceIndex > -1;
1546
+ if (!someVariableMaybeExists)
1547
+ return null;
1548
+ const isInsideString = this._isVariableInsideString(openBraceIndex);
1549
+ if (!isInsideString)
1550
+ return { openBraceIndex, closeBraceIndex };
1551
+ return this._findPositionOfNextVariable(openBraceIndex + 1);
1552
+ }
1553
+ _isVariableInsideString(openBraceIndex) {
1554
+ const unescapedQuoteCount = this._countUnescapedDoubleQuotesUpToIndex(openBraceIndex);
1555
+ return unescapedQuoteCount % 2 === 1;
1556
+ }
1557
+ _countUnescapedDoubleQuotesUpToIndex(index) {
1558
+ const payloadSection = this.payload.substring(0, index);
1559
+ let unescapedQuoteCount = 0;
1560
+ for (let i = 0; i < payloadSection.length; i++) {
1561
+ const char = payloadSection[i];
1562
+ const prevChar = payloadSection[i - 1];
1563
+ if (char === '"' && prevChar !== "\\") {
1564
+ unescapedQuoteCount++;
1565
+ }
1566
+ }
1567
+ return unescapedQuoteCount;
1568
+ }
1569
+ _replaceVariable({ openBraceIndex, closeBraceIndex }) {
1570
+ const variableName = this.payload.substring(openBraceIndex + 2, closeBraceIndex - 1);
1571
+ this._validateVariableName(variableName);
1572
+ const replacement = this._getVariableReplacement(variableName);
1573
+ this.replacedVariables.push({ variableName, replacement });
1574
+ this.payload = this.payload.replace(`{{${variableName}}}`, replacement);
1575
+ }
1576
+ _validateVariableName(variableName) {
1577
+ if (this.allowedVariables === null)
1578
+ return;
1579
+ const [variable] = variableName.split(".");
1580
+ const isVariableValid = this.allowedVariables.has(variable);
1581
+ if (!isVariableValid)
1582
+ throw new InvalidVariableError(variableName);
1583
+ }
1584
+ _getVariableReplacement(variableName) {
1585
+ const [variable, ...properties] = variableName.split(".");
1586
+ const context = this.context[variable];
1587
+ const replacement = properties.reduce((ctx, prop) => {
1588
+ if (!ctx || typeof ctx !== "object")
1589
+ return null;
1590
+ return ctx[prop];
1591
+ }, context);
1592
+ return replacement ? JSON.stringify(replacement) : null;
1593
+ }
1594
+ };
1595
+ __name(WebhookPayloadTemplate, "WebhookPayloadTemplate");
1596
+ export {
1597
+ CHECK_TYPES,
1598
+ HealthChecker,
1599
+ InvalidJsonError,
1600
+ InvalidVariableError,
1601
+ JsonVariable,
1602
+ ParseJsonlStream,
1603
+ RetryableError,
1604
+ WebhookPayloadTemplate,
1605
+ betterClearInterval,
1606
+ betterSetInterval,
1607
+ buildOrVersionNumberIntToStr,
1608
+ checkParamPrototypeOrThrow,
1609
+ concatStreamToBuffer,
1610
+ configureLogger,
1611
+ cryptoRandomObjectId,
1612
+ dateToString,
1613
+ delayPromise,
1614
+ deterministicUniqueId,
1615
+ escapeForBson,
1616
+ escapePropertyName,
1617
+ escapeRegExp,
1618
+ expressErrorHandler,
1619
+ getOrdinalSuffix,
1620
+ getRandomInt,
1621
+ http404Route,
1622
+ isBadForMongo,
1623
+ isBuffer,
1624
+ isForbiddenUsername,
1625
+ isNullOrUndefined,
1626
+ isUrlRelative,
1627
+ jsonStringifyExtended,
1628
+ leftpad,
1629
+ markedDecreaseHeadsLevel,
1630
+ markedSetNofollowLinks,
1631
+ normalizeUrl,
1632
+ parseDateFromJson,
1633
+ parseUrl,
1634
+ promisifyServerListen,
1635
+ readStreamToString,
1636
+ removeFromArray,
1637
+ retryWithExpBackoff,
1638
+ sequentializePromises,
1639
+ splitFullName,
1640
+ timeoutPromise,
1641
+ traverseObject,
1642
+ truncate,
1643
+ unescapeFromBson,
1644
+ unescapePropertyName,
1645
+ weightedAverage
1646
+ };
1647
+ /*!
1648
+ * This module contains various client-side utility and helper functions.
1649
+ *
1650
+ * Author: Jan Curn (jan@apify.com)
1651
+ * Copyright(c) 2016 Apify. All rights reserved.
1652
+ *
1653
+ */
1654
+ /*!
1655
+ * This module contains various server utility and helper functions.
1656
+ * Note that it automatically exports functions from utilities.client.js
1657
+ *
1658
+ * Author: Jan Curn (jan@apify.com)
1659
+ * Copyright(c) 2015 Apify. All rights reserved.
1660
+ *
1661
+ */
1662
+ //# sourceMappingURL=index.mjs.map