@naturalcycles/nodejs-lib 15.147.0 → 15.149.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.
@@ -98,12 +98,8 @@ export function objectToShellExport(obj, prefix = '') {
98
98
  if (!Object.keys(obj).length)
99
99
  return '';
100
100
  return (Object.entries(obj)
101
- .map(([k, v]) => {
102
- if (v !== undefined && v !== null) {
103
- return `export ${prefix}${k}="${v}"`;
104
- }
105
- })
106
- .filter(Boolean)
101
+ .filter(([_k, v]) => v !== undefined && v !== null)
102
+ .map(([k, v]) => `export ${prefix}${k}="${v}"`)
107
103
  .join('\n') + '\n'); // trailing \n is important
108
104
  }
109
105
  /**
@@ -126,11 +122,7 @@ export function objectToGithubActionsEnv(obj, prefix = '') {
126
122
  if (!Object.keys(obj).length)
127
123
  return '';
128
124
  return (Object.entries(obj)
129
- .map(([k, v]) => {
130
- if (v !== undefined && v !== null) {
131
- return `${prefix}${k}=${v}`;
132
- }
133
- })
134
- .filter(Boolean)
125
+ .filter(([_k, v]) => v !== undefined && v !== null)
126
+ .map(([k, v]) => `${prefix}${k}=${v}`)
135
127
  .join('\n') + '\n'); // trailing \n is important
136
128
  }
@@ -1 +1,2 @@
1
+ // oxlint-disable-next-line typescript/no-deprecated -- only the options-only overloads are deprecated
1
2
  export { glob, globSync } from 'tinyglobby';
@@ -1,10 +1,9 @@
1
- import type { BinaryToTextEncoding } from 'node:crypto';
2
1
  import type { Base64String, Base64UrlString } from '@naturalcycles/js-lib/types';
3
- export declare function md5(s: string | Uint8Array, outputEncoding?: BinaryToTextEncoding): string;
2
+ export declare function md5(s: string | Uint8Array, outputEncoding?: BufferEncoding): string;
4
3
  export declare function md5AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer>;
5
- export declare function sha256(s: string | Uint8Array, outputEncoding?: BinaryToTextEncoding): string;
4
+ export declare function sha256(s: string | Uint8Array, outputEncoding?: BufferEncoding): string;
6
5
  export declare function sha256AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer>;
7
- export declare function hash(s: string | Uint8Array, algorithm: string, outputEncoding?: BinaryToTextEncoding): string;
6
+ export declare function hash(s: string | Uint8Array, algorithm: string, outputEncoding?: BufferEncoding): string;
8
7
  export declare function hashAsBuffer(s: string | Uint8Array, algorithm: string): Buffer<ArrayBuffer>;
9
8
  export declare function base64(s: string | Uint8Array): Base64String;
10
9
  export declare function base64Url(s: string | Uint8Array): Base64UrlString;
@@ -0,0 +1,26 @@
1
+ import type { ReadableTyped, WritableTyped } from './stream.model.js';
2
+ /**
3
+ * Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
4
+ *
5
+ * The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
6
+ * afterwards. It is the same approach as in `createReadableFromAsync`.
7
+ *
8
+ * The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
9
+ * which is an optional peer dependency.
10
+ */
11
+ export declare function createCloudStorageReadStream(url: string): ReadableTyped<Uint8Array>;
12
+ /**
13
+ * Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
14
+ *
15
+ * The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
16
+ * which is an optional peer dependency.
17
+ */
18
+ export declare function createCloudStorageWriteStream(url: string): Promise<WritableTyped<Uint8Array>>;
19
+ /**
20
+ * Throws if the given url is not a Cloud Storage url.
21
+ */
22
+ export declare function assertCloudStorageUrl(url: string): void;
23
+ /**
24
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
25
+ */
26
+ export declare function isCloudStorageUrl(path: string): boolean;
@@ -0,0 +1,86 @@
1
+ import { PassThrough } from 'node:stream';
2
+ import { _assert } from '@naturalcycles/js-lib/error/assert.js';
3
+ import { _noop } from '@naturalcycles/js-lib/types';
4
+ const CLOUD_STORAGE_URL_PREFIX = 'gs://';
5
+ const CLOUD_STORAGE_LIB = '@naturalcycles/cloud-storage-lib';
6
+ /**
7
+ * Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
8
+ *
9
+ * The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
10
+ * afterwards. It is the same approach as in `createReadableFromAsync`.
11
+ *
12
+ * The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
13
+ * which is an optional peer dependency.
14
+ */
15
+ export function createCloudStorageReadStream(url) {
16
+ const { bucketName, filePath } = parseCloudStorageUrl(url);
17
+ const readable = new PassThrough();
18
+ // The read can fail before any consumer is attached, and an 'error' event without a listener
19
+ // crashes the process. With this listener the error is kept in the stream instead,
20
+ // and the consumer gets it when it attaches.
21
+ readable.on('error', _noop);
22
+ void getDefaultCloudStorage()
23
+ .then(async (storage) => {
24
+ await storage.getFileReadStream(bucketName, filePath).to(readable);
25
+ })
26
+ // If `readable` is already destroyed (e.g. the consumer stopped early) - this `destroy` does nothing
27
+ .catch(err => readable.destroy(err));
28
+ return readable;
29
+ }
30
+ /**
31
+ * Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
32
+ *
33
+ * The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
34
+ * which is an optional peer dependency.
35
+ */
36
+ export async function createCloudStorageWriteStream(url) {
37
+ const { bucketName, filePath } = parseCloudStorageUrl(url);
38
+ const storage = await getDefaultCloudStorage();
39
+ return storage.getFileWriteStream(bucketName, filePath);
40
+ }
41
+ function parseCloudStorageUrl(url) {
42
+ assertCloudStorageUrl(url);
43
+ const [bucketName, ...pathParts] = url.slice(CLOUD_STORAGE_URL_PREFIX.length).split('/');
44
+ const filePath = pathParts.join('/');
45
+ _assert(bucketName && filePath, `Cloud Storage url should look like gs://bucket/path/to/file but got: ${url}`);
46
+ return { bucketName, filePath };
47
+ }
48
+ /**
49
+ * Throws if the given url is not a Cloud Storage url.
50
+ */
51
+ export function assertCloudStorageUrl(url) {
52
+ _assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${url}`);
53
+ }
54
+ /**
55
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
56
+ */
57
+ export function isCloudStorageUrl(path) {
58
+ return path.startsWith(CLOUD_STORAGE_URL_PREFIX);
59
+ }
60
+ async function getDefaultCloudStorage() {
61
+ const lib = await importCloudStorageLib();
62
+ return await lib.getDefaultCloudStorage();
63
+ }
64
+ /**
65
+ * cloud-storage-lib is an optional peer dependency, so it is imported lazily,
66
+ * only when a `gs://` url is actually used.
67
+ */
68
+ async function importCloudStorageLib() {
69
+ try {
70
+ // The package name is passed as a variable, so that TypeScript does not resolve this import,
71
+ // see the comment at CloudStorageLib
72
+ return await import(CLOUD_STORAGE_LIB);
73
+ }
74
+ catch (err) {
75
+ const { code, message } = err;
76
+ // The message names the missing package in quotes. If it names another package -
77
+ // cloud-storage-lib is installed, and one of its own imports is missing.
78
+ if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`))
79
+ throw err;
80
+ throw new Error([
81
+ `Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
82
+ 'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
83
+ `Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
84
+ ].join('\n'), { cause: err });
85
+ }
86
+ }
@@ -12,5 +12,9 @@ import type { ReadableTyped } from '../stream.model.js';
12
12
  To add a Limit or Offset: just add .take() or .drop(), example:
13
13
 
14
14
  createReadStreamAsNDJson().take(100)
15
+
16
+ inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorageFile`.
17
+ A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
18
+ Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
15
19
  */
16
20
  export declare function createReadStreamAsNDJson<ROW = any>(inputPath: string): ReadableTyped<ROW>;
@@ -2,6 +2,7 @@ import { pipeline } from 'node:stream';
2
2
  import { createUnzip, createZstdDecompress } from 'node:zlib';
3
3
  import { _noop } from '@naturalcycles/js-lib/types';
4
4
  import { fs2 } from '../../fs/fs2.js';
5
+ import { createCloudStorageReadStream, isCloudStorageUrl } from '../cloudStorageStream.js';
5
6
  import { transformSplitOnNewline } from '../transform/transformSplit.js';
6
7
  import { transformJsonParse } from './transformJsonParse.js';
7
8
  /**
@@ -17,14 +18,13 @@ import { transformJsonParse } from './transformJsonParse.js';
17
18
  To add a Limit or Offset: just add .take() or .drop(), example:
18
19
 
19
20
  createReadStreamAsNDJson().take(100)
21
+
22
+ inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorageFile`.
23
+ A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
24
+ Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
20
25
  */
21
26
  export function createReadStreamAsNDJson(inputPath) {
22
- fs2.requireFileToExist(inputPath);
23
- const streams = [
24
- fs2.createReadStream(inputPath, {
25
- highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
26
- }),
27
- ];
27
+ const streams = [createFileReadStream(inputPath)];
28
28
  if (inputPath.endsWith('.gz')) {
29
29
  streams.push(createUnzip({
30
30
  chunkSize: 256 * 1024, // 64KB: speedup from ~3200 to 3800 rps! 256KB: +6-8% more on ~9KB rows, neutral on ~180B rows
@@ -47,3 +47,12 @@ export function createReadStreamAsNDJson(inputPath) {
47
47
  // ~5000 vs ~4000 rps !!!". Measured again on Node 24, it's the opposite: Readable.map costs ~1µs per row in promise machinery,
48
48
  // transformJsonParse() is 1.5x (consumed via pipeline) to 1.75x (consumed via for-await) faster on ~180B rows.
49
49
  }
50
+ function createFileReadStream(inputPath) {
51
+ // A Cloud Storage file is not checked for existence upfront: if it is missing - the stream fails
52
+ if (isCloudStorageUrl(inputPath))
53
+ return createCloudStorageReadStream(inputPath);
54
+ fs2.requireFileToExist(inputPath);
55
+ return fs2.createReadStream(inputPath, {
56
+ highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
57
+ });
58
+ }
@@ -32,8 +32,30 @@ export declare class Pipeline<T = unknown> {
32
32
  */
33
33
  static fromArray<T>(input: readonly T[]): Pipeline<T>;
34
34
  static fromIterable<T>(input: Iterable<T> | AsyncIterable<T>): Pipeline<T>;
35
+ /**
36
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
37
+ * see `fromCloudStorageFile`.
38
+ */
35
39
  static fromNDJsonFile<T>(sourceFilePath: string): Pipeline<T>;
40
+ /**
41
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
42
+ * see `fromCloudStorageFile`.
43
+ */
36
44
  static fromFile(sourceFilePath: string): Pipeline<Uint8Array>;
45
+ /**
46
+ * Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
47
+ * Same as `fromFile`, but it throws if the url does not start with `gs://`.
48
+ *
49
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
50
+ * Its default storage is used (see `getDefaultCloudStorage` there):
51
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
52
+ */
53
+ static fromCloudStorageFile(url: string): Pipeline<Uint8Array>;
54
+ /**
55
+ * Same as `fromNDJsonFile`, but it throws if the url does not start with `gs://`.
56
+ * See `fromCloudStorageFile` for the requirements.
57
+ */
58
+ static fromCloudStorageNDJsonFile<T>(url: string): Pipeline<T>;
37
59
  /**
38
60
  * Limits the source Readable, but using `.take(limit)` on it.
39
61
  * This is THE preferred way of limiting the source.
@@ -98,13 +120,30 @@ export declare class Pipeline<T = unknown> {
98
120
  opt?: ZstdOptions): Pipeline<Uint8Array>;
99
121
  zstdDecompress(this: Pipeline<Uint8Array>, opt?: ZstdOptions): Pipeline<Uint8Array>;
100
122
  toArray(opt?: TransformOptions): Promise<T[]>;
123
+ /**
124
+ * Same as `toFile`, but it rejects if the url does not start with `gs://`.
125
+ * See `fromCloudStorageFile` for the requirements.
126
+ */
127
+ toCloudStorageFile(url: string): Promise<void>;
128
+ /**
129
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
130
+ * see `fromCloudStorageFile` for the requirements.
131
+ */
101
132
  toFile(outputFilePath: string): Promise<void>;
133
+ /**
134
+ * Same as `toNDJsonFile`, but it rejects if the url does not start with `gs://`.
135
+ * See `fromCloudStorageFile` for the requirements.
136
+ */
137
+ toCloudStorageNDJsonFile(url: string, level?: Integer): Promise<void>;
102
138
  /**
103
139
  * level corresponds to zstd compression level (if filename ends with .zst),
104
140
  * or gzip compression level (if filename ends with .gz).
105
141
  * Default levels are:
106
142
  * gzip: 6
107
143
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
144
+ *
145
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
146
+ * see `fromCloudStorageFile` for the requirements.
108
147
  */
109
148
  toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void>;
110
149
  to(destination: WritableTyped<T>): Promise<void>;
@@ -112,4 +151,9 @@ export declare class Pipeline<T = unknown> {
112
151
  forEachSync(fn: AbortableMapper<T, void>, opt?: TransformMapSyncOptions<T, void> & TransformLogProgressOptions<T>): Promise<void>;
113
152
  run(): Promise<void>;
114
153
  private isGracefullyAborted;
154
+ /**
155
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
156
+ */
157
+ private createFileWriteStream;
158
+ private requireCloudStorageUrl;
115
159
  }
@@ -5,6 +5,7 @@ import { createAbortableSignal } from '@naturalcycles/js-lib';
5
5
  import { _passthroughPredicate } from '@naturalcycles/js-lib/types';
6
6
  import { fs2 } from '../fs/fs2.js';
7
7
  import { zip2 } from '../zip/zip2.js';
8
+ import { assertCloudStorageUrl, createCloudStorageReadStream, createCloudStorageWriteStream, isCloudStorageUrl, } from './cloudStorageStream.js';
8
9
  import { createReadStreamAsNDJson } from './ndjson/createReadStreamAsNDJson.js';
9
10
  import { transformJsonParse } from './ndjson/transformJsonParse.js';
10
11
  import { transformToNDJson } from './ndjson/transformToNDJson.js';
@@ -62,6 +63,10 @@ export class Pipeline {
62
63
  static fromIterable(input) {
63
64
  return new Pipeline(Readable.from(input));
64
65
  }
66
+ /**
67
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
68
+ * see `fromCloudStorageFile`.
69
+ */
65
70
  static fromNDJsonFile(sourceFilePath) {
66
71
  // Important that createReadStreamAsNDJson function is used
67
72
  // (and not Pipeline set of individual transforms),
@@ -70,11 +75,37 @@ export class Pipeline {
70
75
  // e.g like Pipeline.fromNDJsonFile().limitSource(limit)
71
76
  return new Pipeline(createReadStreamAsNDJson(sourceFilePath));
72
77
  }
78
+ /**
79
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
80
+ * see `fromCloudStorageFile`.
81
+ */
73
82
  static fromFile(sourceFilePath) {
83
+ if (isCloudStorageUrl(sourceFilePath))
84
+ return Pipeline.fromCloudStorageFile(sourceFilePath);
74
85
  return new Pipeline(fs2.createReadStream(sourceFilePath, {
75
86
  highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
76
87
  }), false);
77
88
  }
89
+ /**
90
+ * Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
91
+ * Same as `fromFile`, but it throws if the url does not start with `gs://`.
92
+ *
93
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
94
+ * Its default storage is used (see `getDefaultCloudStorage` there):
95
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
96
+ */
97
+ static fromCloudStorageFile(url) {
98
+ return new Pipeline(createCloudStorageReadStream(url), false);
99
+ }
100
+ /**
101
+ * Same as `fromNDJsonFile`, but it throws if the url does not start with `gs://`.
102
+ * See `fromCloudStorageFile` for the requirements.
103
+ */
104
+ static fromCloudStorageNDJsonFile(url) {
105
+ assertCloudStorageUrl(url);
106
+ // createReadStreamAsNDJson is used for the same reason as in fromNDJsonFile
107
+ return new Pipeline(createReadStreamAsNDJson(url));
108
+ }
78
109
  /**
79
110
  * Limits the source Readable, but using `.take(limit)` on it.
80
111
  * This is THE preferred way of limiting the source.
@@ -272,20 +303,41 @@ export class Pipeline {
272
303
  await this.run();
273
304
  return arr;
274
305
  }
306
+ /**
307
+ * Same as `toFile`, but it rejects if the url does not start with `gs://`.
308
+ * See `fromCloudStorageFile` for the requirements.
309
+ */
310
+ async toCloudStorageFile(url) {
311
+ this.requireCloudStorageUrl(url);
312
+ await this.toFile(url);
313
+ }
314
+ /**
315
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
316
+ * see `fromCloudStorageFile` for the requirements.
317
+ */
275
318
  async toFile(outputFilePath) {
276
- fs2.ensureFile(outputFilePath);
277
- this.destination = fs2.createWriteStream(outputFilePath);
319
+ this.destination = await this.createFileWriteStream(outputFilePath);
278
320
  await this.run();
279
321
  }
322
+ /**
323
+ * Same as `toNDJsonFile`, but it rejects if the url does not start with `gs://`.
324
+ * See `fromCloudStorageFile` for the requirements.
325
+ */
326
+ async toCloudStorageNDJsonFile(url, level) {
327
+ this.requireCloudStorageUrl(url);
328
+ await this.toNDJsonFile(url, level);
329
+ }
280
330
  /**
281
331
  * level corresponds to zstd compression level (if filename ends with .zst),
282
332
  * or gzip compression level (if filename ends with .gz).
283
333
  * Default levels are:
284
334
  * gzip: 6
285
335
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
336
+ *
337
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
338
+ * see `fromCloudStorageFile` for the requirements.
286
339
  */
287
340
  async toNDJsonFile(outputFilePath, level) {
288
- fs2.ensureFile(outputFilePath);
289
341
  this.transforms.push(transformToNDJson());
290
342
  if (outputFilePath.endsWith('.gz')) {
291
343
  this.transforms.push(createGzip({
@@ -296,9 +348,7 @@ export class Pipeline {
296
348
  else if (outputFilePath.endsWith('.zst')) {
297
349
  this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)));
298
350
  }
299
- this.destination = fs2.createWriteStream(outputFilePath, {
300
- // highWaterMark: 64 * 1024, // no observed speedup
301
- });
351
+ this.destination = await this.createFileWriteStream(outputFilePath);
302
352
  await this.run();
303
353
  }
304
354
  async to(destination) {
@@ -353,4 +403,34 @@ export class Pipeline {
353
403
  const { aborted, reason } = this.abortableSignal;
354
404
  return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT;
355
405
  }
406
+ /**
407
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
408
+ */
409
+ async createFileWriteStream(outputFilePath) {
410
+ try {
411
+ if (isCloudStorageUrl(outputFilePath)) {
412
+ return await createCloudStorageWriteStream(outputFilePath);
413
+ }
414
+ fs2.ensureFile(outputFilePath);
415
+ return fs2.createWriteStream(outputFilePath, {
416
+ // highWaterMark: 64 * 1024, // no observed speedup
417
+ });
418
+ }
419
+ catch (err) {
420
+ // The pipeline does not run, so nothing else closes the source, which can hold an open file
421
+ // or connection. It is destroyed without the error: nothing listens to its 'error' event here.
422
+ this.source.destroy();
423
+ throw err;
424
+ }
425
+ }
426
+ requireCloudStorageUrl(url) {
427
+ try {
428
+ assertCloudStorageUrl(url);
429
+ }
430
+ catch (err) {
431
+ // Same as in createFileWriteStream: the pipeline does not run, so the source is closed here
432
+ this.source.destroy();
433
+ throw err;
434
+ }
435
+ }
356
436
  }
@@ -1,4 +1,5 @@
1
1
  import { Readable, Transform } from 'node:stream';
2
+ import { _noop } from '@naturalcycles/js-lib/types';
2
3
  /**
3
4
  * Convenience function to create a Readable that can be pushed into (similar to RxJS Subject).
4
5
  * Push `null` to it to complete (similar to RxJS `.complete()`).
@@ -43,6 +44,10 @@ export function createReadableFromAsync(fn) {
43
44
  cb(null, chunk);
44
45
  },
45
46
  });
47
+ // `fn` or the source Readable can fail before any consumer is attached, and an 'error' event
48
+ // without a listener crashes the process. With this listener the error is kept in the stream instead,
49
+ // and the consumer gets it when it attaches.
50
+ transform.on('error', _noop);
46
51
  void fn()
47
52
  .then(readable => {
48
53
  readable.on('error', err => transform.destroy(err)).pipe(transform);
@@ -71,15 +71,14 @@ export function transformThrottleByRSS(opt) {
71
71
  clearTimeout(rssCheckTimer);
72
72
  if (onPollTimeout === 'throw') {
73
73
  lock.reject(new Error(`transformThrottleByRSS pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB`));
74
- lock = undefined;
75
74
  }
76
75
  else {
77
76
  // open-the-floodgates
78
77
  logger.error(`${localTime.now().toPretty()} transformThrottleByRSS: pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB — DISABLING THROTTLE`);
79
78
  disabled = true;
80
79
  lock.resolve();
81
- lock = undefined;
82
80
  }
81
+ lock = undefined;
83
82
  }
84
83
  else {
85
84
  logger.log(`${localTime.now().toPretty()} transformThrottleByRSS still paused: RSS ${_mb(rss)} > ${maxRSS} MB, rechecking in ${_ms(pollInterval)}`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/nodejs-lib",
3
3
  "type": "module",
4
- "version": "15.147.0",
4
+ "version": "15.149.0",
5
5
  "dependencies": {
6
6
  "@naturalcycles/js-lib": "^15",
7
7
  "@standard-schema/spec": "^1",
@@ -13,8 +13,17 @@
13
13
  "tslib": "^2",
14
14
  "yaml": "^2"
15
15
  },
16
+ "peerDependencies": {
17
+ "@naturalcycles/cloud-storage-lib": "^2"
18
+ },
19
+ "peerDependenciesMeta": {
20
+ "@naturalcycles/cloud-storage-lib": {
21
+ "optional": true
22
+ }
23
+ },
16
24
  "devDependencies": {
17
- "@naturalcycles/dev-lib": "20.76.0",
25
+ "@naturalcycles/cloud-storage-lib": "2.0.0",
26
+ "@naturalcycles/dev-lib": "0.0.0",
18
27
  "typescript": "^7"
19
28
  },
20
29
  "exports": {
@@ -147,12 +147,8 @@ export function objectToShellExport(obj: AnyObject, prefix = ''): string {
147
147
 
148
148
  return (
149
149
  Object.entries(obj)
150
- .map(([k, v]) => {
151
- if (v !== undefined && v !== null) {
152
- return `export ${prefix}${k}="${v}"`
153
- }
154
- })
155
- .filter(Boolean)
150
+ .filter(([_k, v]) => v !== undefined && v !== null)
151
+ .map(([k, v]) => `export ${prefix}${k}="${v}"`)
156
152
  .join('\n') + '\n'
157
153
  ) // trailing \n is important
158
154
  }
@@ -178,12 +174,8 @@ export function objectToGithubActionsEnv(obj: AnyObject, prefix = ''): string {
178
174
 
179
175
  return (
180
176
  Object.entries(obj)
181
- .map(([k, v]) => {
182
- if (v !== undefined && v !== null) {
183
- return `${prefix}${k}=${v}`
184
- }
185
- })
186
- .filter(Boolean)
177
+ .filter(([_k, v]) => v !== undefined && v !== null)
178
+ .map(([k, v]) => `${prefix}${k}=${v}`)
187
179
  .join('\n') + '\n'
188
180
  ) // trailing \n is important
189
181
  }
package/src/glob/index.ts CHANGED
@@ -1 +1,2 @@
1
+ // oxlint-disable-next-line typescript/no-deprecated -- only the options-only overloads are deprecated
1
2
  export { glob, globSync } from 'tinyglobby'
@@ -1,8 +1,7 @@
1
- import type { BinaryToTextEncoding } from 'node:crypto'
2
1
  import { hash as cryptoHash } from 'node:crypto'
3
2
  import type { Base64String, Base64UrlString } from '@naturalcycles/js-lib/types'
4
3
 
5
- export function md5(s: string | Uint8Array, outputEncoding: BinaryToTextEncoding = 'hex'): string {
4
+ export function md5(s: string | Uint8Array, outputEncoding: BufferEncoding = 'hex'): string {
6
5
  return hash(s, 'md5', outputEncoding)
7
6
  }
8
7
 
@@ -10,10 +9,7 @@ export function md5AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer> {
10
9
  return hashAsBuffer(s, 'md5')
11
10
  }
12
11
 
13
- export function sha256(
14
- s: string | Uint8Array,
15
- outputEncoding: BinaryToTextEncoding = 'hex',
16
- ): string {
12
+ export function sha256(s: string | Uint8Array, outputEncoding: BufferEncoding = 'hex'): string {
17
13
  return hash(s, 'sha256', outputEncoding)
18
14
  }
19
15
 
@@ -24,7 +20,7 @@ export function sha256AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer> {
24
20
  export function hash(
25
21
  s: string | Uint8Array,
26
22
  algorithm: string,
27
- outputEncoding: BinaryToTextEncoding = 'hex',
23
+ outputEncoding: BufferEncoding = 'hex',
28
24
  ): string {
29
25
  return cryptoHash(algorithm, s, outputEncoding)
30
26
  }
@@ -0,0 +1,140 @@
1
+ import { PassThrough } from 'node:stream'
2
+ import type { Writable } from 'node:stream'
3
+ import { _assert } from '@naturalcycles/js-lib/error/assert.js'
4
+ import { _noop } from '@naturalcycles/js-lib/types'
5
+ import type { ReadableTyped, WritableTyped } from './stream.model.js'
6
+
7
+ const CLOUD_STORAGE_URL_PREFIX = 'gs://'
8
+ const CLOUD_STORAGE_LIB = '@naturalcycles/cloud-storage-lib'
9
+
10
+ /**
11
+ * Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
12
+ *
13
+ * The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
14
+ * afterwards. It is the same approach as in `createReadableFromAsync`.
15
+ *
16
+ * The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
17
+ * which is an optional peer dependency.
18
+ */
19
+ export function createCloudStorageReadStream(url: string): ReadableTyped<Uint8Array> {
20
+ const { bucketName, filePath } = parseCloudStorageUrl(url)
21
+ const readable = new PassThrough()
22
+
23
+ // The read can fail before any consumer is attached, and an 'error' event without a listener
24
+ // crashes the process. With this listener the error is kept in the stream instead,
25
+ // and the consumer gets it when it attaches.
26
+ readable.on('error', _noop)
27
+
28
+ void getDefaultCloudStorage()
29
+ .then(async storage => {
30
+ await storage.getFileReadStream(bucketName, filePath).to(readable)
31
+ })
32
+ // If `readable` is already destroyed (e.g. the consumer stopped early) - this `destroy` does nothing
33
+ .catch(err => readable.destroy(err))
34
+
35
+ return readable
36
+ }
37
+
38
+ /**
39
+ * Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
40
+ *
41
+ * The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
42
+ * which is an optional peer dependency.
43
+ */
44
+ export async function createCloudStorageWriteStream(
45
+ url: string,
46
+ ): Promise<WritableTyped<Uint8Array>> {
47
+ const { bucketName, filePath } = parseCloudStorageUrl(url)
48
+ const storage = await getDefaultCloudStorage()
49
+ return storage.getFileWriteStream(bucketName, filePath)
50
+ }
51
+
52
+ function parseCloudStorageUrl(url: string): CloudStorageUrl {
53
+ assertCloudStorageUrl(url)
54
+
55
+ const [bucketName, ...pathParts] = url.slice(CLOUD_STORAGE_URL_PREFIX.length).split('/')
56
+ const filePath = pathParts.join('/')
57
+
58
+ _assert(
59
+ bucketName && filePath,
60
+ `Cloud Storage url should look like gs://bucket/path/to/file but got: ${url}`,
61
+ )
62
+
63
+ return { bucketName, filePath }
64
+ }
65
+
66
+ /**
67
+ * Throws if the given url is not a Cloud Storage url.
68
+ */
69
+ export function assertCloudStorageUrl(url: string): void {
70
+ _assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${url}`)
71
+ }
72
+
73
+ /**
74
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
75
+ */
76
+ export function isCloudStorageUrl(path: string): boolean {
77
+ return path.startsWith(CLOUD_STORAGE_URL_PREFIX)
78
+ }
79
+
80
+ async function getDefaultCloudStorage(): Promise<DefaultCloudStorage> {
81
+ const lib = await importCloudStorageLib()
82
+ return await lib.getDefaultCloudStorage()
83
+ }
84
+
85
+ /**
86
+ * cloud-storage-lib is an optional peer dependency, so it is imported lazily,
87
+ * only when a `gs://` url is actually used.
88
+ */
89
+ async function importCloudStorageLib(): Promise<CloudStorageLib> {
90
+ try {
91
+ // The package name is passed as a variable, so that TypeScript does not resolve this import,
92
+ // see the comment at CloudStorageLib
93
+ return await import(CLOUD_STORAGE_LIB)
94
+ } catch (err) {
95
+ const { code, message } = err as NodeJS.ErrnoException
96
+ // The message names the missing package in quotes. If it names another package -
97
+ // cloud-storage-lib is installed, and one of its own imports is missing.
98
+ if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`)) throw err
99
+
100
+ throw new Error(
101
+ [
102
+ `Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
103
+ 'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
104
+ `Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
105
+ ].join('\n'),
106
+ { cause: err },
107
+ )
108
+ }
109
+ }
110
+
111
+ interface CloudStorageUrl {
112
+ bucketName: string
113
+ filePath: string
114
+ }
115
+
116
+ /**
117
+ * The part of `@naturalcycles/cloud-storage-lib` that is used here.
118
+ *
119
+ * It is declared here, and not imported from there, because cloud-storage-lib depends on nodejs-lib.
120
+ * Its types resolve to the `dist` folder of nodejs-lib, which would then be both an input and the output
121
+ * of the nodejs-lib build: "Cannot write file ... because it would overwrite input file".
122
+ */
123
+ interface CloudStorageLib {
124
+ getDefaultCloudStorage: () => Promise<DefaultCloudStorage>
125
+ }
126
+
127
+ /**
128
+ * The part of `CommonStorage` that is used here.
129
+ */
130
+ interface DefaultCloudStorage {
131
+ /**
132
+ * Returns a `Pipeline<Uint8Array>`.
133
+ */
134
+ getFileReadStream: (bucketName: string, filePath: string) => PipelineTo
135
+ getFileWriteStream: (bucketName: string, filePath: string) => WritableTyped<Uint8Array>
136
+ }
137
+
138
+ interface PipelineTo {
139
+ to: (destination: Writable) => Promise<void>
140
+ }
@@ -3,6 +3,7 @@ import { pipeline } from 'node:stream'
3
3
  import { createUnzip, createZstdDecompress } from 'node:zlib'
4
4
  import { _noop } from '@naturalcycles/js-lib/types'
5
5
  import { fs2 } from '../../fs/fs2.js'
6
+ import { createCloudStorageReadStream, isCloudStorageUrl } from '../cloudStorageStream.js'
6
7
  import type { ReadableTyped } from '../stream.model.js'
7
8
  import { transformSplitOnNewline } from '../transform/transformSplit.js'
8
9
  import { transformJsonParse } from './transformJsonParse.js'
@@ -20,16 +21,14 @@ import { transformJsonParse } from './transformJsonParse.js'
20
21
  To add a Limit or Offset: just add .take() or .drop(), example:
21
22
 
22
23
  createReadStreamAsNDJson().take(100)
24
+
25
+ inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorageFile`.
26
+ A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
27
+ Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
23
28
  */
24
29
 
25
30
  export function createReadStreamAsNDJson<ROW = any>(inputPath: string): ReadableTyped<ROW> {
26
- fs2.requireFileToExist(inputPath)
27
-
28
- const streams: Readable[] = [
29
- fs2.createReadStream(inputPath, {
30
- highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
31
- }),
32
- ]
31
+ const streams: Readable[] = [createFileReadStream(inputPath)]
33
32
 
34
33
  if (inputPath.endsWith('.gz')) {
35
34
  streams.push(
@@ -59,3 +58,14 @@ export function createReadStreamAsNDJson<ROW = any>(inputPath: string): Readable
59
58
  // ~5000 vs ~4000 rps !!!". Measured again on Node 24, it's the opposite: Readable.map costs ~1µs per row in promise machinery,
60
59
  // transformJsonParse() is 1.5x (consumed via pipeline) to 1.75x (consumed via for-await) faster on ~180B rows.
61
60
  }
61
+
62
+ function createFileReadStream(inputPath: string): Readable {
63
+ // A Cloud Storage file is not checked for existence upfront: if it is missing - the stream fails
64
+ if (isCloudStorageUrl(inputPath)) return createCloudStorageReadStream(inputPath)
65
+
66
+ fs2.requireFileToExist(inputPath)
67
+
68
+ return fs2.createReadStream(inputPath, {
69
+ highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
70
+ })
71
+ }
@@ -22,6 +22,12 @@ import type {
22
22
  } from '@naturalcycles/js-lib/types'
23
23
  import { fs2 } from '../fs/fs2.js'
24
24
  import { zip2 } from '../zip/zip2.js'
25
+ import {
26
+ assertCloudStorageUrl,
27
+ createCloudStorageReadStream,
28
+ createCloudStorageWriteStream,
29
+ isCloudStorageUrl,
30
+ } from './cloudStorageStream.js'
25
31
  import { createReadStreamAsNDJson } from './ndjson/createReadStreamAsNDJson.js'
26
32
  import { transformJsonParse } from './ndjson/transformJsonParse.js'
27
33
  import { transformToNDJson } from './ndjson/transformToNDJson.js'
@@ -101,6 +107,10 @@ export class Pipeline<T = unknown> {
101
107
  return new Pipeline(Readable.from(input))
102
108
  }
103
109
 
110
+ /**
111
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
112
+ * see `fromCloudStorageFile`.
113
+ */
104
114
  static fromNDJsonFile<T>(sourceFilePath: string): Pipeline<T> {
105
115
  // Important that createReadStreamAsNDJson function is used
106
116
  // (and not Pipeline set of individual transforms),
@@ -110,7 +120,13 @@ export class Pipeline<T = unknown> {
110
120
  return new Pipeline<T>(createReadStreamAsNDJson(sourceFilePath))
111
121
  }
112
122
 
123
+ /**
124
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
125
+ * see `fromCloudStorageFile`.
126
+ */
113
127
  static fromFile(sourceFilePath: string): Pipeline<Uint8Array> {
128
+ if (isCloudStorageUrl(sourceFilePath)) return Pipeline.fromCloudStorageFile(sourceFilePath)
129
+
114
130
  return new Pipeline(
115
131
  fs2.createReadStream(sourceFilePath, {
116
132
  highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
@@ -119,6 +135,28 @@ export class Pipeline<T = unknown> {
119
135
  )
120
136
  }
121
137
 
138
+ /**
139
+ * Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
140
+ * Same as `fromFile`, but it throws if the url does not start with `gs://`.
141
+ *
142
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
143
+ * Its default storage is used (see `getDefaultCloudStorage` there):
144
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
145
+ */
146
+ static fromCloudStorageFile(url: string): Pipeline<Uint8Array> {
147
+ return new Pipeline(createCloudStorageReadStream(url), false)
148
+ }
149
+
150
+ /**
151
+ * Same as `fromNDJsonFile`, but it throws if the url does not start with `gs://`.
152
+ * See `fromCloudStorageFile` for the requirements.
153
+ */
154
+ static fromCloudStorageNDJsonFile<T>(url: string): Pipeline<T> {
155
+ assertCloudStorageUrl(url)
156
+ // createReadStreamAsNDJson is used for the same reason as in fromNDJsonFile
157
+ return new Pipeline<T>(createReadStreamAsNDJson(url))
158
+ }
159
+
122
160
  /**
123
161
  * Limits the source Readable, but using `.take(limit)` on it.
124
162
  * This is THE preferred way of limiting the source.
@@ -374,21 +412,44 @@ export class Pipeline<T = unknown> {
374
412
  return arr
375
413
  }
376
414
 
415
+ /**
416
+ * Same as `toFile`, but it rejects if the url does not start with `gs://`.
417
+ * See `fromCloudStorageFile` for the requirements.
418
+ */
419
+ async toCloudStorageFile(url: string): Promise<void> {
420
+ this.requireCloudStorageUrl(url)
421
+ await this.toFile(url)
422
+ }
423
+
424
+ /**
425
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
426
+ * see `fromCloudStorageFile` for the requirements.
427
+ */
377
428
  async toFile(outputFilePath: string): Promise<void> {
378
- fs2.ensureFile(outputFilePath)
379
- this.destination = fs2.createWriteStream(outputFilePath)
429
+ this.destination = await this.createFileWriteStream(outputFilePath)
380
430
  await this.run()
381
431
  }
382
432
 
433
+ /**
434
+ * Same as `toNDJsonFile`, but it rejects if the url does not start with `gs://`.
435
+ * See `fromCloudStorageFile` for the requirements.
436
+ */
437
+ async toCloudStorageNDJsonFile(url: string, level?: Integer): Promise<void> {
438
+ this.requireCloudStorageUrl(url)
439
+ await this.toNDJsonFile(url, level)
440
+ }
441
+
383
442
  /**
384
443
  * level corresponds to zstd compression level (if filename ends with .zst),
385
444
  * or gzip compression level (if filename ends with .gz).
386
445
  * Default levels are:
387
446
  * gzip: 6
388
447
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
448
+ *
449
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
450
+ * see `fromCloudStorageFile` for the requirements.
389
451
  */
390
452
  async toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void> {
391
- fs2.ensureFile(outputFilePath)
392
453
  this.transforms.push(transformToNDJson())
393
454
  if (outputFilePath.endsWith('.gz')) {
394
455
  this.transforms.push(
@@ -400,9 +461,7 @@ export class Pipeline<T = unknown> {
400
461
  } else if (outputFilePath.endsWith('.zst')) {
401
462
  this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)))
402
463
  }
403
- this.destination = fs2.createWriteStream(outputFilePath, {
404
- // highWaterMark: 64 * 1024, // no observed speedup
405
- })
464
+ this.destination = await this.createFileWriteStream(outputFilePath)
406
465
  await this.run()
407
466
  }
408
467
 
@@ -472,4 +531,36 @@ export class Pipeline<T = unknown> {
472
531
  const { aborted, reason } = this.abortableSignal
473
532
  return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT
474
533
  }
534
+
535
+ /**
536
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
537
+ */
538
+ private async createFileWriteStream(outputFilePath: string): Promise<NodeJS.WritableStream> {
539
+ try {
540
+ if (isCloudStorageUrl(outputFilePath)) {
541
+ return await createCloudStorageWriteStream(outputFilePath)
542
+ }
543
+
544
+ fs2.ensureFile(outputFilePath)
545
+
546
+ return fs2.createWriteStream(outputFilePath, {
547
+ // highWaterMark: 64 * 1024, // no observed speedup
548
+ })
549
+ } catch (err) {
550
+ // The pipeline does not run, so nothing else closes the source, which can hold an open file
551
+ // or connection. It is destroyed without the error: nothing listens to its 'error' event here.
552
+ this.source.destroy()
553
+ throw err
554
+ }
555
+ }
556
+
557
+ private requireCloudStorageUrl(url: string): void {
558
+ try {
559
+ assertCloudStorageUrl(url)
560
+ } catch (err) {
561
+ // Same as in createFileWriteStream: the pipeline does not run, so the source is closed here
562
+ this.source.destroy()
563
+ throw err
564
+ }
565
+ }
475
566
  }
@@ -1,5 +1,6 @@
1
1
  import { Readable, Transform } from 'node:stream'
2
2
  import type { ReadableOptions } from 'node:stream'
3
+ import { _noop } from '@naturalcycles/js-lib/types'
3
4
  import type { ReadableTyped } from '../stream.model.js'
4
5
 
5
6
  /**
@@ -56,6 +57,11 @@ export function createReadableFromAsync<T>(fn: () => Promise<ReadableTyped<T>>):
56
57
  },
57
58
  })
58
59
 
60
+ // `fn` or the source Readable can fail before any consumer is attached, and an 'error' event
61
+ // without a listener crashes the process. With this listener the error is kept in the stream instead,
62
+ // and the consumer gets it when it attaches.
63
+ transform.on('error', _noop)
64
+
59
65
  void fn()
60
66
  .then(readable => {
61
67
  readable.on('error', err => transform.destroy(err)).pipe(transform)
@@ -130,7 +130,6 @@ export function transformThrottleByRSS<T>(
130
130
  `transformThrottleByRSS pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB`,
131
131
  ),
132
132
  )
133
- lock = undefined
134
133
  } else {
135
134
  // open-the-floodgates
136
135
  logger.error(
@@ -138,8 +137,8 @@ export function transformThrottleByRSS<T>(
138
137
  )
139
138
  disabled = true
140
139
  lock!.resolve()
141
- lock = undefined
142
140
  }
141
+ lock = undefined
143
142
  } else {
144
143
  logger.log(
145
144
  `${localTime.now().toPretty()} transformThrottleByRSS still paused: RSS ${_mb(rss)} > ${maxRSS} MB, rechecking in ${_ms(pollInterval)}`,
@@ -1,8 +1,9 @@
1
- // oxlint-disable-next-line no-restricted-globals -- the worker entry stays dependency-free
2
- const started = Date.now()
3
1
  import { inspect } from 'node:util'
4
2
  import { workerData, parentPort } from 'node:worker_threads'
5
3
 
4
+ // oxlint-disable-next-line no-restricted-globals -- the worker entry stays dependency-free
5
+ const started = Date.now()
6
+
6
7
  const { workerFile, workerIndex, logEvery = 1000, metric = 'worker', silent } = workerData || {}
7
8
 
8
9
  // The worker entry stays dependency-free, so no `_assert` here
@@ -75,7 +75,7 @@ export function mergeJsonSchemaObjects<T1 extends AnyObject, T2 extends AnyObjec
75
75
 
76
76
  // Merge `required`
77
77
  s1.required.push(...s2.required)
78
- s1.required = _uniq(s1.required).sort()
78
+ s1.required = _uniq(s1.required as string[]).sort()
79
79
 
80
80
  // `additionalProperties` remains the same, unless s2 is a string map (schema-valued)
81
81
  if (typeof s2.additionalProperties === 'object') {