Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 | 1790x 29x 12x 3x 6x 6x 90x 1558x 1558x 194x 149x 154x 27x 3x 222x 10x 17x 10x 10x 7x 14x 14x 19x 14x 220x 4x 4x 3x 1209x 1209x 1x 89x 154x 7x 3x 21x 18x 3x 14x 10x 8x 8x 16x 16x 10x 10x 1x 15x 15x 13x 16x 20x 20x 20x 20x 20x 20x 20x 20x 20x 15x 6x 9x 9x 16x 19x 19x 20x 19x 7x 7x 7x 2x 5x 83x 5x 316x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 61x 9x 9x 9x 20x 20x 9x 38x 207x 207x 68x 139x 11x 1x 1x 3x 3x 3x 3x 9x 18x 9x 27x 27x 9x 7x 7x 5x 1x 59x 18x 41x 41x 17x 17x 17x 41x 7x 7x 7x 7x 31x 4x 4x 9x 9x 22x 22x 22x 22x 1x 21x 21x 48x 41x 36x 35x 21x 10x 533x 270x 270x 270x 269x 254x 270x 25x 160x 62x 4x 4x 11x 8x 1x 5x 3x 7x 2x 12x 1x 1x 1x 4x 2x 2x 1x 31x | // @wc-ignore-file
import { Capacitor } from '@capacitor/core';
import fetchProgress from 'fetch-progress';
import JSONC from 'tiny-jsonc';
import YAML from 'yaml';
export function mapValues<K extends string, VIn, VOut>(
subject: Record<K, VIn>,
mapper: (value: VIn) => VOut
): Record<K, VOut> {
// @ts-expect-error can't preserve types through Object.(from)Entries
return Object.fromEntries(Object.entries(subject).map(([key, value]) => [key, mapper(value)]));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('mapValues', () => {
expect(mapValues({ a: 1, b: 2 }, (v) => v + 1)).toEqual({ a: 2, b: 3 });
expect(mapValues({ a: 1, b: 2 }, (v) => v.toString())).toEqual({ a: '1', b: '2' });
});
}
export function mapKeys<KIn extends string, KOut extends string, V>(
subject: Record<KIn, V>,
mapper: (key: KIn, value: V) => KOut
): Record<KOut, V> {
// @ts-expect-error can't preserve types through Object.(from)Entries
return Object.fromEntries(
Object.entries(subject).map(([key, value]) => [mapper(key as KIn, value as V), value])
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('mapKeys', () => {
expect(mapKeys({ a: 1, b: 2 }, (k) => k.toUpperCase())).toEqual({ A: 1, B: 2 });
expect(mapKeys({ a: 1, b: 2 }, (k) => k + k)).toEqual({ aa: 1, bb: 2 });
});
}
/**
* Maps values of an object, and filters out entries with nullable values from the result
*/
export function mapValuesNoNullables<K extends string, VIn, VOut>(
subject: Record<K, VIn>,
mapper: (value: VIn) => VOut
): Record<K, NonNullable<VOut>> {
return Object.fromEntries(
Object.entries(subject)
.map(([key, value]) => [key, mapper(value as VIn)])
.filter(([, value]) => value !== null && value !== undefined)
) as Record<K, NonNullable<VOut>>;
}
/**
* Maps values and keys of an object, and filters out entries with nullable values from the result
*/
export function transformObject<KIn extends string, KOut extends string, VIn, VOut>(
subject: Record<KIn, VIn>,
mapper: (key: KIn, value: VIn) => [KOut, VOut] | undefined
): Record<KOut, VOut> {
return fromEntries(
entries(subject)
.map(([key, value]) => mapper(key, value))
.filter((entry): entry is [KOut, VOut] => entry !== undefined)
);
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('mapValuesNoNullables', () => {
test('without any nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: 2 }, (v) => v + 1)).toEqual({ a: 2, b: 3 });
});
test('with nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: null }, (v) => (v ? v + 1 : v))).toEqual({
a: 2,
});
});
test('with only nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: 2 }, (v) => (v % 2 ? null : undefined))).toEqual(
{}
);
});
});
}
export function keys<K extends string>(subject: Record<K, unknown>): K[] {
// @ts-expect-error can't preserve types through Object.keys
return Object.keys(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('keys', () => {
expect(keys({ a: 1, b: 2 })).toEqual(['a', 'b']);
expect(keys({})).toEqual([]);
});
}
export function fromEntries<K extends string, V>(
subject: Array<[K, V] | readonly [K, V]>
): Record<K, V> {
// @ts-expect-error can't preserve types through Object.fromEntries
return Object.fromEntries(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('fromEntries', () => {
expect(
fromEntries([
['a', 1],
['b', 2],
])
).toEqual({ a: 1, b: 2 });
expect(fromEntries([])).toEqual({});
});
}
export function entries<K extends string, V>(subject: Record<K, V>): Array<[K, V]> {
// @ts-expect-error can't preserve types though Object.entries
return Object.entries(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('entries', () => {
expect(entries({ a: 1, b: 2 })).toEqual([
['a', 1],
['b', 2],
]);
expect(entries({})).toEqual([]);
});
}
export function mapEntries<KIn extends string, VIn, KOut extends string, VOut>(
subject: Record<KIn, VIn>,
mapper: (key: KIn, value: VIn) => [KOut, VOut]
): Record<KOut, VOut> {
return fromEntries(entries(subject).map(([key, value]) => mapper(key, value)));
}
export function invertRecord<K extends string, V extends string>(
subject: Record<K, V>
): Record<V, K> {
return fromEntries(entries(subject).map(([key, value]) => [value, key]));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('invertRecord', () => {
expect(invertRecord({ a: '1', b: '2', c: 'd' })).toEqual({ 1: 'a', 2: 'b', d: 'c' });
expect(invertRecord({})).toEqual({});
});
}
/**
* Checks that a value is included in a list of values
*/
export function oneOf<T extends string>(value: string, values: T[]): value is T {
// @ts-expect-error String#includes:0 is too narrow
return values.includes(value);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('oneOf', () => {
expect(oneOf('a', ['a', 'b', 'c'])).toBe(true);
expect(oneOf('d', ['a', 'b', 'c'])).toBe(false);
});
}
export function hasOnce<T extends string, U extends T>(value: U, values: T[]): boolean {
return values.filter((v) => v === value).length === 1;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('hasOnce', () => {
expect(hasOnce('a', ['a', 'b', 'c'])).toBe(true);
// @ts-expect-error this is expected, we're testing for failure
expect(hasOnce('d', ['a', 'b', 'c'])).toBe(false);
expect(hasOnce('a', ['a', 'b', 'c', 'a'])).toBe(false);
});
}
export function xor(...args: unknown[]): boolean {
if (args.length === 0) return false;
const [first, ...rest] = args;
return xor(...rest) !== Boolean(first);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('xor', () => {
expect(xor()).toBe(false);
expect(xor(true)).toBe(true);
expect(xor(false)).toBe(false);
expect(xor(true, false)).toBe(true);
expect(xor(false, true)).toBe(true);
expect(xor(true, true)).toBe(false);
expect(xor(false, false)).toBe(false);
});
}
export function or(...args: unknown[]): boolean {
return args.some(Boolean);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('or', () => {
expect(or()).toBe(false);
expect(or(true)).toBe(true);
expect(or(false)).toBe(false);
expect(or(true, false)).toBe(true);
expect(or(false, true)).toBe(true);
expect(or(true, true)).toBe(true);
expect(or(false, false)).toBe(false);
});
}
/**
* Pick only some keys from an object
*/
export function pick<Obj, KeysOut extends string & keyof Obj>(
subject: Obj,
...keys: KeysOut[]
): Pick<Obj, KeysOut> {
const result = {} as Pick<Obj, KeysOut>;
for (const key of keys) {
result[key] = subject[key];
}
return result;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('pick', () => {
expect(pick({ a: 1, b: 2 }, 'a')).toEqual({ a: 1 });
expect(pick({ a: 1, b: 2 }, 'b')).toEqual({ b: 2 });
expect(pick({ a: 1, b: 2 }, 'a', 'b')).toEqual({ a: 1, b: 2 });
// @ts-expect-error this is expected, we're testing for an edge case
expect(pick({ a: 1, b: 2 }, 'c')).toEqual({});
class Test {
id: number = 0;
name: string = '';
}
const testZero = new Test();
const testOne = new Test();
testOne.id = 1;
expect(pick(testZero, 'id')).toEqual({ id: 0 });
expect(pick(testOne, 'id')).toEqual({ id: 1 });
expect(pick(testOne, 'name')).toEqual({ name: '' });
});
}
/**
* Omit some keys from an object
*/
export function omit<KeysIn extends string, KeysOut extends KeysIn, V>(
subject: Record<KeysIn, V>,
...keys: KeysOut[]
): Record<Exclude<KeysIn, KeysOut>, V> {
return fromEntries(entries(subject).filter(([key]) => !oneOf(key, keys))) as Record<
Exclude<KeysIn, KeysOut>,
V
>;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('omit', () => {
expect(omit({ a: 1, b: 2 }, 'a')).toEqual({ b: 2 });
expect(omit({ a: 1, b: 2 }, 'b')).toEqual({ a: 1 });
expect(omit({ a: 1, b: 2 }, 'a', 'b')).toEqual({});
// @ts-expect-error this is expected, we're testing for an edge case
expect(omit({ a: 1, b: 2 }, 'c')).toEqual({ a: 1, b: 2 });
});
}
export function safeJSONParse(str: unknown): unknown {
try {
return JSON.parse(str?.toString() ?? '');
} catch {
return undefined;
}
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('safeJSONParse', () => {
expect(safeJSONParse('{"a":1}')).toEqual({ a: 1 });
expect(safeJSONParse('{"a":1')).toBeUndefined();
expect(safeJSONParse(null)).toBeUndefined();
expect(safeJSONParse(undefined)).toBeUndefined();
});
}
export function safeJSONStringify(value: unknown): string | undefined {
try {
return JSON.stringify(value);
} catch {
return undefined;
}
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('safeJSONStringify', () => {
expect(safeJSONStringify({ a: 1 })).toEqual('{"a":1}');
expect(safeJSONStringify(undefined)).toBeUndefined();
expect(safeJSONStringify(null)).toBe('null');
expect(safeJSONStringify(Symbol('feur'))).toBeUndefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const a: any = { b: 2 };
a.a = a;
expect(safeJSONStringify(a)).toBeUndefined();
});
}
/**
* See https://github.com/microsoft/TypeScript/issues/19954
*/
export function sign(value: number) {
return Math.sign(value) as -1 | 0 | 1;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sign', () => {
expect(sign(1)).toBe(1);
expect(sign(-1)).toBe(-1);
expect(sign(0)).toBe(0);
expect(sign(-0)).toBe(-0);
expect(sign(NaN)).toBeNaN();
expect(sign(6732)).toBe(1);
expect(sign(-667)).toBe(-1);
expect(sign(Infinity)).toBe(1);
expect(sign(-Infinity)).toBe(-1);
});
}
export function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('clamp', () => {
expect(clamp(1, 0, 2)).toBe(1);
expect(clamp(-1, 0, 2)).toBe(0);
expect(clamp(3, 0, 2)).toBe(2);
expect(clamp(0, 0, 2)).toBe(0);
expect(clamp(-67, -5, 2)).toBe(-5);
});
}
type ToIterables<T extends unknown[]> = { [K in keyof T]: Iterable<T[K]> };
export function* zip<T extends unknown[]>(...arrays: ToIterables<T>): Generator<T> {
const iterators = arrays.map((i) => i[Symbol.iterator]());
while (true) {
const results = iterators.map((i) => i.next());
if (results.some(({ done }) => done)) {
break;
}
yield results.map(({ value }) => value) as T;
}
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('zip', () => {
test('works with 2 iterators', () => {
expect([...zip([1, 2], ['a', 'b'])]).toEqual([
[1, 'a'],
[2, 'b'],
]);
});
test('works with 3 iterators', () => {
expect([...zip([1, 2], ['a', 'b'], [true, false])]).toEqual([
[1, 'a', true],
[2, 'b', false],
]);
});
test('works with asymmetrically-sized iterators', () => {
expect([...zip([1, 2, 3], [[], []])]).toEqual([
[1, []],
[2, []],
]);
});
});
}
export function unique<T>(
array: T[],
key: (item: T) => string | number = (x) => x as string | number
): T[] {
const seen = new Set();
return array.filter((item) => {
const k = key(item);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('unique', () => {
expect(unique([1, 2, 3, 1, 2])).toEqual([1, 2, 3]);
expect(unique(['a', 'b', 'c', 'a', 'b'])).toEqual(['a', 'b', 'c']);
expect(unique([])).toEqual([]);
expect(unique([{ id: 1 }, { id: 2 }, { id: 1 }], (o) => o.id)).toEqual([
{ id: 1 },
{ id: 2 },
]);
expect(unique([{ id: 1 }, { id: 2 }, { id: 1 }], (o) => o.id.toString())).toEqual([
{ id: 1 },
{ id: 2 },
]);
});
}
export function uint8ArrayToArrayBuffer(uint8Array: Uint8Array): ArrayBuffer {
// @ts-expect-error TODO fix this one
return uint8Array.buffer.slice(
uint8Array.byteOffset,
uint8Array.byteOffset + uint8Array.byteLength
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('uint8ArrayToArrayBuffer', () => {
const uint8Array = new Uint8Array([1, 2, 3]);
const arrayBuffer = uint8ArrayToArrayBuffer(uint8Array);
expect(arrayBuffer).toBeInstanceOf(ArrayBuffer);
expect(new Uint8Array(arrayBuffer)).toEqual(uint8Array);
});
}
/**
* extension is all the last dotted parts: thing.tar.gz is [thing, tar.gz]
*/
export function splitFilenameOnExtension(filename: string): [string, string] {
const match = filename.match(/^([^.]+)\.(.+)$/);
if (!match) return [filename, ''];
return [match[1], match[2]];
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('splitFilenameOnExtension', () => {
expect(splitFilenameOnExtension('file.txt')).toEqual(['file', 'txt']);
expect(splitFilenameOnExtension('file')).toEqual(['file', '']);
expect(splitFilenameOnExtension('file.tar.gz')).toEqual(['file', 'tar.gz']);
});
}
export type Comparator<T> = (a: T, b: T) => number;
export function compareBy<Item>(
...keys: (((item: Item) => string | number | undefined) | (string & keyof Item))[]
): Comparator<Item> {
const _compareWith = (key: (typeof keys)[number], a: Item, b: Item): number => {
const aKey = typeof key === 'string' ? (a as Record<string, unknown>)[key] : key(a);
const bKey = typeof key === 'string' ? (b as Record<string, unknown>)[key] : key(b);
Iif (aKey === undefined && bKey === undefined) return 0;
Iif (aKey === undefined) return -1;
Iif (bKey === undefined) return 1;
Iif (aKey === null && bKey === null) return 0;
Iif (aKey === null) return -1;
Iif (bKey === null) return 1;
if (aKey === bKey) return 0;
if (typeof aKey === 'string' && typeof bKey === 'string') {
return aKey.localeCompare(bKey);
}
Eif (typeof aKey === 'number' && typeof bKey === 'number') {
return aKey - bKey;
}
return aKey.toString().localeCompare(bKey.toString());
};
return (a, b) => {
let comparison = 0;
for (let i = 0; i < keys.length && comparison === 0; i++) {
comparison = _compareWith(keys[i], a, b);
}
return comparison;
};
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('compareBy', () => {
test('.sort works', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' },
];
expect([...items].sort(compareBy((i) => i.id))).toEqual([
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
]);
expect([...items].sort(compareBy((i) => i.name))).toEqual([
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
]);
});
test('it works', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' },
];
expect(compareBy<(typeof items)[number]>((i) => i.id)(items[0], items[1])).toBe(1);
expect(compareBy<(typeof items)[number]>((i) => i.id)(items[1], items[0])).toBe(-1);
expect(compareBy<(typeof items)[number]>((i) => i.id)(items[0], items[0])).toBe(0);
expect(compareBy<(typeof items)[number]>((i) => i.name)(items[0], items[1])).toBe(1);
expect(compareBy<(typeof items)[number]>((i) => i.name)(items[1], items[0])).toBe(-1);
expect(compareBy<(typeof items)[number]>((i) => i.name)(items[0], items[0])).toBe(0);
});
test('it works with key strings', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' },
];
expect(compareBy<(typeof items)[number]>('id')(items[0], items[1])).toBe(1);
expect(compareBy<(typeof items)[number]>('name')(items[1], items[0])).toBe(-1);
expect(compareBy<(typeof items)[number]>('id')(items[0], items[0])).toBe(0);
});
test('it works with multiple keys', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' },
];
expect(compareBy<(typeof items)[number]>('id', 'name')(items[0], items[1])).toBe(1);
expect(compareBy<(typeof items)[number]>('id', 'name')(items[1], items[0])).toBe(-1);
expect(compareBy<(typeof items)[number]>('id', 'name')(items[0], items[0])).toBe(0);
});
});
}
/**
* Returns a new comparator that takes into account a given sorting direction. Input comparator is assumed to be sorting in asc order.
*/
export function applySortDirection<T>(
direction: 'asc' | 'desc',
comparator: Comparator<T>
): Comparator<T> {
const mul = direction === 'asc' ? 1 : -1;
return (a, b) => mul * comparator(a, b);
}
/**
* Add a v= query parameter to the URL to force the browser to reload the resource, using Date.now() as the value
*/
export function cachebust(url: string): string;
export function cachebust(url: URL): URL;
export function cachebust(url: string | URL): string | URL {
const parsedUrl = new URL(url);
parsedUrl.searchParams.set('v', Date.now().toString());
if (typeof url === 'string') {
return parsedUrl.toString();
}
return parsedUrl;
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('cachebust', () => {
test('without any query params', () => {
const url = 'https://example.com/resource';
const cachebustedUrl = cachebust(url);
expect(URL.canParse(cachebustedUrl)).toBeTruthy();
expect([...new URL(cachebustedUrl).searchParams.entries()]).toEqual([
['v', expect.stringMatching(/^\d+$/)],
]);
});
test('with existing query params', () => {
const url = 'https://example.com/resource?param=value';
const cachebustedUrl = cachebust(url);
expect(URL.canParse(cachebustedUrl)).toBeTruthy();
expect(new URL(cachebustedUrl).searchParams.get('param')).toBe('value');
expect(new URL(cachebustedUrl).searchParams.get('v')).toMatch(/^\d+$/);
});
test('with a parsed URL', () => {
const url = new URL('https://example.com/resource?param=value');
const cachebustedUrl = cachebust(url);
expect(cachebustedUrl).toBeInstanceOf(URL);
expect(cachebustedUrl.searchParams.get('param')).toBe('value');
expect(cachebustedUrl.searchParams.get('v')).toMatch(/^\d+$/);
});
});
}
/**
* Semi-open range [start=0, end)
*/
export function range(startOrEnd: number, end?: number): number[] {
if (end === undefined) {
return Array.from({ length: startOrEnd }, (_, i) => i);
}
return Array.from({ length: end - startOrEnd }, (_, i) => i + startOrEnd);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('range', () => {
expect(range(5)).toEqual([0, 1, 2, 3, 4]);
expect(range(2, 5)).toEqual([2, 3, 4]);
expect(range(5, 2)).toEqual([]);
expect(range(3, 3)).toEqual([]);
expect(range(3, 4)).toEqual([3]);
});
}
export async function fetchHttpRequest(
request:
| string
| {
url: string;
method?: string;
headers?: Record<string, string>;
body?: string;
signal?: AbortSignal;
},
{
cacheAs = '' as '' | 'model',
onProgress,
signal,
headers = {},
cachebust: enableCachebusting = false,
}: {
cacheAs?: '' | 'model';
onProgress?: NonNullable<Parameters<typeof fetchProgress>[0]>['onProgress'];
signal?: AbortSignal;
headers?: Record<string, string>;
cachebust?: boolean;
} = {}
): Promise<Response> {
let url = new URL(typeof request === 'string' ? request : request.url);
if (enableCachebusting) url = cachebust(url);
const options: RequestInit = typeof request === 'string' ? { headers: {} } : request;
Iif (cacheAs) {
url.searchParams.set('x-cigale-cache-as', cacheAs);
}
Iif (signal) {
options.signal = signal;
}
Eif (headers) {
options.headers = { ...headers, ...(options.headers as Record<string, string>) };
}
Iif (onProgress) return fetch(url, options).then(fetchProgress({ onProgress }));
return fetch(url, options);
}
/**
* Parse a given Response into a JS value, assuming the response is either:
* - JSONC (if the url pathname ends with .json)
* - YAML (otherwise)
*/
export async function parseYAMLorJSON(response: Response): Promise<unknown> {
Eif (new URL(response.url).pathname.endsWith('.json')) {
return JSONC.parse(await response.text());
}
return YAML.parse(await response.text());
}
export function sum(values: Iterable<number>): number {
return [...values].reduce((acc, cur) => acc + cur, 0);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sum', () => {
expect(sum([1, 2, 3])).toBe(6);
expect(sum([])).toBe(0);
expect(sum([-1, 1])).toBe(0);
});
}
export function avg(values: Iterable<number>, fallback: number = NaN): number {
let summed = 0;
let length = 0;
for (const value of values) {
summed += value;
length++;
}
return length === 0 ? fallback : summed / length;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('avg', () => {
expect(avg([1, 2, 3])).toBe(2);
expect(avg([1, 1, 1])).toBe(1);
expect(avg([1, 3])).toBe(2);
});
}
export function nonnull<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('nonnull', () => {
expect(nonnull(1)).toBe(true);
expect(nonnull(0)).toBe(true);
expect(nonnull('a')).toBe(true);
expect(nonnull('')).toBe(true);
expect(nonnull(true)).toBe(true);
expect(nonnull(false)).toBe(true);
expect(nonnull({})).toBe(true);
expect(nonnull([])).toBe(true);
expect(nonnull(null)).toBe(false);
expect(nonnull(undefined)).toBe(false);
});
}
export function round(value: number, decimals: number = 0): number {
const factor = Math.pow(10, Math.abs(decimals));
if (decimals < 0) {
return Math.round(value / factor) * factor;
}
return Math.round(value * factor) / factor;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('round', () => {
expect(round(1.2345)).toBe(1);
expect(round(1.5)).toBe(2);
expect(round(1.4, 1)).toBe(1.4);
expect(round(1.2345, 2)).toBe(1.23);
expect(round(1.2355, 2)).toBe(1.24);
expect(round(-1.2355, 2)).toBe(-1.24);
expect(round(-1.2345, 2)).toBe(-1.23);
expect(round(1.23456789, 5)).toBe(1.23457);
expect(round(1.23456789, 8)).toBe(1.23456789);
expect(round(1.23456789, 10)).toBe(1.23456789);
expect(round(12345, -1)).toBe(12350);
expect(round(12345, -2)).toBe(12300);
expect(round(12555, -2)).toBe(12600);
expect(round(-12555, -2)).toBe(-12600);
expect(round(-12345, -2)).toBe(-12300);
});
}
export function insideBoundingClientRect(
{ offsetX, offsetY }: { offsetX: number; offsetY: number },
rect: DOMRect,
leeway: number = 0
): boolean {
return (
offsetX >= -leeway &&
offsetX <= rect.width + leeway &&
offsetY >= -leeway &&
offsetY <= rect.height + leeway
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('insideBoundingClientRect', () => {
const rect = new DOMRect(0, 0, 100, 100);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 50 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 0, offsetY: 0 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 100, offsetY: 100 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: -1, offsetY: 50 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: -1 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 101, offsetY: 50 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 101 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: -1, offsetY: 50 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: -1 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 101, offsetY: 50 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 101 }, rect, 2)).toBe(true);
});
}
export function isZip(
contentType: string
): contentType is 'application/zip' | 'application/x-zip-compressed' | 'application/x-zip' {
return (
contentType === 'application/zip' ||
contentType === 'application/x-zip-compressed' ||
contentType === 'application/x-zip'
);
}
export function logexpr<T>(tag: string, expr: T): T {
// oxlint-disable-next-line no-console
console.log(`{${tag}}`, expr);
return expr;
}
/**
* Outputs a [0, 1] progress value based on the progress of several weighted ordered parts.
*/
export function progressSplitter<PartName extends string>(
...layout: (PartName | number)[]
): (part: PartName, progress: number) => number {
const parts: Array<[PartName, number]> = [];
for (let i = 0; i < layout.length; i += 2) {
const name = layout[i] as PartName;
const weight = (layout[i + 1] ?? 1 - sum(parts.map(([, w]) => w))) as number;
parts.push([name, weight]);
}
return (part, progress) => {
let total = 0;
const partIndex = parts.findIndex(([name]) => name === part);
for (const [i, [, weight]] of parts.entries()) {
if (i < partIndex) total += weight;
if (i === partIndex) total += weight * progress;
}
return total;
};
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('progressSplitter', () => {
const splitProgress = progressSplitter('download', 0.7, 'decompression', 0.2, 'parsing');
const expectations = [
['download', 0, 0],
['download', 0.5, 0.35],
['download', 1, 0.7],
['decompression', 0, 0.7],
['decompression', 0.5, 0.8],
['decompression', 1, 0.9],
['parsing', 0, 0.9],
['parsing', 0.5, 0.95],
['parsing', 1, 1],
] as const;
for (const [phase, input, expected] of expectations) {
expect
.soft(splitProgress(phase, input), `with (${phase}, ${input})`)
.toBeCloseTo(expected, 15);
}
});
}
/**
* Replaces accents and punctuations with dashes, lowercases, and replaces accents with ASCII equivalents.
*/
export function slugify(text: string): string {
const result = text
.normalize(/* @wc-ignore */ 'NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '')
.toLowerCase();
if (!result) throw new Error(`Cannot slugify "${text}" (result is empty)`);
return result;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('slugify', () => {
expect(slugify('Hello World!')).toBe('hello-world');
expect(slugify(' Leading and trailing spaces ')).toBe('leading-and-trailing-spaces');
expect(slugify('Multiple spaces')).toBe('multiple-spaces');
expect(slugify('Special #$&* Characters')).toBe('special-characters');
expect(slugify('Accented éàüö Characters')).toBe('accented-eauo-characters');
expect(() => slugify('')).toThrow();
expect(() => slugify('你好')).toThrow();
});
}
/**
* Throws an error with the given message.
* Useful to throw inside expressions.
* Example: `const value = possiblyNull ?? throws('value is null')`
*/
export function throws(message: string): never {
throw new Error(message);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('throws', () => {
expect(() => throws('test error')).toThrow('test error');
});
}
export function groupBy<T, K, V = T>(
array: Iterable<T>,
key: (item: T) => K,
valueMapper?: (item: T) => V
): Map<K, V[]> {
if ('groupBy' in Map && !valueMapper) {
// @ts-expect-error types can't be preserved through Map.groupBy
return Map.groupBy(array, key);
}
const map = new Map<K, V[]>();
for (const item of array) {
const k = key(item);
if (!map.has(k)) map.set(k, []);
map.get(k)!.push(valueMapper ? valueMapper(item) : (item as unknown as V));
}
return map;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('groupBy', () => {
expect(groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? 'even' : 'odd'))).toEqual(
new Map([
['odd', [1, 3, 5]],
['even', [2, 4]],
])
);
expect(
groupBy(
[
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' },
],
(user) => (user.id % 2 === 0 ? 'even' : 'odd'),
(user) => user.name
)
).toEqual(
new Map([
['odd', ['Alice', 'Charlie']],
['even', ['Bob', 'David']],
])
);
});
}
/**
* Returns a LAB color-mix placing the value on the color scale made from the given color stops
*/
export function gradientedColor(value: number, ...stops: string[]): string {
if (value >= 1) return `var(--${stops.at(-1)})`;
if (value <= 0) return `var(--${stops[0]})`;
const scale = stops.length - 1;
const stop = Math.floor(value * scale);
return `color-mix(
in lab,
var(--${stops[stop + 1]})
${round((value * scale - stop) * 100, 2)}%,
var(--${stops[stop]})
)`
.replaceAll('\n', '')
.replaceAll(/\s+/g, ' ')
.replaceAll('( ', '(')
.replaceAll(' )', ')');
}
/**
* Fades out an element matching the given selector over the given duration, then removes it from the DOM.
*/
export function fadeOutElement(
selector: string,
duration: number,
{ firstTimeDuration }: { firstTimeDuration?: number } = {}
): void {
const firstStart = !localStorage.getItem('app_started_before');
localStorage.setItem('app_started_before', 'true');
if (firstStart) duration = firstTimeDuration ?? duration;
const element = document.querySelector(selector);
if (!(element instanceof HTMLElement)) {
element?.remove();
return;
}
element.style.transition = `opacity ${duration}ms linear`;
element.style.opacity = '0';
setTimeout(() => {
element.remove();
}, duration);
}
/**
* @param color Hex of background color string, e.g. #RRGGBB
*/
export function readableOn(color: string): '#000000' | '#ffffff' {
const rgb = color.replace(/^#/, '').match(/.{2}/g);
Iif (rgb === null) throw new Error('Invalid color, use hex notation');
const o = Math.round(
(parseInt(rgb[0], 16) * 299 + parseInt(rgb[1], 16) * 587 + parseInt(rgb[2], 16) * 114) /
1000
);
return o > 125 ? '#000000' : '#ffffff';
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('readableOn', () => {
expect(readableOn('#ffffff')).toBe('#000000');
expect(readableOn('#000000')).toBe('#ffffff');
expect(readableOn('#ff0000')).toBe('#ffffff');
expect(readableOn('#00ff00')).toBe('#000000');
expect(readableOn('#0000ff')).toBe('#ffffff');
expect(readableOn('#808080')).toBe('#000000');
expect(readableOn('#c0ffee')).toBe('#000000');
});
}
export function throwError(message: string): never {
throw new Error(message);
}
/**
* Await to await the given promise, but throw if the given AbortSignal is aborted before the promise resolves
*/
export async function unlessAborted<T>(
signal: AbortSignal | undefined,
promise: Promise<T>
): Promise<T> {
return Promise.race([
promise,
new Promise<T>((_, reject) => {
signal?.addEventListener('abort', () => {
reject(signal.reason);
});
}),
]);
}
export const LOREM_IPSUM = `Lorem ipsum dolor sit amet. A impedit beatae sed nostrum voluptatem
ut omnis aliquid et galisum quaerat. Est sunt voluptatem aut porro iste et tempora voluptatem
aut pariatur minima sed omnis cumque est iusto fugit vel rerum magni. 33 ducimus nesciunt ut
consequuntur esse nam necessitatibus tempore sit suscipit voluptatibus qui rerum earum non autem
doloribus. Rem itaque esse est nostrum optio id repellat recusandae et ipsa quis.
Aut odio ipsa sed autem esse ut autem error qui voluptates perspiciatis aut officiis consequuntur
sit amet nihil. Eos delectus consequatur sit natus iure qui omnis omnis ea illum distinctio et
quos quidem. Et nisi autem est rerum eius ut dolorum commodi et temporibus expedita ea dolorem
error ad asperiores facilis ad numquam libero. Aut suscipit maxime sit explicabo dolorem est
accusantium enim et repudiandae omnis cum dolorem nemo id quia facilis.
Et dolorem perferendis et rerum suscipit qui voluptatibus quia et nihil nostrum 33 omnis soluta.
Nam minus minima et perspiciatis velit et eveniet rerum et nihil voluptates aut eaque ipsa et
ratione facere!`;
export function isAbortError(error: unknown): error is DOMException {
return error instanceof DOMException && error.name === 'AbortError';
}
/**
* [] if predicate is falsy, [obj] if predicate is truthy.
* Spread into an array literal to conditionally add something to it.
*/
export function orEmpty<T>(predicate: boolean | undefined | null, obj: T): [T] | [] {
return predicate ? [obj] : [];
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('orEmpty', () => {
expect(orEmpty(true, 1)).toEqual([1]);
expect(orEmpty(false, 1)).toEqual([]);
expect(orEmpty(undefined, 1)).toEqual([]);
expect(orEmpty(null, 1)).toEqual([]);
});
}
/**
* [] if predicate is falsy, [obj(subject)] if predicate is truthy.
* Spread into an array literal to conditionally add something to it.
*/
export function orEmpty2<T, O>(subject: T, obj: (subject: NonNullable<T>) => O): [O] | [] {
if (subject === null || subject === undefined) return [];
return [obj(subject as NonNullable<T>)];
}
/**
* {} if predicate is falsy, obj if predicate is truthy.
* Spread into an object literal to conditionally add something to it.
*/
export function orEmptyObj<T>(predicate: boolean | undefined | null, obj: T): T | object {
return predicate ? obj : {};
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('orEmptyObj', () => {
expect(orEmptyObj(true, { a: 1 })).toEqual({ a: 1 });
expect(orEmptyObj(false, { a: 1 })).toEqual({});
expect(orEmptyObj(undefined, { a: 1 })).toEqual({});
expect(orEmptyObj(null, { a: 1 })).toEqual({});
});
}
/* eslint-disable @typescript-eslint/no-explicit-any */
export function orEmptyObj2<K extends string, T, O>(
key: K,
subject: T,
obj: (subject: NonNullable<T>) => O
): T extends null | undefined ? object : { [key in K]: O } {
Iif (subject === null) return {} as any;
Eif (subject === undefined) return {} as any;
return { [key]: obj(subject as NonNullable<T>) } as any;
}
export function orEmptyObj3<K extends string, T>(obj: { [key in K]: T }): T extends null | undefined
? object
: { [key in K]: T } {
const key = Object.keys(obj)[0] as K | undefined;
Iif (key === undefined) return {} as any;
Iif (obj[key] === null) return {} as any;
Eif (obj[key] === undefined) return {} as any;
return obj as any;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
export type RemovePrefix<Prefix extends string, T> = T extends `${Prefix}${infer P}` ? P : never;
export type WithPrefix<Prefix extends string, T> = Extract<T, `${Prefix}${string}`>;
export type WithoutPrefix<Prefix extends string, T> = Exclude<T, `${Prefix}${string}`>;
/**
* Promisified setTimeout
*/
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sleep', async () => {
const start = Date.now();
await sleep(100);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(99);
});
}
/**
* Syntactically clean filepaths.
*/
export function cleanFilepath(filepath: string): string {
const segments: string[] = [];
for (const segment of filepath.replaceAll('\\', '/').split('/')) {
if (segment === '') continue;
if (segment === '.') continue;
if (segment === '..' && segments.length > 0) segments.pop();
else segments.push(segment);
}
return segments.join('/');
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('cleanFilepath', () => {
expect(cleanFilepath('foo/bar/baz')).toBe('foo/bar/baz');
expect(cleanFilepath('foo//bar///baz')).toBe('foo/bar/baz');
expect(cleanFilepath('/foo/bar/baz/')).toBe('foo/bar/baz');
expect(cleanFilepath('./foo/./bar/./baz/.')).toBe('foo/bar/baz');
expect(cleanFilepath('foo/../bar/baz')).toBe('bar/baz');
expect(cleanFilepath('../foo/bar/baz')).toBe('../foo/bar/baz');
expect(cleanFilepath('..')).toBe('..');
expect(cleanFilepath('.')).toBe('');
expect(cleanFilepath('/')).toBe('');
expect(cleanFilepath('C:\\foo\\bar\\baz')).toBe('C:/foo/bar/baz');
});
}
export function prefixIDBKeyRange(prefix: string): IDBKeyRange {
return IDBKeyRange.bound(prefix, prefix + '\uffff');
}
export function ensureArray<T>(subject: T | T[]): T[] {
return Array.isArray(subject) ? subject : [subject];
}
if (import.meta.vitest) {
const { test, expect } = await import('vitest');
test('ensureArray', () => {
expect(ensureArray(1)).toEqual([1]);
expect(ensureArray([1])).toEqual([1]);
expect(ensureArray([[3]])).toEqual([[3]]);
});
}
type ProfilerData = Record<string, string | number | boolean>;
export function profiler(group: string) {
async function profile<T>(
track: string,
label: string,
dataOrFn: ProfilerData | (() => Promise<T> | T),
fnIfHasData?: () => Promise<T> | T
): Promise<T> {
const fn = fnIfHasData ?? (dataOrFn as () => Promise<T> | T);
const start = performance.now();
const result = await fn();
performance.measure(label, {
start,
detail: {
devtools: {
dataType: 'track-entry',
track,
trackGroup: group,
properties:
typeof dataOrFn === 'function'
? undefined
: Object.entries(dataOrFn).map(([key, value]) => [
key,
value.toString(),
]),
},
},
});
return result;
}
return profile;
}
export function displayKeyRange(keyRange: string | IDBKeyRange | undefined): string {
if (!keyRange) return 'none';
Eif (typeof keyRange === 'string') return `{${keyRange}}`;
let lowerBound: string;
let upperBound: string;
if (keyRange.lower === undefined) {
lowerBound = '(-∞';
} else if (keyRange.lowerOpen) {
lowerBound = `(${keyRange.lower}`;
} else {
lowerBound = `[${keyRange.lower}`;
}
if (keyRange.upper === undefined) {
upperBound = '∞)';
} else if (keyRange.upperOpen) {
upperBound = `${keyRange.upper})`;
} else {
upperBound = `${keyRange.upper}]`;
}
return `${lowerBound}, ${upperBound}`;
}
export function switchValue<const T extends Record<string | number, unknown>, V extends keyof T>(
value: V,
cases: Partial<T>,
fallback?: T[V]
): T[V] {
return (cases[value] ?? fallback) as T[V];
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('switchValue', () => {
expect(switchValue('a', { a: 1, b: 2 })).toBe(1);
expect(switchValue('b', { a: 1, b: 2 })).toBe(2);
// @ts-expect-error this is expected, we're testing for an edge case
expect(switchValue('c', { a: 1, b: 2 }, 3)).toBe(3);
// @ts-expect-error test that it returns undefined if no fallback is provided
expect(switchValue('c', { a: 1, b: 2 })).toBeUndefined();
});
}
export function climbDOMUntil(
element: HTMLElement | null,
predicate: (element: HTMLElement) => boolean
): HTMLElement | null {
while (element) {
if (predicate(element)) return element;
element = element.parentElement;
}
return null;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('climbDOMUntil', () => {
document.body.innerHTML = `
<div id="parent">
<div id="child">
<div id="grandchild"></div>
</div>
</div>
`;
const parent = document.getElementById('parent');
const child = document.getElementById('child');
const grandchild = document.getElementById('grandchild');
expect(climbDOMUntil(grandchild, (el) => el.id === 'child')).toBe(child);
expect(climbDOMUntil(grandchild, (el) => el.id === 'parent')).toBe(parent);
expect(climbDOMUntil(grandchild, (el) => el.id === 'grandchild')).toBe(grandchild);
expect(climbDOMUntil(grandchild, (el) => el.id === 'nonexistent')).toBe(null);
});
}
/**
* Turns an async function into a { do: starts the function synchronously, cancel: cancels the function if it's still running } object
*/
export function cancellable<Args extends unknown[], R>(
asyncFunction: (signal: AbortSignal, ...args: Args) => Promise<R>
): (...args: Args) => { do: () => Promise<R>; cancel: () => void } {
let controller = new AbortController();
return (...args: Args) => {
controller.abort();
controller = new AbortController();
return {
do: () => asyncFunction(controller.signal, ...args),
cancel: () => controller.abort(),
};
};
}
export function setsAreEqual<T>(setA: Set<T>, setB: Set<T>): boolean {
if (setA.size !== setB.size) return false;
for (const item of setA) {
if (!setB.has(item)) return false;
}
return true;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('setsAreEqual', () => {
expect(setsAreEqual(new Set([1, 2, 3]), new Set([1, 2, 3]))).toBe(true);
expect(setsAreEqual(new Set([1, 2, 3]), new Set([3, 2, 1]))).toBe(true);
expect(setsAreEqual(new Set([1, 2, 3]), new Set([1, 2]))).toBe(false);
expect(setsAreEqual(new Set([1, 2]), new Set([1, 2, 3]))).toBe(false);
expect(setsAreEqual(new Set([1, 2, 3]), new Set([4, 5, 6]))).toBe(false);
});
}
export function corsfix(url: string | URL): string {
return 'https://cors.gwen.works/' + url.toString().replace(/^https?:\/\//, '');
}
export function corsfixIfLocalhost(src: string): string {
if (location.hostname !== 'localhost') return src;
return corsfix(src);
}
export function splitRecord<K1 extends string, K2 extends string, V>(
record: Record<K1 | K2, V>,
predicate: ((key: K1 | K2) => key is K1) | ((key: K1 | K2) => boolean)
): [Record<K1, V>, Record<K2, V>] {
const record1 = {} as Record<K1, V>;
const record2 = {} as Record<K2, V>;
for (const key of keys(record)) {
if (predicate(key as K1 | K2)) {
(record1 as Record<string, V>)[key] = record[key as K1 | K2];
} else {
(record2 as Record<string, V>)[key] = record[key as K1 | K2];
}
}
return [record1, record2];
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('splitRecord', () => {
const record = { a: 1, b: 2, c: 3, d: 4 };
const [record1, record2] = splitRecord(record, (key) => key === 'a' || key === 'c');
expect(record1).toEqual({ a: 1, c: 3 });
expect(record2).toEqual({ b: 2, d: 4 });
});
}
export const UTF8_BOM = '\xEF\xBB\xBF';
export function platform() {
return Capacitor.getPlatform() as 'web' | 'android' | 'ios';
}
|