|
| 1 | +import * as zlib from 'zlib'; |
| 2 | + |
1 | 3 | import { type Stream } from './cmap/connect'; |
2 | 4 | import { MongoMissingDependencyError } from './error'; |
3 | 5 | import type { Callback } from './utils'; |
@@ -60,15 +62,49 @@ type ZStandardLib = { |
60 | 62 |
|
61 | 63 | export type ZStandard = ZStandardLib | { kModuleError: MongoMissingDependencyError }; |
62 | 64 |
|
| 65 | +function getBuiltInZstdLibrary(): ZStandardLib | null { |
| 66 | + if (typeof zlib.zstdCompress !== 'function' || typeof zlib.zstdDecompress !== 'function') { |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + return { |
| 71 | + compress(buf: Uint8Array, level?: number): Promise<Uint8Array> { |
| 72 | + return new Promise((resolve, reject) => { |
| 73 | + zlib.zstdCompress( |
| 74 | + buf, |
| 75 | + level == null ? {} : { params: { [zlib.constants.ZSTD_c_compressionLevel]: level } }, |
| 76 | + (error, result) => { |
| 77 | + if (error) return reject(error); |
| 78 | + resolve(result); |
| 79 | + } |
| 80 | + ); |
| 81 | + }); |
| 82 | + }, |
| 83 | + decompress(buf: Uint8Array): Promise<Uint8Array> { |
| 84 | + return new Promise((resolve, reject) => { |
| 85 | + zlib.zstdDecompress(buf, (error, result) => { |
| 86 | + if (error) return reject(error); |
| 87 | + resolve(result); |
| 88 | + }); |
| 89 | + }); |
| 90 | + } |
| 91 | + }; |
| 92 | +} |
| 93 | + |
63 | 94 | export function getZstdLibrary(): ZStandardLib | { kModuleError: MongoMissingDependencyError } { |
| 95 | + const builtInZstdLibrary = getBuiltInZstdLibrary(); |
| 96 | + if (builtInZstdLibrary != null) { |
| 97 | + return builtInZstdLibrary; |
| 98 | + } |
| 99 | + |
64 | 100 | let ZStandard: ZStandardLib | { kModuleError: MongoMissingDependencyError }; |
65 | 101 | try { |
66 | 102 | // eslint-disable-next-line @typescript-eslint/no-require-imports |
67 | 103 | ZStandard = require('@mongodb-js/zstd'); |
68 | 104 | } catch (error) { |
69 | 105 | ZStandard = makeErrorModule( |
70 | 106 | new MongoMissingDependencyError( |
71 | | - 'Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression', |
| 107 | + 'Built-in zstd support is unavailable and optional module `@mongodb-js/zstd` not found. Please use Node.js 22.15.0+ or install `@mongodb-js/zstd` to enable zstd compression', |
72 | 108 | { cause: error, dependencyName: 'zstd' } |
73 | 109 | ) |
74 | 110 | ); |
|
0 commit comments