@antti5/ship-tool-common 1.1.0 → 1.1.2

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/bin/repos CHANGED
@@ -33,7 +33,7 @@ PWD=`pwd`
33
33
 
34
34
  # List local source files
35
35
 
36
- FILES_INCLUDE='js$\|jsx$\|py$\|css$'
36
+ FILES_INCLUDE='js$\|jsx$\|ts$\|tsx$\|py$\|css$'
37
37
  FILES_EXCLUDE='^build.*/'
38
38
 
39
39
  files=''
package/lib/Semaphore.ts CHANGED
@@ -15,11 +15,10 @@ class Semaphore {
15
15
  #queue: QueueItem[] = [];
16
16
 
17
17
  #rateLimit: number = 0;
18
- #rateLimitInterval: number | null = null;
18
+ #rateLimitInterval: NodeJS.Timeout | null = null;
19
19
 
20
20
  #waiters: Waiter[] = [];
21
21
 
22
-
23
22
  constructor(max = 1, { rateLimit = 0 }: { rateLimit?: number } = {}) {
24
23
  this.#max = max;
25
24
  this.#rateLimit = rateLimit;
@@ -5,7 +5,7 @@ class Util {
5
5
  The executor function given to the Promise constructor simply sets a timeout to call
6
6
  the resolve function. The Promise is never rejected. */
7
7
 
8
- static async sleep(ms) {
8
+ static async sleep(ms: number) {
9
9
  await new Promise(res => setTimeout(res, ms));
10
10
  }
11
11
 
@@ -26,25 +26,34 @@ class Util {
26
26
  is thrown. The error message contains the HTTP status text and code, and the "cause" property
27
27
  contains the Window.fetch() response object. */
28
28
 
29
- static #fetchResponse = {};
29
+ static #fetchResponse: Record<string, { body: unknown, timestamp: number }> = {};
30
30
 
31
- static async fetch (url, {
32
- urlSearchParams,
33
- method = 'GET',
34
- body,
35
- headers = {},
36
- timeout,
37
- debug
38
- } = {}) {
31
+ static async fetch (
32
+ url: string,
33
+ {
34
+ urlSearchParams,
35
+ method = 'GET',
36
+ body,
37
+ headers = {},
38
+ timeout,
39
+ debug
40
+ }: {
41
+ urlSearchParams?: Record<string,string>,
42
+ method?: string,
43
+ body?: unknown,
44
+ headers?: Record<string,string>,
45
+ timeout?: number,
46
+ debug?: boolean
47
+ } = {}
48
+ ) {
39
49
 
40
50
  if (urlSearchParams)
41
- url += '?' + new URLSearchParams(urlSearchParams);
51
+ url += '?' + new URLSearchParams(urlSearchParams).toString();
42
52
 
43
- const cacheMs = Number(
53
+ const cacheMs =
44
54
  typeof process !== 'undefined' ?
45
- process.env?.VITE_FETCH_CACHE_MS : // Vitest
46
- import.meta?.env?.VITE_FETCH_CACHE_MS // Development and production
47
- );
55
+ Number(process.env.VITE_FETCH_CACHE_MS) : // Vitest
56
+ null;
48
57
 
49
58
  if (cacheMs && Util.#fetchResponse[url]?.timestamp + cacheMs > Date.now()) {
50
59
  console.debug('Returning cached response for URL', url);
@@ -76,7 +85,7 @@ class Util {
76
85
 
77
86
  const responseBody =
78
87
  response.headers.get('Content-Type')?.includes('application/json') ?
79
- await response.json() :
88
+ await response.json() as unknown :
80
89
  await response.text(); // If response isn't JSON, return a String instead -- TODO: This may be a poor design
81
90
 
82
91
  if (debug)
@@ -93,44 +102,10 @@ class Util {
93
102
  return responseBody;
94
103
  }
95
104
 
96
- static #getEnvironment() {
97
- return typeof process !== 'undefined' ?
98
- process.env.NODE_ENV.trim() :
99
- import.meta.env.MODE.trim();
100
- }
101
-
102
- static #isProduction() {
103
- return window.location.host.endsWith('shiptool.st');
104
- }
105
-
106
- static envDevelopment() {
107
- return Util.#getEnvironment() === 'development';
108
- }
109
-
110
- static envTest() {
111
- return Util.#getEnvironment() === 'test';
112
- }
113
-
114
- static envDeployed() {
115
- return Util.#getEnvironment() === 'production';
116
- }
117
-
118
- static envDeployedProduction() {
119
- return Util.envDeployed() && Util.#isProduction();
120
- }
121
-
122
- static envDeployedTest() {
123
- return Util.envDeployed() && !Util.#isProduction();
124
- }
125
-
126
- static envExperimental() {
127
- return !Util.envDeployedProduction() && !window.ST_NO_EXPERIMENTAL;
128
- }
129
-
130
105
 
131
106
  /* Generated random numbers and index for the next number */
132
107
 
133
- static #randoms = [];
108
+ static #randoms: number[] = [];
134
109
  static #randomsIndex = 0;
135
110
 
136
111
  /* Get a random number, either from the #randoms array or create and store a new one */
@@ -148,51 +123,9 @@ class Util {
148
123
  }
149
124
 
150
125
 
151
- static perfObject(key) {
152
- window.ST_PERF ??= {};
153
- window.ST_PERF[key] ??= [];
154
- return window.ST_PERF[key];
155
- }
156
-
157
- static perfStart() {
158
- return performance.now();
159
- }
160
-
161
- static perfEndMany(count, startTime, key, { log } = {}) {
162
- const ms = performance.now() - startTime;
163
- const o = Util.perfObject(key);
164
-
165
- for (let i = 0; i < count; i++)
166
- o.push(ms / count);
167
-
168
- if (log) {
169
- console.debug('Performance:', `${count}x`, key, Util.round(ms / count, 2), 'ms');
170
- if (count > 1)
171
- console.debug('Performance: Total:', Util.round(ms, 2), 'ms');
172
- }
173
- }
174
-
175
- static perfEnd(...args) {
176
- return Util.perfEndMany(1, ...args);
177
- }
178
-
179
- static perfReport() {
180
- const result = {};
181
- for (const [key, values] of Object.entries(window.ST_PERF ?? {}))
182
- result[key] = {
183
- count: values.length,
184
- total: values.reduce((sum, ms) => sum + ms).toFixed(2) + ' ms',
185
- avg: (values.reduce((sum, ms) => sum + ms) / values.length).toFixed(2) + ' ms',
186
- min: Math.min(...values).toFixed(2) + ' ms',
187
- max: Math.max(...values).toFixed(2) + ' ms'
188
- };
189
- return result;
190
- }
191
-
192
-
193
126
  /* Returns s converted to an integer, but only if it falls into the acceptable range */
194
127
 
195
- static parseIntRange(s, min, max) {
128
+ static parseIntRange(s: string, min: number, max: number) {
196
129
  if (isNaN(+s))
197
130
  return null;
198
131
  const n = Math.round(+s);
@@ -204,7 +137,7 @@ class Util {
204
137
 
205
138
  /* Round the number to given number of decimals. */
206
139
 
207
- static round(number, decimals = 0) {
140
+ static round(number: number, decimals: number = 0) {
208
141
  const multiplier = Math.pow(10, decimals);
209
142
  return Math.round(number * multiplier) / multiplier;
210
143
  }
@@ -215,7 +148,7 @@ class Util {
215
148
 
216
149
  The integer part is not rounded, however. So (123.45, 4) --> 123.5, but (12345, 4) --> 12345. */
217
150
 
218
- static roundPrecision(number, significantDigits) {
151
+ static roundPrecision(number: number, significantDigits: number) {
219
152
  return Util.round(
220
153
  number,
221
154
  Number(number) === 0 ?
@@ -241,12 +174,20 @@ class Util {
241
174
  "decimals" can also be a two-element array that gives the minimum and maximum number of
242
175
  fraction digits. */
243
176
 
244
- static formatNumber(value, {
245
- locale = 'en',
246
- signed = false,
247
- separatorMin = 1000,
248
- decimals = 0
249
- } = {}) {
177
+ static formatNumber(
178
+ value: unknown,
179
+ {
180
+ locale = 'en',
181
+ signed = false,
182
+ separatorMin = 1000,
183
+ decimals = 0
184
+ }: {
185
+ locale?: string,
186
+ signed?: boolean,
187
+ separatorMin?: number,
188
+ decimals?: number | number[]
189
+ } = {}
190
+ ) {
250
191
 
251
192
  const number = Number(value);
252
193
 
@@ -256,7 +197,7 @@ class Util {
256
197
  return String(NaN);
257
198
  }
258
199
 
259
- const options = {
200
+ const options: Intl.NumberFormatOptions = {
260
201
  /* Add thousand separators if value is big/small enough */
261
202
  useGrouping: Math.abs(number) >= separatorMin,
262
203
  signDisplay: signed ? 'exceptZero' : 'auto'
@@ -297,7 +238,7 @@ class Util {
297
238
 
298
239
  /* Format number of seconds to either like "40 or like "1:40". */
299
240
 
300
- static formatSeconds(seconds) {
241
+ static formatSeconds(seconds: number) {
301
242
  if (seconds <= 60)
302
243
  return Math.round(seconds);
303
244
  else
@@ -309,21 +250,21 @@ class Util {
309
250
 
310
251
  https://stackoverflow.com/a/56444611 */
311
252
 
312
- static toRoman(int) {
253
+ static toRoman(integer: number) {
313
254
  let roman = '';
314
- roman += 'M'.repeat(int / 1000); int %= 1000;
315
- roman += 'CM'.repeat(int / 900); int %= 900;
316
- roman += 'D'.repeat(int / 500); int %= 500;
317
- roman += 'CD'.repeat(int / 400); int %= 400;
318
- roman += 'C'.repeat(int / 100); int %= 100;
319
- roman += 'XC'.repeat(int / 90); int %= 90;
320
- roman += 'L'.repeat(int / 50); int %= 50;
321
- roman += 'XL'.repeat(int / 40); int %= 40;
322
- roman += 'X'.repeat(int / 10); int %= 10;
323
- roman += 'IX'.repeat(int / 9); int %= 9;
324
- roman += 'V'.repeat(int / 5); int %= 5;
325
- roman += 'IV'.repeat(int / 4); int %= 4;
326
- roman += 'I'.repeat(int);
255
+ roman += 'M'.repeat(integer / 1000); integer %= 1000;
256
+ roman += 'CM'.repeat(integer / 900); integer %= 900;
257
+ roman += 'D'.repeat(integer / 500); integer %= 500;
258
+ roman += 'CD'.repeat(integer / 400); integer %= 400;
259
+ roman += 'C'.repeat(integer / 100); integer %= 100;
260
+ roman += 'XC'.repeat(integer / 90); integer %= 90;
261
+ roman += 'L'.repeat(integer / 50); integer %= 50;
262
+ roman += 'XL'.repeat(integer / 40); integer %= 40;
263
+ roman += 'X'.repeat(integer / 10); integer %= 10;
264
+ roman += 'IX'.repeat(integer / 9); integer %= 9;
265
+ roman += 'V'.repeat(integer / 5); integer %= 5;
266
+ roman += 'IV'.repeat(integer / 4); integer %= 4;
267
+ roman += 'I'.repeat(integer);
327
268
  return roman;
328
269
  }
329
270
 
@@ -332,7 +273,7 @@ class Util {
332
273
 
333
274
  Note: Step can be negative, or non-integer. */
334
275
 
335
- static seq(start, end, step = 1) {
276
+ static seq(start: number, end: number, step = 1) {
336
277
  const result = [];
337
278
  for (let value = start; step > 0 ? value <= end : value >= end; value += step)
338
279
  result.push(value);
@@ -344,7 +285,7 @@ class Util {
344
285
 
345
286
  If the array has only one value, then return the array is returned. */
346
287
 
347
- static minMax(array) {
288
+ static minMax(array: number[]) {
348
289
  if (array.length > 1)
349
290
  return [Math.min(...array), Math.max(...array)];
350
291
  else
@@ -352,34 +293,12 @@ class Util {
352
293
  }
353
294
 
354
295
 
355
- /* Write log messages with a time in milliseconds elapsed since window.ST_TIMELINE_START that should be stored
356
- at the earliest possible moment in the first <script> element of <head>. */
357
-
358
- static logTimeline(message, { devel = false } = {}) {
359
-
360
- /* If window.ST_TIMELINE_START is not set, set it on first call */
361
-
362
- if (!window.ST_TIMELINE_START) {
363
- console.info('Initializing window.ST_TIMELINE_START as it is not set');
364
- window.ST_TIMELINE_START = Date.now();
365
- }
366
-
367
- if (devel && !Util.envDevelopment)
368
- return;
369
-
370
- console.info(
371
- `%c<< ${Date.now() - +window.ST_TIMELINE_START} ms >> ${message}`,
372
- `font-weight: ${devel ? 'normal' : 'bold'}; font-size: 1.1em;`
373
- );
374
- }
375
-
376
-
377
296
  /* Like Python's zip(): Return an array of arrays from a set of iterables. Each item of the
378
297
  returned array is an array of values of the iterables.
379
298
 
380
299
  For example: ['a', 'b', 'c'], [1, 2] => [['a', 1], ['b', 2], ['c', undefined]] */
381
300
 
382
- static zip(...args) {
301
+ static zip(...args: unknown[][]) {
383
302
  const iterators = args.map(arg => arg[Symbol.iterator]());
384
303
  const result = [];
385
304
 
@@ -408,8 +327,8 @@ class Util {
408
327
  this can be limited by providing the third parameter maxComponents. */
409
328
 
410
329
  static versionCompare(
411
- version1,
412
- version2,
330
+ version1: string,
331
+ version2: string,
413
332
  {
414
333
  maxComponents = Number.MAX_VALUE,
415
334
  skipLeadingZeros = false
@@ -442,17 +361,26 @@ class Util {
442
361
 
443
362
  Positive offset returns an older version, negative offset a newer version. */
444
363
 
445
- static #versionCalculate(version, offset) {
446
- const [, major, minor] = version.match(/^[0-9]+\.([0-9]+)\.([0-9]+)/);
447
- const oldVersion = Number(major) * 12 + Number(minor) - Number(offset);
448
- return `0.${Math.floor(oldVersion / 12)}.${oldVersion % 12}`;
364
+ static #versionCalculate(version: string, offset: number) {
365
+ const versionMatch: RegExpMatchArray | null = version.match(/^[0-9]+\.([0-9]+)\.([0-9]+)/);
366
+
367
+ if (versionMatch?.length === 3) {
368
+ const [, major, minor] = versionMatch;
369
+ const oldVersion = Number(major) * 12 + Number(minor) - Number(offset);
370
+ return `0.${Math.floor(oldVersion / 12)}.${oldVersion % 12}`;
371
+ } else
372
+ throw new Error('Invalid version: ' + version);
449
373
  }
450
374
 
451
- static versionEarlier(version, offset) {
375
+ /* Calculate earlier version */
376
+
377
+ static versionEarlier(version: string, offset: number) {
452
378
  return Util.#versionCalculate(version, offset);
453
379
  }
454
380
 
455
- static versionLater(version, offset) {
381
+ /* Calculate later version */
382
+
383
+ static versionLater(version: string, offset: number) {
456
384
  return Util.#versionCalculate(version, -offset);
457
385
  }
458
386
 
@@ -464,7 +392,7 @@ class Util {
464
392
 
465
393
  TODO: Configurable handling for duplicate values? Currently they are also spaced out. */
466
394
 
467
- static distNumbers(src, dist) {
395
+ static distNumbers(src: number[], dist: number) {
468
396
 
469
397
  /* Shift integer value at the given index by the given amount.
470
398
 
@@ -472,7 +400,7 @@ class Util {
472
400
  too close. If it is, recursively shift it either the same amount or to
473
401
  the minimum distance, whichever is less. */
474
402
 
475
- const move = (j, shift) => {
403
+ const move = (j: number, shift: number) => {
476
404
  a[j].n += shift;
477
405
  if (shift > 0 && j + 1 in a) {
478
406
  const spread = dist - (a[j + 1].n - a[j].n);
@@ -508,10 +436,12 @@ class Util {
508
436
  }
509
437
 
510
438
 
511
- static arrayIntersection(...arrays) {
439
+ /* Intersection of two or more arrays */
440
+
441
+ static arrayIntersection(...arrays: unknown[][]) {
512
442
 
513
- /* Recursively intersect two or more arrays */
514
- const doIntersection = (...arrays) => {
443
+ // Recursive worker to handle two arrays at a time
444
+ const doIntersection = (...arrays: unknown[][]) => {
515
445
  const set = new Set(arrays[1]);
516
446
  const intersection = arrays[0].filter(value => set.has(value));
517
447
  if (arrays.length > 2)
@@ -528,11 +458,12 @@ class Util {
528
458
  return doIntersection(...arrays);
529
459
  }
530
460
 
461
+ /* Intersection of two or more arrays */
531
462
 
532
- static arrayUnion(...arrays) {
463
+ static arrayUnion(...arrays: unknown[][]) {
533
464
 
534
- /* Recursively make a union of two or more arrays */
535
- const doUnion = (...arrays) => {
465
+ // Recursive worker to handle two arrays at a time
466
+ const doUnion = (...arrays: unknown[][]) => {
536
467
  const set = new Set(arrays[0]);
537
468
  const union = [...arrays[0], ...arrays[1].filter(value => !set.has(value))];
538
469
  if (arrays.length > 2)
@@ -549,11 +480,12 @@ class Util {
549
480
  return doUnion(...arrays);
550
481
  }
551
482
 
483
+ /* Difference of two or more arrays */
552
484
 
553
- static arrayDifference(...arrays) {
485
+ static arrayDifference(...arrays: unknown[][]) {
554
486
 
555
- /* Recursively make a difference of two or more arrays */
556
- const doDifference = (...arrays) => {
487
+ // Recursive worker to handle two arrays at a time
488
+ const doDifference = (...arrays: unknown[][]) => {
557
489
  const set = new Set(arrays[1]);
558
490
  const difference = arrays[0].filter(value => !set.has(value));
559
491
  if (arrays.length > 2)
@@ -583,27 +515,30 @@ class Util {
583
515
  Warning: Duplicate values are not handled consistently. Duplicates included only in one of the
584
516
  arrays are retained, but if included in both only duplicates of A are retained. */
585
517
 
586
- static arrayCompare(a, b) {
518
+ static arrayCompare(a: unknown[], b: unknown[]) {
587
519
  const onlyA = [];
588
520
  const onlyB = [];
589
521
  const both = [];
590
522
  const aSet = new Set(a);
591
523
  const bSet = new Set(b);
524
+
592
525
  for (const aValue of a)
593
526
  if (bSet.has(aValue))
594
527
  both.push(aValue);
595
528
  else
596
529
  onlyA.push(aValue);
530
+
597
531
  for (const bValue of b)
598
532
  if (!aSet.has(bValue))
599
533
  onlyB.push(bValue);
534
+
600
535
  return [onlyA, both, onlyB];
601
536
  }
602
537
 
603
538
 
604
539
  /* Split array into chunks of the given size. Last chunk may be shorter. */
605
540
 
606
- static arrayChunks(a, chunkSize) {
541
+ static arrayChunks(a: unknown[], chunkSize: number) {
607
542
  const result = [];
608
543
  for (let i = 0; i < a.length; i += chunkSize)
609
544
  result.push(a.slice(i, i + chunkSize));
@@ -617,7 +552,7 @@ class Util {
617
552
  As an example, if an array of length 9 is split to chunks of maximum length 4,
618
553
  three arrays of length 3 are returned. */
619
554
 
620
- static arrayChunksEqual(a, maxChunkSize) {
555
+ static arrayChunksEqual(a: unknown[], maxChunkSize: number) {
621
556
  const noChunks = Math.ceil(a.length / maxChunkSize);
622
557
  const chunkSize = Math.ceil(a.length / noChunks);
623
558
  return Util.arrayChunks(a, chunkSize);
@@ -630,7 +565,7 @@ class Util {
630
565
 
631
566
  Currently only slope is used so the rest have been commented. */
632
567
 
633
- static linearRegression(y, x) {
568
+ static linearRegression(y: number[], x: number[]) {
634
569
  const n = y.length;
635
570
  let sumX = 0;
636
571
  let sumY = 0;
@@ -658,20 +593,29 @@ class Util {
658
593
  }
659
594
 
660
595
 
661
- static camelToUpperCase(s) {
596
+ /* Convert "camelCase" to "UPPER_CASE" */
597
+
598
+ static camelToUpperCase(s: string) {
662
599
  return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toUpperCase();
663
600
  }
664
601
 
665
- static camelToLowerCase(s) {
602
+ /* Convert "camelCase" to "lower_case" */
603
+
604
+ static camelToLowerCase(s: string) {
666
605
  return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toLowerCase();
667
606
  }
668
607
 
669
608
 
670
- static #tableColumns;
671
- static #tableLogger;
672
- static #tableRule;
609
+ static #tableColumns: { width: number, right?: boolean }[];
610
+ static #tableLogger: (message: string) => void;
611
+ static #tableRule: string;
612
+
613
+ /* Start printing table to console or given logger */
673
614
 
674
- static tableStart(columns, { logger = null } = {}) {
615
+ static tableStart(
616
+ columns: { name: string, width: number, right?: boolean }[],
617
+ { logger }: { logger?: (message: string) => void } = {}
618
+ ) {
675
619
  Util.#tableColumns = columns.map(({ name, width, right }) => ({
676
620
  width: width || name.length,
677
621
  right
@@ -683,7 +627,9 @@ class Util {
683
627
  Util.#tableLogger(Util.#tableRule);
684
628
  }
685
629
 
686
- static tableRow(...values) {
630
+ /* Print a table row */
631
+
632
+ static tableRow(...values: unknown[]) {
687
633
  Util.#tableLogger(values.map((value, i) =>
688
634
  Util.#tableColumns[i].right ?
689
635
  String(value).padEnd(Util.#tableColumns[i].width) :
@@ -691,6 +637,8 @@ class Util {
691
637
  ).join(' '));
692
638
  }
693
639
 
640
+ /* Print a horizontal line to end the table */
641
+
694
642
  static tableEnd() {
695
643
  Util.#tableLogger(Util.#tableRule);
696
644
  }
@@ -698,26 +646,26 @@ class Util {
698
646
 
699
647
  /* Asynchronous intervals, adapted from: https://dev.to/jsmccrumb/asynchronous-setinterval-4j69 */
700
648
 
701
- static #asyncIntervals = [];
649
+ static #asyncIntervals: boolean[] = [];
702
650
 
703
- static async #runAsyncInterval(callback, interval, intervalIndex) {
651
+ static async #runAsyncInterval(callback: () => Promise<void>, interval: number, intervalIndex: number) {
704
652
  await callback();
705
653
  if (Util.#asyncIntervals[intervalIndex])
706
- setTimeout(() => Util.#runAsyncInterval(callback, interval, intervalIndex), interval);
654
+ setTimeout(() => void Util.#runAsyncInterval(callback, interval, intervalIndex), interval);
707
655
  }
708
656
 
709
- static setAsyncInterval(callback, interval) {
657
+ static setAsyncInterval(callback: () => Promise<void>, interval: number) {
710
658
  if (typeof callback === 'function') {
711
659
  const intervalIndex = Util.#asyncIntervals.length;
712
660
  Util.#asyncIntervals.push(true);
713
- Util.#runAsyncInterval(callback, interval, intervalIndex);
661
+ void Util.#runAsyncInterval(callback, interval, intervalIndex);
714
662
  return intervalIndex;
715
663
  } else {
716
664
  throw new Error('Callback must be a function');
717
665
  }
718
666
  }
719
667
 
720
- static clearAsyncInterval(intervalIndex) {
668
+ static clearAsyncInterval(intervalIndex: number) {
721
669
  if (Util.#asyncIntervals[intervalIndex])
722
670
  Util.#asyncIntervals[intervalIndex] = false;
723
671
  }
@@ -3,49 +3,57 @@ import path from 'path';
3
3
  import zlib from 'zlib';
4
4
  import dotenv from 'dotenv';
5
5
  import findConfig from 'find-config';
6
- import Util from './Util.js';
6
+ import Util from './Util.ts';
7
7
 
8
8
 
9
9
  /* Additional utility functions that only work in Node.js */
10
10
 
11
11
  class UtilNode extends Util {
12
12
 
13
- /* Return environment variable. The given .env file is loaded with find-config
13
+ static #envFileLoaded: Record<string,boolean> = {};
14
+
15
+ /* Return environment variable value. The given .env file is loaded with find-config
14
16
  so that it is also loaded from a parent directory.
15
17
 
16
18
  If the environment variable cannot be found the process exits with exit value 1. */
17
19
 
18
- static #envFileLoaded = {};
20
+ static env(name: string, envFile = '.env') {
19
21
 
20
- static env(name, envFile = '.env') {
21
22
  if (envFile in UtilNode.#envFileLoaded === false) {
23
+ const path = findConfig(envFile);
24
+ if (!path) {
25
+ console.warn(`Environment variable file "${envFile}" not found`);
26
+ process.exit(1);
27
+ }
28
+
22
29
  dotenv.config({
23
- path: findConfig(envFile),
30
+ path,
24
31
  quiet: true
25
32
  });
26
33
  UtilNode.#envFileLoaded[envFile] = true;
27
34
  }
28
35
 
29
36
  const value = process.env[name];
30
- if (value)
31
- return value;
32
- else {
37
+ if (!value) {
33
38
  console.warn(`Environment variable ${name} not defined`);
34
39
  process.exit(1);
35
40
  }
41
+
42
+ return value;
36
43
  }
37
44
 
38
45
 
39
- /* Return a list of files under the given directory,
40
- recursively including subdirectories. */
46
+ /* Return a list of filenames under the given directory, recursively including
47
+ subdirectories. Optionally, the array to which the filenames are added can be
48
+ given as the second argument. */
41
49
 
42
- static walkSync(dir, filelist = []) {
50
+ static walkSync(dir: string, target: string[] = []) {
43
51
  for (const file of fs.readdirSync(dir)) {
44
- filelist = fs.statSync(path.join(dir, file)).isDirectory() ?
45
- UtilNode.walkSync(path.join(dir, file), filelist) :
46
- filelist.concat(path.join(dir, file));
52
+ target = fs.statSync(path.join(dir, file)).isDirectory() ?
53
+ UtilNode.walkSync(path.join(dir, file), target) :
54
+ target.concat(path.join(dir, file));
47
55
  }
48
- return filelist;
56
+ return target;
49
57
  }
50
58
 
51
59
 
@@ -54,23 +62,23 @@ class UtilNode extends Util {
54
62
  If the filename ends with ".gz" or ".br", it is decompressed first. If the filename
55
63
  contains ".jsonc", then comments are removed before the JSON is parsed. */
56
64
 
57
- static jsonRead(filename) {
58
- let input = fs.readFileSync(filename);
65
+ static jsonRead(filename: string) {
66
+ let input = fs.readFileSync(filename).toString();
59
67
  if (filename.endsWith('.gz'))
60
- input = zlib.gunzipSync(input);
68
+ input = zlib.gunzipSync(input).toString();
61
69
  if (filename.endsWith('.br'))
62
- input = zlib.brotliDecompressSync(input);
70
+ input = zlib.brotliDecompressSync(input).toString();
63
71
  if (filename.includes('.jsonc'))
64
72
  input = input.toString().replaceAll(/\/\*.*?\*\//gs, '').replaceAll(/\/\/.*$/gm, '');
65
- return JSON.parse(input);
73
+ return JSON.parse(input) as unknown;
66
74
  }
67
75
 
68
76
 
69
77
  /* Write object to file as JSON. If the filename ends with ".gz" or ".br", then the
70
78
  file content is compressed before being written. */
71
79
 
72
- static jsonWrite(filename, object, replacer = null, space = 2) {
73
- let output = JSON.stringify(object, replacer, space);
80
+ static jsonWrite(filename: string, object: unknown, replacer = null, space = 2) {
81
+ let output: string | Buffer = JSON.stringify(object, replacer, space);
74
82
  if (filename.endsWith('.gz'))
75
83
  output = zlib.gzipSync(output);
76
84
  if (filename.endsWith('.br'))
@@ -0,0 +1,216 @@
1
+ import Semaphore from '../Semaphore.ts';
2
+ import z from 'zod';
3
+
4
+
5
+ /* Helper function to call any of the API endpoints */
6
+
7
+ const WgResponseSchema = z.object({
8
+ status: z.string(),
9
+
10
+ // Error is present when status is not "ok"
11
+
12
+ error: z.optional(z.object({
13
+ message: z.string()
14
+ })),
15
+
16
+ // Meta is present when status is "ok"
17
+
18
+ meta: z.optional(z.object({
19
+ page: z.number().optional(),
20
+ page_total: z.number().optional()
21
+ })),
22
+
23
+ // Depending on the response, data is either an object or an array of objects.
24
+ // In either case, the value is parsed with another schema.
25
+
26
+ data: z.union([z.looseObject({}), z.array(z.unknown())])
27
+ });
28
+
29
+ const callApi = async (url: string) => {
30
+ const data = await (await fetch(url)).json() as unknown;
31
+ const response = WgResponseSchema.parse(data);
32
+
33
+ if (response.status !== 'ok')
34
+ throw new Error(`Wargaming API error: ${response?.error?.message}`);
35
+
36
+ return response;
37
+ };
38
+
39
+
40
+ /* /encyclopedia/info -- Contains current game version */
41
+
42
+ const EncyclopediaInfoSchema = z.object({
43
+ game_version: z.string()
44
+ });
45
+
46
+ const encyclopediaInfo = async (apiId: string) => {
47
+ const { data } = await callApi(`https://api.worldofwarships.eu/wows/encyclopedia/info/?application_id=${apiId}`);
48
+ return EncyclopediaInfoSchema.parse(data);
49
+ };
50
+
51
+
52
+ /* /encyclopedia/ships -- List of ships in the current game version */
53
+
54
+ const EncyclopediaShipsSchema = z.record(
55
+ z.number(),
56
+ z.object({
57
+ ship_id: z.number(),
58
+ tier: z.number(),
59
+ ship_id_str: z.string()
60
+ })
61
+ );
62
+
63
+ const encyclopediaShips = async (apiId: string, { concurrency = 1 } = {}) => {
64
+ const { meta, data } = await callApi(`https://api.worldofwarships.eu/wows/encyclopedia/ships/?application_id=${apiId}`);
65
+
66
+ if (!meta || !meta.page_total)
67
+ throw new Error('Unexpected /encyclopedia/ships response');
68
+
69
+ const ships = EncyclopediaShipsSchema.parse(data);
70
+ console.debug(`Loaded encyclopedia page ${meta.page} / ${meta.page_total}`);
71
+
72
+ const sem = new Semaphore(concurrency);
73
+
74
+ for (let page = 2; page <= meta.page_total; page++)
75
+ void sem.run(async () => {
76
+ const { data } = await callApi(`https://api.worldofwarships.eu/wows/encyclopedia/ships/?application_id=${apiId}&page_no=${page}`);
77
+ Object.assign(ships, EncyclopediaShipsSchema.parse(data));
78
+ console.debug(`Loaded encyclopedia page ${page} / ${meta.page_total}`);
79
+ });
80
+
81
+ await sem.wait();
82
+ return ships;
83
+ };
84
+
85
+
86
+ /* /clans/list -- Clans whose tags match the given string
87
+
88
+ Note: The implementation only returns the one clan whose tag is an exact match */
89
+
90
+ const ClansListSchema = z.array(
91
+ z.object({
92
+ clan_id: z.number(),
93
+ tag: z.string(),
94
+ name: z.string()
95
+ })
96
+ );
97
+
98
+ const clansList = async (apiId: string, region: string, clanTag: string) => {
99
+ const { data } = await callApi(`https://api.worldofwarships.${region}/wows/clans/list/?application_id=${apiId}&search=${clanTag}`);
100
+ const response = ClansListSchema.parse(data);
101
+ const clanInfo = response.find(({ tag }) => tag === clanTag);
102
+
103
+ if (!clanInfo)
104
+ throw new Error('Clan tag not found in /clans/list response: ' + clanTag);
105
+
106
+ return clanInfo;
107
+ };
108
+
109
+
110
+ /* /clans/info -- Information about the given clan, including a list of members */
111
+
112
+ const ClansInfoSchema = z.record(
113
+ z.number(),
114
+ z.nullable(z.object({ // null for invalid clan identifier
115
+ clan_id: z.number(),
116
+ members_ids: z.array(
117
+ z.number()
118
+ ),
119
+ members: z.record(
120
+ z.number(),
121
+ z.object({
122
+ account_id: z.number(),
123
+ account_name: z.string(),
124
+ role: z.string(),
125
+ joined_at: z.number()
126
+ })
127
+ )
128
+ }))
129
+ );
130
+
131
+ const clansInfoMany = async (apiId: string, region: string, clanIds: number[]) => {
132
+ const { data } = await callApi(`https://api.worldofwarships.${region}/wows/clans/info/?application_id=${apiId}&clan_id=${clanIds.join(',')}&extra=members`);
133
+ return ClansInfoSchema.parse(data);
134
+ };
135
+
136
+ const clansInfoOne = async (apiId: string, region: string, clanId: number) => {
137
+ const response = await clansInfoMany(apiId, region, [clanId]);
138
+
139
+ if (!response[clanId])
140
+ throw new Error('Clan not found in /clans/info response: ' + clanId);
141
+
142
+ return response[clanId];
143
+ };
144
+
145
+
146
+ /* /account/info -- Information about given players */
147
+
148
+ const AccountInfoSchema = z.record(
149
+ z.number(),
150
+ z.object({
151
+ account_id: z.number(),
152
+ nickname: z.string(),
153
+ created_at: z.number(),
154
+ last_battle_time: z.number(),
155
+ statistics: z.nullable(z.object({ // null for private accounts
156
+ pvp: z.optional(z.object({
157
+ battles: z.number(),
158
+ wins: z.number()
159
+ })),
160
+ pvp_solo: z.optional(z.object({
161
+ battles: z.number()
162
+ }))
163
+ }))
164
+ })
165
+ );
166
+
167
+ const accountInfoMany = async (apiId: string, region: string, accountIds: number[]) => {
168
+ const { data } = await callApi(`https://api.worldofwarships.${region}/wows/account/info/?application_id=${apiId}&account_id=${accountIds.join(',')}&extra=statistics.pvp_solo`);
169
+ return AccountInfoSchema.parse(data);
170
+ };
171
+
172
+ const accountInfoOne = async (apiId: string, region: string, accountId: number) => {
173
+ const response = await accountInfoMany(apiId, region, [accountId]);
174
+
175
+ if (!response[accountId])
176
+ throw new Error('Account not found in /account/info response: ' + accountId);
177
+
178
+ return response[accountId];
179
+ };
180
+
181
+
182
+ /* /ships/stats -- Given players' stats in different ships */
183
+
184
+ const ShipsStatsSchema = z.record(
185
+ z.number(),
186
+ z.array(
187
+ z.object({
188
+ ship_id: z.number(),
189
+ pvp: z.object({
190
+ battles: z.number()
191
+ }).optional()
192
+ })
193
+ )
194
+ );
195
+
196
+ const shipsStats = async (apiId: string, region: string, accountId: number) => {
197
+ const { data } = await callApi(`https://api.worldofwarships.${region}/wows/ships/stats/?application_id=${apiId}&account_id=${accountId}`);
198
+ const response = ShipsStatsSchema.parse(data);
199
+
200
+ if (!response[accountId])
201
+ throw new Error('Account not found in /ships/stats response: ' + accountId);
202
+
203
+ return response[accountId];
204
+ };
205
+
206
+
207
+ export default {
208
+ encyclopediaInfo,
209
+ encyclopediaShips,
210
+ clansList,
211
+ clansInfoMany,
212
+ clansInfoOne,
213
+ accountInfoMany,
214
+ accountInfoOne,
215
+ shipsStats
216
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antti5/ship-tool-common",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Ship Tool common utils and library code",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,23 +16,27 @@
16
16
  "tag": "bin/tag"
17
17
  },
18
18
  "exports": {
19
- "./Util": "./lib/Util.js",
19
+ "./Util": "./lib/Util.ts",
20
20
  "./Semaphore": "./lib/Semaphore.ts",
21
21
  "./UID": "./lib/UID.ts",
22
22
  "./Trajectory": "./lib/trajectory/Trajectory.ts",
23
- "./node/Util": "./lib/UtilNode.js"
23
+ "./node/Util": "./lib/UtilNode.ts",
24
+ "./publicApi": "./lib/services/publicApi.ts"
24
25
  },
25
26
  "scripts": {
26
27
  "eslint": "eslint . --ignore-pattern \"node_modules/*\""
27
28
  },
29
+ "dependencies": {
30
+ "dotenv": "17.4.2",
31
+ "find-config": "1.0.0",
32
+ "zod": "4.6.7"
33
+ },
28
34
  "devDependencies": {
29
35
  "@eslint/js": "9.39.2",
36
+ "@types/find-config": "1.0.4",
37
+ "@types/node": "26.6.6",
30
38
  "eslint": "9.36.0",
31
39
  "globals": "16.4.0",
32
40
  "typescript-eslint": "8.73.0"
33
- },
34
- "dependencies": {
35
- "dotenv": "17.4.2",
36
- "find-config": "1.0.0"
37
41
  }
38
42
  }
package/tsconfig.json CHANGED
@@ -1,24 +1,13 @@
1
1
  {
2
2
  "compilerOptions": {
3
- // "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
4
3
  "target": "es2022",
5
- // "useDefineForClassFields": true,
6
- // "lib": [
7
- // "es2022",
8
- // "DOM",
9
- // "DOM.Iterable"
10
- // ],
11
4
  "module": "nodenext",
12
- // "types": ["vite/client"],
13
- // "skipLibCheck": true,
5
+ "types": ["node"],
14
6
 
15
7
  /* Bundler mode */
16
8
  "moduleResolution": "nodenext",
17
9
  "allowImportingTsExtensions": true,
18
- // "verbatimModuleSyntax": true,
19
- // "moduleDetection": "force",
20
10
  "noEmit": true,
21
- // "jsx": "react-jsx",
22
11
 
23
12
  /* Linting */
24
13
  "strict": true,
@@ -1,9 +0,0 @@
1
- import Vector3 from './Vector3.ts';
2
- import BulletSim from './BulletSim.ts';
3
-
4
- const pos = new Vector3(0, 0, 0);
5
- const dir = new Vector3(1, 1, 1);
6
- const sim = new BulletSim(1, 1, 1, 1, pos, dir);
7
- sim.step();
8
- sim.step();
9
- sim.step();