@naturalcycles/nodejs-lib 15.146.0 → 15.148.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fs/fs2.js CHANGED
@@ -271,11 +271,9 @@ class FS2 {
271
271
  * Doesn't throw, returns false instead.
272
272
  */
273
273
  isDirectory(filePath) {
274
- return (fs2
275
- .stat(filePath, {
274
+ return (this.stat(filePath, {
276
275
  throwIfNoEntry: false,
277
- })
278
- ?.isDirectory() || false);
276
+ })?.isDirectory() || false);
279
277
  }
280
278
  // Re-export the whole fs/fsp, for the edge cases where they are needed
281
279
  fs = fs;
@@ -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,22 @@
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
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
21
+ */
22
+ export declare function isCloudStorageUrl(path: string): boolean;
@@ -0,0 +1,80 @@
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
+ _assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${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
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
50
+ */
51
+ export function isCloudStorageUrl(path) {
52
+ return path.startsWith(CLOUD_STORAGE_URL_PREFIX);
53
+ }
54
+ async function getDefaultCloudStorage() {
55
+ const lib = await importCloudStorageLib();
56
+ return await lib.getDefaultCloudStorage();
57
+ }
58
+ /**
59
+ * cloud-storage-lib is an optional peer dependency, so it is imported lazily,
60
+ * only when a `gs://` url is actually used.
61
+ */
62
+ async function importCloudStorageLib() {
63
+ try {
64
+ // The package name is passed as a variable, so that TypeScript does not resolve this import,
65
+ // see the comment at CloudStorageLib
66
+ return await import(CLOUD_STORAGE_LIB);
67
+ }
68
+ catch (err) {
69
+ const { code, message } = err;
70
+ // The message names the missing package in quotes. If it names another package -
71
+ // cloud-storage-lib is installed, and one of its own imports is missing.
72
+ if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`))
73
+ throw err;
74
+ throw new Error([
75
+ `Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
76
+ 'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
77
+ `Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
78
+ ].join('\n'), { cause: err });
79
+ }
80
+ }
@@ -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.fromCloudStorage`.
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.fromCloudStorage`.
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,24 @@ 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 `fromCloudStorage`.
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 `fromCloudStorage`.
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
+ *
48
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
49
+ * Its default storage is used (see `getDefaultCloudStorage` there):
50
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
51
+ */
52
+ static fromCloudStorage(url: string): Pipeline<Uint8Array>;
37
53
  /**
38
54
  * Limits the source Readable, but using `.take(limit)` on it.
39
55
  * This is THE preferred way of limiting the source.
@@ -98,6 +114,10 @@ export declare class Pipeline<T = unknown> {
98
114
  opt?: ZstdOptions): Pipeline<Uint8Array>;
99
115
  zstdDecompress(this: Pipeline<Uint8Array>, opt?: ZstdOptions): Pipeline<Uint8Array>;
100
116
  toArray(opt?: TransformOptions): Promise<T[]>;
117
+ /**
118
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
119
+ * see `fromCloudStorage` for the requirements.
120
+ */
101
121
  toFile(outputFilePath: string): Promise<void>;
102
122
  /**
103
123
  * level corresponds to zstd compression level (if filename ends with .zst),
@@ -105,6 +125,9 @@ export declare class Pipeline<T = unknown> {
105
125
  * Default levels are:
106
126
  * gzip: 6
107
127
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
128
+ *
129
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
130
+ * see `fromCloudStorage` for the requirements.
108
131
  */
109
132
  toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void>;
110
133
  to(destination: WritableTyped<T>): Promise<void>;
@@ -112,4 +135,8 @@ export declare class Pipeline<T = unknown> {
112
135
  forEachSync(fn: AbortableMapper<T, void>, opt?: TransformMapSyncOptions<T, void> & TransformLogProgressOptions<T>): Promise<void>;
113
136
  run(): Promise<void>;
114
137
  private isGracefullyAborted;
138
+ /**
139
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
140
+ */
141
+ private createFileWriteStream;
115
142
  }
@@ -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 { 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 `fromCloudStorage`.
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,27 @@ 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 `fromCloudStorage`.
81
+ */
73
82
  static fromFile(sourceFilePath) {
83
+ if (isCloudStorageUrl(sourceFilePath))
84
+ return Pipeline.fromCloudStorage(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
+ *
92
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
93
+ * Its default storage is used (see `getDefaultCloudStorage` there):
94
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
95
+ */
96
+ static fromCloudStorage(url) {
97
+ return new Pipeline(createCloudStorageReadStream(url), false);
98
+ }
78
99
  /**
79
100
  * Limits the source Readable, but using `.take(limit)` on it.
80
101
  * This is THE preferred way of limiting the source.
@@ -272,9 +293,12 @@ export class Pipeline {
272
293
  await this.run();
273
294
  return arr;
274
295
  }
296
+ /**
297
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
298
+ * see `fromCloudStorage` for the requirements.
299
+ */
275
300
  async toFile(outputFilePath) {
276
- fs2.ensureFile(outputFilePath);
277
- this.destination = fs2.createWriteStream(outputFilePath);
301
+ this.destination = await this.createFileWriteStream(outputFilePath);
278
302
  await this.run();
279
303
  }
280
304
  /**
@@ -283,9 +307,11 @@ export class Pipeline {
283
307
  * Default levels are:
284
308
  * gzip: 6
285
309
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
310
+ *
311
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
312
+ * see `fromCloudStorage` for the requirements.
286
313
  */
287
314
  async toNDJsonFile(outputFilePath, level) {
288
- fs2.ensureFile(outputFilePath);
289
315
  this.transforms.push(transformToNDJson());
290
316
  if (outputFilePath.endsWith('.gz')) {
291
317
  this.transforms.push(createGzip({
@@ -296,9 +322,7 @@ export class Pipeline {
296
322
  else if (outputFilePath.endsWith('.zst')) {
297
323
  this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)));
298
324
  }
299
- this.destination = fs2.createWriteStream(outputFilePath, {
300
- // highWaterMark: 64 * 1024, // no observed speedup
301
- });
325
+ this.destination = await this.createFileWriteStream(outputFilePath);
302
326
  await this.run();
303
327
  }
304
328
  async to(destination) {
@@ -353,4 +377,24 @@ export class Pipeline {
353
377
  const { aborted, reason } = this.abortableSignal;
354
378
  return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT;
355
379
  }
380
+ /**
381
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
382
+ */
383
+ async createFileWriteStream(outputFilePath) {
384
+ try {
385
+ if (isCloudStorageUrl(outputFilePath)) {
386
+ return await createCloudStorageWriteStream(outputFilePath);
387
+ }
388
+ fs2.ensureFile(outputFilePath);
389
+ return fs2.createWriteStream(outputFilePath, {
390
+ // highWaterMark: 64 * 1024, // no observed speedup
391
+ });
392
+ }
393
+ catch (err) {
394
+ // The pipeline does not run, so nothing else closes the source, which can hold an open file
395
+ // or connection. It is destroyed without the error: nothing listens to its 'error' event here.
396
+ this.source.destroy();
397
+ throw err;
398
+ }
399
+ }
356
400
  }
@@ -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)}`);
@@ -430,17 +430,15 @@ export declare class JObjectInfer<PROPS extends Record<string, JSchema<any, any>
430
430
  * When set, the validation will not strip away properties that are not specified explicitly in the schema.
431
431
  */
432
432
  allowAdditionalProperties(): this;
433
- extend<NEW_PROPS extends Record<string, JSchema<any, any>>>(props: NEW_PROPS): JObjectInfer<{
434
- [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS ? NEW_PROPS[K] : K extends keyof PROPS ? PROPS[K] : never;
435
- }, Opt>;
433
+ extend<NEW_PROPS extends Record<string, JSchema<any, any>>>(props: NEW_PROPS): JObjectInfer<ExtendedProps<PROPS, NEW_PROPS>, Opt>;
436
434
  /**
437
435
  * Extends the current schema with `id`, `created` and `updated` according to NC DB conventions.
438
436
  */
439
- dbEntity(): JObjectInfer<{ [K in "created" | "id" | "updated" | keyof PROPS]: K extends "created" | "id" | "updated" ? {
437
+ dbEntity(): JObjectInfer<ExtendedProps<PROPS, {
440
438
  id: JString<string, false>;
441
439
  created: JNumber<UnixTimestamp, false>;
442
440
  updated: JNumber<UnixTimestamp, false>;
443
- }[K] : K extends keyof PROPS ? PROPS[K] : never; }, Opt>;
441
+ }>, Opt>;
444
442
  }
445
443
  export declare class JArray<OUT, Opt, ARR extends OUT[] = OUT[]> extends JBuilder<ARR, Opt> {
446
444
  constructor(itemsSchema: JSchema<OUT, Opt>);
@@ -709,6 +707,15 @@ type RelaxIndexSignature<T> = T extends readonly unknown[] ? T : T extends AnyOb
709
707
  [K in keyof T]: RelaxIndexSignature<T[K]>;
710
708
  } : T;
711
709
  type Override<T, U> = Omit<T, keyof U> & U;
710
+ /**
711
+ * Props of `JObjectInfer.extend()`: NEW_PROPS override PROPS with the same key.
712
+ *
713
+ * A named alias keeps the return type annotation and the cast in `extend()` identical.
714
+ * TypeScript 7.1 reports two separately written copies of this mapped type as unrelated (TS2719).
715
+ */
716
+ type ExtendedProps<PROPS, NEW_PROPS> = {
717
+ [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS ? NEW_PROPS[K] : K extends keyof PROPS ? PROPS[K] : never;
718
+ };
712
719
  declare const allowExtraKeysSymbol: unique symbol;
713
720
  type HasAllowExtraKeys<T> = T extends {
714
721
  readonly [allowExtraKeysSymbol]?: true;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/nodejs-lib",
3
3
  "type": "module",
4
- "version": "15.146.0",
4
+ "version": "15.148.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.73.0",
25
+ "@naturalcycles/cloud-storage-lib": "2.19.0",
26
+ "@naturalcycles/dev-lib": "0.0.0",
18
27
  "typescript": "^7"
19
28
  },
20
29
  "exports": {
package/src/fs/fs2.ts CHANGED
@@ -312,11 +312,9 @@ class FS2 {
312
312
  */
313
313
  isDirectory(filePath: string): boolean {
314
314
  return (
315
- fs2
316
- .stat(filePath, {
317
- throwIfNoEntry: false,
318
- })
319
- ?.isDirectory() || false
315
+ this.stat(filePath, {
316
+ throwIfNoEntry: false,
317
+ })?.isDirectory() || false
320
318
  )
321
319
  }
322
320
 
@@ -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,133 @@
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
+ _assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${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
+ * Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
68
+ */
69
+ export function isCloudStorageUrl(path: string): boolean {
70
+ return path.startsWith(CLOUD_STORAGE_URL_PREFIX)
71
+ }
72
+
73
+ async function getDefaultCloudStorage(): Promise<DefaultCloudStorage> {
74
+ const lib = await importCloudStorageLib()
75
+ return await lib.getDefaultCloudStorage()
76
+ }
77
+
78
+ /**
79
+ * cloud-storage-lib is an optional peer dependency, so it is imported lazily,
80
+ * only when a `gs://` url is actually used.
81
+ */
82
+ async function importCloudStorageLib(): Promise<CloudStorageLib> {
83
+ try {
84
+ // The package name is passed as a variable, so that TypeScript does not resolve this import,
85
+ // see the comment at CloudStorageLib
86
+ return await import(CLOUD_STORAGE_LIB)
87
+ } catch (err) {
88
+ const { code, message } = err as NodeJS.ErrnoException
89
+ // The message names the missing package in quotes. If it names another package -
90
+ // cloud-storage-lib is installed, and one of its own imports is missing.
91
+ if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`)) throw err
92
+
93
+ throw new Error(
94
+ [
95
+ `Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
96
+ 'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
97
+ `Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
98
+ ].join('\n'),
99
+ { cause: err },
100
+ )
101
+ }
102
+ }
103
+
104
+ interface CloudStorageUrl {
105
+ bucketName: string
106
+ filePath: string
107
+ }
108
+
109
+ /**
110
+ * The part of `@naturalcycles/cloud-storage-lib` that is used here.
111
+ *
112
+ * It is declared here, and not imported from there, because cloud-storage-lib depends on nodejs-lib.
113
+ * Its types resolve to the `dist` folder of nodejs-lib, which would then be both an input and the output
114
+ * of the nodejs-lib build: "Cannot write file ... because it would overwrite input file".
115
+ */
116
+ interface CloudStorageLib {
117
+ getDefaultCloudStorage: () => Promise<DefaultCloudStorage>
118
+ }
119
+
120
+ /**
121
+ * The part of `CommonStorage` that is used here.
122
+ */
123
+ interface DefaultCloudStorage {
124
+ /**
125
+ * Returns a `Pipeline<Uint8Array>`.
126
+ */
127
+ getFileReadStream: (bucketName: string, filePath: string) => PipelineTo
128
+ getFileWriteStream: (bucketName: string, filePath: string) => WritableTyped<Uint8Array>
129
+ }
130
+
131
+ interface PipelineTo {
132
+ to: (destination: Writable) => Promise<void>
133
+ }
@@ -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.fromCloudStorage`.
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,11 @@ 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
+ createCloudStorageReadStream,
27
+ createCloudStorageWriteStream,
28
+ isCloudStorageUrl,
29
+ } from './cloudStorageStream.js'
25
30
  import { createReadStreamAsNDJson } from './ndjson/createReadStreamAsNDJson.js'
26
31
  import { transformJsonParse } from './ndjson/transformJsonParse.js'
27
32
  import { transformToNDJson } from './ndjson/transformToNDJson.js'
@@ -101,6 +106,10 @@ export class Pipeline<T = unknown> {
101
106
  return new Pipeline(Readable.from(input))
102
107
  }
103
108
 
109
+ /**
110
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
111
+ * see `fromCloudStorage`.
112
+ */
104
113
  static fromNDJsonFile<T>(sourceFilePath: string): Pipeline<T> {
105
114
  // Important that createReadStreamAsNDJson function is used
106
115
  // (and not Pipeline set of individual transforms),
@@ -110,7 +119,13 @@ export class Pipeline<T = unknown> {
110
119
  return new Pipeline<T>(createReadStreamAsNDJson(sourceFilePath))
111
120
  }
112
121
 
122
+ /**
123
+ * sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
124
+ * see `fromCloudStorage`.
125
+ */
113
126
  static fromFile(sourceFilePath: string): Pipeline<Uint8Array> {
127
+ if (isCloudStorageUrl(sourceFilePath)) return Pipeline.fromCloudStorage(sourceFilePath)
128
+
114
129
  return new Pipeline(
115
130
  fs2.createReadStream(sourceFilePath, {
116
131
  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 +134,17 @@ export class Pipeline<T = unknown> {
119
134
  )
120
135
  }
121
136
 
137
+ /**
138
+ * Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
139
+ *
140
+ * Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
141
+ * Its default storage is used (see `getDefaultCloudStorage` there):
142
+ * it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
143
+ */
144
+ static fromCloudStorage(url: string): Pipeline<Uint8Array> {
145
+ return new Pipeline(createCloudStorageReadStream(url), false)
146
+ }
147
+
122
148
  /**
123
149
  * Limits the source Readable, but using `.take(limit)` on it.
124
150
  * This is THE preferred way of limiting the source.
@@ -374,9 +400,12 @@ export class Pipeline<T = unknown> {
374
400
  return arr
375
401
  }
376
402
 
403
+ /**
404
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
405
+ * see `fromCloudStorage` for the requirements.
406
+ */
377
407
  async toFile(outputFilePath: string): Promise<void> {
378
- fs2.ensureFile(outputFilePath)
379
- this.destination = fs2.createWriteStream(outputFilePath)
408
+ this.destination = await this.createFileWriteStream(outputFilePath)
380
409
  await this.run()
381
410
  }
382
411
 
@@ -386,9 +415,11 @@ export class Pipeline<T = unknown> {
386
415
  * Default levels are:
387
416
  * gzip: 6
388
417
  * zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
418
+ *
419
+ * outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
420
+ * see `fromCloudStorage` for the requirements.
389
421
  */
390
422
  async toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void> {
391
- fs2.ensureFile(outputFilePath)
392
423
  this.transforms.push(transformToNDJson())
393
424
  if (outputFilePath.endsWith('.gz')) {
394
425
  this.transforms.push(
@@ -400,9 +431,7 @@ export class Pipeline<T = unknown> {
400
431
  } else if (outputFilePath.endsWith('.zst')) {
401
432
  this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)))
402
433
  }
403
- this.destination = fs2.createWriteStream(outputFilePath, {
404
- // highWaterMark: 64 * 1024, // no observed speedup
405
- })
434
+ this.destination = await this.createFileWriteStream(outputFilePath)
406
435
  await this.run()
407
436
  }
408
437
 
@@ -472,4 +501,26 @@ export class Pipeline<T = unknown> {
472
501
  const { aborted, reason } = this.abortableSignal
473
502
  return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT
474
503
  }
504
+
505
+ /**
506
+ * Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
507
+ */
508
+ private async createFileWriteStream(outputFilePath: string): Promise<NodeJS.WritableStream> {
509
+ try {
510
+ if (isCloudStorageUrl(outputFilePath)) {
511
+ return await createCloudStorageWriteStream(outputFilePath)
512
+ }
513
+
514
+ fs2.ensureFile(outputFilePath)
515
+
516
+ return fs2.createWriteStream(outputFilePath, {
517
+ // highWaterMark: 64 * 1024, // no observed speedup
518
+ })
519
+ } catch (err) {
520
+ // The pipeline does not run, so nothing else closes the source, which can hold an open file
521
+ // or connection. It is destroyed without the error: nothing listens to its 'error' event here.
522
+ this.source.destroy()
523
+ throw err
524
+ }
525
+ }
475
526
  }
@@ -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
@@ -1306,16 +1306,7 @@ export class JObjectInfer<
1306
1306
 
1307
1307
  extend<NEW_PROPS extends Record<string, JSchema<any, any>>>(
1308
1308
  props: NEW_PROPS,
1309
- ): JObjectInfer<
1310
- {
1311
- [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS
1312
- ? NEW_PROPS[K]
1313
- : K extends keyof PROPS
1314
- ? PROPS[K]
1315
- : never
1316
- },
1317
- Opt
1318
- > {
1309
+ ): JObjectInfer<ExtendedProps<PROPS, NEW_PROPS>, Opt> {
1319
1310
  const newBuilder = new JObjectInfer<PROPS, Opt>()
1320
1311
  _objectAssign(newBuilder.schema, deepCopyPreservingFunctions(this.schema))
1321
1312
 
@@ -1327,16 +1318,7 @@ export class JObjectInfer<
1327
1318
  // the new schema loses that quality.
1328
1319
  _objectAssign(newBuilder.schema, { hasIsOfTypeCheck: false })
1329
1320
 
1330
- return newBuilder as any as JObjectInfer<
1331
- {
1332
- [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS
1333
- ? NEW_PROPS[K]
1334
- : K extends keyof PROPS
1335
- ? PROPS[K]
1336
- : never
1337
- },
1338
- Opt
1339
- >
1321
+ return newBuilder as any as JObjectInfer<ExtendedProps<PROPS, NEW_PROPS>, Opt>
1340
1322
  }
1341
1323
 
1342
1324
  /**
@@ -2283,6 +2265,20 @@ type RelaxIndexSignature<T> = T extends readonly unknown[]
2283
2265
 
2284
2266
  type Override<T, U> = Omit<T, keyof U> & U
2285
2267
 
2268
+ /**
2269
+ * Props of `JObjectInfer.extend()`: NEW_PROPS override PROPS with the same key.
2270
+ *
2271
+ * A named alias keeps the return type annotation and the cast in `extend()` identical.
2272
+ * TypeScript 7.1 reports two separately written copies of this mapped type as unrelated (TS2719).
2273
+ */
2274
+ type ExtendedProps<PROPS, NEW_PROPS> = {
2275
+ [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS
2276
+ ? NEW_PROPS[K]
2277
+ : K extends keyof PROPS
2278
+ ? PROPS[K]
2279
+ : never
2280
+ }
2281
+
2286
2282
  declare const allowExtraKeysSymbol: unique symbol
2287
2283
 
2288
2284
  type HasAllowExtraKeys<T> = T extends { readonly [allowExtraKeysSymbol]?: true } ? true : false
@@ -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') {