react-native-nitro-net 0.2.0 → 0.3.1

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.
Files changed (83) hide show
  1. package/README.md +70 -12
  2. package/android/libs/arm64-v8a/librust_c_net.so +0 -0
  3. package/android/libs/armeabi-v7a/librust_c_net.so +0 -0
  4. package/android/libs/x86/librust_c_net.so +0 -0
  5. package/android/libs/x86_64/librust_c_net.so +0 -0
  6. package/cpp/HybridHttpParser.hpp +67 -0
  7. package/cpp/HybridNetDriver.hpp +6 -0
  8. package/cpp/HybridNetServerDriver.hpp +7 -0
  9. package/cpp/HybridNetSocketDriver.hpp +27 -0
  10. package/cpp/NetBindings.hpp +15 -0
  11. package/ios/Frameworks/RustCNet.xcframework/Info.plist +5 -5
  12. package/ios/Frameworks/RustCNet.xcframework/ios-arm64/RustCNet.framework/RustCNet +0 -0
  13. package/ios/Frameworks/RustCNet.xcframework/ios-arm64_x86_64-simulator/RustCNet.framework/RustCNet +0 -0
  14. package/lib/Driver.d.ts +1 -0
  15. package/lib/Driver.d.ts.map +1 -0
  16. package/lib/Driver.js +2 -5
  17. package/lib/Net.nitro.d.ts +20 -0
  18. package/lib/Net.nitro.d.ts.map +1 -0
  19. package/lib/Net.nitro.js +4 -7
  20. package/lib/http.d.ts +204 -0
  21. package/lib/http.d.ts.map +1 -0
  22. package/lib/http.js +1126 -0
  23. package/lib/https.d.ts +25 -0
  24. package/lib/https.d.ts.map +1 -0
  25. package/lib/https.js +102 -0
  26. package/lib/index.d.ts +41 -160
  27. package/lib/index.d.ts.map +1 -0
  28. package/lib/index.js +11 -821
  29. package/lib/net.d.ts +197 -0
  30. package/lib/net.d.ts.map +1 -0
  31. package/lib/net.js +875 -0
  32. package/lib/tls.d.ts +23 -1
  33. package/lib/tls.d.ts.map +1 -0
  34. package/lib/tls.js +108 -54
  35. package/nitrogen/generated/android/RustCNet+autolinking.cmake +2 -0
  36. package/nitrogen/generated/android/RustCNetOnLoad.cpp +2 -0
  37. package/nitrogen/generated/android/c++/JHybridHttpParserSpec.cpp +54 -0
  38. package/nitrogen/generated/android/c++/JHybridHttpParserSpec.hpp +65 -0
  39. package/nitrogen/generated/android/c++/JHybridNetDriverSpec.cpp +9 -0
  40. package/nitrogen/generated/android/c++/JHybridNetDriverSpec.hpp +1 -0
  41. package/nitrogen/generated/android/c++/JHybridNetServerDriverSpec.cpp +4 -0
  42. package/nitrogen/generated/android/c++/JHybridNetServerDriverSpec.hpp +1 -0
  43. package/nitrogen/generated/android/c++/JHybridNetSocketDriverSpec.cpp +9 -0
  44. package/nitrogen/generated/android/c++/JHybridNetSocketDriverSpec.hpp +2 -0
  45. package/nitrogen/generated/android/c++/JNetConfig.hpp +7 -3
  46. package/nitrogen/generated/android/kotlin/com/margelo/nitro/net/HybridHttpParserSpec.kt +58 -0
  47. package/nitrogen/generated/android/kotlin/com/margelo/nitro/net/HybridNetDriverSpec.kt +4 -0
  48. package/nitrogen/generated/android/kotlin/com/margelo/nitro/net/HybridNetServerDriverSpec.kt +4 -0
  49. package/nitrogen/generated/android/kotlin/com/margelo/nitro/net/HybridNetSocketDriverSpec.kt +8 -0
  50. package/nitrogen/generated/android/kotlin/com/margelo/nitro/net/NetConfig.kt +6 -3
  51. package/nitrogen/generated/ios/RustCNet-Swift-Cxx-Bridge.cpp +17 -0
  52. package/nitrogen/generated/ios/RustCNet-Swift-Cxx-Bridge.hpp +26 -0
  53. package/nitrogen/generated/ios/RustCNet-Swift-Cxx-Umbrella.hpp +5 -0
  54. package/nitrogen/generated/ios/c++/HybridHttpParserSpecSwift.cpp +11 -0
  55. package/nitrogen/generated/ios/c++/HybridHttpParserSpecSwift.hpp +79 -0
  56. package/nitrogen/generated/ios/c++/HybridNetDriverSpecSwift.hpp +11 -0
  57. package/nitrogen/generated/ios/c++/HybridNetServerDriverSpecSwift.hpp +6 -0
  58. package/nitrogen/generated/ios/c++/HybridNetSocketDriverSpecSwift.hpp +14 -0
  59. package/nitrogen/generated/ios/swift/HybridHttpParserSpec.swift +56 -0
  60. package/nitrogen/generated/ios/swift/HybridHttpParserSpec_cxx.swift +131 -0
  61. package/nitrogen/generated/ios/swift/HybridNetDriverSpec.swift +1 -0
  62. package/nitrogen/generated/ios/swift/HybridNetDriverSpec_cxx.swift +15 -0
  63. package/nitrogen/generated/ios/swift/HybridNetServerDriverSpec.swift +1 -0
  64. package/nitrogen/generated/ios/swift/HybridNetServerDriverSpec_cxx.swift +11 -0
  65. package/nitrogen/generated/ios/swift/HybridNetSocketDriverSpec.swift +2 -0
  66. package/nitrogen/generated/ios/swift/HybridNetSocketDriverSpec_cxx.swift +36 -0
  67. package/nitrogen/generated/ios/swift/NetConfig.swift +19 -1
  68. package/nitrogen/generated/shared/c++/HybridHttpParserSpec.cpp +21 -0
  69. package/nitrogen/generated/shared/c++/HybridHttpParserSpec.hpp +63 -0
  70. package/nitrogen/generated/shared/c++/HybridNetDriverSpec.cpp +1 -0
  71. package/nitrogen/generated/shared/c++/HybridNetDriverSpec.hpp +4 -0
  72. package/nitrogen/generated/shared/c++/HybridNetServerDriverSpec.cpp +1 -0
  73. package/nitrogen/generated/shared/c++/HybridNetServerDriverSpec.hpp +1 -0
  74. package/nitrogen/generated/shared/c++/HybridNetSocketDriverSpec.cpp +2 -0
  75. package/nitrogen/generated/shared/c++/HybridNetSocketDriverSpec.hpp +2 -0
  76. package/nitrogen/generated/shared/c++/NetConfig.hpp +6 -2
  77. package/package.json +9 -7
  78. package/src/Net.nitro.ts +17 -0
  79. package/src/http.ts +1303 -0
  80. package/src/https.ts +125 -0
  81. package/src/index.ts +13 -874
  82. package/src/net.ts +1005 -0
  83. package/src/tls.ts +82 -6
package/lib/index.js CHANGED
@@ -1,822 +1,12 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.tls = exports.connect = exports.Server = exports.Socket = exports.BlockList = exports.SocketAddress = void 0;
37
- exports.createConnection = createConnection;
38
- exports.createServer = createServer;
39
- exports.isIP = isIP;
40
- exports.isIPv4 = isIPv4;
41
- exports.isIPv6 = isIPv6;
42
- exports.getDefaultAutoSelectFamily = getDefaultAutoSelectFamily;
43
- exports.setDefaultAutoSelectFamily = setDefaultAutoSelectFamily;
44
- exports.setVerbose = setVerbose;
45
- exports.initWithConfig = initWithConfig;
46
- const readable_stream_1 = require("readable-stream");
47
- const eventemitter3_1 = require("eventemitter3");
48
- const Driver_1 = require("./Driver");
49
- const Net_nitro_1 = require("./Net.nitro");
50
- const react_native_nitro_buffer_1 = require("react-native-nitro-buffer");
51
- // -----------------------------------------------------------------------------
52
- // Utils
53
- // -----------------------------------------------------------------------------
54
- function isIP(input) {
55
- // Simple regex check
56
- if (/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(input))
57
- return 4;
58
- // Basic IPv6 check allowing double colons
59
- if (/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(input))
60
- return 6;
61
- if (/^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$/.test(input))
62
- return 6;
63
- return 0;
64
- }
65
- function isIPv4(input) {
66
- return isIP(input) === 4;
67
- }
68
- function isIPv6(input) {
69
- return isIP(input) === 6;
70
- }
71
- // -----------------------------------------------------------------------------
72
- // Global Configuration
73
- // -----------------------------------------------------------------------------
74
- let _autoSelectFamilyDefault = 4; // Node default is usually 4/6 independent, but we mock it.
75
- let _isVerbose = false;
76
- let _isInitialized = false;
77
- function debugLog(message) {
78
- if (_isVerbose) {
79
- console.log(`[NET DEBUG] ${message}`);
80
- }
81
- }
82
- function setVerbose(enabled) {
83
- _isVerbose = enabled;
84
- }
85
- function getDefaultAutoSelectFamily() {
86
- return _autoSelectFamilyDefault;
87
- }
88
- function setDefaultAutoSelectFamily(family) {
89
- if (family !== 4 && family !== 6)
90
- throw new Error('Family must be 4 or 6');
91
- _autoSelectFamilyDefault = family;
92
- }
93
- /**
94
- * Ensures that the network module is initialized.
95
- * If initWithConfig hasn't been called, it will be called with default options.
96
- */
97
- function ensureInitialized() {
98
- if (!_isInitialized) {
99
- initWithConfig({});
100
- }
101
- }
102
- /**
103
- * Initialize the network module with custom configuration.
104
- * Must be called before any socket/server operations, or the config will be ignored.
105
- *
106
- * @param config Configuration options
107
- * @param config.workerThreads Number of worker threads (0 = use CPU core count)
108
- *
109
- * @example
110
- * ```ts
111
- * import { initWithConfig } from 'react-native-nitro-net';
112
- *
113
- * // Initialize with 4 worker threads
114
- * initWithConfig({ workerThreads: 4 });
115
- * ```
116
- */
117
- function initWithConfig(config) {
118
- _isInitialized = true;
119
- Driver_1.Driver.initWithConfig(config);
120
- }
121
- // -----------------------------------------------------------------------------
122
- // SocketAddress
123
- // -----------------------------------------------------------------------------
124
- // SocketAddress
125
- // -----------------------------------------------------------------------------
126
- class SocketAddress {
127
- constructor(options) {
128
- this.address = options.address;
129
- this.family = options.family || (isIPv6(options.address) ? 'ipv6' : 'ipv4');
130
- this.port = options.port;
131
- this.flowlabel = options.flowlabel || 0;
132
- }
133
- }
134
- exports.SocketAddress = SocketAddress;
135
- // -----------------------------------------------------------------------------
136
- // BlockList
137
- // -----------------------------------------------------------------------------
138
- class BlockList {
139
- constructor() {
140
- this._rules = [];
141
- }
142
- addAddress(address, family) {
143
- this._rules.push({ type: 'address', data: { address, family: family || (isIPv6(address) ? 'ipv6' : 'ipv4') } });
144
- }
145
- addRange(start, end, family) {
146
- this._rules.push({ type: 'range', data: { start, end, family: family || (isIPv6(start) ? 'ipv6' : 'ipv4') } });
147
- }
148
- addSubnet(net, prefix, family) {
149
- this._rules.push({ type: 'subnet', data: { net, prefix, family: family || (isIPv6(net) ? 'ipv6' : 'ipv4') } });
150
- }
151
- check(address, family) {
152
- const addrFamily = family || (isIPv6(address) ? 'ipv6' : 'ipv4');
153
- const addrNum = addrFamily === 'ipv4' ? ipv4ToLong(address) : null;
154
- for (const rule of this._rules) {
155
- if (rule.data.family !== addrFamily)
156
- continue;
157
- if (rule.type === 'address') {
158
- if (rule.data.address === address)
159
- return true;
160
- }
161
- else if (rule.type === 'range' && addrNum !== null) {
162
- const start = ipv4ToLong(rule.data.start);
163
- const end = ipv4ToLong(rule.data.end);
164
- if (addrNum >= start && addrNum <= end)
165
- return true;
166
- }
167
- else if (rule.type === 'subnet' && addrNum !== null) {
168
- const net = ipv4ToLong(rule.data.net);
169
- const mask = ~(Math.pow(2, 32 - rule.data.prefix) - 1);
170
- if ((addrNum & mask) === (net & mask))
171
- return true;
172
- }
173
- }
174
- return false;
175
- }
176
- }
177
- exports.BlockList = BlockList;
178
- function ipv4ToLong(ip) {
179
- return ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
180
- }
181
- class Socket extends readable_stream_1.Duplex {
182
- get localFamily() {
183
- return this.localAddress && this.localAddress.includes(':') ? 'IPv6' : 'IPv4';
184
- }
185
- get readyState() {
186
- if (this.connecting)
187
- return 'opening';
188
- if (this._connected) {
189
- // @ts-ignore
190
- if (this.writable && this.readable)
191
- return 'open';
192
- // @ts-ignore
193
- if (this.writable)
194
- return 'writeOnly';
195
- // @ts-ignore
196
- if (this.readable)
197
- return 'readOnly';
198
- }
199
- return 'closed';
200
- }
201
- get pending() {
202
- return this.connecting;
203
- }
204
- constructor(options) {
205
- super({
206
- allowHalfOpen: options?.allowHalfOpen ?? false,
207
- readable: options?.readable ?? true,
208
- writable: options?.writable ?? true
209
- });
210
- this.connecting = false; // Changed from private _connecting
211
- this._connected = false;
212
- this._hadError = false; // Added
213
- this.bytesRead = 0;
214
- this.bytesWritten = 0;
215
- this.autoSelectFamilyAttemptedAddresses = [];
216
- this._autoSelectFamily = false;
217
- if (options?.socketDriver) {
218
- // Wrapping existing socket (from Server)
219
- this._driver = options.socketDriver;
220
- this._connected = true;
221
- this._setupEvents();
222
- // Resume the socket since it starts paused on server-accept
223
- this.resume();
224
- // Emit connect for server-side socket? No, it's already connected.
225
- }
226
- else {
227
- // New client socket
228
- ensureInitialized();
229
- this._driver = Driver_1.Driver.createSocket();
230
- this._setupEvents();
231
- // Also resume client socket initially so it's ready to receive
232
- this.resume();
233
- }
234
- this.on('finish', () => {
235
- // Writable side finished
236
- });
237
- }
238
- on(event, listener) {
239
- if (event === 'connect' && this._connected) {
240
- process.nextTick(listener);
241
- return this;
242
- }
243
- const ret = super.on(event, listener);
244
- if (event === 'data' && !this.isPaused() && this.readableFlowing !== true) {
245
- debugLog(`Socket on('data'), flowing: ${this.readableFlowing}`);
246
- this.resume();
247
- }
248
- return ret;
249
- }
250
- _setupEvents() {
251
- if (!this._driver)
252
- return;
253
- const id = this._driver.id ?? this._driver._id;
254
- this._driver.onEvent = (eventType, data) => {
255
- this.emit('event', eventType, data);
256
- if (eventType === 3) { // ERROR
257
- const msg = new TextDecoder().decode(data);
258
- debugLog(`Socket (id: ${id}) NATIVE ERROR: ${msg}`);
259
- }
260
- if (eventType === 9) { // SESSION/DEBUG
261
- debugLog(`Socket (id: ${id}) NATIVE SESSION EVENT RECEIVED`);
262
- this.emit('session', data);
263
- return;
264
- }
265
- debugLog(`Socket (id: ${id}, localPort: ${this.localPort}) Event TYPE: ${eventType}, data len: ${data?.byteLength}`);
266
- switch (eventType) {
267
- case Net_nitro_1.NetSocketEvent.CONNECT:
268
- this.connecting = false;
269
- this._connected = true;
270
- this._updateAddresses();
271
- this.emit('connect');
272
- this.emit('ready');
273
- break;
274
- case Net_nitro_1.NetSocketEvent.DATA:
275
- debugLog(`Socket onEvent(DATA), len: ${data?.byteLength}, flowing: ${this.readableFlowing}`);
276
- if (data && data.byteLength > 0) {
277
- const buffer = react_native_nitro_buffer_1.Buffer.from(data);
278
- this.bytesRead += buffer.length;
279
- if (!this.push(buffer)) {
280
- this.pause();
281
- }
282
- }
283
- break;
284
- case Net_nitro_1.NetSocketEvent.ERROR: {
285
- this._hadError = true;
286
- const errorMsg = data ? react_native_nitro_buffer_1.Buffer.from(data).toString() : 'Unknown socket error';
287
- const error = new Error(errorMsg);
288
- if (this.connecting && this._autoSelectFamily) {
289
- // If we were connecting, this is a connection attempt failure
290
- // We attempt to get the last attempted address if available
291
- const lastAttempt = this.autoSelectFamilyAttemptedAddresses[this.autoSelectFamilyAttemptedAddresses.length - 1];
292
- if (lastAttempt) {
293
- const [ip, port] = lastAttempt.split(':'); // distinct if ipv6?
294
- // Simple parsing for event emission
295
- const family = ip.includes(':') ? 6 : 4;
296
- this.emit('connectionAttemptFailed', ip, parseInt(port || '0', 10), family, error);
297
- }
298
- }
299
- this.emit('error', error);
300
- this.destroy();
301
- break;
302
- }
303
- case Net_nitro_1.NetSocketEvent.CLOSE:
304
- this._connected = false;
305
- this.connecting = false;
306
- this.push(null); // EOF
307
- this.emit('close', this._hadError);
308
- break;
309
- case Net_nitro_1.NetSocketEvent.DRAIN:
310
- this.emit('drain');
311
- break;
312
- case Net_nitro_1.NetSocketEvent.TIMEOUT:
313
- if (this.connecting && this._autoSelectFamily) {
314
- const lastAttempt = this.autoSelectFamilyAttemptedAddresses[this.autoSelectFamilyAttemptedAddresses.length - 1];
315
- if (lastAttempt) {
316
- const [ip, port] = lastAttempt.split(':');
317
- const family = ip.includes(':') ? 6 : 4;
318
- this.emit('connectionAttemptTimeout', ip, parseInt(port || '0', 10), family);
319
- }
320
- }
321
- this.emit('timeout');
322
- break;
323
- case Net_nitro_1.NetSocketEvent.LOOKUP: {
324
- if (data) {
325
- const lookupStr = react_native_nitro_buffer_1.Buffer.from(data).toString();
326
- const parts = lookupStr.split(',');
327
- if (parts.length >= 2) {
328
- const [ip, family] = parts;
329
- this.remoteAddress = ip;
330
- this.remoteFamily = family === '6' ? 'IPv6' : 'IPv4';
331
- // Emit connectionAttempt
332
- // We don't have the port in LOOKUP data usually, but we stored it in this.remotePort (dest)
333
- // actually remotePort might not be set yet if we used _connect with port arg.
334
- // But _connect sets this.remotePort = port.
335
- const port = this.remotePort || 0;
336
- const fam = family === '6' ? 6 : 4;
337
- if (this._autoSelectFamily) {
338
- this.emit('connectionAttempt', ip, port, fam);
339
- }
340
- this.autoSelectFamilyAttemptedAddresses.push(`${ip}:${port}`);
341
- }
342
- const host = parts.length > 2 ? parts[2] : undefined;
343
- this.emit('lookup', null, parts[0], parts[1] ? parseInt(parts[1], 10) : undefined, host);
344
- }
345
- break;
346
- }
347
- }
348
- };
349
- }
350
- _updateAddresses() {
351
- try {
352
- const local = this._driver?.getLocalAddress();
353
- if (local) {
354
- const parts = local.split(':');
355
- if (parts.length >= 2) {
356
- this.localPort = parseInt(parts[parts.length - 1], 10);
357
- this.localAddress = parts.slice(0, parts.length - 1).join(':').replace(/[\[\]]/g, '');
358
- }
359
- }
360
- const remote = this._driver?.getRemoteAddress();
361
- if (remote) {
362
- const parts = remote.split(':');
363
- if (parts.length >= 2) {
364
- this.remotePort = parseInt(parts[parts.length - 1], 10);
365
- this.remoteAddress = parts.slice(0, parts.length - 1).join(':').replace(/[\[\]]/g, '');
366
- this.remoteFamily = this.remoteAddress.includes(':') ? 'IPv6' : 'IPv4';
367
- }
368
- }
369
- }
370
- catch (e) {
371
- // Ignore errors for now
372
- }
373
- }
374
- address() {
375
- if (!this.localAddress)
376
- return null;
377
- return {
378
- port: this.localPort || 0,
379
- family: this.localAddress.includes(':') ? 'IPv6' : 'IPv4',
380
- address: this.localAddress
381
- };
382
- }
383
- connect(options, connectionListener) {
384
- if (typeof options === 'string') {
385
- // Path?
386
- if (isNaN(Number(options))) {
387
- return this._connectUnix(options, connectionListener);
388
- }
389
- }
390
- if (typeof options === 'number' || typeof options === 'string') {
391
- const port = Number(options);
392
- const host = (arguments.length > 1 && typeof arguments[1] === 'string') ? arguments[1] : 'localhost';
393
- const cb = typeof arguments[1] === 'function' ? arguments[1] : connectionListener;
394
- // Default: Node 20 defaults autoSelectFamily to true
395
- this._autoSelectFamily = true;
396
- return this._connect(port, host, cb || arguments[2]);
397
- }
398
- if (options.path) {
399
- return this._connectUnix(options.path, connectionListener, options.signal);
400
- }
401
- const port = options.port;
402
- const host = options.host || 'localhost';
403
- // Handle autoSelectFamily option
404
- if (typeof options.autoSelectFamily === 'boolean') {
405
- this._autoSelectFamily = options.autoSelectFamily;
406
- }
407
- else {
408
- this._autoSelectFamily = true;
409
- }
410
- return this._connect(port, host, connectionListener, options.signal);
411
- }
412
- _connect(port, host, listener, signal) {
413
- this.remotePort = port; // Store intended remote port
414
- if (this.connecting || this._connected)
415
- return this;
416
- if (signal?.aborted) {
417
- process.nextTick(() => this.emit('error', new Error('The operation was aborted')));
418
- return this;
419
- }
420
- this.connecting = true;
421
- if (listener)
422
- this.once('connect', listener);
423
- if (signal) {
424
- const abortHandler = () => {
425
- this.destroy(new Error('The operation was aborted'));
426
- };
427
- signal.addEventListener('abort', abortHandler, { once: true });
428
- this.once('connect', () => signal.removeEventListener('abort', abortHandler));
429
- this.once('close', () => signal.removeEventListener('abort', abortHandler));
430
- }
431
- this._driver?.connect(host, port);
432
- return this;
433
- }
434
- _connectUnix(path, listener, signal) {
435
- if (this.connecting || this._connected)
436
- return this;
437
- if (signal?.aborted) {
438
- process.nextTick(() => this.emit('error', new Error('The operation was aborted')));
439
- return this;
440
- }
441
- this.connecting = true;
442
- if (listener)
443
- this.once('connect', listener);
444
- if (signal) {
445
- const abortHandler = () => {
446
- this.destroy(new Error('The operation was aborted'));
447
- };
448
- signal.addEventListener('abort', abortHandler, { once: true });
449
- this.once('connect', () => signal.removeEventListener('abort', abortHandler));
450
- this.once('close', () => signal.removeEventListener('abort', abortHandler));
451
- }
452
- this._driver?.connectUnix(path);
453
- return this;
454
- }
455
- end(chunk, encoding, cb) {
456
- debugLog(`Socket (localPort: ${this.localPort}) .end() called`);
457
- return super.end(chunk, encoding, cb);
458
- }
459
- _write(chunk, encoding, callback) {
460
- if (!this._driver) {
461
- return callback(new Error('Socket not connected'));
462
- }
463
- try {
464
- const buffer = (chunk instanceof react_native_nitro_buffer_1.Buffer) ? chunk : react_native_nitro_buffer_1.Buffer.from(chunk, encoding);
465
- this.bytesWritten += buffer.length;
466
- const ab = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
467
- debugLog(`Socket _write, len: ${ab.byteLength}`);
468
- this._driver.write(ab);
469
- callback(null);
470
- }
471
- catch (err) {
472
- callback(err);
473
- }
474
- }
475
- _read(size) {
476
- if (this._driver)
477
- this._driver.resume();
478
- }
479
- _final(callback) {
480
- if (this._driver) {
481
- this._driver.shutdown();
482
- }
483
- callback(null);
484
- }
485
- destroy(reason) {
486
- debugLog(`Socket (localPort: ${this.localPort}) .destroy() called, reason: ${reason?.message}`);
487
- return super.destroy(reason);
488
- }
489
- _destroy(err, callback) {
490
- debugLog(`Socket (localPort: ${this.localPort}) ._destroy() called`);
491
- this._connected = false;
492
- this.connecting = false;
493
- this.destroyed = true;
494
- if (this._driver) {
495
- this._driver.destroy();
496
- this._driver = undefined;
497
- }
498
- callback(err);
499
- }
500
- // Standard net.Socket methods
501
- setTimeout(msecs, callback) {
502
- if (this._driver) {
503
- this._driver.setTimeout(msecs);
504
- }
505
- if (callback)
506
- this.once('timeout', callback);
507
- return this;
508
- }
509
- /**
510
- * Pause the reading of data. That is, 'data' events will not be emitted.
511
- * Useful to throttle back an upload.
512
- */
513
- pause() {
514
- super.pause();
515
- if (this._driver) {
516
- this._driver.pause();
517
- }
518
- return this;
519
- }
520
- /**
521
- * Resume reading after a call to pause().
522
- */
523
- resume() {
524
- const id = this._driver?.id;
525
- debugLog(`Socket.resume() called, id: ${id}`);
526
- super.resume();
527
- if (this._driver) {
528
- debugLog(`Socket.resume() calling driver.resume(), id: ${id}`);
529
- this._driver.resume();
530
- }
531
- return this;
532
- }
533
- /**
534
- * Enable/disable the use of Nagle's algorithm.
535
- */
536
- setNoDelay(noDelay) {
537
- this._driver?.setNoDelay(noDelay !== false);
538
- return this;
539
- }
540
- setKeepAlive(enable, initialDelay) {
541
- this._driver?.setKeepAlive(enable !== false, initialDelay || 0);
542
- return this;
543
- }
544
- ref() { return this; }
545
- unref() { return this; }
546
- /**
547
- * Set the encoding for the socket as a Readable Stream.
548
- * Use 'utf8', 'hex', etc.
549
- */
550
- setEncoding(encoding) {
551
- super.setEncoding(encoding);
552
- return this;
553
- }
554
- get timeout() {
555
- return undefined; // Not tracked strictly as a property yet
556
- }
557
- get bufferSize() {
558
- return 0; // Deprecated but often accessed
559
- }
560
- resetAndDestroy() {
561
- if (this._driver) {
562
- this._driver.resetAndDestroy();
563
- this._driver = undefined;
564
- }
565
- this._connected = false;
566
- this.connecting = false;
567
- this.destroyed = true;
568
- return this;
569
- }
570
- }
571
- exports.Socket = Socket;
572
- // -----------------------------------------------------------------------------
573
- // Server
574
- // -----------------------------------------------------------------------------
575
- class Server extends eventemitter3_1.EventEmitter {
576
- get maxConnections() {
577
- return this._maxConnections;
578
- }
579
- set maxConnections(value) {
580
- this._maxConnections = value;
581
- // We handle maxConnections in JS to support 'drop' event.
582
- // Disable native limit to ensure we receive the connection attempt.
583
- this._driver.maxConnections = 0;
584
- }
585
- get dropMaxConnection() {
586
- return this._dropMaxConnection;
587
- }
588
- set dropMaxConnection(value) {
589
- this._dropMaxConnection = value;
590
- }
591
- get listening() {
592
- // If we have a driver and we assume it's listening if it has been started?
593
- // Actually, checking _driver state might be hard if not exposed.
594
- // But typically 'listening' is true after 'listening' event.
595
- // We can track it with a private flag or by checking address() which returns null if not listening.
596
- return !!this.address();
597
- }
598
- constructor(options, connectionListener) {
599
- super();
600
- this._sockets = new Set();
601
- this._connections = 0;
602
- this._maxConnections = 0;
603
- this._dropMaxConnection = false;
604
- ensureInitialized();
605
- this._driver = Driver_1.Driver.createServer();
606
- if (typeof options === 'function') {
607
- connectionListener = options;
608
- options = {};
609
- }
610
- if (connectionListener) {
611
- this.on('connection', connectionListener);
612
- }
613
- this._driver.onEvent = (eventType, data) => {
614
- switch (eventType) {
615
- case Net_nitro_1.NetServerEvent.CONNECTION: {
616
- const payload = data ? react_native_nitro_buffer_1.Buffer.from(data).toString() : '';
617
- if (payload === 'success') {
618
- this.emit('listening');
619
- }
620
- else {
621
- const clientId = payload;
622
- debugLog(`Server connection clientId: '${clientId}', current connections: ${this._connections}, max: ${this._maxConnections}`);
623
- if (clientId) {
624
- // Check maxConnections
625
- if (this._maxConnections > 0 && this._connections >= this._maxConnections) {
626
- debugLog(`Server maxConnections reached (${this._connections} >= ${this._maxConnections}). Dropping connection. clientId: ${clientId}`);
627
- const socketDriver = Driver_1.Driver.createSocket(clientId);
628
- const socket = new Socket({
629
- socketDriver: socketDriver,
630
- readable: true,
631
- writable: true
632
- });
633
- // @ts-ignore
634
- socket._updateAddresses();
635
- this.emit('drop', {
636
- localAddress: socket.localAddress,
637
- localPort: socket.localPort,
638
- localFamily: socket.localFamily,
639
- remoteAddress: socket.remoteAddress,
640
- remotePort: socket.remotePort,
641
- remoteFamily: socket.remoteFamily
642
- });
643
- socket.destroy();
644
- return;
645
- }
646
- const socketDriver = Driver_1.Driver.createSocket(clientId);
647
- const socket = new Socket({
648
- socketDriver: socketDriver,
649
- readable: true,
650
- writable: true
651
- });
652
- // Initialize addresses immediately for server-side socket
653
- // @ts-ignore
654
- socket._updateAddresses();
655
- debugLog(`Socket initialized addresses: local=${socket.localAddress}:${socket.localPort}, remote=${socket.remoteAddress}:${socket.remotePort}`);
656
- // Keep reference to prevent GC
657
- this._sockets.add(socket);
658
- this._connections++;
659
- socket.on('close', () => {
660
- this._connections--;
661
- this._sockets.delete(socket);
662
- });
663
- this.emit('connection', socket);
664
- }
665
- }
666
- break;
667
- }
668
- case Net_nitro_1.NetServerEvent.ERROR:
669
- this.emit('error', new Error(data ? react_native_nitro_buffer_1.Buffer.from(data).toString() : 'Unknown server error'));
670
- break;
671
- case Net_nitro_1.NetServerEvent.DEBUG: {
672
- debugLog(`Server NATIVE SESSION/DEBUG EVENT RECEIVED`);
673
- this.emit('session', data);
674
- break;
675
- }
676
- case Net_nitro_1.NetServerEvent.CLOSE:
677
- this.emit('close');
678
- break;
679
- }
680
- };
681
- }
682
- ref() { return this; }
683
- unref() { return this; }
684
- // @ts-ignore
685
- [Symbol.asyncDispose]() {
686
- return new Promise((resolve) => {
687
- this.close(() => resolve());
688
- });
689
- }
690
- listen(port, host, backlog, callback) {
691
- let _port = 0;
692
- let _host;
693
- let _backlog;
694
- let _path;
695
- let _callback;
696
- let signal;
697
- let ipv6Only = false;
698
- let reusePort = false;
699
- let handle;
700
- if (typeof port === 'object' && port !== null) {
701
- // Check if it's a handle object with fd property
702
- if (typeof port.fd === 'number') {
703
- handle = port;
704
- _backlog = port.backlog;
705
- _callback = host; // listen(handle, cb)
706
- }
707
- else {
708
- _port = port.port;
709
- _host = port.host;
710
- _backlog = port.backlog;
711
- _path = port.path;
712
- signal = port.signal;
713
- ipv6Only = port.ipv6Only === true;
714
- reusePort = port.reusePort === true;
715
- _callback = host; // listen(options, cb)
716
- }
717
- }
718
- else {
719
- _port = typeof port === 'number' ? port : (typeof port === 'string' && !isNaN(Number(port)) ? Number(port) : 0);
720
- if (typeof port === 'string' && isNaN(Number(port)))
721
- _path = port;
722
- if (typeof host === 'string')
723
- _host = host;
724
- else if (typeof host === 'function')
725
- _callback = host;
726
- if (typeof backlog === 'number')
727
- _backlog = backlog;
728
- else if (typeof backlog === 'function')
729
- _callback = backlog;
730
- if (typeof callback === 'function')
731
- _callback = callback;
732
- }
733
- if (_callback)
734
- this.once('listening', _callback);
735
- if (signal?.aborted) {
736
- process.nextTick(() => this.emit('error', new Error('The operation was aborted')));
737
- return this;
738
- }
739
- if (signal) {
740
- const abortHandler = () => {
741
- this.close();
742
- this.emit('error', new Error('The operation was aborted'));
743
- };
744
- signal.addEventListener('abort', abortHandler, { once: true });
745
- this.once('listening', () => signal.removeEventListener('abort', abortHandler));
746
- this.once('close', () => signal.removeEventListener('abort', abortHandler));
747
- }
748
- if (handle && typeof handle.fd === 'number') {
749
- // Listen on an existing file descriptor (handle)
750
- this._driver.listenHandle(handle.fd, _backlog);
751
- }
752
- else if (_path) {
753
- this._driver.listenUnix(_path, _backlog);
754
- }
755
- else {
756
- this._driver.listen(_port || 0, _backlog, ipv6Only, reusePort);
757
- }
758
- return this;
759
- }
760
- close(callback) {
761
- // Destroy all active connections first
762
- for (const socket of this._sockets) {
763
- socket.destroy();
764
- }
765
- this._sockets.clear();
766
- this._connections = 0;
767
- this._driver.close();
768
- if (callback)
769
- this.once('close', callback);
770
- return this;
771
- }
772
- address() {
773
- try {
774
- const addr = this._driver.getLocalAddress();
775
- if (addr) {
776
- const parts = addr.split(':');
777
- if (parts.length >= 2) {
778
- const port = parseInt(parts[parts.length - 1], 10);
779
- const address = parts.slice(0, parts.length - 1).join(':').replace(/[\[\]]/g, '');
780
- const family = address.includes(':') ? 'IPv6' : 'IPv4';
781
- return { port, family, address };
782
- }
783
- }
784
- }
785
- catch (e) {
786
- // Ignore
787
- }
788
- return null;
789
- }
790
- getConnections(cb) {
791
- cb(null, this._connections);
792
- }
793
- }
794
- exports.Server = Server;
795
- // -----------------------------------------------------------------------------
796
- // Exports
797
- // -----------------------------------------------------------------------------
798
- function createConnection(options, connectionListener) {
799
- const socket = new Socket(options);
800
- return socket.connect(options, connectionListener);
801
- }
802
- exports.connect = createConnection;
803
- function createServer(options, connectionListener) {
804
- return new Server(options, connectionListener);
805
- }
806
- exports.tls = __importStar(require("./tls"));
807
- exports.default = {
808
- Socket,
809
- Server,
810
- SocketAddress,
811
- BlockList,
812
- createConnection,
813
- createServer,
814
- connect: exports.connect,
815
- isIP,
816
- isIPv4,
817
- isIPv6,
818
- getDefaultAutoSelectFamily,
819
- setDefaultAutoSelectFamily,
820
- setVerbose,
821
- initWithConfig,
1
+ import * as net from './net';
2
+ import * as tls from './tls';
3
+ import * as http from './http';
4
+ import * as https from './https';
5
+ export * from './net';
6
+ export { tls, http, https };
7
+ export default {
8
+ ...net,
9
+ tls,
10
+ http,
11
+ https,
822
12
  };