@holydeck/cli 2026.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +234 -0
  3. package/dist/BrowserWebSocketTransport-H3D6MINS.js +12 -0
  4. package/dist/BrowserWebSocketTransport-H3D6MINS.js.map +1 -0
  5. package/dist/LaunchOptions-42ZS55HH.js +12 -0
  6. package/dist/LaunchOptions-42ZS55HH.js.map +1 -0
  7. package/dist/NodeWebSocketTransport-BXHQGXRM.js +15 -0
  8. package/dist/NodeWebSocketTransport-BXHQGXRM.js.map +1 -0
  9. package/dist/bidi-25S23FWJ.js +18358 -0
  10. package/dist/bidi-25S23FWJ.js.map +1 -0
  11. package/dist/chunk-2BLOYUSF.js +795 -0
  12. package/dist/chunk-2BLOYUSF.js.map +1 -0
  13. package/dist/chunk-43CZTS57.js +38 -0
  14. package/dist/chunk-43CZTS57.js.map +1 -0
  15. package/dist/chunk-DIBLSFAG.js +34 -0
  16. package/dist/chunk-DIBLSFAG.js.map +1 -0
  17. package/dist/chunk-IEJ3OX3N.js +52 -0
  18. package/dist/chunk-IEJ3OX3N.js.map +1 -0
  19. package/dist/chunk-JM4YIWBN.js +3796 -0
  20. package/dist/chunk-JM4YIWBN.js.map +1 -0
  21. package/dist/chunk-NP3DTWF7.js +23282 -0
  22. package/dist/chunk-NP3DTWF7.js.map +1 -0
  23. package/dist/chunk-SWG4X375.js +51 -0
  24. package/dist/chunk-SWG4X375.js.map +1 -0
  25. package/dist/chunk-UC6TFXMD.js +2821 -0
  26. package/dist/chunk-UC6TFXMD.js.map +1 -0
  27. package/dist/chunk-V4BIHFVZ.js +2287 -0
  28. package/dist/chunk-V4BIHFVZ.js.map +1 -0
  29. package/dist/chunk-V77AQPDK.js +20 -0
  30. package/dist/chunk-V77AQPDK.js.map +1 -0
  31. package/dist/chunk-XAENXL52.js +101 -0
  32. package/dist/chunk-XAENXL52.js.map +1 -0
  33. package/dist/cli.js +64101 -0
  34. package/dist/cli.js.map +1 -0
  35. package/dist/dist-3ZE2HBJQ.js +20447 -0
  36. package/dist/dist-3ZE2HBJQ.js.map +1 -0
  37. package/dist/dist-575AQY5L.js +1161 -0
  38. package/dist/dist-575AQY5L.js.map +1 -0
  39. package/dist/dist-DL5M2SDJ.js +117 -0
  40. package/dist/dist-DL5M2SDJ.js.map +1 -0
  41. package/dist/dist-OMWR53J4.js +4713 -0
  42. package/dist/dist-OMWR53J4.js.map +1 -0
  43. package/dist/dist-UT6HKKCD.js +281 -0
  44. package/dist/dist-UT6HKKCD.js.map +1 -0
  45. package/dist/fs-P6GYHPGZ.js +1685 -0
  46. package/dist/fs-P6GYHPGZ.js.map +1 -0
  47. package/dist/helpers-64DWIL6C.js +21 -0
  48. package/dist/helpers-64DWIL6C.js.map +1 -0
  49. package/dist/main-IQ64YDOJ.js +61 -0
  50. package/dist/main-IQ64YDOJ.js.map +1 -0
  51. package/dist/puppeteer-RDWY6FSG.js +2386 -0
  52. package/dist/puppeteer-RDWY6FSG.js.map +1 -0
  53. package/dist/yargs-KMQWKLG6.js +3264 -0
  54. package/dist/yargs-KMQWKLG6.js.map +1 -0
  55. package/dist/yauzl-7KG7KPPF.js +1355 -0
  56. package/dist/yauzl-7KG7KPPF.js.map +1 -0
  57. package/package.json +44 -0
@@ -0,0 +1,4713 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __holydeckCreateRequire } from 'node:module';
3
+ const require = __holydeckCreateRequire(import.meta.url);
4
+ import {
5
+ Agent,
6
+ require_src
7
+ } from "./chunk-2BLOYUSF.js";
8
+ import {
9
+ __commonJS,
10
+ __require,
11
+ __toESM
12
+ } from "./chunk-IEJ3OX3N.js";
13
+
14
+ // ../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js
15
+ var require_utils = __commonJS({
16
+ "../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js"(exports) {
17
+ "use strict";
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ var buffer_1 = __require("buffer");
20
+ var ERRORS = {
21
+ INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",
22
+ INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.",
23
+ INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.",
24
+ INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",
25
+ INVALID_OFFSET: "An invalid offset value was provided.",
26
+ INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.",
27
+ INVALID_LENGTH: "An invalid length value was provided.",
28
+ INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.",
29
+ INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.",
30
+ INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",
31
+ INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.",
32
+ INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data."
33
+ };
34
+ exports.ERRORS = ERRORS;
35
+ function checkEncoding(encoding) {
36
+ if (!buffer_1.Buffer.isEncoding(encoding)) {
37
+ throw new Error(ERRORS.INVALID_ENCODING);
38
+ }
39
+ }
40
+ exports.checkEncoding = checkEncoding;
41
+ function isFiniteInteger(value) {
42
+ return typeof value === "number" && isFinite(value) && isInteger(value);
43
+ }
44
+ exports.isFiniteInteger = isFiniteInteger;
45
+ function checkOffsetOrLengthValue(value, offset) {
46
+ if (typeof value === "number") {
47
+ if (!isFiniteInteger(value) || value < 0) {
48
+ throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
49
+ }
50
+ } else {
51
+ throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
52
+ }
53
+ }
54
+ function checkLengthValue(length) {
55
+ checkOffsetOrLengthValue(length, false);
56
+ }
57
+ exports.checkLengthValue = checkLengthValue;
58
+ function checkOffsetValue(offset) {
59
+ checkOffsetOrLengthValue(offset, true);
60
+ }
61
+ exports.checkOffsetValue = checkOffsetValue;
62
+ function checkTargetOffset(offset, buff) {
63
+ if (offset < 0 || offset > buff.length) {
64
+ throw new Error(ERRORS.INVALID_TARGET_OFFSET);
65
+ }
66
+ }
67
+ exports.checkTargetOffset = checkTargetOffset;
68
+ function isInteger(value) {
69
+ return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
70
+ }
71
+ function bigIntAndBufferInt64Check(bufferMethod) {
72
+ if (typeof BigInt === "undefined") {
73
+ throw new Error("Platform does not support JS BigInt type.");
74
+ }
75
+ if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") {
76
+ throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
77
+ }
78
+ }
79
+ exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
80
+ }
81
+ });
82
+
83
+ // ../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js
84
+ var require_smartbuffer = __commonJS({
85
+ "../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js"(exports) {
86
+ "use strict";
87
+ Object.defineProperty(exports, "__esModule", { value: true });
88
+ var utils_1 = require_utils();
89
+ var DEFAULT_SMARTBUFFER_SIZE = 4096;
90
+ var DEFAULT_SMARTBUFFER_ENCODING = "utf8";
91
+ var SmartBuffer = class _SmartBuffer {
92
+ /**
93
+ * Creates a new SmartBuffer instance.
94
+ *
95
+ * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance.
96
+ */
97
+ constructor(options) {
98
+ this.length = 0;
99
+ this._encoding = DEFAULT_SMARTBUFFER_ENCODING;
100
+ this._writeOffset = 0;
101
+ this._readOffset = 0;
102
+ if (_SmartBuffer.isSmartBufferOptions(options)) {
103
+ if (options.encoding) {
104
+ utils_1.checkEncoding(options.encoding);
105
+ this._encoding = options.encoding;
106
+ }
107
+ if (options.size) {
108
+ if (utils_1.isFiniteInteger(options.size) && options.size > 0) {
109
+ this._buff = Buffer.allocUnsafe(options.size);
110
+ } else {
111
+ throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);
112
+ }
113
+ } else if (options.buff) {
114
+ if (Buffer.isBuffer(options.buff)) {
115
+ this._buff = options.buff;
116
+ this.length = options.buff.length;
117
+ } else {
118
+ throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);
119
+ }
120
+ } else {
121
+ this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
122
+ }
123
+ } else {
124
+ if (typeof options !== "undefined") {
125
+ throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);
126
+ }
127
+ this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
128
+ }
129
+ }
130
+ /**
131
+ * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding.
132
+ *
133
+ * @param size { Number } The size of the internal Buffer.
134
+ * @param encoding { String } The BufferEncoding to use for strings.
135
+ *
136
+ * @return { SmartBuffer }
137
+ */
138
+ static fromSize(size, encoding) {
139
+ return new this({
140
+ size,
141
+ encoding
142
+ });
143
+ }
144
+ /**
145
+ * Creates a new SmartBuffer instance with the provided Buffer and optional encoding.
146
+ *
147
+ * @param buffer { Buffer } The Buffer to use as the internal Buffer value.
148
+ * @param encoding { String } The BufferEncoding to use for strings.
149
+ *
150
+ * @return { SmartBuffer }
151
+ */
152
+ static fromBuffer(buff, encoding) {
153
+ return new this({
154
+ buff,
155
+ encoding
156
+ });
157
+ }
158
+ /**
159
+ * Creates a new SmartBuffer instance with the provided SmartBufferOptions options.
160
+ *
161
+ * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance.
162
+ */
163
+ static fromOptions(options) {
164
+ return new this(options);
165
+ }
166
+ /**
167
+ * Type checking function that determines if an object is a SmartBufferOptions object.
168
+ */
169
+ static isSmartBufferOptions(options) {
170
+ const castOptions = options;
171
+ return castOptions && (castOptions.encoding !== void 0 || castOptions.size !== void 0 || castOptions.buff !== void 0);
172
+ }
173
+ // Signed integers
174
+ /**
175
+ * Reads an Int8 value from the current read position or an optionally provided offset.
176
+ *
177
+ * @param offset { Number } The offset to read data from (optional)
178
+ * @return { Number }
179
+ */
180
+ readInt8(offset) {
181
+ return this._readNumberValue(Buffer.prototype.readInt8, 1, offset);
182
+ }
183
+ /**
184
+ * Reads an Int16BE value from the current read position or an optionally provided offset.
185
+ *
186
+ * @param offset { Number } The offset to read data from (optional)
187
+ * @return { Number }
188
+ */
189
+ readInt16BE(offset) {
190
+ return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset);
191
+ }
192
+ /**
193
+ * Reads an Int16LE value from the current read position or an optionally provided offset.
194
+ *
195
+ * @param offset { Number } The offset to read data from (optional)
196
+ * @return { Number }
197
+ */
198
+ readInt16LE(offset) {
199
+ return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset);
200
+ }
201
+ /**
202
+ * Reads an Int32BE value from the current read position or an optionally provided offset.
203
+ *
204
+ * @param offset { Number } The offset to read data from (optional)
205
+ * @return { Number }
206
+ */
207
+ readInt32BE(offset) {
208
+ return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset);
209
+ }
210
+ /**
211
+ * Reads an Int32LE value from the current read position or an optionally provided offset.
212
+ *
213
+ * @param offset { Number } The offset to read data from (optional)
214
+ * @return { Number }
215
+ */
216
+ readInt32LE(offset) {
217
+ return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset);
218
+ }
219
+ /**
220
+ * Reads a BigInt64BE value from the current read position or an optionally provided offset.
221
+ *
222
+ * @param offset { Number } The offset to read data from (optional)
223
+ * @return { BigInt }
224
+ */
225
+ readBigInt64BE(offset) {
226
+ utils_1.bigIntAndBufferInt64Check("readBigInt64BE");
227
+ return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset);
228
+ }
229
+ /**
230
+ * Reads a BigInt64LE value from the current read position or an optionally provided offset.
231
+ *
232
+ * @param offset { Number } The offset to read data from (optional)
233
+ * @return { BigInt }
234
+ */
235
+ readBigInt64LE(offset) {
236
+ utils_1.bigIntAndBufferInt64Check("readBigInt64LE");
237
+ return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset);
238
+ }
239
+ /**
240
+ * Writes an Int8 value to the current write position (or at optional offset).
241
+ *
242
+ * @param value { Number } The value to write.
243
+ * @param offset { Number } The offset to write the value at.
244
+ *
245
+ * @return this
246
+ */
247
+ writeInt8(value, offset) {
248
+ this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
249
+ return this;
250
+ }
251
+ /**
252
+ * Inserts an Int8 value at the given offset value.
253
+ *
254
+ * @param value { Number } The value to insert.
255
+ * @param offset { Number } The offset to insert the value at.
256
+ *
257
+ * @return this
258
+ */
259
+ insertInt8(value, offset) {
260
+ return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
261
+ }
262
+ /**
263
+ * Writes an Int16BE value to the current write position (or at optional offset).
264
+ *
265
+ * @param value { Number } The value to write.
266
+ * @param offset { Number } The offset to write the value at.
267
+ *
268
+ * @return this
269
+ */
270
+ writeInt16BE(value, offset) {
271
+ return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
272
+ }
273
+ /**
274
+ * Inserts an Int16BE value at the given offset value.
275
+ *
276
+ * @param value { Number } The value to insert.
277
+ * @param offset { Number } The offset to insert the value at.
278
+ *
279
+ * @return this
280
+ */
281
+ insertInt16BE(value, offset) {
282
+ return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
283
+ }
284
+ /**
285
+ * Writes an Int16LE value to the current write position (or at optional offset).
286
+ *
287
+ * @param value { Number } The value to write.
288
+ * @param offset { Number } The offset to write the value at.
289
+ *
290
+ * @return this
291
+ */
292
+ writeInt16LE(value, offset) {
293
+ return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
294
+ }
295
+ /**
296
+ * Inserts an Int16LE value at the given offset value.
297
+ *
298
+ * @param value { Number } The value to insert.
299
+ * @param offset { Number } The offset to insert the value at.
300
+ *
301
+ * @return this
302
+ */
303
+ insertInt16LE(value, offset) {
304
+ return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
305
+ }
306
+ /**
307
+ * Writes an Int32BE value to the current write position (or at optional offset).
308
+ *
309
+ * @param value { Number } The value to write.
310
+ * @param offset { Number } The offset to write the value at.
311
+ *
312
+ * @return this
313
+ */
314
+ writeInt32BE(value, offset) {
315
+ return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
316
+ }
317
+ /**
318
+ * Inserts an Int32BE value at the given offset value.
319
+ *
320
+ * @param value { Number } The value to insert.
321
+ * @param offset { Number } The offset to insert the value at.
322
+ *
323
+ * @return this
324
+ */
325
+ insertInt32BE(value, offset) {
326
+ return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
327
+ }
328
+ /**
329
+ * Writes an Int32LE value to the current write position (or at optional offset).
330
+ *
331
+ * @param value { Number } The value to write.
332
+ * @param offset { Number } The offset to write the value at.
333
+ *
334
+ * @return this
335
+ */
336
+ writeInt32LE(value, offset) {
337
+ return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
338
+ }
339
+ /**
340
+ * Inserts an Int32LE value at the given offset value.
341
+ *
342
+ * @param value { Number } The value to insert.
343
+ * @param offset { Number } The offset to insert the value at.
344
+ *
345
+ * @return this
346
+ */
347
+ insertInt32LE(value, offset) {
348
+ return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
349
+ }
350
+ /**
351
+ * Writes a BigInt64BE value to the current write position (or at optional offset).
352
+ *
353
+ * @param value { BigInt } The value to write.
354
+ * @param offset { Number } The offset to write the value at.
355
+ *
356
+ * @return this
357
+ */
358
+ writeBigInt64BE(value, offset) {
359
+ utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
360
+ return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
361
+ }
362
+ /**
363
+ * Inserts a BigInt64BE value at the given offset value.
364
+ *
365
+ * @param value { BigInt } The value to insert.
366
+ * @param offset { Number } The offset to insert the value at.
367
+ *
368
+ * @return this
369
+ */
370
+ insertBigInt64BE(value, offset) {
371
+ utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
372
+ return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
373
+ }
374
+ /**
375
+ * Writes a BigInt64LE value to the current write position (or at optional offset).
376
+ *
377
+ * @param value { BigInt } The value to write.
378
+ * @param offset { Number } The offset to write the value at.
379
+ *
380
+ * @return this
381
+ */
382
+ writeBigInt64LE(value, offset) {
383
+ utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
384
+ return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
385
+ }
386
+ /**
387
+ * Inserts a Int64LE value at the given offset value.
388
+ *
389
+ * @param value { BigInt } The value to insert.
390
+ * @param offset { Number } The offset to insert the value at.
391
+ *
392
+ * @return this
393
+ */
394
+ insertBigInt64LE(value, offset) {
395
+ utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
396
+ return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
397
+ }
398
+ // Unsigned Integers
399
+ /**
400
+ * Reads an UInt8 value from the current read position or an optionally provided offset.
401
+ *
402
+ * @param offset { Number } The offset to read data from (optional)
403
+ * @return { Number }
404
+ */
405
+ readUInt8(offset) {
406
+ return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset);
407
+ }
408
+ /**
409
+ * Reads an UInt16BE value from the current read position or an optionally provided offset.
410
+ *
411
+ * @param offset { Number } The offset to read data from (optional)
412
+ * @return { Number }
413
+ */
414
+ readUInt16BE(offset) {
415
+ return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset);
416
+ }
417
+ /**
418
+ * Reads an UInt16LE value from the current read position or an optionally provided offset.
419
+ *
420
+ * @param offset { Number } The offset to read data from (optional)
421
+ * @return { Number }
422
+ */
423
+ readUInt16LE(offset) {
424
+ return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset);
425
+ }
426
+ /**
427
+ * Reads an UInt32BE value from the current read position or an optionally provided offset.
428
+ *
429
+ * @param offset { Number } The offset to read data from (optional)
430
+ * @return { Number }
431
+ */
432
+ readUInt32BE(offset) {
433
+ return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset);
434
+ }
435
+ /**
436
+ * Reads an UInt32LE value from the current read position or an optionally provided offset.
437
+ *
438
+ * @param offset { Number } The offset to read data from (optional)
439
+ * @return { Number }
440
+ */
441
+ readUInt32LE(offset) {
442
+ return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset);
443
+ }
444
+ /**
445
+ * Reads a BigUInt64BE value from the current read position or an optionally provided offset.
446
+ *
447
+ * @param offset { Number } The offset to read data from (optional)
448
+ * @return { BigInt }
449
+ */
450
+ readBigUInt64BE(offset) {
451
+ utils_1.bigIntAndBufferInt64Check("readBigUInt64BE");
452
+ return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset);
453
+ }
454
+ /**
455
+ * Reads a BigUInt64LE value from the current read position or an optionally provided offset.
456
+ *
457
+ * @param offset { Number } The offset to read data from (optional)
458
+ * @return { BigInt }
459
+ */
460
+ readBigUInt64LE(offset) {
461
+ utils_1.bigIntAndBufferInt64Check("readBigUInt64LE");
462
+ return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset);
463
+ }
464
+ /**
465
+ * Writes an UInt8 value to the current write position (or at optional offset).
466
+ *
467
+ * @param value { Number } The value to write.
468
+ * @param offset { Number } The offset to write the value at.
469
+ *
470
+ * @return this
471
+ */
472
+ writeUInt8(value, offset) {
473
+ return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
474
+ }
475
+ /**
476
+ * Inserts an UInt8 value at the given offset value.
477
+ *
478
+ * @param value { Number } The value to insert.
479
+ * @param offset { Number } The offset to insert the value at.
480
+ *
481
+ * @return this
482
+ */
483
+ insertUInt8(value, offset) {
484
+ return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
485
+ }
486
+ /**
487
+ * Writes an UInt16BE value to the current write position (or at optional offset).
488
+ *
489
+ * @param value { Number } The value to write.
490
+ * @param offset { Number } The offset to write the value at.
491
+ *
492
+ * @return this
493
+ */
494
+ writeUInt16BE(value, offset) {
495
+ return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
496
+ }
497
+ /**
498
+ * Inserts an UInt16BE value at the given offset value.
499
+ *
500
+ * @param value { Number } The value to insert.
501
+ * @param offset { Number } The offset to insert the value at.
502
+ *
503
+ * @return this
504
+ */
505
+ insertUInt16BE(value, offset) {
506
+ return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
507
+ }
508
+ /**
509
+ * Writes an UInt16LE value to the current write position (or at optional offset).
510
+ *
511
+ * @param value { Number } The value to write.
512
+ * @param offset { Number } The offset to write the value at.
513
+ *
514
+ * @return this
515
+ */
516
+ writeUInt16LE(value, offset) {
517
+ return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
518
+ }
519
+ /**
520
+ * Inserts an UInt16LE value at the given offset value.
521
+ *
522
+ * @param value { Number } The value to insert.
523
+ * @param offset { Number } The offset to insert the value at.
524
+ *
525
+ * @return this
526
+ */
527
+ insertUInt16LE(value, offset) {
528
+ return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
529
+ }
530
+ /**
531
+ * Writes an UInt32BE value to the current write position (or at optional offset).
532
+ *
533
+ * @param value { Number } The value to write.
534
+ * @param offset { Number } The offset to write the value at.
535
+ *
536
+ * @return this
537
+ */
538
+ writeUInt32BE(value, offset) {
539
+ return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
540
+ }
541
+ /**
542
+ * Inserts an UInt32BE value at the given offset value.
543
+ *
544
+ * @param value { Number } The value to insert.
545
+ * @param offset { Number } The offset to insert the value at.
546
+ *
547
+ * @return this
548
+ */
549
+ insertUInt32BE(value, offset) {
550
+ return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
551
+ }
552
+ /**
553
+ * Writes an UInt32LE value to the current write position (or at optional offset).
554
+ *
555
+ * @param value { Number } The value to write.
556
+ * @param offset { Number } The offset to write the value at.
557
+ *
558
+ * @return this
559
+ */
560
+ writeUInt32LE(value, offset) {
561
+ return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
562
+ }
563
+ /**
564
+ * Inserts an UInt32LE value at the given offset value.
565
+ *
566
+ * @param value { Number } The value to insert.
567
+ * @param offset { Number } The offset to insert the value at.
568
+ *
569
+ * @return this
570
+ */
571
+ insertUInt32LE(value, offset) {
572
+ return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
573
+ }
574
+ /**
575
+ * Writes a BigUInt64BE value to the current write position (or at optional offset).
576
+ *
577
+ * @param value { Number } The value to write.
578
+ * @param offset { Number } The offset to write the value at.
579
+ *
580
+ * @return this
581
+ */
582
+ writeBigUInt64BE(value, offset) {
583
+ utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
584
+ return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
585
+ }
586
+ /**
587
+ * Inserts a BigUInt64BE value at the given offset value.
588
+ *
589
+ * @param value { Number } The value to insert.
590
+ * @param offset { Number } The offset to insert the value at.
591
+ *
592
+ * @return this
593
+ */
594
+ insertBigUInt64BE(value, offset) {
595
+ utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
596
+ return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
597
+ }
598
+ /**
599
+ * Writes a BigUInt64LE value to the current write position (or at optional offset).
600
+ *
601
+ * @param value { Number } The value to write.
602
+ * @param offset { Number } The offset to write the value at.
603
+ *
604
+ * @return this
605
+ */
606
+ writeBigUInt64LE(value, offset) {
607
+ utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
608
+ return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
609
+ }
610
+ /**
611
+ * Inserts a BigUInt64LE value at the given offset value.
612
+ *
613
+ * @param value { Number } The value to insert.
614
+ * @param offset { Number } The offset to insert the value at.
615
+ *
616
+ * @return this
617
+ */
618
+ insertBigUInt64LE(value, offset) {
619
+ utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
620
+ return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
621
+ }
622
+ // Floating Point
623
+ /**
624
+ * Reads an FloatBE value from the current read position or an optionally provided offset.
625
+ *
626
+ * @param offset { Number } The offset to read data from (optional)
627
+ * @return { Number }
628
+ */
629
+ readFloatBE(offset) {
630
+ return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset);
631
+ }
632
+ /**
633
+ * Reads an FloatLE value from the current read position or an optionally provided offset.
634
+ *
635
+ * @param offset { Number } The offset to read data from (optional)
636
+ * @return { Number }
637
+ */
638
+ readFloatLE(offset) {
639
+ return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset);
640
+ }
641
+ /**
642
+ * Writes a FloatBE value to the current write position (or at optional offset).
643
+ *
644
+ * @param value { Number } The value to write.
645
+ * @param offset { Number } The offset to write the value at.
646
+ *
647
+ * @return this
648
+ */
649
+ writeFloatBE(value, offset) {
650
+ return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
651
+ }
652
+ /**
653
+ * Inserts a FloatBE value at the given offset value.
654
+ *
655
+ * @param value { Number } The value to insert.
656
+ * @param offset { Number } The offset to insert the value at.
657
+ *
658
+ * @return this
659
+ */
660
+ insertFloatBE(value, offset) {
661
+ return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
662
+ }
663
+ /**
664
+ * Writes a FloatLE value to the current write position (or at optional offset).
665
+ *
666
+ * @param value { Number } The value to write.
667
+ * @param offset { Number } The offset to write the value at.
668
+ *
669
+ * @return this
670
+ */
671
+ writeFloatLE(value, offset) {
672
+ return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
673
+ }
674
+ /**
675
+ * Inserts a FloatLE value at the given offset value.
676
+ *
677
+ * @param value { Number } The value to insert.
678
+ * @param offset { Number } The offset to insert the value at.
679
+ *
680
+ * @return this
681
+ */
682
+ insertFloatLE(value, offset) {
683
+ return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
684
+ }
685
+ // Double Floating Point
686
+ /**
687
+ * Reads an DoublEBE value from the current read position or an optionally provided offset.
688
+ *
689
+ * @param offset { Number } The offset to read data from (optional)
690
+ * @return { Number }
691
+ */
692
+ readDoubleBE(offset) {
693
+ return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset);
694
+ }
695
+ /**
696
+ * Reads an DoubleLE value from the current read position or an optionally provided offset.
697
+ *
698
+ * @param offset { Number } The offset to read data from (optional)
699
+ * @return { Number }
700
+ */
701
+ readDoubleLE(offset) {
702
+ return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset);
703
+ }
704
+ /**
705
+ * Writes a DoubleBE value to the current write position (or at optional offset).
706
+ *
707
+ * @param value { Number } The value to write.
708
+ * @param offset { Number } The offset to write the value at.
709
+ *
710
+ * @return this
711
+ */
712
+ writeDoubleBE(value, offset) {
713
+ return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
714
+ }
715
+ /**
716
+ * Inserts a DoubleBE value at the given offset value.
717
+ *
718
+ * @param value { Number } The value to insert.
719
+ * @param offset { Number } The offset to insert the value at.
720
+ *
721
+ * @return this
722
+ */
723
+ insertDoubleBE(value, offset) {
724
+ return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
725
+ }
726
+ /**
727
+ * Writes a DoubleLE value to the current write position (or at optional offset).
728
+ *
729
+ * @param value { Number } The value to write.
730
+ * @param offset { Number } The offset to write the value at.
731
+ *
732
+ * @return this
733
+ */
734
+ writeDoubleLE(value, offset) {
735
+ return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
736
+ }
737
+ /**
738
+ * Inserts a DoubleLE value at the given offset value.
739
+ *
740
+ * @param value { Number } The value to insert.
741
+ * @param offset { Number } The offset to insert the value at.
742
+ *
743
+ * @return this
744
+ */
745
+ insertDoubleLE(value, offset) {
746
+ return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
747
+ }
748
+ // Strings
749
+ /**
750
+ * Reads a String from the current read position.
751
+ *
752
+ * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for
753
+ * the string (Defaults to instance level encoding).
754
+ * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
755
+ *
756
+ * @return { String }
757
+ */
758
+ readString(arg1, encoding) {
759
+ let lengthVal;
760
+ if (typeof arg1 === "number") {
761
+ utils_1.checkLengthValue(arg1);
762
+ lengthVal = Math.min(arg1, this.length - this._readOffset);
763
+ } else {
764
+ encoding = arg1;
765
+ lengthVal = this.length - this._readOffset;
766
+ }
767
+ if (typeof encoding !== "undefined") {
768
+ utils_1.checkEncoding(encoding);
769
+ }
770
+ const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding);
771
+ this._readOffset += lengthVal;
772
+ return value;
773
+ }
774
+ /**
775
+ * Inserts a String
776
+ *
777
+ * @param value { String } The String value to insert.
778
+ * @param offset { Number } The offset to insert the string at.
779
+ * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
780
+ *
781
+ * @return this
782
+ */
783
+ insertString(value, offset, encoding) {
784
+ utils_1.checkOffsetValue(offset);
785
+ return this._handleString(value, true, offset, encoding);
786
+ }
787
+ /**
788
+ * Writes a String
789
+ *
790
+ * @param value { String } The String value to write.
791
+ * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use.
792
+ * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
793
+ *
794
+ * @return this
795
+ */
796
+ writeString(value, arg2, encoding) {
797
+ return this._handleString(value, false, arg2, encoding);
798
+ }
799
+ /**
800
+ * Reads a null-terminated String from the current read position.
801
+ *
802
+ * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
803
+ *
804
+ * @return { String }
805
+ */
806
+ readStringNT(encoding) {
807
+ if (typeof encoding !== "undefined") {
808
+ utils_1.checkEncoding(encoding);
809
+ }
810
+ let nullPos = this.length;
811
+ for (let i = this._readOffset; i < this.length; i++) {
812
+ if (this._buff[i] === 0) {
813
+ nullPos = i;
814
+ break;
815
+ }
816
+ }
817
+ const value = this._buff.slice(this._readOffset, nullPos);
818
+ this._readOffset = nullPos + 1;
819
+ return value.toString(encoding || this._encoding);
820
+ }
821
+ /**
822
+ * Inserts a null-terminated String.
823
+ *
824
+ * @param value { String } The String value to write.
825
+ * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
826
+ * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
827
+ *
828
+ * @return this
829
+ */
830
+ insertStringNT(value, offset, encoding) {
831
+ utils_1.checkOffsetValue(offset);
832
+ this.insertString(value, offset, encoding);
833
+ this.insertUInt8(0, offset + value.length);
834
+ return this;
835
+ }
836
+ /**
837
+ * Writes a null-terminated String.
838
+ *
839
+ * @param value { String } The String value to write.
840
+ * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
841
+ * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
842
+ *
843
+ * @return this
844
+ */
845
+ writeStringNT(value, arg2, encoding) {
846
+ this.writeString(value, arg2, encoding);
847
+ this.writeUInt8(0, typeof arg2 === "number" ? arg2 + value.length : this.writeOffset);
848
+ return this;
849
+ }
850
+ // Buffers
851
+ /**
852
+ * Reads a Buffer from the internal read position.
853
+ *
854
+ * @param length { Number } The length of data to read as a Buffer.
855
+ *
856
+ * @return { Buffer }
857
+ */
858
+ readBuffer(length) {
859
+ if (typeof length !== "undefined") {
860
+ utils_1.checkLengthValue(length);
861
+ }
862
+ const lengthVal = typeof length === "number" ? length : this.length;
863
+ const endPoint = Math.min(this.length, this._readOffset + lengthVal);
864
+ const value = this._buff.slice(this._readOffset, endPoint);
865
+ this._readOffset = endPoint;
866
+ return value;
867
+ }
868
+ /**
869
+ * Writes a Buffer to the current write position.
870
+ *
871
+ * @param value { Buffer } The Buffer to write.
872
+ * @param offset { Number } The offset to write the Buffer to.
873
+ *
874
+ * @return this
875
+ */
876
+ insertBuffer(value, offset) {
877
+ utils_1.checkOffsetValue(offset);
878
+ return this._handleBuffer(value, true, offset);
879
+ }
880
+ /**
881
+ * Writes a Buffer to the current write position.
882
+ *
883
+ * @param value { Buffer } The Buffer to write.
884
+ * @param offset { Number } The offset to write the Buffer to.
885
+ *
886
+ * @return this
887
+ */
888
+ writeBuffer(value, offset) {
889
+ return this._handleBuffer(value, false, offset);
890
+ }
891
+ /**
892
+ * Reads a null-terminated Buffer from the current read poisiton.
893
+ *
894
+ * @return { Buffer }
895
+ */
896
+ readBufferNT() {
897
+ let nullPos = this.length;
898
+ for (let i = this._readOffset; i < this.length; i++) {
899
+ if (this._buff[i] === 0) {
900
+ nullPos = i;
901
+ break;
902
+ }
903
+ }
904
+ const value = this._buff.slice(this._readOffset, nullPos);
905
+ this._readOffset = nullPos + 1;
906
+ return value;
907
+ }
908
+ /**
909
+ * Inserts a null-terminated Buffer.
910
+ *
911
+ * @param value { Buffer } The Buffer to write.
912
+ * @param offset { Number } The offset to write the Buffer to.
913
+ *
914
+ * @return this
915
+ */
916
+ insertBufferNT(value, offset) {
917
+ utils_1.checkOffsetValue(offset);
918
+ this.insertBuffer(value, offset);
919
+ this.insertUInt8(0, offset + value.length);
920
+ return this;
921
+ }
922
+ /**
923
+ * Writes a null-terminated Buffer.
924
+ *
925
+ * @param value { Buffer } The Buffer to write.
926
+ * @param offset { Number } The offset to write the Buffer to.
927
+ *
928
+ * @return this
929
+ */
930
+ writeBufferNT(value, offset) {
931
+ if (typeof offset !== "undefined") {
932
+ utils_1.checkOffsetValue(offset);
933
+ }
934
+ this.writeBuffer(value, offset);
935
+ this.writeUInt8(0, typeof offset === "number" ? offset + value.length : this._writeOffset);
936
+ return this;
937
+ }
938
+ /**
939
+ * Clears the SmartBuffer instance to its original empty state.
940
+ */
941
+ clear() {
942
+ this._writeOffset = 0;
943
+ this._readOffset = 0;
944
+ this.length = 0;
945
+ return this;
946
+ }
947
+ /**
948
+ * Gets the remaining data left to be read from the SmartBuffer instance.
949
+ *
950
+ * @return { Number }
951
+ */
952
+ remaining() {
953
+ return this.length - this._readOffset;
954
+ }
955
+ /**
956
+ * Gets the current read offset value of the SmartBuffer instance.
957
+ *
958
+ * @return { Number }
959
+ */
960
+ get readOffset() {
961
+ return this._readOffset;
962
+ }
963
+ /**
964
+ * Sets the read offset value of the SmartBuffer instance.
965
+ *
966
+ * @param offset { Number } - The offset value to set.
967
+ */
968
+ set readOffset(offset) {
969
+ utils_1.checkOffsetValue(offset);
970
+ utils_1.checkTargetOffset(offset, this);
971
+ this._readOffset = offset;
972
+ }
973
+ /**
974
+ * Gets the current write offset value of the SmartBuffer instance.
975
+ *
976
+ * @return { Number }
977
+ */
978
+ get writeOffset() {
979
+ return this._writeOffset;
980
+ }
981
+ /**
982
+ * Sets the write offset value of the SmartBuffer instance.
983
+ *
984
+ * @param offset { Number } - The offset value to set.
985
+ */
986
+ set writeOffset(offset) {
987
+ utils_1.checkOffsetValue(offset);
988
+ utils_1.checkTargetOffset(offset, this);
989
+ this._writeOffset = offset;
990
+ }
991
+ /**
992
+ * Gets the currently set string encoding of the SmartBuffer instance.
993
+ *
994
+ * @return { BufferEncoding } The string Buffer encoding currently set.
995
+ */
996
+ get encoding() {
997
+ return this._encoding;
998
+ }
999
+ /**
1000
+ * Sets the string encoding of the SmartBuffer instance.
1001
+ *
1002
+ * @param encoding { BufferEncoding } The string Buffer encoding to set.
1003
+ */
1004
+ set encoding(encoding) {
1005
+ utils_1.checkEncoding(encoding);
1006
+ this._encoding = encoding;
1007
+ }
1008
+ /**
1009
+ * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer)
1010
+ *
1011
+ * @return { Buffer } The Buffer value.
1012
+ */
1013
+ get internalBuffer() {
1014
+ return this._buff;
1015
+ }
1016
+ /**
1017
+ * Gets the value of the internal managed Buffer (Includes managed data only)
1018
+ *
1019
+ * @param { Buffer }
1020
+ */
1021
+ toBuffer() {
1022
+ return this._buff.slice(0, this.length);
1023
+ }
1024
+ /**
1025
+ * Gets the String value of the internal managed Buffer
1026
+ *
1027
+ * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding).
1028
+ */
1029
+ toString(encoding) {
1030
+ const encodingVal = typeof encoding === "string" ? encoding : this._encoding;
1031
+ utils_1.checkEncoding(encodingVal);
1032
+ return this._buff.toString(encodingVal, 0, this.length);
1033
+ }
1034
+ /**
1035
+ * Destroys the SmartBuffer instance.
1036
+ */
1037
+ destroy() {
1038
+ this.clear();
1039
+ return this;
1040
+ }
1041
+ /**
1042
+ * Handles inserting and writing strings.
1043
+ *
1044
+ * @param value { String } The String value to insert.
1045
+ * @param isInsert { Boolean } True if inserting a string, false if writing.
1046
+ * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use.
1047
+ * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
1048
+ */
1049
+ _handleString(value, isInsert, arg3, encoding) {
1050
+ let offsetVal = this._writeOffset;
1051
+ let encodingVal = this._encoding;
1052
+ if (typeof arg3 === "number") {
1053
+ offsetVal = arg3;
1054
+ } else if (typeof arg3 === "string") {
1055
+ utils_1.checkEncoding(arg3);
1056
+ encodingVal = arg3;
1057
+ }
1058
+ if (typeof encoding === "string") {
1059
+ utils_1.checkEncoding(encoding);
1060
+ encodingVal = encoding;
1061
+ }
1062
+ const byteLength = Buffer.byteLength(value, encodingVal);
1063
+ if (isInsert) {
1064
+ this.ensureInsertable(byteLength, offsetVal);
1065
+ } else {
1066
+ this._ensureWriteable(byteLength, offsetVal);
1067
+ }
1068
+ this._buff.write(value, offsetVal, byteLength, encodingVal);
1069
+ if (isInsert) {
1070
+ this._writeOffset += byteLength;
1071
+ } else {
1072
+ if (typeof arg3 === "number") {
1073
+ this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength);
1074
+ } else {
1075
+ this._writeOffset += byteLength;
1076
+ }
1077
+ }
1078
+ return this;
1079
+ }
1080
+ /**
1081
+ * Handles writing or insert of a Buffer.
1082
+ *
1083
+ * @param value { Buffer } The Buffer to write.
1084
+ * @param offset { Number } The offset to write the Buffer to.
1085
+ */
1086
+ _handleBuffer(value, isInsert, offset) {
1087
+ const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
1088
+ if (isInsert) {
1089
+ this.ensureInsertable(value.length, offsetVal);
1090
+ } else {
1091
+ this._ensureWriteable(value.length, offsetVal);
1092
+ }
1093
+ value.copy(this._buff, offsetVal);
1094
+ if (isInsert) {
1095
+ this._writeOffset += value.length;
1096
+ } else {
1097
+ if (typeof offset === "number") {
1098
+ this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length);
1099
+ } else {
1100
+ this._writeOffset += value.length;
1101
+ }
1102
+ }
1103
+ return this;
1104
+ }
1105
+ /**
1106
+ * Ensures that the internal Buffer is large enough to read data.
1107
+ *
1108
+ * @param length { Number } The length of the data that needs to be read.
1109
+ * @param offset { Number } The offset of the data that needs to be read.
1110
+ */
1111
+ ensureReadable(length, offset) {
1112
+ let offsetVal = this._readOffset;
1113
+ if (typeof offset !== "undefined") {
1114
+ utils_1.checkOffsetValue(offset);
1115
+ offsetVal = offset;
1116
+ }
1117
+ if (offsetVal < 0 || offsetVal + length > this.length) {
1118
+ throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS);
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Ensures that the internal Buffer is large enough to insert data.
1123
+ *
1124
+ * @param dataLength { Number } The length of the data that needs to be written.
1125
+ * @param offset { Number } The offset of the data to be written.
1126
+ */
1127
+ ensureInsertable(dataLength, offset) {
1128
+ utils_1.checkOffsetValue(offset);
1129
+ this._ensureCapacity(this.length + dataLength);
1130
+ if (offset < this.length) {
1131
+ this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length);
1132
+ }
1133
+ if (offset + dataLength > this.length) {
1134
+ this.length = offset + dataLength;
1135
+ } else {
1136
+ this.length += dataLength;
1137
+ }
1138
+ }
1139
+ /**
1140
+ * Ensures that the internal Buffer is large enough to write data.
1141
+ *
1142
+ * @param dataLength { Number } The length of the data that needs to be written.
1143
+ * @param offset { Number } The offset of the data to be written (defaults to writeOffset).
1144
+ */
1145
+ _ensureWriteable(dataLength, offset) {
1146
+ const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
1147
+ this._ensureCapacity(offsetVal + dataLength);
1148
+ if (offsetVal + dataLength > this.length) {
1149
+ this.length = offsetVal + dataLength;
1150
+ }
1151
+ }
1152
+ /**
1153
+ * Ensures that the internal Buffer is large enough to write at least the given amount of data.
1154
+ *
1155
+ * @param minLength { Number } The minimum length of the data needs to be written.
1156
+ */
1157
+ _ensureCapacity(minLength) {
1158
+ const oldLength = this._buff.length;
1159
+ if (minLength > oldLength) {
1160
+ let data = this._buff;
1161
+ let newLength = oldLength * 3 / 2 + 1;
1162
+ if (newLength < minLength) {
1163
+ newLength = minLength;
1164
+ }
1165
+ this._buff = Buffer.allocUnsafe(newLength);
1166
+ data.copy(this._buff, 0, 0, oldLength);
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Reads a numeric number value using the provided function.
1171
+ *
1172
+ * @typeparam T { number | bigint } The type of the value to be read
1173
+ *
1174
+ * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with.
1175
+ * @param byteSize { Number } The number of bytes read.
1176
+ * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead.
1177
+ *
1178
+ * @returns { T } the number value
1179
+ */
1180
+ _readNumberValue(func, byteSize, offset) {
1181
+ this.ensureReadable(byteSize, offset);
1182
+ const value = func.call(this._buff, typeof offset === "number" ? offset : this._readOffset);
1183
+ if (typeof offset === "undefined") {
1184
+ this._readOffset += byteSize;
1185
+ }
1186
+ return value;
1187
+ }
1188
+ /**
1189
+ * Inserts a numeric number value based on the given offset and value.
1190
+ *
1191
+ * @typeparam T { number | bigint } The type of the value to be written
1192
+ *
1193
+ * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
1194
+ * @param byteSize { Number } The number of bytes written.
1195
+ * @param value { T } The number value to write.
1196
+ * @param offset { Number } the offset to write the number at (REQUIRED).
1197
+ *
1198
+ * @returns SmartBuffer this buffer
1199
+ */
1200
+ _insertNumberValue(func, byteSize, value, offset) {
1201
+ utils_1.checkOffsetValue(offset);
1202
+ this.ensureInsertable(byteSize, offset);
1203
+ func.call(this._buff, value, offset);
1204
+ this._writeOffset += byteSize;
1205
+ return this;
1206
+ }
1207
+ /**
1208
+ * Writes a numeric number value based on the given offset and value.
1209
+ *
1210
+ * @typeparam T { number | bigint } The type of the value to be written
1211
+ *
1212
+ * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
1213
+ * @param byteSize { Number } The number of bytes written.
1214
+ * @param value { T } The number value to write.
1215
+ * @param offset { Number } the offset to write the number at (REQUIRED).
1216
+ *
1217
+ * @returns SmartBuffer this buffer
1218
+ */
1219
+ _writeNumberValue(func, byteSize, value, offset) {
1220
+ if (typeof offset === "number") {
1221
+ if (offset < 0) {
1222
+ throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);
1223
+ }
1224
+ utils_1.checkOffsetValue(offset);
1225
+ }
1226
+ const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
1227
+ this._ensureWriteable(byteSize, offsetVal);
1228
+ func.call(this._buff, value, offsetVal);
1229
+ if (typeof offset === "number") {
1230
+ this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize);
1231
+ } else {
1232
+ this._writeOffset += byteSize;
1233
+ }
1234
+ return this;
1235
+ }
1236
+ };
1237
+ exports.SmartBuffer = SmartBuffer;
1238
+ }
1239
+ });
1240
+
1241
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/constants.js
1242
+ var require_constants = __commonJS({
1243
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/constants.js"(exports) {
1244
+ "use strict";
1245
+ Object.defineProperty(exports, "__esModule", { value: true });
1246
+ exports.SOCKS5_NO_ACCEPTABLE_AUTH = exports.SOCKS5_CUSTOM_AUTH_END = exports.SOCKS5_CUSTOM_AUTH_START = exports.SOCKS_INCOMING_PACKET_SIZES = exports.SocksClientState = exports.Socks5Response = exports.Socks5HostType = exports.Socks5Auth = exports.Socks4Response = exports.SocksCommand = exports.ERRORS = exports.DEFAULT_TIMEOUT = void 0;
1247
+ var DEFAULT_TIMEOUT = 3e4;
1248
+ exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
1249
+ var ERRORS = {
1250
+ InvalidSocksCommand: "An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",
1251
+ InvalidSocksCommandForOperation: "An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",
1252
+ InvalidSocksCommandChain: "An invalid SOCKS command was provided. Chaining currently only supports the connect command.",
1253
+ InvalidSocksClientOptionsDestination: "An invalid destination host was provided.",
1254
+ InvalidSocksClientOptionsExistingSocket: "An invalid existing socket was provided. This should be an instance of stream.Duplex.",
1255
+ InvalidSocksClientOptionsProxy: "Invalid SOCKS proxy details were provided.",
1256
+ InvalidSocksClientOptionsTimeout: "An invalid timeout value was provided. Please enter a value above 0 (in ms).",
1257
+ InvalidSocksClientOptionsProxiesLength: "At least two socks proxies must be provided for chaining.",
1258
+ InvalidSocksClientOptionsCustomAuthRange: "Custom auth must be a value between 0x80 and 0xFE.",
1259
+ InvalidSocksClientOptionsCustomAuthOptions: "When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",
1260
+ NegotiationError: "Negotiation error",
1261
+ SocketClosed: "Socket closed",
1262
+ ProxyConnectionTimedOut: "Proxy connection timed out",
1263
+ InternalError: "SocksClient internal error (this should not happen)",
1264
+ InvalidSocks4HandshakeResponse: "Received invalid Socks4 handshake response",
1265
+ Socks4ProxyRejectedConnection: "Socks4 Proxy rejected connection",
1266
+ InvalidSocks4IncomingConnectionResponse: "Socks4 invalid incoming connection response",
1267
+ Socks4ProxyRejectedIncomingBoundConnection: "Socks4 Proxy rejected incoming bound connection",
1268
+ InvalidSocks5InitialHandshakeResponse: "Received invalid Socks5 initial handshake response",
1269
+ InvalidSocks5IntiailHandshakeSocksVersion: "Received invalid Socks5 initial handshake (invalid socks version)",
1270
+ InvalidSocks5InitialHandshakeNoAcceptedAuthType: "Received invalid Socks5 initial handshake (no accepted authentication type)",
1271
+ InvalidSocks5InitialHandshakeUnknownAuthType: "Received invalid Socks5 initial handshake (unknown authentication type)",
1272
+ Socks5AuthenticationFailed: "Socks5 Authentication failed",
1273
+ InvalidSocks5FinalHandshake: "Received invalid Socks5 final handshake response",
1274
+ InvalidSocks5FinalHandshakeRejected: "Socks5 proxy rejected connection",
1275
+ InvalidSocks5IncomingConnectionResponse: "Received invalid Socks5 incoming connection response",
1276
+ Socks5ProxyRejectedIncomingBoundConnection: "Socks5 Proxy rejected incoming bound connection"
1277
+ };
1278
+ exports.ERRORS = ERRORS;
1279
+ var SOCKS_INCOMING_PACKET_SIZES = {
1280
+ Socks5InitialHandshakeResponse: 2,
1281
+ Socks5UserPassAuthenticationResponse: 2,
1282
+ // Command response + incoming connection (bind)
1283
+ Socks5ResponseHeader: 5,
1284
+ // We need at least 5 to read the hostname length, then we wait for the address+port information.
1285
+ Socks5ResponseIPv4: 10,
1286
+ // 4 header + 4 ip + 2 port
1287
+ Socks5ResponseIPv6: 22,
1288
+ // 4 header + 16 ip + 2 port
1289
+ Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7,
1290
+ // 4 header + 1 host length + host + 2 port
1291
+ // Command response + incoming connection (bind)
1292
+ Socks4Response: 8
1293
+ // 2 header + 2 port + 4 ip
1294
+ };
1295
+ exports.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES;
1296
+ var SocksCommand;
1297
+ (function(SocksCommand2) {
1298
+ SocksCommand2[SocksCommand2["connect"] = 1] = "connect";
1299
+ SocksCommand2[SocksCommand2["bind"] = 2] = "bind";
1300
+ SocksCommand2[SocksCommand2["associate"] = 3] = "associate";
1301
+ })(SocksCommand || (exports.SocksCommand = SocksCommand = {}));
1302
+ var Socks4Response;
1303
+ (function(Socks4Response2) {
1304
+ Socks4Response2[Socks4Response2["Granted"] = 90] = "Granted";
1305
+ Socks4Response2[Socks4Response2["Failed"] = 91] = "Failed";
1306
+ Socks4Response2[Socks4Response2["Rejected"] = 92] = "Rejected";
1307
+ Socks4Response2[Socks4Response2["RejectedIdent"] = 93] = "RejectedIdent";
1308
+ })(Socks4Response || (exports.Socks4Response = Socks4Response = {}));
1309
+ var Socks5Auth;
1310
+ (function(Socks5Auth2) {
1311
+ Socks5Auth2[Socks5Auth2["NoAuth"] = 0] = "NoAuth";
1312
+ Socks5Auth2[Socks5Auth2["GSSApi"] = 1] = "GSSApi";
1313
+ Socks5Auth2[Socks5Auth2["UserPass"] = 2] = "UserPass";
1314
+ })(Socks5Auth || (exports.Socks5Auth = Socks5Auth = {}));
1315
+ var SOCKS5_CUSTOM_AUTH_START = 128;
1316
+ exports.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START;
1317
+ var SOCKS5_CUSTOM_AUTH_END = 254;
1318
+ exports.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END;
1319
+ var SOCKS5_NO_ACCEPTABLE_AUTH = 255;
1320
+ exports.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH;
1321
+ var Socks5Response;
1322
+ (function(Socks5Response2) {
1323
+ Socks5Response2[Socks5Response2["Granted"] = 0] = "Granted";
1324
+ Socks5Response2[Socks5Response2["Failure"] = 1] = "Failure";
1325
+ Socks5Response2[Socks5Response2["NotAllowed"] = 2] = "NotAllowed";
1326
+ Socks5Response2[Socks5Response2["NetworkUnreachable"] = 3] = "NetworkUnreachable";
1327
+ Socks5Response2[Socks5Response2["HostUnreachable"] = 4] = "HostUnreachable";
1328
+ Socks5Response2[Socks5Response2["ConnectionRefused"] = 5] = "ConnectionRefused";
1329
+ Socks5Response2[Socks5Response2["TTLExpired"] = 6] = "TTLExpired";
1330
+ Socks5Response2[Socks5Response2["CommandNotSupported"] = 7] = "CommandNotSupported";
1331
+ Socks5Response2[Socks5Response2["AddressNotSupported"] = 8] = "AddressNotSupported";
1332
+ })(Socks5Response || (exports.Socks5Response = Socks5Response = {}));
1333
+ var Socks5HostType;
1334
+ (function(Socks5HostType2) {
1335
+ Socks5HostType2[Socks5HostType2["IPv4"] = 1] = "IPv4";
1336
+ Socks5HostType2[Socks5HostType2["Hostname"] = 3] = "Hostname";
1337
+ Socks5HostType2[Socks5HostType2["IPv6"] = 4] = "IPv6";
1338
+ })(Socks5HostType || (exports.Socks5HostType = Socks5HostType = {}));
1339
+ var SocksClientState;
1340
+ (function(SocksClientState2) {
1341
+ SocksClientState2[SocksClientState2["Created"] = 0] = "Created";
1342
+ SocksClientState2[SocksClientState2["Connecting"] = 1] = "Connecting";
1343
+ SocksClientState2[SocksClientState2["Connected"] = 2] = "Connected";
1344
+ SocksClientState2[SocksClientState2["SentInitialHandshake"] = 3] = "SentInitialHandshake";
1345
+ SocksClientState2[SocksClientState2["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse";
1346
+ SocksClientState2[SocksClientState2["SentAuthentication"] = 5] = "SentAuthentication";
1347
+ SocksClientState2[SocksClientState2["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse";
1348
+ SocksClientState2[SocksClientState2["SentFinalHandshake"] = 7] = "SentFinalHandshake";
1349
+ SocksClientState2[SocksClientState2["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse";
1350
+ SocksClientState2[SocksClientState2["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection";
1351
+ SocksClientState2[SocksClientState2["Established"] = 10] = "Established";
1352
+ SocksClientState2[SocksClientState2["Disconnected"] = 11] = "Disconnected";
1353
+ SocksClientState2[SocksClientState2["Error"] = 99] = "Error";
1354
+ })(SocksClientState || (exports.SocksClientState = SocksClientState = {}));
1355
+ }
1356
+ });
1357
+
1358
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/util.js
1359
+ var require_util = __commonJS({
1360
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/util.js"(exports) {
1361
+ "use strict";
1362
+ Object.defineProperty(exports, "__esModule", { value: true });
1363
+ exports.SocksClientError = void 0;
1364
+ exports.shuffleArray = shuffleArray;
1365
+ var SocksClientError = class extends Error {
1366
+ constructor(message, options) {
1367
+ super(message);
1368
+ this.options = options;
1369
+ }
1370
+ };
1371
+ exports.SocksClientError = SocksClientError;
1372
+ function shuffleArray(array) {
1373
+ for (let i = array.length - 1; i > 0; i--) {
1374
+ const j = Math.floor(Math.random() * (i + 1));
1375
+ [array[i], array[j]] = [array[j], array[i]];
1376
+ }
1377
+ }
1378
+ }
1379
+ });
1380
+
1381
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/address-error.js
1382
+ var require_address_error = __commonJS({
1383
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/address-error.js"(exports) {
1384
+ "use strict";
1385
+ Object.defineProperty(exports, "__esModule", { value: true });
1386
+ exports.AddressError = void 0;
1387
+ var AddressError = class extends Error {
1388
+ constructor(message, parseMessage) {
1389
+ super(message);
1390
+ this.name = "AddressError";
1391
+ this.parseMessage = parseMessage;
1392
+ }
1393
+ };
1394
+ exports.AddressError = AddressError;
1395
+ }
1396
+ });
1397
+
1398
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/common.js
1399
+ var require_common = __commonJS({
1400
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/common.js"(exports) {
1401
+ "use strict";
1402
+ Object.defineProperty(exports, "__esModule", { value: true });
1403
+ exports.isInSubnet = isInSubnet;
1404
+ exports.isHostInSubnet = isHostInSubnet;
1405
+ exports.isGloballyReachable = isGloballyReachable;
1406
+ exports.offsetBigInt = offsetBigInt;
1407
+ exports.isCorrect = isCorrect;
1408
+ exports.prefixLengthFromMask = prefixLengthFromMask;
1409
+ exports.assertByteArray = assertByteArray;
1410
+ exports.numberToPaddedHex = numberToPaddedHex;
1411
+ exports.stringToPaddedHex = stringToPaddedHex;
1412
+ exports.testBit = testBit;
1413
+ var address_error_1 = require_address_error();
1414
+ function isInSubnet(address) {
1415
+ if (this.subnetMask < address.subnetMask) {
1416
+ return false;
1417
+ }
1418
+ return isHostInSubnet.call(this, address);
1419
+ }
1420
+ function isHostInSubnet(address) {
1421
+ return this.mask(address.subnetMask) === address.mask();
1422
+ }
1423
+ function isGloballyReachable(entries) {
1424
+ let best = null;
1425
+ for (let i = 0; i < entries.length; i++) {
1426
+ const entry = entries[i];
1427
+ if (entry.reachable !== null && isHostInSubnet.call(this, entry.subnet) && (best === null || entry.subnet.subnetMask > best.subnet.subnetMask)) {
1428
+ best = entry;
1429
+ }
1430
+ }
1431
+ return best === null ? true : best.reachable;
1432
+ }
1433
+ function offsetBigInt(value, n, bits, family) {
1434
+ if (typeof n === "number" && !Number.isSafeInteger(n)) {
1435
+ throw new address_error_1.AddressError(`${family} offset must be an integer`);
1436
+ }
1437
+ if (typeof n !== "number" && typeof n !== "bigint") {
1438
+ throw new address_error_1.AddressError(`${family} offset must be an integer`);
1439
+ }
1440
+ const result = value + BigInt(n);
1441
+ if (result < BigInt(0) || result > (BigInt(1) << BigInt(bits)) - BigInt(1)) {
1442
+ throw new address_error_1.AddressError(`${family} offset leaves the address space`);
1443
+ }
1444
+ return result;
1445
+ }
1446
+ function isCorrect(defaultBits) {
1447
+ return function isCorrectForm() {
1448
+ if (this.addressMinusSuffix !== this.correctForm()) {
1449
+ return false;
1450
+ }
1451
+ if (this.subnetMask === defaultBits && !this.parsedSubnet) {
1452
+ return true;
1453
+ }
1454
+ return this.parsedSubnet === String(this.subnetMask);
1455
+ };
1456
+ }
1457
+ function prefixLengthFromMask(value, totalBits) {
1458
+ const binary = value.toString(2).padStart(totalBits, "0");
1459
+ if (binary.length > totalBits) {
1460
+ throw new address_error_1.AddressError("Invalid subnet mask.");
1461
+ }
1462
+ const firstZero = binary.indexOf("0");
1463
+ if (firstZero === -1) {
1464
+ return totalBits;
1465
+ }
1466
+ if (binary.slice(firstZero).includes("1")) {
1467
+ throw new address_error_1.AddressError("Invalid subnet mask.");
1468
+ }
1469
+ return firstZero;
1470
+ }
1471
+ function assertByteArray(bytes, byteCount, family, minimum) {
1472
+ if (bytes.length !== byteCount) {
1473
+ throw new address_error_1.AddressError(`${family} addresses require exactly ${byteCount} bytes`);
1474
+ }
1475
+ for (let i = 0; i < bytes.length; i++) {
1476
+ if (!Number.isInteger(bytes[i]) || bytes[i] < minimum || bytes[i] > 255) {
1477
+ throw new address_error_1.AddressError(`All bytes must be integers between ${minimum} and 255`);
1478
+ }
1479
+ }
1480
+ }
1481
+ function numberToPaddedHex(number) {
1482
+ return number.toString(16).padStart(2, "0");
1483
+ }
1484
+ function stringToPaddedHex(numberString) {
1485
+ return numberToPaddedHex(parseInt(numberString, 10));
1486
+ }
1487
+ function testBit(binaryValue, position) {
1488
+ const { length } = binaryValue;
1489
+ if (position > length) {
1490
+ return false;
1491
+ }
1492
+ const positionInString = length - position;
1493
+ return binaryValue.substring(positionInString, positionInString + 1) === "1";
1494
+ }
1495
+ }
1496
+ });
1497
+
1498
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v4/constants.js
1499
+ var require_constants2 = __commonJS({
1500
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v4/constants.js"(exports) {
1501
+ "use strict";
1502
+ Object.defineProperty(exports, "__esModule", { value: true });
1503
+ exports.SPECIAL_PURPOSE = exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0;
1504
+ exports.BITS = 32;
1505
+ exports.GROUPS = 4;
1506
+ exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;
1507
+ exports.RE_SUBNET_STRING = /\/\d{1,2}$/;
1508
+ exports.SPECIAL_PURPOSE = [
1509
+ ["0.0.0.0/8", "This network", false],
1510
+ ["0.0.0.0/32", "This host on this network", false],
1511
+ ["10.0.0.0/8", "Private-Use", false],
1512
+ ["100.64.0.0/10", "Shared Address Space", false],
1513
+ ["127.0.0.0/8", "Loopback", false],
1514
+ ["169.254.0.0/16", "Link Local", false],
1515
+ ["172.16.0.0/12", "Private-Use", false],
1516
+ ["192.0.0.0/24", "IETF Protocol Assignments", false],
1517
+ ["192.0.0.0/29", "IPv4 Service Continuity Prefix", false],
1518
+ ["192.0.0.8/32", "IPv4 dummy address", false],
1519
+ ["192.0.0.9/32", "Port Control Protocol Anycast", true],
1520
+ ["192.0.0.10/32", "Traversal Using Relays around NAT Anycast", true],
1521
+ ["192.0.0.170/32", "NAT64/DNS64 Discovery", false],
1522
+ ["192.0.0.171/32", "NAT64/DNS64 Discovery", false],
1523
+ ["192.0.2.0/24", "Documentation (TEST-NET-1)", false],
1524
+ ["192.31.196.0/24", "AS112-v4", true],
1525
+ ["192.52.193.0/24", "AMT", true],
1526
+ ["192.88.99.0/24", "Deprecated (6to4 Relay Anycast)", null],
1527
+ ["192.88.99.2/32", "6a44-relay anycast address", false],
1528
+ ["192.168.0.0/16", "Private-Use", false],
1529
+ ["192.175.48.0/24", "Direct Delegation AS112 Service", true],
1530
+ ["198.18.0.0/15", "Benchmarking", false],
1531
+ ["198.51.100.0/24", "Documentation (TEST-NET-2)", false],
1532
+ ["203.0.113.0/24", "Documentation (TEST-NET-3)", false],
1533
+ ["240.0.0.0/4", "Reserved", false],
1534
+ ["255.255.255.255/32", "Limited Broadcast", false]
1535
+ ];
1536
+ }
1537
+ });
1538
+
1539
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ipv4.js
1540
+ var require_ipv4 = __commonJS({
1541
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ipv4.js"(exports) {
1542
+ "use strict";
1543
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
1544
+ if (k2 === void 0) k2 = k;
1545
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1546
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1547
+ desc = { enumerable: true, get: function() {
1548
+ return m[k];
1549
+ } };
1550
+ }
1551
+ Object.defineProperty(o, k2, desc);
1552
+ }) : (function(o, m, k, k2) {
1553
+ if (k2 === void 0) k2 = k;
1554
+ o[k2] = m[k];
1555
+ }));
1556
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
1557
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1558
+ }) : function(o, v) {
1559
+ o["default"] = v;
1560
+ });
1561
+ var __importStar = exports && exports.__importStar || function(mod) {
1562
+ if (mod && mod.__esModule) return mod;
1563
+ var result = {};
1564
+ if (mod != null) {
1565
+ for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1566
+ }
1567
+ __setModuleDefault(result, mod);
1568
+ return result;
1569
+ };
1570
+ Object.defineProperty(exports, "__esModule", { value: true });
1571
+ exports.Address4 = void 0;
1572
+ var common = __importStar(require_common());
1573
+ var constants = __importStar(require_constants2());
1574
+ var address_error_1 = require_address_error();
1575
+ var isCorrect4 = common.isCorrect(constants.BITS);
1576
+ var Address4 = class _Address4 {
1577
+ constructor(address) {
1578
+ this.addressMinusSuffix = "";
1579
+ this.groups = constants.GROUPS;
1580
+ this.parsedAddress = [];
1581
+ this.parsedSubnet = "";
1582
+ this.subnet = "/32";
1583
+ this.subnetMask = 32;
1584
+ this.v4 = true;
1585
+ this.isCorrect = isCorrect4;
1586
+ this.isInSubnet = common.isInSubnet;
1587
+ this.isHostInSubnet = common.isHostInSubnet;
1588
+ this.address = address;
1589
+ const subnet = constants.RE_SUBNET_STRING.exec(address);
1590
+ if (subnet) {
1591
+ this.parsedSubnet = subnet[0].replace("/", "");
1592
+ this.subnetMask = parseInt(this.parsedSubnet, 10);
1593
+ this.subnet = `/${this.subnetMask}`;
1594
+ if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
1595
+ throw new address_error_1.AddressError("Invalid subnet mask.");
1596
+ }
1597
+ address = address.replace(constants.RE_SUBNET_STRING, "");
1598
+ }
1599
+ this.addressMinusSuffix = address;
1600
+ this.parsedAddress = this.parse(address);
1601
+ }
1602
+ /**
1603
+ * Returns true if the given string is a valid IPv4 address (with optional
1604
+ * CIDR subnet), false otherwise. Host bits in the subnet portion are
1605
+ * allowed (e.g. `192.168.1.5/24` is valid); for strict network-address
1606
+ * validation compare `correctForm()` to `startAddress().correctForm()`,
1607
+ * or use `networkForm()`.
1608
+ */
1609
+ static isValid(address) {
1610
+ try {
1611
+ new _Address4(address);
1612
+ return true;
1613
+ } catch {
1614
+ return false;
1615
+ }
1616
+ }
1617
+ /**
1618
+ * Parses an IPv4 address string into its four octet groups and stores the
1619
+ * result on `this.parsedAddress`. Called automatically by the constructor;
1620
+ * you typically don't need to call it directly. Throws `AddressError` if
1621
+ * the input is not a valid IPv4 address.
1622
+ */
1623
+ parse(address) {
1624
+ const groups = address.split(".");
1625
+ if (groups.some((group) => /^0\d/.test(group))) {
1626
+ throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.");
1627
+ }
1628
+ if (!address.match(constants.RE_ADDRESS)) {
1629
+ throw new address_error_1.AddressError("Invalid IPv4 address.");
1630
+ }
1631
+ return groups;
1632
+ }
1633
+ /**
1634
+ * Returns the address in correct form: octets joined with `.` and any
1635
+ * leading zeros stripped (e.g. `192.168.1.1`). For IPv4 this matches the
1636
+ * canonical dotted-decimal representation.
1637
+ */
1638
+ correctForm() {
1639
+ return this.parsedAddress.map((part) => parseInt(part, 10)).join(".");
1640
+ }
1641
+ /**
1642
+ * Construct an `Address4` from an address and a dotted-decimal subnet
1643
+ * mask given as separate strings (e.g. as returned by Node's
1644
+ * `os.networkInterfaces()`). Throws `AddressError` if the mask is
1645
+ * non-contiguous (e.g. `255.0.255.0`).
1646
+ * @example
1647
+ * var address = Address4.fromAddressAndMask('192.168.1.1', '255.255.255.0');
1648
+ * address.subnetMask; // 24
1649
+ */
1650
+ static fromAddressAndMask(address, mask) {
1651
+ const bits = common.prefixLengthFromMask(new _Address4(mask).bigInt(), constants.BITS);
1652
+ return new _Address4(`${address}/${bits}`);
1653
+ }
1654
+ /**
1655
+ * Construct an `Address4` from an address and a Cisco-style wildcard mask
1656
+ * given as separate strings (e.g. `0.0.0.255` for a `/24`). The wildcard
1657
+ * mask is the bitwise inverse of the subnet mask. Throws `AddressError`
1658
+ * if the mask is non-contiguous (e.g. `0.255.0.255`).
1659
+ * @example
1660
+ * var address = Address4.fromAddressAndWildcardMask('10.0.0.1', '0.0.0.255');
1661
+ * address.subnetMask; // 24
1662
+ */
1663
+ static fromAddressAndWildcardMask(address, wildcardMask) {
1664
+ const wildcard = new _Address4(wildcardMask).bigInt();
1665
+ const allOnes = (BigInt(1) << BigInt(constants.BITS)) - BigInt(1);
1666
+ const mask = wildcard ^ allOnes;
1667
+ const bits = common.prefixLengthFromMask(mask, constants.BITS);
1668
+ return new _Address4(`${address}/${bits}`);
1669
+ }
1670
+ /**
1671
+ * Construct an `Address4` from a wildcard pattern with trailing `*`
1672
+ * octets. The number of trailing wildcards determines the prefix
1673
+ * length: each `*` represents 8 bits.
1674
+ *
1675
+ * Only trailing whole-octet wildcards are supported. Partial-octet
1676
+ * wildcards (e.g. `192.168.0.1*`) and interior wildcards (e.g.
1677
+ * `192.*.0.1`) throw `AddressError`.
1678
+ * @example
1679
+ * Address4.fromWildcard('192.168.0.*').subnet; // '/24'
1680
+ * Address4.fromWildcard('192.168.*.*').subnet; // '/16'
1681
+ * Address4.fromWildcard('*.*.*.*').subnet; // '/0'
1682
+ */
1683
+ static fromWildcard(input) {
1684
+ const groups = input.split(".");
1685
+ if (groups.length !== constants.GROUPS) {
1686
+ throw new address_error_1.AddressError("Wildcard pattern must have 4 octets");
1687
+ }
1688
+ let firstWildcard = -1;
1689
+ for (let i = 0; i < groups.length; i++) {
1690
+ if (groups[i] === "*") {
1691
+ if (firstWildcard === -1) {
1692
+ firstWildcard = i;
1693
+ }
1694
+ } else if (firstWildcard !== -1) {
1695
+ throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");
1696
+ }
1697
+ }
1698
+ const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard;
1699
+ const replaced = groups.map((g) => g === "*" ? "0" : g);
1700
+ const subnetBits = constants.BITS - trailing * 8;
1701
+ return new _Address4(`${replaced.join(".")}/${subnetBits}`);
1702
+ }
1703
+ /**
1704
+ * Converts a hex string to an IPv4 address object. Accepts 8 hex digits
1705
+ * with optional `:` separators (e.g. `'7f000001'` or `'7f:00:00:01'`).
1706
+ * Throws `AddressError` for any other length or for non-hex characters.
1707
+ * @param {string} hex - a hex string to convert
1708
+ * @returns {Address4}
1709
+ */
1710
+ static fromHex(hex) {
1711
+ const stripped = hex.replace(/:/g, "");
1712
+ if (!/^[0-9a-fA-F]{8}$/.test(stripped)) {
1713
+ throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits");
1714
+ }
1715
+ const groups = [];
1716
+ for (let i = 0; i < 8; i += 2) {
1717
+ groups.push(parseInt(stripped.slice(i, i + 2), 16));
1718
+ }
1719
+ return new _Address4(groups.join("."));
1720
+ }
1721
+ /**
1722
+ * Converts an integer into a IPv4 address object. The integer must be a
1723
+ * non-negative safe integer in the range `[0, 2**32 - 1]`; otherwise
1724
+ * `AddressError` is thrown.
1725
+ * @param {integer} integer - a number to convert
1726
+ * @returns {Address4}
1727
+ */
1728
+ static fromInteger(integer) {
1729
+ if (!Number.isInteger(integer) || integer < 0 || integer > 4294967295) {
1730
+ throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");
1731
+ }
1732
+ return _Address4.fromHex(integer.toString(16).padStart(8, "0"));
1733
+ }
1734
+ /**
1735
+ * Return an address from in-addr.arpa form
1736
+ * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
1737
+ * @returns {Adress4}
1738
+ * @example
1739
+ * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
1740
+ * address.correctForm(); // '192.0.2.42'
1741
+ */
1742
+ static fromArpa(arpaFormAddress) {
1743
+ const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, "");
1744
+ const address = leader.split(".").reverse().join(".");
1745
+ return new _Address4(address);
1746
+ }
1747
+ /**
1748
+ * Converts an IPv4 address object to a hex string
1749
+ * @returns {String}
1750
+ */
1751
+ toHex() {
1752
+ return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(":");
1753
+ }
1754
+ /**
1755
+ * Converts an IPv4 address object to an array of bytes.
1756
+ *
1757
+ * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toArray())`.
1758
+ * @returns {Array}
1759
+ */
1760
+ toArray() {
1761
+ return this.parsedAddress.map((part) => parseInt(part, 10));
1762
+ }
1763
+ /**
1764
+ * Converts an IPv4 address object to an IPv6 address group
1765
+ * @returns {String}
1766
+ */
1767
+ toGroup6() {
1768
+ const output = [];
1769
+ let i;
1770
+ for (i = 0; i < constants.GROUPS; i += 2) {
1771
+ output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`);
1772
+ }
1773
+ return output.join(":");
1774
+ }
1775
+ /**
1776
+ * Returns the address as a `bigint`
1777
+ * @returns {bigint}
1778
+ */
1779
+ bigInt() {
1780
+ return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join("")}`);
1781
+ }
1782
+ /**
1783
+ * Helper function getting start address.
1784
+ * @returns {bigint}
1785
+ */
1786
+ _startAddress() {
1787
+ return BigInt(`0b${this.mask() + "0".repeat(constants.BITS - this.subnetMask)}`);
1788
+ }
1789
+ /**
1790
+ * The first address in the range given by this address' subnet.
1791
+ * Often referred to as the Network Address.
1792
+ * @returns {Address4}
1793
+ */
1794
+ startAddress() {
1795
+ return _Address4.fromBigInt(this._startAddress());
1796
+ }
1797
+ /**
1798
+ * The first host address in the range given by this address's subnet ie
1799
+ * the first address after the Network Address
1800
+ * @returns {Address4}
1801
+ */
1802
+ startAddressExclusive() {
1803
+ const adjust = BigInt("1");
1804
+ return _Address4.fromBigInt(this._startAddress() + adjust);
1805
+ }
1806
+ /**
1807
+ * Returns the address `n` addresses after this one (or before, when `n` is
1808
+ * negative), keeping this address's subnet mask. Throws `AddressError` when
1809
+ * the result would fall outside the IPv4 address space or `n` is not an
1810
+ * integer.
1811
+ * @param {number | bigint} n
1812
+ * @returns {Address4}
1813
+ * @example
1814
+ * new Address4('10.0.0.0/24').offset(1).correctForm(); // '10.0.0.1'
1815
+ */
1816
+ offset(n) {
1817
+ return _Address4.fromBigInt(common.offsetBigInt(this.bigInt(), n, constants.BITS, "IPv4")).withSubnetMask(this.subnetMask);
1818
+ }
1819
+ /**
1820
+ * Returns the network that follows this address's network: the address after
1821
+ * {@link endAddress}, with the same subnet mask. Throws `AddressError` when
1822
+ * this network is the last one in the address space.
1823
+ * @returns {Address4}
1824
+ * @example
1825
+ * new Address4('10.0.0.0/24').nextNetwork().networkForm(); // '10.0.1.0/24'
1826
+ */
1827
+ nextNetwork() {
1828
+ return _Address4.fromBigInt(common.offsetBigInt(this._endAddress(), 1, constants.BITS, "IPv4")).withSubnetMask(this.subnetMask);
1829
+ }
1830
+ withSubnetMask(subnetMask) {
1831
+ return new _Address4(`${this.correctForm()}/${subnetMask}`);
1832
+ }
1833
+ /**
1834
+ * Helper function getting end address.
1835
+ * @returns {bigint}
1836
+ */
1837
+ _endAddress() {
1838
+ return BigInt(`0b${this.mask() + "1".repeat(constants.BITS - this.subnetMask)}`);
1839
+ }
1840
+ /**
1841
+ * The last address in the range given by this address' subnet
1842
+ * Often referred to as the Broadcast
1843
+ * @returns {Address4}
1844
+ */
1845
+ endAddress() {
1846
+ return _Address4.fromBigInt(this._endAddress());
1847
+ }
1848
+ /**
1849
+ * The last host address in the range given by this address's subnet ie
1850
+ * the last address prior to the Broadcast Address
1851
+ * @returns {Address4}
1852
+ */
1853
+ endAddressExclusive() {
1854
+ const adjust = BigInt("1");
1855
+ return _Address4.fromBigInt(this._endAddress() - adjust);
1856
+ }
1857
+ /**
1858
+ * The dotted-decimal form of the subnet mask, e.g. `255.255.240.0` for
1859
+ * a `/20`. Returns an `Address4`; call `.correctForm()` for the string.
1860
+ * @returns {Address4}
1861
+ */
1862
+ subnetMaskAddress() {
1863
+ return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS - this.subnetMask)}`));
1864
+ }
1865
+ /**
1866
+ * The Cisco-style wildcard mask, e.g. `0.0.0.255` for a `/24`. This is
1867
+ * the bitwise inverse of `subnetMaskAddress()`. Returns an `Address4`;
1868
+ * call `.correctForm()` for the string.
1869
+ * @returns {Address4}
1870
+ */
1871
+ wildcardMask() {
1872
+ return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS - this.subnetMask)}`));
1873
+ }
1874
+ /**
1875
+ * The network address in CIDR string form, e.g. `192.168.1.0/24` for
1876
+ * `192.168.1.5/24`. For an address with no explicit subnet the prefix is
1877
+ * `/32`, e.g. `networkForm()` on `192.168.1.5` returns `192.168.1.5/32`.
1878
+ * @returns {string}
1879
+ */
1880
+ networkForm() {
1881
+ return `${this.startAddress().correctForm()}/${this.subnetMask}`;
1882
+ }
1883
+ /**
1884
+ * Converts a BigInt to a v4 address object. The value must be in the
1885
+ * range `[0, 2**32 - 1]`; otherwise `AddressError` is thrown.
1886
+ * @param {bigint} bigInt - a BigInt to convert
1887
+ * @returns {Address4}
1888
+ */
1889
+ static fromBigInt(bigInt) {
1890
+ if (bigInt < BigInt(0) || bigInt > BigInt(4294967295)) {
1891
+ throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");
1892
+ }
1893
+ return _Address4.fromHex(bigInt.toString(16).padStart(8, "0"));
1894
+ }
1895
+ /**
1896
+ * Convert a byte array to an Address4 object. Throws `AddressError` unless
1897
+ * given exactly 4 integers from 0 to 255. Signed bytes are rejected, so
1898
+ * this differs from `Address6.fromByteArray`, which folds them; the two
1899
+ * contracts converge on this stricter form in the next major version.
1900
+ *
1901
+ * To convert from a Node.js `Buffer`, spread it: `Address4.fromByteArray([...buf])`.
1902
+ * @param {Array<number>} bytes - an array of 4 bytes (0-255)
1903
+ * @returns {Address4}
1904
+ */
1905
+ static fromByteArray(bytes) {
1906
+ common.assertByteArray(bytes, 4, "IPv4", 0);
1907
+ return this.fromUnsignedByteArray(bytes);
1908
+ }
1909
+ /**
1910
+ * Convert an unsigned byte array to an Address4 object. Throws
1911
+ * `AddressError` unless given exactly 4 bytes, and rejects values outside
1912
+ * 0 to 255 when parsing the resulting address.
1913
+ *
1914
+ * To convert from a Node.js `Buffer`, spread it:
1915
+ * `Address4.fromUnsignedByteArray([...buf])`.
1916
+ * @param {Array<number>} bytes - an array of 4 unsigned bytes (0-255)
1917
+ * @returns {Address4}
1918
+ */
1919
+ static fromUnsignedByteArray(bytes) {
1920
+ if (bytes.length !== 4) {
1921
+ throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");
1922
+ }
1923
+ const address = bytes.join(".");
1924
+ return new _Address4(address);
1925
+ }
1926
+ /**
1927
+ * Returns the first n bits of the address, defaulting to the
1928
+ * subnet mask
1929
+ * @returns {String}
1930
+ */
1931
+ mask(mask) {
1932
+ if (mask === void 0) {
1933
+ mask = this.subnetMask;
1934
+ }
1935
+ return this.getBitsBase2(0, mask);
1936
+ }
1937
+ /**
1938
+ * Returns the bits in the given range as a base-2 string
1939
+ * @returns {string}
1940
+ */
1941
+ getBitsBase2(start, end) {
1942
+ return this.binaryZeroPad().slice(start, end);
1943
+ }
1944
+ /**
1945
+ * Return the reversed in-addr.arpa form of the address, e.g.
1946
+ * `42.2.0.192.in-addr.arpa.` for `192.0.2.42`.
1947
+ * @param {Object} options
1948
+ * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
1949
+ * @returns {String}
1950
+ */
1951
+ reverseForm(options) {
1952
+ if (!options) {
1953
+ options = {};
1954
+ }
1955
+ const reversed = this.correctForm().split(".").reverse().join(".");
1956
+ if (options.omitSuffix) {
1957
+ return reversed;
1958
+ }
1959
+ return `${reversed}.in-addr.arpa.`;
1960
+ }
1961
+ /**
1962
+ * Returns true if the given address is a multicast address
1963
+ * @returns {boolean}
1964
+ */
1965
+ isMulticast() {
1966
+ return this.isHostInSubnet(MULTICAST_V4);
1967
+ }
1968
+ /**
1969
+ * Returns true if the address is in one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private address ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`).
1970
+ * @returns {boolean}
1971
+ */
1972
+ isPrivate() {
1973
+ return PRIVATE_V4.some((subnet) => this.isHostInSubnet(subnet));
1974
+ }
1975
+ /**
1976
+ * Returns true if the address is in the loopback range `127.0.0.0/8` ([RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122)).
1977
+ * @returns {boolean}
1978
+ */
1979
+ isLoopback() {
1980
+ return this.isHostInSubnet(LOOPBACK_V4);
1981
+ }
1982
+ /**
1983
+ * Returns true if the address is in the link-local range `169.254.0.0/16` ([RFC 3927](https://datatracker.ietf.org/doc/html/rfc3927)).
1984
+ * @returns {boolean}
1985
+ */
1986
+ isLinkLocal() {
1987
+ return this.isHostInSubnet(LINK_LOCAL_V4);
1988
+ }
1989
+ /**
1990
+ * Returns true if the address is the unspecified address `0.0.0.0`.
1991
+ * @returns {boolean}
1992
+ */
1993
+ isUnspecified() {
1994
+ return this.isHostInSubnet(UNSPECIFIED_V4);
1995
+ }
1996
+ /**
1997
+ * Returns true if the address is the limited broadcast address `255.255.255.255` ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)).
1998
+ * @returns {boolean}
1999
+ */
2000
+ isBroadcast() {
2001
+ return this.isHostInSubnet(BROADCAST_V4);
2002
+ }
2003
+ /**
2004
+ * Returns true if the address is in the carrier-grade NAT range `100.64.0.0/10` ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)).
2005
+ * @returns {boolean}
2006
+ */
2007
+ isCGNAT() {
2008
+ return this.isHostInSubnet(CGNAT_V4);
2009
+ }
2010
+ /**
2011
+ * Returns true if the address is in one of the documentation ranges
2012
+ * `192.0.2.0/24`, `198.51.100.0/24`, or `203.0.113.0/24` ([RFC 5737](https://datatracker.ietf.org/doc/html/rfc5737)).
2013
+ * @returns {boolean}
2014
+ */
2015
+ isDocumentation() {
2016
+ return DOCUMENTATION_V4.some((subnet) => this.isHostInSubnet(subnet));
2017
+ }
2018
+ /**
2019
+ * Returns true if the address is in the benchmarking range `198.18.0.0/15` ([RFC 2544](https://datatracker.ietf.org/doc/html/rfc2544)).
2020
+ * @returns {boolean}
2021
+ */
2022
+ isBenchmarking() {
2023
+ return this.isHostInSubnet(BENCHMARKING_V4);
2024
+ }
2025
+ /**
2026
+ * Returns true if the address is in the reserved range `240.0.0.0/4` ([RFC 1112](https://datatracker.ietf.org/doc/html/rfc1112)),
2027
+ * which includes the limited broadcast address.
2028
+ * @returns {boolean}
2029
+ */
2030
+ isReserved() {
2031
+ return this.isHostInSubnet(RESERVED_V4);
2032
+ }
2033
+ /**
2034
+ * Returns true if the address is globally reachable: not multicast, and not
2035
+ * in any block the [IANA IPv4 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv4-special-registry/)
2036
+ * marks as not globally reachable. That covers everything the individual
2037
+ * classifiers name (private, loopback, link-local, CGNAT, unspecified,
2038
+ * broadcast, documentation, benchmarking, reserved) and the blocks they do
2039
+ * not, such as `0.0.0.0/8` and the IETF protocol assignments in
2040
+ * `192.0.0.0/24`. This is the single predicate to use where a request must
2041
+ * not reach an internal or special-purpose destination; see SECURITY.md.
2042
+ * @returns {boolean}
2043
+ */
2044
+ isGlobal() {
2045
+ return !this.isMulticast() && common.isGloballyReachable.call(this, SPECIAL_PURPOSE_V4);
2046
+ }
2047
+ /**
2048
+ * Returns a zero-padded base-2 string representation of the address
2049
+ * @returns {string}
2050
+ */
2051
+ binaryZeroPad() {
2052
+ if (this._binaryZeroPad === void 0) {
2053
+ this._binaryZeroPad = this.bigInt().toString(2).padStart(constants.BITS, "0");
2054
+ }
2055
+ return this._binaryZeroPad;
2056
+ }
2057
+ /**
2058
+ * Groups an IPv4 address for inclusion at the end of an IPv6 address.
2059
+ *
2060
+ * Returns an HTML fragment: each half of the address is wrapped in a
2061
+ * `<span>` carrying the group classes an address-inspector UI hovers on.
2062
+ * The address content is HTML-escaped; anything you concatenate around it
2063
+ * is your responsibility.
2064
+ * @returns {String}
2065
+ */
2066
+ groupForV6() {
2067
+ const segments = this.parsedAddress;
2068
+ return this.correctForm().replace(constants.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${segments.slice(0, 2).join(".")}</span>.<span class="hover-group group-v4 group-7">${segments.slice(2, 4).join(".")}</span>`);
2069
+ }
2070
+ };
2071
+ exports.Address4 = Address4;
2072
+ var MULTICAST_V4 = new Address4("224.0.0.0/4");
2073
+ var PRIVATE_V4 = [
2074
+ new Address4("10.0.0.0/8"),
2075
+ new Address4("172.16.0.0/12"),
2076
+ new Address4("192.168.0.0/16")
2077
+ ];
2078
+ var LOOPBACK_V4 = new Address4("127.0.0.0/8");
2079
+ var LINK_LOCAL_V4 = new Address4("169.254.0.0/16");
2080
+ var UNSPECIFIED_V4 = new Address4("0.0.0.0/32");
2081
+ var BROADCAST_V4 = new Address4("255.255.255.255/32");
2082
+ var CGNAT_V4 = new Address4("100.64.0.0/10");
2083
+ var DOCUMENTATION_V4 = [
2084
+ new Address4("192.0.2.0/24"),
2085
+ new Address4("198.51.100.0/24"),
2086
+ new Address4("203.0.113.0/24")
2087
+ ];
2088
+ var BENCHMARKING_V4 = new Address4("198.18.0.0/15");
2089
+ var RESERVED_V4 = new Address4("240.0.0.0/4");
2090
+ var SPECIAL_PURPOSE_V4 = constants.SPECIAL_PURPOSE.map(([cidr, , reachable]) => ({
2091
+ subnet: new Address4(cidr),
2092
+ reachable
2093
+ }));
2094
+ }
2095
+ });
2096
+
2097
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/constants.js
2098
+ var require_constants3 = __commonJS({
2099
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/constants.js"(exports) {
2100
+ "use strict";
2101
+ Object.defineProperty(exports, "__esModule", { value: true });
2102
+ exports.SPECIAL_PURPOSE = exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0;
2103
+ exports.BITS = 128;
2104
+ exports.GROUPS = 8;
2105
+ exports.SCOPES = {
2106
+ 0: "Reserved",
2107
+ 1: "Interface local",
2108
+ 2: "Link local",
2109
+ 4: "Admin local",
2110
+ 5: "Site local",
2111
+ 8: "Organization local",
2112
+ 14: "Global",
2113
+ 15: "Reserved"
2114
+ };
2115
+ exports.TYPES = {
2116
+ "ff01::1/128": "Multicast (All nodes on this interface)",
2117
+ "ff01::2/128": "Multicast (All routers on this interface)",
2118
+ "ff02::1/128": "Multicast (All nodes on this link)",
2119
+ "ff02::2/128": "Multicast (All routers on this link)",
2120
+ "ff05::2/128": "Multicast (All routers in this site)",
2121
+ "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)",
2122
+ "ff02::6/128": "Multicast (OSPFv3 AllDR routers)",
2123
+ "ff02::9/128": "Multicast (RIP routers)",
2124
+ "ff02::a/128": "Multicast (EIGRP routers)",
2125
+ "ff02::d/128": "Multicast (PIM routers)",
2126
+ "ff02::16/128": "Multicast (MLDv2 reports)",
2127
+ "ff01::fb/128": "Multicast (mDNSv6)",
2128
+ "ff02::fb/128": "Multicast (mDNSv6)",
2129
+ "ff05::fb/128": "Multicast (mDNSv6)",
2130
+ "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)",
2131
+ "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)",
2132
+ "ff02::1:3/128": "Multicast (All DHCP servers on this link)",
2133
+ "ff05::1:3/128": "Multicast (All DHCP servers in this site)",
2134
+ "::/128": "Unspecified",
2135
+ "::1/128": "Loopback",
2136
+ "::ffff:0:0/96": "IPv4-mapped",
2137
+ "ff00::/8": "Multicast",
2138
+ "fe80::/10": "Link-local unicast",
2139
+ "fc00::/7": "Unique local",
2140
+ "2001::/32": "Teredo",
2141
+ "2001:2::/48": "Benchmarking",
2142
+ "2002::/16": "6to4",
2143
+ "2001:db8::/32": "Documentation",
2144
+ "3fff::/20": "Documentation",
2145
+ "100::/64": "Discard-only",
2146
+ "fec0::/10": "Site-local unicast (deprecated)",
2147
+ "::/96": "IPv4-compatible (deprecated)",
2148
+ "64:ff9b::/96": "NAT64 (well-known)",
2149
+ "64:ff9b:1::/48": "NAT64 (local-use)"
2150
+ };
2151
+ exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
2152
+ exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
2153
+ exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
2154
+ exports.RE_ZONE_STRING = /%.*$/;
2155
+ exports.RE_URL = /^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;
2156
+ exports.RE_URL_WITH_PORT = /^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i;
2157
+ exports.SPECIAL_PURPOSE = [
2158
+ ["::1/128", "Loopback Address", false],
2159
+ ["::/128", "Unspecified Address", false],
2160
+ ["::ffff:0:0/96", "IPv4-mapped Address", false],
2161
+ ["64:ff9b::/96", "IPv4-IPv6 Translat.", true],
2162
+ ["64:ff9b:1::/48", "IPv4-IPv6 Translat.", false],
2163
+ ["100::/64", "Discard-Only Address Block", false],
2164
+ ["100:0:0:1::/64", "Dummy IPv6 Prefix", false],
2165
+ ["2001::/23", "IETF Protocol Assignments", false],
2166
+ ["2001::/32", "TEREDO", false],
2167
+ ["2001:1::1/128", "Port Control Protocol Anycast", true],
2168
+ ["2001:1::2/128", "Traversal Using Relays around NAT Anycast", true],
2169
+ ["2001:1::3/128", "DNS-SD Service Registration Protocol Anycast", true],
2170
+ ["2001:2::/48", "Benchmarking", false],
2171
+ ["2001:3::/32", "AMT", true],
2172
+ ["2001:4:112::/48", "AS112-v6", true],
2173
+ ["2001:10::/28", "Deprecated (previously ORCHID)", null],
2174
+ ["2001:20::/28", "ORCHIDv2", true],
2175
+ ["2001:30::/28", "Drone Remote ID Protocol Entity Tags (DETs) Prefix", true],
2176
+ ["2001:db8::/32", "Documentation", false],
2177
+ ["2002::/16", "6to4", false],
2178
+ ["2620:4f:8000::/48", "Direct Delegation AS112 Service", true],
2179
+ ["3fff::/20", "Documentation", false],
2180
+ ["5f00::/16", "Segment Routing (SRv6) SIDs", false],
2181
+ ["fc00::/7", "Unique-Local", false],
2182
+ ["fe80::/10", "Link-Local Unicast", false]
2183
+ ];
2184
+ }
2185
+ });
2186
+
2187
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/helpers.js
2188
+ var require_helpers = __commonJS({
2189
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/helpers.js"(exports) {
2190
+ "use strict";
2191
+ Object.defineProperty(exports, "__esModule", { value: true });
2192
+ exports.escapeHtml = escapeHtml;
2193
+ exports.spanAllZeroes = spanAllZeroes;
2194
+ exports.spanAll = spanAll;
2195
+ exports.spanLeadingZeroes = spanLeadingZeroes;
2196
+ exports.simpleGroup = simpleGroup;
2197
+ function escapeHtml(s) {
2198
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2199
+ }
2200
+ function spanAllZeroes(s) {
2201
+ return escapeHtml(s).replace(/(0+)/g, '<span class="zero">$1</span>');
2202
+ }
2203
+ function spanAll(s, offset = 0) {
2204
+ const letters = s.split("");
2205
+ return letters.map((n, i) => `<span class="digit value-${escapeHtml(n)} position-${i + offset}">${spanAllZeroes(n)}</span>`).join("");
2206
+ }
2207
+ function spanLeadingZeroesSimple(group) {
2208
+ return escapeHtml(group).replace(/^(0+)/, '<span class="zero">$1</span>');
2209
+ }
2210
+ function spanLeadingZeroes(address) {
2211
+ const groups = address.split(":");
2212
+ return groups.map((g) => spanLeadingZeroesSimple(g)).join(":");
2213
+ }
2214
+ function simpleGroup(addressString, offset = 0) {
2215
+ const groups = addressString.split(":");
2216
+ return groups.map((g, i) => {
2217
+ if (/group-v4/.test(g)) {
2218
+ return g;
2219
+ }
2220
+ return `<span class="hover-group group-${i + offset}">${spanLeadingZeroesSimple(g)}</span>`;
2221
+ });
2222
+ }
2223
+ }
2224
+ });
2225
+
2226
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/regular-expressions.js
2227
+ var require_regular_expressions = __commonJS({
2228
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/v6/regular-expressions.js"(exports) {
2229
+ "use strict";
2230
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
2231
+ if (k2 === void 0) k2 = k;
2232
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2233
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2234
+ desc = { enumerable: true, get: function() {
2235
+ return m[k];
2236
+ } };
2237
+ }
2238
+ Object.defineProperty(o, k2, desc);
2239
+ }) : (function(o, m, k, k2) {
2240
+ if (k2 === void 0) k2 = k;
2241
+ o[k2] = m[k];
2242
+ }));
2243
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
2244
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2245
+ }) : function(o, v) {
2246
+ o["default"] = v;
2247
+ });
2248
+ var __importStar = exports && exports.__importStar || function(mod) {
2249
+ if (mod && mod.__esModule) return mod;
2250
+ var result = {};
2251
+ if (mod != null) {
2252
+ for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
2253
+ }
2254
+ __setModuleDefault(result, mod);
2255
+ return result;
2256
+ };
2257
+ Object.defineProperty(exports, "__esModule", { value: true });
2258
+ exports.ADDRESS_BOUNDARY = void 0;
2259
+ exports.groupPossibilities = groupPossibilities;
2260
+ exports.padGroup = padGroup;
2261
+ exports.simpleRegularExpression = simpleRegularExpression;
2262
+ exports.possibleElisions = possibleElisions;
2263
+ var v6 = __importStar(require_constants3());
2264
+ function groupPossibilities(possibilities) {
2265
+ return `(${possibilities.join("|")})`;
2266
+ }
2267
+ function padGroup(group) {
2268
+ if (group.length < 4) {
2269
+ return `0{0,${4 - group.length}}${group}`;
2270
+ }
2271
+ return group;
2272
+ }
2273
+ exports.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]";
2274
+ function simpleRegularExpression(groups) {
2275
+ const zeroIndexes = [];
2276
+ groups.forEach((group, i) => {
2277
+ const groupInteger = parseInt(group, 16);
2278
+ if (groupInteger === 0) {
2279
+ zeroIndexes.push(i);
2280
+ }
2281
+ });
2282
+ const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => {
2283
+ if (i === zeroIndex) {
2284
+ const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : "";
2285
+ return groupPossibilities([padGroup(group), elision]);
2286
+ }
2287
+ return padGroup(group);
2288
+ }).join(":"));
2289
+ possibilities.push(groups.map(padGroup).join(":"));
2290
+ return groupPossibilities(possibilities);
2291
+ }
2292
+ function possibleElisions(elidedGroups, moreLeft, moreRight) {
2293
+ const left = moreLeft ? "" : ":";
2294
+ const right = moreRight ? "" : ":";
2295
+ const possibilities = [];
2296
+ if (!moreLeft && !moreRight) {
2297
+ possibilities.push("::");
2298
+ }
2299
+ if (moreLeft && moreRight) {
2300
+ possibilities.push("");
2301
+ }
2302
+ if (moreRight && !moreLeft || !moreRight && moreLeft) {
2303
+ possibilities.push(":");
2304
+ }
2305
+ possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`);
2306
+ possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`);
2307
+ possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`);
2308
+ for (let groups = 1; groups < elidedGroups - 1; groups++) {
2309
+ for (let position = 1; position < elidedGroups - groups; position++) {
2310
+ possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`);
2311
+ }
2312
+ }
2313
+ return groupPossibilities(possibilities);
2314
+ }
2315
+ }
2316
+ });
2317
+
2318
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ipv6.js
2319
+ var require_ipv6 = __commonJS({
2320
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ipv6.js"(exports) {
2321
+ "use strict";
2322
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
2323
+ if (k2 === void 0) k2 = k;
2324
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2325
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2326
+ desc = { enumerable: true, get: function() {
2327
+ return m[k];
2328
+ } };
2329
+ }
2330
+ Object.defineProperty(o, k2, desc);
2331
+ }) : (function(o, m, k, k2) {
2332
+ if (k2 === void 0) k2 = k;
2333
+ o[k2] = m[k];
2334
+ }));
2335
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
2336
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2337
+ }) : function(o, v) {
2338
+ o["default"] = v;
2339
+ });
2340
+ var __importStar = exports && exports.__importStar || function(mod) {
2341
+ if (mod && mod.__esModule) return mod;
2342
+ var result = {};
2343
+ if (mod != null) {
2344
+ for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
2345
+ }
2346
+ __setModuleDefault(result, mod);
2347
+ return result;
2348
+ };
2349
+ Object.defineProperty(exports, "__esModule", { value: true });
2350
+ exports.Address6 = void 0;
2351
+ var common = __importStar(require_common());
2352
+ var constants4 = __importStar(require_constants2());
2353
+ var constants6 = __importStar(require_constants3());
2354
+ var helpers = __importStar(require_helpers());
2355
+ var ipv4_1 = require_ipv4();
2356
+ var regular_expressions_1 = require_regular_expressions();
2357
+ var address_error_1 = require_address_error();
2358
+ var common_1 = require_common();
2359
+ var isCorrect6 = common.isCorrect(constants6.BITS);
2360
+ function assert(condition) {
2361
+ if (!condition) {
2362
+ throw new Error("Assertion failed.");
2363
+ }
2364
+ }
2365
+ function addCommas(number) {
2366
+ const r = /(\d+)(\d{3})/;
2367
+ while (r.test(number)) {
2368
+ number = number.replace(r, "$1,$2");
2369
+ }
2370
+ return number;
2371
+ }
2372
+ function spanLeadingZeroes4(n) {
2373
+ n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
2374
+ n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
2375
+ return n;
2376
+ }
2377
+ function compact(address, slice) {
2378
+ const s1 = [];
2379
+ const s2 = [];
2380
+ let i;
2381
+ for (i = 0; i < address.length; i++) {
2382
+ if (i < slice[0]) {
2383
+ s1.push(address[i]);
2384
+ } else if (i > slice[1]) {
2385
+ s2.push(address[i]);
2386
+ }
2387
+ }
2388
+ return s1.concat(["compact"]).concat(s2);
2389
+ }
2390
+ function paddedHex(octet) {
2391
+ return parseInt(octet, 16).toString(16).padStart(4, "0");
2392
+ }
2393
+ function unsignByte(b) {
2394
+ return b & 255;
2395
+ }
2396
+ var Address6 = class _Address6 {
2397
+ constructor(address, optionalGroups) {
2398
+ this.addressMinusSuffix = "";
2399
+ this.parsedSubnet = "";
2400
+ this.subnet = "/128";
2401
+ this.subnetMask = 128;
2402
+ this.v4 = false;
2403
+ this.zone = "";
2404
+ this.isInSubnet = common.isInSubnet;
2405
+ this.isHostInSubnet = common.isHostInSubnet;
2406
+ this.isCorrect = isCorrect6;
2407
+ if (optionalGroups === void 0) {
2408
+ this.groups = constants6.GROUPS;
2409
+ } else {
2410
+ this.groups = optionalGroups;
2411
+ }
2412
+ this.address = address;
2413
+ const subnet = constants6.RE_SUBNET_STRING.exec(address);
2414
+ if (subnet) {
2415
+ this.parsedSubnet = subnet[0].replace("/", "");
2416
+ this.subnetMask = parseInt(this.parsedSubnet, 10);
2417
+ this.subnet = `/${this.subnetMask}`;
2418
+ if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) {
2419
+ throw new address_error_1.AddressError("Invalid subnet mask.");
2420
+ }
2421
+ address = address.replace(constants6.RE_SUBNET_STRING, "");
2422
+ }
2423
+ if (/\//.test(address)) {
2424
+ throw new address_error_1.AddressError("Invalid subnet mask.");
2425
+ }
2426
+ const zone = constants6.RE_ZONE_STRING.exec(address);
2427
+ if (zone) {
2428
+ this.zone = zone[0];
2429
+ address = address.replace(constants6.RE_ZONE_STRING, "");
2430
+ }
2431
+ this.addressMinusSuffix = address;
2432
+ this.parsedAddress = this.parse(this.addressMinusSuffix);
2433
+ }
2434
+ /**
2435
+ * Returns true if the given string is a valid IPv6 address (with optional
2436
+ * CIDR subnet and zone identifier), false otherwise. Host bits in the
2437
+ * subnet portion are allowed (e.g. `2001:db8::1/32` is valid); for strict
2438
+ * network-address validation compare `correctForm()` to
2439
+ * `startAddress().correctForm()`, or use `networkForm()`.
2440
+ */
2441
+ static isValid(address) {
2442
+ try {
2443
+ new _Address6(address);
2444
+ return true;
2445
+ } catch {
2446
+ return false;
2447
+ }
2448
+ }
2449
+ /**
2450
+ * Convert a BigInt to a v6 address object. The value must be in the
2451
+ * range `[0, 2**128 - 1]`; otherwise `AddressError` is thrown.
2452
+ * @param {bigint} bigInt - a BigInt to convert
2453
+ * @returns {Address6}
2454
+ * @example
2455
+ * var bigInt = BigInt('1000000000000');
2456
+ * var address = Address6.fromBigInt(bigInt);
2457
+ * address.correctForm(); // '::e8:d4a5:1000'
2458
+ */
2459
+ static fromBigInt(bigInt) {
2460
+ if (bigInt < BigInt(0) || bigInt > (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1)) {
2461
+ throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");
2462
+ }
2463
+ const hex = bigInt.toString(16).padStart(32, "0");
2464
+ const groups = [];
2465
+ for (let i = 0; i < constants6.GROUPS; i++) {
2466
+ groups.push(hex.slice(i * 4, (i + 1) * 4));
2467
+ }
2468
+ return new _Address6(groups.join(":"));
2469
+ }
2470
+ /**
2471
+ * Parse a URL (with optional bracketed host and port) into an address and
2472
+ * port. Returns either `{ address, port }` on success or
2473
+ * `{ error, address: null, port: null }` if the URL could not be parsed.
2474
+ * Ports are returned as numbers (or `null` if absent or out of range).
2475
+ * @example
2476
+ * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
2477
+ * addressAndPort.address.correctForm(); // 'ffff::'
2478
+ * addressAndPort.port; // 8080
2479
+ */
2480
+ static fromURL(url) {
2481
+ var _a;
2482
+ let host;
2483
+ let port = null;
2484
+ let result;
2485
+ let error;
2486
+ const stripped = url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
2487
+ if (stripped.indexOf("[") !== -1 && stripped.indexOf("]:") !== -1) {
2488
+ error = "failed to parse address with port";
2489
+ result = constants6.RE_URL_WITH_PORT.exec(stripped);
2490
+ if (result === null) {
2491
+ return { error, address: null, port: null };
2492
+ }
2493
+ host = result[1];
2494
+ port = result[2];
2495
+ } else {
2496
+ error = "failed to parse address from URL";
2497
+ result = constants6.RE_URL.exec(stripped);
2498
+ if (result === null) {
2499
+ return { error, address: null, port: null };
2500
+ }
2501
+ host = (_a = result[1]) !== null && _a !== void 0 ? _a : result[2];
2502
+ }
2503
+ if (port) {
2504
+ port = parseInt(port, 10);
2505
+ if (port < 0 || port > 65535) {
2506
+ port = null;
2507
+ }
2508
+ } else {
2509
+ port = null;
2510
+ }
2511
+ let address;
2512
+ try {
2513
+ address = new _Address6(host);
2514
+ } catch {
2515
+ return { error, address: null, port: null };
2516
+ }
2517
+ return { address, port };
2518
+ }
2519
+ /**
2520
+ * Construct an `Address6` from an address and a hex subnet mask given as
2521
+ * separate strings (e.g. as returned by Node's `os.networkInterfaces()`).
2522
+ * Throws `AddressError` if the mask is non-contiguous (e.g.
2523
+ * `ffff::ffff`).
2524
+ * @example
2525
+ * var address = Address6.fromAddressAndMask('fe80::1', 'ffff:ffff:ffff:ffff::');
2526
+ * address.subnetMask; // 64
2527
+ */
2528
+ static fromAddressAndMask(address, mask) {
2529
+ const bits = common.prefixLengthFromMask(new _Address6(mask).bigInt(), constants6.BITS);
2530
+ return new _Address6(`${address}/${bits}`);
2531
+ }
2532
+ /**
2533
+ * Construct an `Address6` from an address and a Cisco-style wildcard mask
2534
+ * given as separate strings (e.g. `::ffff:ffff:ffff:ffff` for a `/64`).
2535
+ * The wildcard mask is the bitwise inverse of the subnet mask. Throws
2536
+ * `AddressError` if the mask is non-contiguous.
2537
+ * @example
2538
+ * var address = Address6.fromAddressAndWildcardMask('fe80::1', '::ffff:ffff:ffff:ffff');
2539
+ * address.subnetMask; // 64
2540
+ */
2541
+ static fromAddressAndWildcardMask(address, wildcardMask) {
2542
+ const wildcard = new _Address6(wildcardMask).bigInt();
2543
+ const allOnes = (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1);
2544
+ const mask = wildcard ^ allOnes;
2545
+ const bits = common.prefixLengthFromMask(mask, constants6.BITS);
2546
+ return new _Address6(`${address}/${bits}`);
2547
+ }
2548
+ /**
2549
+ * Construct an `Address6` from a wildcard pattern with trailing `*`
2550
+ * groups. The number of trailing wildcards determines the prefix
2551
+ * length: each `*` represents 16 bits. `::` is expanded to zero groups
2552
+ * (not wildcards) before evaluating trailing wildcards.
2553
+ *
2554
+ * Only trailing whole-group wildcards are supported. Partial-group
2555
+ * wildcards (e.g. `2001:db8::0*`) and interior wildcards (e.g.
2556
+ * `*::1`) throw `AddressError`.
2557
+ * @example
2558
+ * Address6.fromWildcard('2001:db8:*:*:*:*:*:*').subnet; // '/32'
2559
+ * Address6.fromWildcard('2001:db8::*').subnet; // '/112'
2560
+ * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0'
2561
+ */
2562
+ static fromWildcard(input) {
2563
+ if (input.includes("%") || input.includes("/")) {
2564
+ throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix");
2565
+ }
2566
+ const halves = input.split("::");
2567
+ if (halves.length > 2) {
2568
+ throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'");
2569
+ }
2570
+ let groups;
2571
+ if (halves.length === 2) {
2572
+ const left = halves[0] === "" ? [] : halves[0].split(":");
2573
+ const right = halves[1] === "" ? [] : halves[1].split(":");
2574
+ const remaining = constants6.GROUPS - left.length - right.length;
2575
+ if (remaining < 1) {
2576
+ throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups");
2577
+ }
2578
+ groups = [...left, ...new Array(remaining).fill("0"), ...right];
2579
+ } else {
2580
+ groups = input.split(":");
2581
+ }
2582
+ if (groups.length !== constants6.GROUPS) {
2583
+ throw new address_error_1.AddressError("Wildcard pattern must have 8 groups");
2584
+ }
2585
+ let firstWildcard = -1;
2586
+ for (let i = 0; i < groups.length; i++) {
2587
+ if (groups[i] === "*") {
2588
+ if (firstWildcard === -1) {
2589
+ firstWildcard = i;
2590
+ }
2591
+ } else if (firstWildcard !== -1) {
2592
+ throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");
2593
+ }
2594
+ }
2595
+ const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard;
2596
+ const replaced = groups.map((g) => g === "*" ? "0" : g);
2597
+ const subnetBits = constants6.BITS - trailing * 16;
2598
+ return new _Address6(`${replaced.join(":")}/${subnetBits}`);
2599
+ }
2600
+ /**
2601
+ * Create an IPv6-mapped address given an IPv4 address
2602
+ * @param {string} address - An IPv4 address string
2603
+ * @returns {Address6}
2604
+ * @example
2605
+ * var address = Address6.fromAddress4('192.168.0.1');
2606
+ * address.correctForm(); // '::ffff:c0a8:1'
2607
+ * address.to4in6(); // '::ffff:192.168.0.1'
2608
+ */
2609
+ static fromAddress4(address) {
2610
+ const address4 = new ipv4_1.Address4(address);
2611
+ const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
2612
+ return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`);
2613
+ }
2614
+ /**
2615
+ * Return an address from ip6.arpa form. A full 32-nibble name gives a /128
2616
+ * address; a shorter name, as used for a delegated reverse zone, gives the
2617
+ * network it covers, with a subnet mask of four bits per nibble, so
2618
+ * `fromArpa(x.reverseForm())` round-trips {@link reverseForm} for any prefix.
2619
+ * @param {string} arpaFormAddress - an 'ip6.arpa' form address
2620
+ * @returns {Adress6}
2621
+ * @example
2622
+ * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
2623
+ * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
2624
+ * Address6.fromArpa('8.b.d.0.1.0.0.2.ip6.arpa.').networkForm(); // '2001:db8::/32'
2625
+ */
2626
+ static fromArpa(arpaFormAddress) {
2627
+ const nibbles = arpaFormAddress.replace(/(\.ip6\.arpa)?\.?$/, "");
2628
+ if (!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(nibbles)) {
2629
+ throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
2630
+ }
2631
+ const reversed = nibbles.split(".").reverse();
2632
+ const subnetMask = reversed.length * 4;
2633
+ const hex = reversed.join("").padEnd(32, "0");
2634
+ const groups = [];
2635
+ for (let i = 0; i < constants6.GROUPS; i++) {
2636
+ groups.push(hex.slice(i * 4, (i + 1) * 4));
2637
+ }
2638
+ return new _Address6(`${groups.join(":")}/${subnetMask}`);
2639
+ }
2640
+ /**
2641
+ * Return the Microsoft UNC transcription of the address
2642
+ * @returns {String} the Microsoft UNC transcription of the address
2643
+ */
2644
+ microsoftTranscription() {
2645
+ return `${this.correctForm().replace(/:/g, "-")}.ipv6-literal.net`;
2646
+ }
2647
+ /**
2648
+ * Return the first n bits of the address, defaulting to the subnet mask
2649
+ * @param {number} [mask=subnet] - the number of bits to mask
2650
+ * @returns {String} the first n bits of the address as a string
2651
+ */
2652
+ mask(mask = this.subnetMask) {
2653
+ return this.getBitsBase2(0, mask);
2654
+ }
2655
+ /**
2656
+ * Return the number of possible subnets of a given size in the address
2657
+ * @param {number} [subnetSize=128] - the subnet size
2658
+ * @returns {String}
2659
+ */
2660
+ // TODO: probably useful to have a numeric version of this too
2661
+ possibleSubnets(subnetSize = 128) {
2662
+ const availableBits = constants6.BITS - this.subnetMask;
2663
+ const subnetBits = Math.abs(subnetSize - constants6.BITS);
2664
+ const subnetPowers = availableBits - subnetBits;
2665
+ if (subnetPowers < 0) {
2666
+ return "0";
2667
+ }
2668
+ return addCommas((BigInt("2") ** BigInt(subnetPowers)).toString(10));
2669
+ }
2670
+ /**
2671
+ * Helper function getting start address.
2672
+ * @returns {bigint}
2673
+ */
2674
+ _startAddress() {
2675
+ return BigInt(`0b${this.mask() + "0".repeat(constants6.BITS - this.subnetMask)}`);
2676
+ }
2677
+ /**
2678
+ * The first address in the range given by this address' subnet
2679
+ * Often referred to as the Network Address.
2680
+ * @returns {Address6}
2681
+ */
2682
+ startAddress() {
2683
+ return _Address6.fromBigInt(this._startAddress());
2684
+ }
2685
+ /**
2686
+ * The first host address in the range given by this address's subnet ie
2687
+ * the first address after the Network Address
2688
+ * @returns {Address6}
2689
+ */
2690
+ startAddressExclusive() {
2691
+ const adjust = BigInt("1");
2692
+ return _Address6.fromBigInt(this._startAddress() + adjust);
2693
+ }
2694
+ /**
2695
+ * Helper function getting end address.
2696
+ * @returns {bigint}
2697
+ */
2698
+ _endAddress() {
2699
+ return BigInt(`0b${this.mask() + "1".repeat(constants6.BITS - this.subnetMask)}`);
2700
+ }
2701
+ /**
2702
+ * The last address in the range given by this address's subnet. IPv6 has
2703
+ * no broadcast address, so this is an ordinary assignable address (in a
2704
+ * 64-bit-interface-identifier subnet it falls inside the reserved
2705
+ * subnet-anycast block of [RFC 2526](https://datatracker.ietf.org/doc/html/rfc2526)).
2706
+ * @returns {Address6}
2707
+ */
2708
+ endAddress() {
2709
+ return _Address6.fromBigInt(this._endAddress());
2710
+ }
2711
+ /**
2712
+ * The address one before {@link endAddress}. This is the IPv6 counterpart
2713
+ * of the IPv4 method that skips the broadcast address; IPv6 has no broadcast,
2714
+ * so it drops exactly one address and does not model the 128 reserved
2715
+ * subnet-anycast identifiers of [RFC 2526](https://datatracker.ietf.org/doc/html/rfc2526).
2716
+ * @returns {Address6}
2717
+ */
2718
+ endAddressExclusive() {
2719
+ const adjust = BigInt("1");
2720
+ return _Address6.fromBigInt(this._endAddress() - adjust);
2721
+ }
2722
+ /**
2723
+ * Returns the address `n` addresses after this one (or before, when `n` is
2724
+ * negative), keeping this address's subnet mask. Throws `AddressError` when
2725
+ * the result would fall outside the IPv6 address space or `n` is not an
2726
+ * integer.
2727
+ * @param {number | bigint} n
2728
+ * @returns {Address6}
2729
+ * @example
2730
+ * new Address6('2001:db8::/64').offset(1).correctForm(); // '2001:db8::1'
2731
+ */
2732
+ offset(n) {
2733
+ return _Address6.fromBigInt(common.offsetBigInt(this.bigInt(), n, constants6.BITS, "IPv6")).withSubnetMask(this.subnetMask);
2734
+ }
2735
+ /**
2736
+ * Returns the network that follows this address's network: the address after
2737
+ * {@link endAddress}, with the same subnet mask. Throws `AddressError` when
2738
+ * this network is the last one in the address space.
2739
+ * @returns {Address6}
2740
+ * @example
2741
+ * new Address6('2001:db8::/64').nextNetwork().networkForm(); // '2001:db8:0:1::/64'
2742
+ */
2743
+ nextNetwork() {
2744
+ return _Address6.fromBigInt(common.offsetBigInt(this._endAddress(), 1, constants6.BITS, "IPv6")).withSubnetMask(this.subnetMask);
2745
+ }
2746
+ withSubnetMask(subnetMask) {
2747
+ return new _Address6(`${this.correctForm()}/${subnetMask}`);
2748
+ }
2749
+ /**
2750
+ * The hex form of the subnet mask, e.g. `ffff:ffff:ffff:ffff::` for a
2751
+ * `/64`. Returns an `Address6`; call `.correctForm()` for the string.
2752
+ * @returns {Address6}
2753
+ */
2754
+ subnetMaskAddress() {
2755
+ return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS - this.subnetMask)}`));
2756
+ }
2757
+ /**
2758
+ * The Cisco-style wildcard mask, e.g. `::ffff:ffff:ffff:ffff` for a
2759
+ * `/64`. This is the bitwise inverse of `subnetMaskAddress()`. Returns
2760
+ * an `Address6`; call `.correctForm()` for the string.
2761
+ * @returns {Address6}
2762
+ */
2763
+ wildcardMask() {
2764
+ return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS - this.subnetMask)}`));
2765
+ }
2766
+ /**
2767
+ * The network address in CIDR string form, e.g. `2001:db8::/32` for
2768
+ * `2001:db8::1/32`. For an address with no explicit subnet the prefix
2769
+ * is `/128`, e.g. `networkForm()` on `2001:db8::1` returns
2770
+ * `2001:db8::1/128`.
2771
+ * @returns {string}
2772
+ */
2773
+ networkForm() {
2774
+ return `${this.startAddress().correctForm()}/${this.subnetMask}`;
2775
+ }
2776
+ /**
2777
+ * Return the scope of the address. The 4-bit scope field
2778
+ * ([RFC 4291 §2.7](https://datatracker.ietf.org/doc/html/rfc4291#section-2.7))
2779
+ * is only defined for multicast addresses; for unicast addresses the scope
2780
+ * is derived from the address type per
2781
+ * [RFC 4007 §6](https://datatracker.ietf.org/doc/html/rfc4007#section-6).
2782
+ * @returns {String}
2783
+ */
2784
+ getScope() {
2785
+ const type = this.getType();
2786
+ if (type === "Multicast" || type.startsWith("Multicast ")) {
2787
+ const scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)];
2788
+ return scope || "Unknown";
2789
+ }
2790
+ if (type === "Link-local unicast" || type === "Loopback") {
2791
+ return "Link local";
2792
+ }
2793
+ if (type === "Unspecified") {
2794
+ return "Unknown";
2795
+ }
2796
+ return "Global";
2797
+ }
2798
+ /**
2799
+ * Return the type of the address
2800
+ * @returns {String}
2801
+ */
2802
+ getType() {
2803
+ for (let i = 0; i < TYPE_SUBNETS.length; i++) {
2804
+ const entry = TYPE_SUBNETS[i];
2805
+ if (this.isHostInSubnet(entry[0])) {
2806
+ return entry[1];
2807
+ }
2808
+ }
2809
+ return "Global unicast";
2810
+ }
2811
+ /**
2812
+ * Return the bits in the given range as a BigInt
2813
+ * @returns {bigint}
2814
+ */
2815
+ getBits(start, end) {
2816
+ return BigInt(`0b${this.getBitsBase2(start, end)}`);
2817
+ }
2818
+ /**
2819
+ * Return the bits in the given range as a base-2 string
2820
+ * @returns {String}
2821
+ */
2822
+ getBitsBase2(start, end) {
2823
+ return this.binaryZeroPad().slice(start, end);
2824
+ }
2825
+ /**
2826
+ * Return the bits in the given range as a base-16 string
2827
+ * @returns {String}
2828
+ */
2829
+ getBitsBase16(start, end) {
2830
+ const length = end - start;
2831
+ if (length % 4 !== 0) {
2832
+ throw new Error("Length of bits to retrieve must be divisible by four");
2833
+ }
2834
+ return this.getBits(start, end).toString(16).padStart(length / 4, "0");
2835
+ }
2836
+ /**
2837
+ * Return the bits that are set past the subnet mask length
2838
+ * @returns {String}
2839
+ */
2840
+ getBitsPastSubnet() {
2841
+ return this.getBitsBase2(this.subnetMask, constants6.BITS);
2842
+ }
2843
+ /**
2844
+ * Return the reversed ip6.arpa form of the address
2845
+ * @param {Object} options
2846
+ * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
2847
+ * @returns {String}
2848
+ */
2849
+ reverseForm(options) {
2850
+ if (!options) {
2851
+ options = {};
2852
+ }
2853
+ const characters = Math.floor(this.subnetMask / 4);
2854
+ const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join(".");
2855
+ if (characters > 0) {
2856
+ if (options.omitSuffix) {
2857
+ return reversed;
2858
+ }
2859
+ return `${reversed}.ip6.arpa.`;
2860
+ }
2861
+ if (options.omitSuffix) {
2862
+ return "";
2863
+ }
2864
+ return "ip6.arpa.";
2865
+ }
2866
+ /**
2867
+ * Returns the address in correct form, per
2868
+ * [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952): leading zeros
2869
+ * stripped, the longest run of zero groups collapsed to `::`, and hex digits
2870
+ * lowercased (e.g. `2001:db8::1`). This is the recommended form for display.
2871
+ */
2872
+ correctForm() {
2873
+ let i;
2874
+ let groups = [];
2875
+ let zeroCounter = 0;
2876
+ const zeroes = [];
2877
+ for (i = 0; i < this.parsedAddress.length; i++) {
2878
+ const value = parseInt(this.parsedAddress[i], 16);
2879
+ if (value === 0) {
2880
+ zeroCounter++;
2881
+ }
2882
+ if (value !== 0 && zeroCounter > 0) {
2883
+ if (zeroCounter > 1) {
2884
+ zeroes.push([i - zeroCounter, i - 1]);
2885
+ }
2886
+ zeroCounter = 0;
2887
+ }
2888
+ }
2889
+ if (zeroCounter > 1) {
2890
+ zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
2891
+ }
2892
+ const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
2893
+ if (zeroes.length > 0) {
2894
+ const index = zeroLengths.indexOf(Math.max(...zeroLengths));
2895
+ groups = compact(this.parsedAddress, zeroes[index]);
2896
+ } else {
2897
+ groups = this.parsedAddress;
2898
+ }
2899
+ for (i = 0; i < groups.length; i++) {
2900
+ if (groups[i] !== "compact") {
2901
+ groups[i] = parseInt(groups[i], 16).toString(16);
2902
+ }
2903
+ }
2904
+ let correct = groups.join(":");
2905
+ correct = correct.replace(/^compact$/, "::");
2906
+ correct = correct.replace(/(^compact)|(compact$)/, ":");
2907
+ correct = correct.replace(/compact/, "");
2908
+ return correct;
2909
+ }
2910
+ /**
2911
+ * Return a zero-padded base-2 string representation of the address
2912
+ * @returns {String}
2913
+ * @example
2914
+ * var address = new Address6('2001:4860:4001:803::1011');
2915
+ * address.binaryZeroPad();
2916
+ * // '0010000000000001010010000110000001000000000000010000100000000011
2917
+ * // 0000000000000000000000000000000000000000000000000001000000010001'
2918
+ */
2919
+ binaryZeroPad() {
2920
+ if (this._binaryZeroPad === void 0) {
2921
+ this._binaryZeroPad = this.bigInt().toString(2).padStart(constants6.BITS, "0");
2922
+ }
2923
+ return this._binaryZeroPad;
2924
+ }
2925
+ /**
2926
+ * Parses a v4-in-v6 string (e.g. `::ffff:192.168.0.1`) by extracting the
2927
+ * trailing IPv4 address into `this.address4` / `this.parsedAddress4` and
2928
+ * returning the address with the v4 portion converted to two v6 groups.
2929
+ * Used internally by `parse()`.
2930
+ */
2931
+ // TODO: Improve the semantics of this helper function
2932
+ parse4in6(address) {
2933
+ if (address.indexOf(".") === -1) {
2934
+ return address;
2935
+ }
2936
+ const groups = address.split(":");
2937
+ const lastGroup = groups.slice(-1)[0];
2938
+ const v4Octets = lastGroup.split(".");
2939
+ if (v4Octets.length === constants4.GROUPS && v4Octets.every((octet) => /^\d{1,3}$/.test(octet))) {
2940
+ if (v4Octets.some((octet) => /^0\d/.test(octet))) {
2941
+ const highlighted = v4Octets.map(spanLeadingZeroes4).join(".");
2942
+ const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(":");
2943
+ const separator = groups.length > 1 ? ":" : "";
2944
+ throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", `${prefix}${separator}${highlighted}`);
2945
+ }
2946
+ }
2947
+ const address4 = lastGroup.match(constants4.RE_ADDRESS);
2948
+ if (address4) {
2949
+ this.parsedAddress4 = address4[0];
2950
+ const v4Suffix = this.subnetMask >= 96 ? `/${this.subnetMask - 96}` : "";
2951
+ this.address4 = new ipv4_1.Address4(`${this.parsedAddress4}${v4Suffix}`);
2952
+ this.v4 = true;
2953
+ groups[groups.length - 1] = this.address4.toGroup6();
2954
+ address = groups.join(":");
2955
+ }
2956
+ return address;
2957
+ }
2958
+ /**
2959
+ * Parses an IPv6 address string into its 8 hexadecimal groups (expanding
2960
+ * any `::` elision and any trailing v4-in-v6 portion) and stores the result
2961
+ * on `this.parsedAddress`. Called automatically by the constructor; you
2962
+ * typically don't need to call it directly. Throws `AddressError` if the
2963
+ * input is malformed.
2964
+ */
2965
+ // TODO: Make private?
2966
+ parse(address) {
2967
+ address = this.parse4in6(address);
2968
+ const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
2969
+ if (badCharacters) {
2970
+ throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? "s" : ""} detected in address: ${badCharacters.join("")}`, address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
2971
+ }
2972
+ const badAddress = address.match(constants6.RE_BAD_ADDRESS);
2973
+ if (badAddress) {
2974
+ throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`, address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
2975
+ }
2976
+ let groups = [];
2977
+ const halves = address.split("::");
2978
+ if (halves.length === 2) {
2979
+ let first = halves[0].split(":");
2980
+ let last = halves[1].split(":");
2981
+ if (first.length === 1 && first[0] === "") {
2982
+ first = [];
2983
+ }
2984
+ if (last.length === 1 && last[0] === "") {
2985
+ last = [];
2986
+ }
2987
+ const remaining = this.groups - (first.length + last.length);
2988
+ if (!remaining) {
2989
+ throw new address_error_1.AddressError("Error parsing groups");
2990
+ }
2991
+ this.elidedGroups = remaining;
2992
+ this.elisionBegin = first.length;
2993
+ this.elisionEnd = first.length + this.elidedGroups;
2994
+ groups = groups.concat(first);
2995
+ for (let i = 0; i < remaining; i++) {
2996
+ groups.push("0");
2997
+ }
2998
+ groups = groups.concat(last);
2999
+ } else if (halves.length === 1) {
3000
+ groups = address.split(":");
3001
+ this.elidedGroups = 0;
3002
+ } else {
3003
+ throw new address_error_1.AddressError("Too many :: groups found");
3004
+ }
3005
+ groups = groups.map((group) => parseInt(group, 16).toString(16));
3006
+ if (groups.length !== this.groups) {
3007
+ throw new address_error_1.AddressError("Incorrect number of groups found");
3008
+ }
3009
+ return groups;
3010
+ }
3011
+ /**
3012
+ * Returns the canonical (fully expanded) form of the address: all 8 groups,
3013
+ * each padded to 4 hex digits, with no `::` collapsing
3014
+ * (e.g. `2001:0db8:0000:0000:0000:0000:0000:0001`). Useful for sorting and
3015
+ * byte-exact comparison.
3016
+ */
3017
+ canonicalForm() {
3018
+ return this.parsedAddress.map(paddedHex).join(":");
3019
+ }
3020
+ /**
3021
+ * Return the decimal form of the address
3022
+ * @returns {String}
3023
+ */
3024
+ decimal() {
3025
+ return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, "0")).join(":");
3026
+ }
3027
+ /**
3028
+ * Return the address as a BigInt
3029
+ * @returns {bigint}
3030
+ */
3031
+ bigInt() {
3032
+ return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`);
3033
+ }
3034
+ /**
3035
+ * Return the last two groups of this address as an IPv4 address string.
3036
+ * If this address carries a CIDR prefix that covers the trailing 32 bits
3037
+ * (i.e. `subnetMask >= 96`), the resulting `Address4` inherits the
3038
+ * corresponding v4 prefix (`subnetMask - 96`); otherwise it defaults to
3039
+ * `/32`.
3040
+ * @returns {Address4}
3041
+ * @example
3042
+ * var address = new Address6('2001:4860:4001::1825:bf11');
3043
+ * address.to4().correctForm(); // '24.37.191.17'
3044
+ */
3045
+ to4() {
3046
+ const binary = this.binaryZeroPad().split("");
3047
+ const hex = BigInt(`0b${binary.slice(96, 128).join("")}`).toString(16).padStart(8, "0");
3048
+ if (this.subnetMask >= 96) {
3049
+ const v4Mask = this.subnetMask - 96;
3050
+ const groups = [];
3051
+ for (let i = 0; i < 8; i += 2) {
3052
+ groups.push(parseInt(hex.slice(i, i + 2), 16));
3053
+ }
3054
+ return new ipv4_1.Address4(`${groups.join(".")}/${v4Mask}`);
3055
+ }
3056
+ return ipv4_1.Address4.fromHex(hex);
3057
+ }
3058
+ /**
3059
+ * Return the v4-in-v6 form of the address
3060
+ * @returns {String}
3061
+ */
3062
+ to4in6() {
3063
+ const address4 = this.to4();
3064
+ const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6);
3065
+ const correct = address6.correctForm();
3066
+ let infix = "";
3067
+ if (!/:$/.test(correct)) {
3068
+ infix = ":";
3069
+ }
3070
+ return correct + infix + address4.correctForm();
3071
+ }
3072
+ /**
3073
+ * Decodes the Teredo tunneling fields embedded in this address. Returns the
3074
+ * Teredo prefix, server IPv4, client IPv4, raw flag bits, cone-NAT flag,
3075
+ * UDP port, and Microsoft-format flag breakdown (reserved, universal/local,
3076
+ * group/individual, nonce). Only meaningful for addresses in `2001::/32`.
3077
+ */
3078
+ inspectTeredo() {
3079
+ const prefix = this.getBitsBase16(0, 32);
3080
+ const bitsForUdpPort = this.getBits(80, 96);
3081
+ const udpPort = (bitsForUdpPort ^ BigInt("0xffff")).toString();
3082
+ const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
3083
+ const bitsForClient4 = this.getBits(96, 128);
3084
+ const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt("0xffffffff")).toString(16).padStart(8, "0"));
3085
+ const flagsBase2 = this.getBitsBase2(64, 80);
3086
+ const coneNat = (0, common_1.testBit)(flagsBase2, 15);
3087
+ const reserved = (0, common_1.testBit)(flagsBase2, 14);
3088
+ const groupIndividual = (0, common_1.testBit)(flagsBase2, 8);
3089
+ const universalLocal = (0, common_1.testBit)(flagsBase2, 9);
3090
+ const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10);
3091
+ return {
3092
+ prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`,
3093
+ server4: server4.address,
3094
+ client4: client4.address,
3095
+ flags: flagsBase2,
3096
+ coneNat,
3097
+ microsoft: {
3098
+ reserved,
3099
+ universalLocal,
3100
+ groupIndividual,
3101
+ nonce
3102
+ },
3103
+ udpPort
3104
+ };
3105
+ }
3106
+ /**
3107
+ * Decodes the 6to4 tunneling fields embedded in this address. Returns the
3108
+ * 6to4 prefix and the embedded IPv4 gateway address. Only meaningful for
3109
+ * addresses in `2002::/16`.
3110
+ */
3111
+ inspect6to4() {
3112
+ const prefix = this.getBitsBase16(0, 16);
3113
+ const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
3114
+ return {
3115
+ prefix: prefix.slice(0, 4),
3116
+ gateway: gateway.address
3117
+ };
3118
+ }
3119
+ /**
3120
+ * Return a v6 6to4 address from a v6 v4inv6 address
3121
+ * @returns {Address6}
3122
+ */
3123
+ to6to4() {
3124
+ if (!this.is4()) {
3125
+ return null;
3126
+ }
3127
+ const addr6to4 = [
3128
+ "2002",
3129
+ this.getBitsBase16(96, 112),
3130
+ this.getBitsBase16(112, 128),
3131
+ "",
3132
+ "/16"
3133
+ ].join(":");
3134
+ return new _Address6(addr6to4);
3135
+ }
3136
+ /**
3137
+ * Embed an IPv4 address into a NAT64 IPv6 address using the encoding
3138
+ * defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052).
3139
+ * The default prefix is the well-known prefix `64:ff9b::/96`. The prefix
3140
+ * length must be one of 32, 40, 48, 56, 64, or 96; for prefixes shorter
3141
+ * than /64 the IPv4 octets are split around the reserved bits 64–71.
3142
+ * @example
3143
+ * Address6.fromAddress4Nat64('192.0.2.33').correctForm(); // '64:ff9b::c000:221'
3144
+ * Address6.fromAddress4Nat64('192.0.2.33', '2001:db8::/32').correctForm(); // '2001:db8:c000:221::'
3145
+ */
3146
+ static fromAddress4Nat64(address, prefix = "64:ff9b::/96") {
3147
+ const v4 = new ipv4_1.Address4(address);
3148
+ const prefix6 = new _Address6(prefix);
3149
+ const pl = prefix6.subnetMask;
3150
+ if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) {
3151
+ throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");
3152
+ }
3153
+ const prefixBits = prefix6.binaryZeroPad();
3154
+ const v4Bits = v4.binaryZeroPad();
3155
+ let bits;
3156
+ if (pl === 96) {
3157
+ bits = prefixBits.slice(0, 96) + v4Bits;
3158
+ } else {
3159
+ const beforeU = 64 - pl;
3160
+ bits = [
3161
+ prefixBits.slice(0, pl),
3162
+ v4Bits.slice(0, beforeU),
3163
+ // Bits 64 to 71 are the reserved u octet and are always zero.
3164
+ "00000000",
3165
+ v4Bits.slice(beforeU),
3166
+ "0".repeat(128 - 72 - (32 - beforeU))
3167
+ ].join("");
3168
+ }
3169
+ const hex = BigInt(`0b${bits}`).toString(16).padStart(32, "0");
3170
+ const groups = [];
3171
+ for (let i = 0; i < 8; i++) {
3172
+ groups.push(hex.slice(i * 4, (i + 1) * 4));
3173
+ }
3174
+ return new _Address6(groups.join(":"));
3175
+ }
3176
+ /**
3177
+ * Extract the embedded IPv4 address from a NAT64 IPv6 address using the
3178
+ * encoding defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052).
3179
+ * The default prefix is the well-known prefix `64:ff9b::/96`. Returns
3180
+ * `null` if this address is not contained within the given prefix.
3181
+ * @example
3182
+ * new Address6('64:ff9b::c000:221').toAddress4Nat64()!.correctForm(); // '192.0.2.33'
3183
+ */
3184
+ toAddress4Nat64(prefix = "64:ff9b::/96") {
3185
+ const prefix6 = new _Address6(prefix);
3186
+ const pl = prefix6.subnetMask;
3187
+ if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) {
3188
+ throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");
3189
+ }
3190
+ if (!this.isHostInSubnet(prefix6)) {
3191
+ return null;
3192
+ }
3193
+ const bits = this.binaryZeroPad();
3194
+ let v4Bits;
3195
+ if (pl === 96) {
3196
+ v4Bits = bits.slice(96, 128);
3197
+ } else {
3198
+ const beforeU = 64 - pl;
3199
+ v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU));
3200
+ }
3201
+ const octets = [];
3202
+ for (let i = 0; i < 4; i++) {
3203
+ octets.push(parseInt(v4Bits.slice(i * 8, (i + 1) * 8), 2).toString());
3204
+ }
3205
+ return new ipv4_1.Address4(octets.join("."));
3206
+ }
3207
+ /**
3208
+ * Return a byte array.
3209
+ *
3210
+ * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toByteArray())`.
3211
+ * @returns {Array}
3212
+ */
3213
+ toByteArray() {
3214
+ const value = this.bigInt().toString(16).padStart(constants6.BITS / 4, "0");
3215
+ const bytes = [];
3216
+ for (let i = 0, length = value.length; i < length; i += 2) {
3217
+ bytes.push(parseInt(value.substring(i, i + 2), 16));
3218
+ }
3219
+ return bytes;
3220
+ }
3221
+ /**
3222
+ * Return an unsigned byte array.
3223
+ *
3224
+ * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toUnsignedByteArray())`.
3225
+ * @returns {Array}
3226
+ */
3227
+ toUnsignedByteArray() {
3228
+ return this.toByteArray().map(unsignByte);
3229
+ }
3230
+ /**
3231
+ * Convert a byte array to an Address6 object.
3232
+ *
3233
+ * Accepts unsigned bytes (0 to 255) or signed bytes (-128 to 127, as an
3234
+ * `Int8Array` or a Java `byte[]` holds them), folding signed values to their
3235
+ * unsigned equivalent. Throws `AddressError` unless given exactly 16
3236
+ * integers from -128 to 255.
3237
+ *
3238
+ * To convert from a Node.js `Buffer`, spread it: `Address6.fromByteArray([...buf])`.
3239
+ * @returns {Address6}
3240
+ */
3241
+ static fromByteArray(bytes) {
3242
+ common.assertByteArray(bytes, 16, "IPv6", -128);
3243
+ return this.fromUnsignedByteArray(bytes.map(unsignByte));
3244
+ }
3245
+ /**
3246
+ * Convert an unsigned byte array to an Address6 object.
3247
+ *
3248
+ * Throws `AddressError` unless given exactly 16 integers from 0 to 255.
3249
+ *
3250
+ * To convert from a Node.js `Buffer`, spread it: `Address6.fromUnsignedByteArray([...buf])`.
3251
+ * @returns {Address6}
3252
+ */
3253
+ static fromUnsignedByteArray(bytes) {
3254
+ common.assertByteArray(bytes, 16, "IPv6", 0);
3255
+ const BYTE_MAX = BigInt("256");
3256
+ let result = BigInt("0");
3257
+ let multiplier = BigInt("1");
3258
+ for (let i = bytes.length - 1; i >= 0; i--) {
3259
+ result += multiplier * BigInt(bytes[i].toString(10));
3260
+ multiplier *= BYTE_MAX;
3261
+ }
3262
+ return _Address6.fromBigInt(result);
3263
+ }
3264
+ /**
3265
+ * Returns true if the address is in the canonical form, false otherwise
3266
+ * @returns {boolean}
3267
+ */
3268
+ isCanonical() {
3269
+ return this.addressMinusSuffix === this.canonicalForm();
3270
+ }
3271
+ /**
3272
+ * Returns true if the address is a link-local unicast address in `fe80::/10`
3273
+ * ([RFC 4291 §2.4](https://datatracker.ietf.org/doc/html/rfc4291#section-2.4))
3274
+ * or an IPv4-mapped / NAT64 address whose embedded IPv4 address is link-local
3275
+ * (`169.254.0.0/16`, e.g. `::ffff:169.254.169.254`), false otherwise.
3276
+ * @returns {boolean}
3277
+ */
3278
+ isLinkLocal() {
3279
+ const embedded = this.embeddedIPv4();
3280
+ if (embedded) {
3281
+ return embedded.isLinkLocal();
3282
+ }
3283
+ return this.isHostInSubnet(LINK_LOCAL_SUBNET);
3284
+ }
3285
+ /**
3286
+ * Returns true if the address is a multicast address, false otherwise
3287
+ * @returns {boolean}
3288
+ */
3289
+ isMulticast() {
3290
+ const embedded = this.embeddedIPv4();
3291
+ if (embedded) {
3292
+ return embedded.isMulticast();
3293
+ }
3294
+ const type = this.getType();
3295
+ return type === "Multicast" || type.startsWith("Multicast ");
3296
+ }
3297
+ /**
3298
+ * Returns true if the address was written in v4-in-v6 dotted-quad notation
3299
+ * (e.g. `::ffff:127.0.0.1`), false otherwise. This is a notation-level flag
3300
+ * and does not reflect whether the address bits lie in the IPv4-mapped
3301
+ * (`::ffff:0:0/96`) subnet — for that, see {@link isMapped4}.
3302
+ * @returns {boolean}
3303
+ */
3304
+ is4() {
3305
+ return this.v4;
3306
+ }
3307
+ /**
3308
+ * Returns true if the address is an IPv4-mapped IPv6 address in
3309
+ * `::ffff:0:0/96` ([RFC 4291 §2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2)),
3310
+ * false otherwise. Unlike {@link is4}, this checks the underlying address
3311
+ * bits rather than the textual notation, so `::ffff:127.0.0.1` and
3312
+ * `::ffff:7f00:1` both return true.
3313
+ * @returns {boolean}
3314
+ */
3315
+ isMapped4() {
3316
+ return this.isHostInSubnet(IPV4_MAPPED_SUBNET);
3317
+ }
3318
+ /**
3319
+ * If this address embeds a routable IPv4 address — i.e. it is IPv4-mapped
3320
+ * (`::ffff:0:0/96`) or sits in the NAT64 well-known prefix (`64:ff9b::/96`,
3321
+ * [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052)) — return that
3322
+ * embedded address as an {@link Address4}; otherwise return null.
3323
+ *
3324
+ * The special-property checks (`isLoopback`, `isLinkLocal`, `isMulticast`,
3325
+ * `isUnspecified`, `isPrivate`, `isCGNAT`, `isBroadcast`) call this first and
3326
+ * delegate to the embedded {@link Address4} when present, so a literal such as
3327
+ * `::ffff:127.0.0.1` is classified by what it actually reaches (loopback)
3328
+ * rather than by its IPv6 wrapper (which `getType()` reports as IPv4-mapped).
3329
+ * This matters wherever the checks back a trust-boundary decision (e.g. an
3330
+ * SSRF allow/deny filter): without normalization, `::ffff:10.0.0.1`,
3331
+ * `::ffff:169.254.169.254`, `64:ff9b::7f00:1`, etc. would all read as
3332
+ * non-internal.
3333
+ * @returns {Address4 | null}
3334
+ */
3335
+ embeddedIPv4() {
3336
+ if (this.isMapped4() || this.isHostInSubnet(NAT64_WELL_KNOWN_SUBNET)) {
3337
+ return this.to4();
3338
+ }
3339
+ return null;
3340
+ }
3341
+ /**
3342
+ * Returns true if the address is a Teredo address, false otherwise
3343
+ * @returns {boolean}
3344
+ */
3345
+ isTeredo() {
3346
+ return this.isHostInSubnet(TEREDO_SUBNET);
3347
+ }
3348
+ /**
3349
+ * Returns true if the address is a 6to4 address, false otherwise
3350
+ * @returns {boolean}
3351
+ */
3352
+ is6to4() {
3353
+ return this.isHostInSubnet(SIX_TO_FOUR_SUBNET);
3354
+ }
3355
+ /**
3356
+ * Returns true if the address is a loopback address, false otherwise
3357
+ * @returns {boolean}
3358
+ */
3359
+ isLoopback() {
3360
+ const embedded = this.embeddedIPv4();
3361
+ if (embedded) {
3362
+ return embedded.isLoopback();
3363
+ }
3364
+ return this.getType() === "Loopback";
3365
+ }
3366
+ /**
3367
+ * Returns true if the address is a Unique Local Address in `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)). ULAs are the IPv6 equivalent of IPv4 [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private addresses.
3368
+ * @returns {boolean}
3369
+ */
3370
+ isULA() {
3371
+ return this.isHostInSubnet(ULA_SUBNET);
3372
+ }
3373
+ /**
3374
+ * Returns true if the address is private, i.e. a Unique Local Address in
3375
+ * `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)), an
3376
+ * address in the NAT64 local-use range `64:ff9b:1::/48`
3377
+ * ([RFC 8215](https://datatracker.ietf.org/doc/html/rfc8215)), or an
3378
+ * IPv4-mapped / NAT64 well-known address whose embedded IPv4 address is in
3379
+ * one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918)
3380
+ * private ranges (e.g. `::ffff:10.0.0.1`). This is the IPv6 counterpart to
3381
+ * {@link Address4.isPrivate}; use it instead of {@link isULA} when you need to
3382
+ * catch mapped RFC 1918 addresses as well as native ULAs.
3383
+ *
3384
+ * The local-use NAT64 range is reported private as a whole rather than by
3385
+ * its embedded IPv4 address: an operator may carve a prefix of any RFC 6052
3386
+ * length out of `64:ff9b:1::/48`, so the same bits decode to different IPv4
3387
+ * addresses under different deployments and no single decoding is correct.
3388
+ * Use {@link toAddress4Nat64} with the deployment's prefix to decode one.
3389
+ * @returns {boolean}
3390
+ */
3391
+ isPrivate() {
3392
+ const embedded = this.embeddedIPv4();
3393
+ if (embedded) {
3394
+ return embedded.isPrivate();
3395
+ }
3396
+ return this.isULA() || this.isHostInSubnet(NAT64_LOCAL_USE_SUBNET);
3397
+ }
3398
+ /**
3399
+ * Returns true if the address is an IPv4-mapped / NAT64 address whose embedded
3400
+ * IPv4 address is in the carrier-grade NAT range `100.64.0.0/10`
3401
+ * ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)), false
3402
+ * otherwise. There is no native IPv6 CGNAT range, so this only ever returns
3403
+ * true for an embedded IPv4 address (e.g. `::ffff:100.64.0.1`).
3404
+ * @returns {boolean}
3405
+ */
3406
+ isCGNAT() {
3407
+ const embedded = this.embeddedIPv4();
3408
+ if (embedded) {
3409
+ return embedded.isCGNAT();
3410
+ }
3411
+ return false;
3412
+ }
3413
+ /**
3414
+ * Returns true if the address is an IPv4-mapped / NAT64 address whose embedded
3415
+ * IPv4 address is the limited broadcast address `255.255.255.255`
3416
+ * ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)), false otherwise.
3417
+ * There is no IPv6 broadcast, so this only ever returns true for an embedded
3418
+ * IPv4 address (e.g. `::ffff:255.255.255.255`).
3419
+ * @returns {boolean}
3420
+ */
3421
+ isBroadcast() {
3422
+ const embedded = this.embeddedIPv4();
3423
+ if (embedded) {
3424
+ return embedded.isBroadcast();
3425
+ }
3426
+ return false;
3427
+ }
3428
+ /**
3429
+ * Returns true if the address is the unspecified address `::`.
3430
+ * @returns {boolean}
3431
+ */
3432
+ isUnspecified() {
3433
+ const embedded = this.embeddedIPv4();
3434
+ if (embedded) {
3435
+ return embedded.isUnspecified();
3436
+ }
3437
+ return this.getType() === "Unspecified";
3438
+ }
3439
+ /**
3440
+ * Returns true if the address is in the documentation prefix `2001:db8::/32` ([RFC 3849](https://datatracker.ietf.org/doc/html/rfc3849)).
3441
+ * @returns {boolean}
3442
+ */
3443
+ isDocumentation() {
3444
+ return DOCUMENTATION_SUBNETS.some((subnet) => this.isHostInSubnet(subnet));
3445
+ }
3446
+ /**
3447
+ * Returns true if the address is in the benchmarking range `2001:2::/48`
3448
+ * ([RFC 5180](https://datatracker.ietf.org/doc/html/rfc5180)) or is an
3449
+ * IPv4-mapped / NAT64 address whose embedded IPv4 address is in
3450
+ * `198.18.0.0/15`, false otherwise.
3451
+ * @returns {boolean}
3452
+ */
3453
+ isBenchmarking() {
3454
+ const embedded = this.embeddedIPv4();
3455
+ if (embedded) {
3456
+ return embedded.isBenchmarking();
3457
+ }
3458
+ return this.isHostInSubnet(BENCHMARKING_SUBNET);
3459
+ }
3460
+ /**
3461
+ * Returns true if the address is globally reachable: inside the global
3462
+ * unicast allocation `2000::/3` (the only range the [IANA IPv6 Address Space
3463
+ * Registry](https://www.iana.org/assignments/ipv6-address-space/) assigns
3464
+ * for global unicast; everything else is reserved, ULA, link-local, or
3465
+ * multicast) and not in any block the [IANA IPv6 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv6-special-registry/)
3466
+ * marks as not globally reachable. An IPv4-mapped or NAT64 well-known
3467
+ * address answers for its embedded IPv4 address, so `::ffff:10.0.0.1` and
3468
+ * `64:ff9b::7f00:1` are not global. Teredo (`2001::/32`) and 6to4
3469
+ * (`2002::/16`) are not global either: the registry lists them as N/A and a
3470
+ * packet to one needs a relay.
3471
+ *
3472
+ * This covers everything the individual classifiers name and the blocks they
3473
+ * do not: the discard-only prefix `100::/64`, the IETF protocol assignments
3474
+ * in `2001::/23`, the deprecated site-local `fec0::/10` and IPv4-compatible
3475
+ * `::/96` ranges, and unallocated space such as `4000::/3`. It is the single
3476
+ * predicate to use where a request must not reach an internal or
3477
+ * special-purpose destination; see SECURITY.md.
3478
+ * @returns {boolean}
3479
+ */
3480
+ isGlobal() {
3481
+ const embedded = this.embeddedIPv4();
3482
+ if (embedded) {
3483
+ return embedded.isGlobal();
3484
+ }
3485
+ return this.isHostInSubnet(GLOBAL_UNICAST_SUBNET) && common.isGloballyReachable.call(this, SPECIAL_PURPOSE_V6);
3486
+ }
3487
+ // #endregion
3488
+ // #region HTML
3489
+ /**
3490
+ * Returns the address as an HTTP URL with the host bracketed, e.g.
3491
+ * `http://[2001:db8::1]/`. If `optionalPort` is provided it is appended,
3492
+ * e.g. `http://[2001:db8::1]:8080/`.
3493
+ */
3494
+ href(optionalPort) {
3495
+ if (optionalPort === void 0) {
3496
+ optionalPort = "";
3497
+ } else {
3498
+ optionalPort = `:${optionalPort}`;
3499
+ }
3500
+ return `http://[${this.correctForm()}]${optionalPort}/`;
3501
+ }
3502
+ /**
3503
+ * Returns an HTML `<a>` element whose `href` encodes the address in a URL
3504
+ * hash fragment (default prefix `/#address=`). Useful for linking between
3505
+ * pages of an address-inspector UI.
3506
+ * @param options.className - CSS class for the rendered `<a>` element
3507
+ * @param options.prefix - hash prefix prepended to the address (default `/#address=`)
3508
+ * @param options.v4 - when true, render the address in v4-in-v6 form
3509
+ */
3510
+ link(options) {
3511
+ if (!options) {
3512
+ options = {};
3513
+ }
3514
+ if (options.className === void 0) {
3515
+ options.className = "";
3516
+ }
3517
+ if (options.prefix === void 0) {
3518
+ options.prefix = "/#address=";
3519
+ }
3520
+ if (options.v4 === void 0) {
3521
+ options.v4 = false;
3522
+ }
3523
+ let formFunction = this.correctForm;
3524
+ if (options.v4) {
3525
+ formFunction = this.to4in6;
3526
+ }
3527
+ const form = formFunction.call(this);
3528
+ const safeHref = helpers.escapeHtml(`${options.prefix}${form}`);
3529
+ const safeForm = helpers.escapeHtml(form);
3530
+ if (options.className) {
3531
+ const safeClass = helpers.escapeHtml(options.className);
3532
+ return `<a href="${safeHref}" class="${safeClass}">${safeForm}</a>`;
3533
+ }
3534
+ return `<a href="${safeHref}">${safeForm}</a>`;
3535
+ }
3536
+ /**
3537
+ * Groups an address.
3538
+ *
3539
+ * Returns an HTML fragment: each group is wrapped in a `<span>` carrying
3540
+ * the group classes an address-inspector UI hovers on. The address content
3541
+ * is HTML-escaped; anything you concatenate around it is your
3542
+ * responsibility.
3543
+ * @returns {String}
3544
+ */
3545
+ group() {
3546
+ if (this.elidedGroups === 0) {
3547
+ return helpers.simpleGroup(this.addressMinusSuffix).join(":");
3548
+ }
3549
+ assert(typeof this.elidedGroups === "number");
3550
+ assert(typeof this.elisionBegin === "number");
3551
+ const output = [];
3552
+ const [left, right] = this.addressMinusSuffix.split("::");
3553
+ if (left.length) {
3554
+ output.push(...helpers.simpleGroup(left));
3555
+ } else {
3556
+ output.push("");
3557
+ }
3558
+ const classes = ["hover-group"];
3559
+ for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
3560
+ classes.push(`group-${i}`);
3561
+ }
3562
+ output.push(`<span class="${classes.join(" ")}"></span>`);
3563
+ if (right.length) {
3564
+ output.push(...helpers.simpleGroup(right, this.elisionEnd));
3565
+ } else {
3566
+ output.push("");
3567
+ }
3568
+ if (this.is4()) {
3569
+ assert(this.address4 instanceof ipv4_1.Address4);
3570
+ output.pop();
3571
+ output.push(this.address4.groupForV6());
3572
+ }
3573
+ return output.join(":");
3574
+ }
3575
+ // #endregion
3576
+ // #region Regular expressions
3577
+ /**
3578
+ * Generate a regular expression string that can be used to find or validate
3579
+ * all variations of this address
3580
+ * @param {boolean} substringSearch
3581
+ * @returns {string}
3582
+ */
3583
+ regularExpressionString(substringSearch = false) {
3584
+ let output = [];
3585
+ const address6 = new _Address6(this.correctForm());
3586
+ if (address6.elidedGroups === 0) {
3587
+ output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
3588
+ } else if (address6.elidedGroups === constants6.GROUPS) {
3589
+ output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
3590
+ } else {
3591
+ const halves = address6.address.split("::");
3592
+ if (halves[0].length) {
3593
+ output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":")));
3594
+ }
3595
+ assert(typeof address6.elidedGroups === "number");
3596
+ output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
3597
+ if (halves[1].length) {
3598
+ output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":")));
3599
+ }
3600
+ output = [output.join(":")];
3601
+ }
3602
+ if (!substringSearch) {
3603
+ output = [
3604
+ "(?=^|",
3605
+ regular_expressions_1.ADDRESS_BOUNDARY,
3606
+ "|[^\\w\\:])(",
3607
+ ...output,
3608
+ ")(?=[^\\w\\:]|",
3609
+ regular_expressions_1.ADDRESS_BOUNDARY,
3610
+ "|$)"
3611
+ ];
3612
+ }
3613
+ return output.join("");
3614
+ }
3615
+ /**
3616
+ * Generate a regular expression that can be used to find or validate all
3617
+ * variations of this address.
3618
+ * @param {boolean} substringSearch
3619
+ * @returns {RegExp}
3620
+ */
3621
+ regularExpression(substringSearch = false) {
3622
+ return new RegExp(this.regularExpressionString(substringSearch), "i");
3623
+ }
3624
+ };
3625
+ exports.Address6 = Address6;
3626
+ var TYPE_SUBNETS = Object.keys(constants6.TYPES).map((subnet) => [
3627
+ new Address6(subnet),
3628
+ constants6.TYPES[subnet]
3629
+ ]);
3630
+ var TEREDO_SUBNET = new Address6("2001::/32");
3631
+ var SIX_TO_FOUR_SUBNET = new Address6("2002::/16");
3632
+ var ULA_SUBNET = new Address6("fc00::/7");
3633
+ var LINK_LOCAL_SUBNET = new Address6("fe80::/10");
3634
+ var DOCUMENTATION_SUBNETS = [new Address6("2001:db8::/32"), new Address6("3fff::/20")];
3635
+ var BENCHMARKING_SUBNET = new Address6("2001:2::/48");
3636
+ var GLOBAL_UNICAST_SUBNET = new Address6("2000::/3");
3637
+ var SPECIAL_PURPOSE_V6 = constants6.SPECIAL_PURPOSE.map(([cidr, , reachable]) => ({
3638
+ subnet: new Address6(cidr),
3639
+ reachable
3640
+ }));
3641
+ var IPV4_MAPPED_SUBNET = new Address6("::ffff:0:0/96");
3642
+ var NAT64_WELL_KNOWN_SUBNET = new Address6("64:ff9b::/96");
3643
+ var NAT64_LOCAL_USE_SUBNET = new Address6("64:ff9b:1::/48");
3644
+ }
3645
+ });
3646
+
3647
+ // ../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ip-address.js
3648
+ var require_ip_address = __commonJS({
3649
+ "../../node_modules/.pnpm/ip-address@10.7.0/node_modules/ip-address/dist/ip-address.js"(exports) {
3650
+ "use strict";
3651
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
3652
+ if (k2 === void 0) k2 = k;
3653
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3654
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3655
+ desc = { enumerable: true, get: function() {
3656
+ return m[k];
3657
+ } };
3658
+ }
3659
+ Object.defineProperty(o, k2, desc);
3660
+ }) : (function(o, m, k, k2) {
3661
+ if (k2 === void 0) k2 = k;
3662
+ o[k2] = m[k];
3663
+ }));
3664
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
3665
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3666
+ }) : function(o, v) {
3667
+ o["default"] = v;
3668
+ });
3669
+ var __importStar = exports && exports.__importStar || function(mod) {
3670
+ if (mod && mod.__esModule) return mod;
3671
+ var result = {};
3672
+ if (mod != null) {
3673
+ for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
3674
+ }
3675
+ __setModuleDefault(result, mod);
3676
+ return result;
3677
+ };
3678
+ Object.defineProperty(exports, "__esModule", { value: true });
3679
+ exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0;
3680
+ var ipv4_1 = require_ipv4();
3681
+ Object.defineProperty(exports, "Address4", { enumerable: true, get: function() {
3682
+ return ipv4_1.Address4;
3683
+ } });
3684
+ var ipv6_1 = require_ipv6();
3685
+ Object.defineProperty(exports, "Address6", { enumerable: true, get: function() {
3686
+ return ipv6_1.Address6;
3687
+ } });
3688
+ var address_error_1 = require_address_error();
3689
+ Object.defineProperty(exports, "AddressError", { enumerable: true, get: function() {
3690
+ return address_error_1.AddressError;
3691
+ } });
3692
+ var helpers = __importStar(require_helpers());
3693
+ exports.v6 = { helpers };
3694
+ }
3695
+ });
3696
+
3697
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/helpers.js
3698
+ var require_helpers2 = __commonJS({
3699
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/helpers.js"(exports) {
3700
+ "use strict";
3701
+ Object.defineProperty(exports, "__esModule", { value: true });
3702
+ exports.validateSocksClientOptions = validateSocksClientOptions;
3703
+ exports.validateSocksClientChainOptions = validateSocksClientChainOptions;
3704
+ exports.ipv4ToInt32 = ipv4ToInt32;
3705
+ exports.int32ToIpv4 = int32ToIpv4;
3706
+ exports.ipToBuffer = ipToBuffer;
3707
+ var util_1 = require_util();
3708
+ var constants_1 = require_constants();
3709
+ var stream = __require("stream");
3710
+ var ip_address_1 = require_ip_address();
3711
+ var net2 = __require("net");
3712
+ function validateSocksClientOptions(options, acceptedCommands = ["connect", "bind", "associate"]) {
3713
+ if (!constants_1.SocksCommand[options.command]) {
3714
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options);
3715
+ }
3716
+ if (acceptedCommands.indexOf(options.command) === -1) {
3717
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options);
3718
+ }
3719
+ if (!isValidSocksRemoteHost(options.destination)) {
3720
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
3721
+ }
3722
+ if (!isValidSocksProxy(options.proxy)) {
3723
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
3724
+ }
3725
+ validateCustomProxyAuth(options.proxy, options);
3726
+ if (options.timeout && !isValidTimeoutValue(options.timeout)) {
3727
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
3728
+ }
3729
+ if (options.existing_socket && !(options.existing_socket instanceof stream.Duplex)) {
3730
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options);
3731
+ }
3732
+ }
3733
+ function validateSocksClientChainOptions(options) {
3734
+ if (options.command !== "connect") {
3735
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options);
3736
+ }
3737
+ if (!isValidSocksRemoteHost(options.destination)) {
3738
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
3739
+ }
3740
+ if (!(options.proxies && Array.isArray(options.proxies) && options.proxies.length >= 2)) {
3741
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options);
3742
+ }
3743
+ options.proxies.forEach((proxy) => {
3744
+ if (!isValidSocksProxy(proxy)) {
3745
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
3746
+ }
3747
+ validateCustomProxyAuth(proxy, options);
3748
+ });
3749
+ if (options.timeout && !isValidTimeoutValue(options.timeout)) {
3750
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
3751
+ }
3752
+ }
3753
+ function validateCustomProxyAuth(proxy, options) {
3754
+ if (proxy.custom_auth_method !== void 0) {
3755
+ if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) {
3756
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options);
3757
+ }
3758
+ if (proxy.custom_auth_request_handler === void 0 || typeof proxy.custom_auth_request_handler !== "function") {
3759
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
3760
+ }
3761
+ if (proxy.custom_auth_response_size === void 0) {
3762
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
3763
+ }
3764
+ if (proxy.custom_auth_response_handler === void 0 || typeof proxy.custom_auth_response_handler !== "function") {
3765
+ throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
3766
+ }
3767
+ }
3768
+ }
3769
+ function isValidSocksRemoteHost(remoteHost) {
3770
+ return remoteHost && typeof remoteHost.host === "string" && Buffer.byteLength(remoteHost.host) < 256 && typeof remoteHost.port === "number" && remoteHost.port >= 0 && remoteHost.port <= 65535;
3771
+ }
3772
+ function isValidSocksProxy(proxy) {
3773
+ return proxy && (typeof proxy.host === "string" || typeof proxy.ipaddress === "string") && typeof proxy.port === "number" && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5);
3774
+ }
3775
+ function isValidTimeoutValue(value) {
3776
+ return typeof value === "number" && value > 0;
3777
+ }
3778
+ function ipv4ToInt32(ip) {
3779
+ const address = new ip_address_1.Address4(ip);
3780
+ return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0;
3781
+ }
3782
+ function int32ToIpv4(int32) {
3783
+ const octet1 = int32 >>> 24 & 255;
3784
+ const octet2 = int32 >>> 16 & 255;
3785
+ const octet3 = int32 >>> 8 & 255;
3786
+ const octet4 = int32 & 255;
3787
+ return [octet1, octet2, octet3, octet4].join(".");
3788
+ }
3789
+ function ipToBuffer(ip) {
3790
+ if (net2.isIPv4(ip)) {
3791
+ const address = new ip_address_1.Address4(ip);
3792
+ return Buffer.from(address.toArray());
3793
+ } else if (net2.isIPv6(ip)) {
3794
+ const address = new ip_address_1.Address6(ip);
3795
+ return Buffer.from(address.canonicalForm().split(":").map((segment) => segment.padStart(4, "0")).join(""), "hex");
3796
+ } else {
3797
+ throw new Error("Invalid IP address format");
3798
+ }
3799
+ }
3800
+ }
3801
+ });
3802
+
3803
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/receivebuffer.js
3804
+ var require_receivebuffer = __commonJS({
3805
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/common/receivebuffer.js"(exports) {
3806
+ "use strict";
3807
+ Object.defineProperty(exports, "__esModule", { value: true });
3808
+ exports.ReceiveBuffer = void 0;
3809
+ var ReceiveBuffer = class {
3810
+ constructor(size = 4096) {
3811
+ this.buffer = Buffer.allocUnsafe(size);
3812
+ this.offset = 0;
3813
+ this.originalSize = size;
3814
+ }
3815
+ get length() {
3816
+ return this.offset;
3817
+ }
3818
+ append(data) {
3819
+ if (!Buffer.isBuffer(data)) {
3820
+ throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");
3821
+ }
3822
+ if (this.offset + data.length >= this.buffer.length) {
3823
+ const tmp = this.buffer;
3824
+ this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
3825
+ tmp.copy(this.buffer);
3826
+ }
3827
+ data.copy(this.buffer, this.offset);
3828
+ return this.offset += data.length;
3829
+ }
3830
+ peek(length) {
3831
+ if (length > this.offset) {
3832
+ throw new Error("Attempted to read beyond the bounds of the managed internal data.");
3833
+ }
3834
+ return this.buffer.slice(0, length);
3835
+ }
3836
+ get(length) {
3837
+ if (length > this.offset) {
3838
+ throw new Error("Attempted to read beyond the bounds of the managed internal data.");
3839
+ }
3840
+ const value = Buffer.allocUnsafe(length);
3841
+ this.buffer.slice(0, length).copy(value);
3842
+ this.buffer.copyWithin(0, length, length + this.offset - length);
3843
+ this.offset -= length;
3844
+ return value;
3845
+ }
3846
+ };
3847
+ exports.ReceiveBuffer = ReceiveBuffer;
3848
+ }
3849
+ });
3850
+
3851
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/client/socksclient.js
3852
+ var require_socksclient = __commonJS({
3853
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/client/socksclient.js"(exports) {
3854
+ "use strict";
3855
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
3856
+ function adopt(value) {
3857
+ return value instanceof P ? value : new P(function(resolve) {
3858
+ resolve(value);
3859
+ });
3860
+ }
3861
+ return new (P || (P = Promise))(function(resolve, reject) {
3862
+ function fulfilled(value) {
3863
+ try {
3864
+ step(generator.next(value));
3865
+ } catch (e) {
3866
+ reject(e);
3867
+ }
3868
+ }
3869
+ function rejected(value) {
3870
+ try {
3871
+ step(generator["throw"](value));
3872
+ } catch (e) {
3873
+ reject(e);
3874
+ }
3875
+ }
3876
+ function step(result) {
3877
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
3878
+ }
3879
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3880
+ });
3881
+ };
3882
+ Object.defineProperty(exports, "__esModule", { value: true });
3883
+ exports.SocksClientError = exports.SocksClient = void 0;
3884
+ var events_1 = __require("events");
3885
+ var net2 = __require("net");
3886
+ var smart_buffer_1 = require_smartbuffer();
3887
+ var constants_1 = require_constants();
3888
+ var helpers_1 = require_helpers2();
3889
+ var receivebuffer_1 = require_receivebuffer();
3890
+ var util_1 = require_util();
3891
+ Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function() {
3892
+ return util_1.SocksClientError;
3893
+ } });
3894
+ var ip_address_1 = require_ip_address();
3895
+ var SocksClient2 = class _SocksClient extends events_1.EventEmitter {
3896
+ constructor(options) {
3897
+ super();
3898
+ this.options = Object.assign({}, options);
3899
+ (0, helpers_1.validateSocksClientOptions)(options);
3900
+ this.setState(constants_1.SocksClientState.Created);
3901
+ }
3902
+ /**
3903
+ * Creates a new SOCKS connection.
3904
+ *
3905
+ * Note: Supports callbacks and promises. Only supports the connect command.
3906
+ * @param options { SocksClientOptions } Options.
3907
+ * @param callback { Function } An optional callback function.
3908
+ * @returns { Promise }
3909
+ */
3910
+ static createConnection(options, callback) {
3911
+ return new Promise((resolve, reject) => {
3912
+ try {
3913
+ (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
3914
+ } catch (err) {
3915
+ if (typeof callback === "function") {
3916
+ callback(err);
3917
+ return resolve(err);
3918
+ } else {
3919
+ return reject(err);
3920
+ }
3921
+ }
3922
+ const client = new _SocksClient(options);
3923
+ client.connect(options.existing_socket);
3924
+ client.once("established", (info) => {
3925
+ client.removeAllListeners();
3926
+ if (typeof callback === "function") {
3927
+ callback(null, info);
3928
+ resolve(info);
3929
+ } else {
3930
+ resolve(info);
3931
+ }
3932
+ });
3933
+ client.once("error", (err) => {
3934
+ client.removeAllListeners();
3935
+ if (typeof callback === "function") {
3936
+ callback(err);
3937
+ resolve(err);
3938
+ } else {
3939
+ reject(err);
3940
+ }
3941
+ });
3942
+ });
3943
+ }
3944
+ /**
3945
+ * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
3946
+ *
3947
+ * Note: Supports callbacks and promises. Only supports the connect method.
3948
+ * Note: Implemented via createConnection() factory function.
3949
+ * @param options { SocksClientChainOptions } Options
3950
+ * @param callback { Function } An optional callback function.
3951
+ * @returns { Promise }
3952
+ */
3953
+ static createConnectionChain(options, callback) {
3954
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
3955
+ try {
3956
+ (0, helpers_1.validateSocksClientChainOptions)(options);
3957
+ } catch (err) {
3958
+ if (typeof callback === "function") {
3959
+ callback(err);
3960
+ return resolve(err);
3961
+ } else {
3962
+ return reject(err);
3963
+ }
3964
+ }
3965
+ if (options.randomizeChain) {
3966
+ (0, util_1.shuffleArray)(options.proxies);
3967
+ }
3968
+ try {
3969
+ let sock;
3970
+ for (let i = 0; i < options.proxies.length; i++) {
3971
+ const nextProxy = options.proxies[i];
3972
+ const nextDestination = i === options.proxies.length - 1 ? options.destination : {
3973
+ host: options.proxies[i + 1].host || options.proxies[i + 1].ipaddress,
3974
+ port: options.proxies[i + 1].port
3975
+ };
3976
+ const result = yield _SocksClient.createConnection({
3977
+ command: "connect",
3978
+ proxy: nextProxy,
3979
+ destination: nextDestination,
3980
+ existing_socket: sock
3981
+ });
3982
+ sock = sock || result.socket;
3983
+ }
3984
+ if (typeof callback === "function") {
3985
+ callback(null, { socket: sock });
3986
+ resolve({ socket: sock });
3987
+ } else {
3988
+ resolve({ socket: sock });
3989
+ }
3990
+ } catch (err) {
3991
+ if (typeof callback === "function") {
3992
+ callback(err);
3993
+ resolve(err);
3994
+ } else {
3995
+ reject(err);
3996
+ }
3997
+ }
3998
+ }));
3999
+ }
4000
+ /**
4001
+ * Creates a SOCKS UDP Frame.
4002
+ * @param options
4003
+ */
4004
+ static createUDPFrame(options) {
4005
+ const buff = new smart_buffer_1.SmartBuffer();
4006
+ buff.writeUInt16BE(0);
4007
+ buff.writeUInt8(options.frameNumber || 0);
4008
+ if (net2.isIPv4(options.remoteHost.host)) {
4009
+ buff.writeUInt8(constants_1.Socks5HostType.IPv4);
4010
+ buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
4011
+ } else if (net2.isIPv6(options.remoteHost.host)) {
4012
+ buff.writeUInt8(constants_1.Socks5HostType.IPv6);
4013
+ buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
4014
+ } else {
4015
+ buff.writeUInt8(constants_1.Socks5HostType.Hostname);
4016
+ buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
4017
+ buff.writeString(options.remoteHost.host);
4018
+ }
4019
+ buff.writeUInt16BE(options.remoteHost.port);
4020
+ buff.writeBuffer(options.data);
4021
+ return buff.toBuffer();
4022
+ }
4023
+ /**
4024
+ * Parses a SOCKS UDP frame.
4025
+ * @param data
4026
+ */
4027
+ static parseUDPFrame(data) {
4028
+ const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
4029
+ buff.readOffset = 2;
4030
+ const frameNumber = buff.readUInt8();
4031
+ const hostType = buff.readUInt8();
4032
+ let remoteHost;
4033
+ if (hostType === constants_1.Socks5HostType.IPv4) {
4034
+ remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
4035
+ } else if (hostType === constants_1.Socks5HostType.IPv6) {
4036
+ remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
4037
+ } else {
4038
+ remoteHost = buff.readString(buff.readUInt8());
4039
+ }
4040
+ const remotePort = buff.readUInt16BE();
4041
+ return {
4042
+ frameNumber,
4043
+ remoteHost: {
4044
+ host: remoteHost,
4045
+ port: remotePort
4046
+ },
4047
+ data: buff.readBuffer()
4048
+ };
4049
+ }
4050
+ /**
4051
+ * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
4052
+ */
4053
+ setState(newState) {
4054
+ if (this.state !== constants_1.SocksClientState.Error) {
4055
+ this.state = newState;
4056
+ }
4057
+ }
4058
+ /**
4059
+ * Starts the connection establishment to the proxy and destination.
4060
+ * @param existingSocket Connected socket to use instead of creating a new one (internal use).
4061
+ */
4062
+ connect(existingSocket) {
4063
+ this.onDataReceived = (data) => this.onDataReceivedHandler(data);
4064
+ this.onClose = () => this.onCloseHandler();
4065
+ this.onError = (err) => this.onErrorHandler(err);
4066
+ this.onConnect = () => this.onConnectHandler();
4067
+ const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
4068
+ if (timer.unref && typeof timer.unref === "function") {
4069
+ timer.unref();
4070
+ }
4071
+ if (existingSocket) {
4072
+ this.socket = existingSocket;
4073
+ } else {
4074
+ this.socket = new net2.Socket();
4075
+ }
4076
+ this.socket.once("close", this.onClose);
4077
+ this.socket.once("error", this.onError);
4078
+ this.socket.once("connect", this.onConnect);
4079
+ this.socket.on("data", this.onDataReceived);
4080
+ this.setState(constants_1.SocksClientState.Connecting);
4081
+ this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
4082
+ if (existingSocket) {
4083
+ this.socket.emit("connect");
4084
+ } else {
4085
+ this.socket.connect(this.getSocketOptions());
4086
+ if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) {
4087
+ this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
4088
+ }
4089
+ }
4090
+ this.prependOnceListener("established", (info) => {
4091
+ setImmediate(() => {
4092
+ if (this.receiveBuffer.length > 0) {
4093
+ const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
4094
+ info.socket.emit("data", excessData);
4095
+ }
4096
+ info.socket.resume();
4097
+ });
4098
+ });
4099
+ }
4100
+ // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
4101
+ getSocketOptions() {
4102
+ return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
4103
+ }
4104
+ /**
4105
+ * Handles internal Socks timeout callback.
4106
+ * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
4107
+ */
4108
+ onEstablishedTimeout() {
4109
+ if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
4110
+ this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
4111
+ }
4112
+ }
4113
+ /**
4114
+ * Handles Socket connect event.
4115
+ */
4116
+ onConnectHandler() {
4117
+ this.setState(constants_1.SocksClientState.Connected);
4118
+ if (this.options.proxy.type === 4) {
4119
+ this.sendSocks4InitialHandshake();
4120
+ } else {
4121
+ this.sendSocks5InitialHandshake();
4122
+ }
4123
+ this.setState(constants_1.SocksClientState.SentInitialHandshake);
4124
+ }
4125
+ /**
4126
+ * Handles Socket data event.
4127
+ * @param data
4128
+ */
4129
+ onDataReceivedHandler(data) {
4130
+ this.receiveBuffer.append(data);
4131
+ this.processData();
4132
+ }
4133
+ /**
4134
+ * Handles processing of the data we have received.
4135
+ */
4136
+ processData() {
4137
+ while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
4138
+ if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
4139
+ if (this.options.proxy.type === 4) {
4140
+ this.handleSocks4FinalHandshakeResponse();
4141
+ } else {
4142
+ this.handleInitialSocks5HandshakeResponse();
4143
+ }
4144
+ } else if (this.state === constants_1.SocksClientState.SentAuthentication) {
4145
+ this.handleInitialSocks5AuthenticationHandshakeResponse();
4146
+ } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
4147
+ this.handleSocks5FinalHandshakeResponse();
4148
+ } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
4149
+ if (this.options.proxy.type === 4) {
4150
+ this.handleSocks4IncomingConnectionResponse();
4151
+ } else {
4152
+ this.handleSocks5IncomingConnectionResponse();
4153
+ }
4154
+ } else {
4155
+ this.closeSocket(constants_1.ERRORS.InternalError);
4156
+ break;
4157
+ }
4158
+ }
4159
+ }
4160
+ /**
4161
+ * Handles Socket close event.
4162
+ * @param had_error
4163
+ */
4164
+ onCloseHandler() {
4165
+ this.closeSocket(constants_1.ERRORS.SocketClosed);
4166
+ }
4167
+ /**
4168
+ * Handles Socket error event.
4169
+ * @param err
4170
+ */
4171
+ onErrorHandler(err) {
4172
+ this.closeSocket(err.message);
4173
+ }
4174
+ /**
4175
+ * Removes internal event listeners on the underlying Socket.
4176
+ */
4177
+ removeInternalSocketHandlers() {
4178
+ this.socket.pause();
4179
+ this.socket.removeListener("data", this.onDataReceived);
4180
+ this.socket.removeListener("close", this.onClose);
4181
+ this.socket.removeListener("error", this.onError);
4182
+ this.socket.removeListener("connect", this.onConnect);
4183
+ }
4184
+ /**
4185
+ * Closes and destroys the underlying Socket. Emits an error event.
4186
+ * @param err { String } An error string to include in error event.
4187
+ */
4188
+ closeSocket(err) {
4189
+ if (this.state !== constants_1.SocksClientState.Error) {
4190
+ this.setState(constants_1.SocksClientState.Error);
4191
+ this.socket.destroy();
4192
+ this.removeInternalSocketHandlers();
4193
+ this.emit("error", new util_1.SocksClientError(err, this.options));
4194
+ }
4195
+ }
4196
+ /**
4197
+ * Sends initial Socks v4 handshake request.
4198
+ */
4199
+ sendSocks4InitialHandshake() {
4200
+ const userId = this.options.proxy.userId || "";
4201
+ const buff = new smart_buffer_1.SmartBuffer();
4202
+ buff.writeUInt8(4);
4203
+ buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
4204
+ buff.writeUInt16BE(this.options.destination.port);
4205
+ if (net2.isIPv4(this.options.destination.host)) {
4206
+ buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
4207
+ buff.writeStringNT(userId);
4208
+ } else {
4209
+ buff.writeUInt8(0);
4210
+ buff.writeUInt8(0);
4211
+ buff.writeUInt8(0);
4212
+ buff.writeUInt8(1);
4213
+ buff.writeStringNT(userId);
4214
+ buff.writeStringNT(this.options.destination.host);
4215
+ }
4216
+ this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
4217
+ this.socket.write(buff.toBuffer());
4218
+ }
4219
+ /**
4220
+ * Handles Socks v4 handshake response.
4221
+ * @param data
4222
+ */
4223
+ handleSocks4FinalHandshakeResponse() {
4224
+ const data = this.receiveBuffer.get(8);
4225
+ if (data[1] !== constants_1.Socks4Response.Granted) {
4226
+ this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
4227
+ } else {
4228
+ if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
4229
+ const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
4230
+ buff.readOffset = 2;
4231
+ const remoteHost = {
4232
+ port: buff.readUInt16BE(),
4233
+ host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
4234
+ };
4235
+ if (remoteHost.host === "0.0.0.0") {
4236
+ remoteHost.host = this.options.proxy.ipaddress;
4237
+ }
4238
+ this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
4239
+ this.emit("bound", { remoteHost, socket: this.socket });
4240
+ } else {
4241
+ this.setState(constants_1.SocksClientState.Established);
4242
+ this.removeInternalSocketHandlers();
4243
+ this.emit("established", { socket: this.socket });
4244
+ }
4245
+ }
4246
+ }
4247
+ /**
4248
+ * Handles Socks v4 incoming connection request (BIND)
4249
+ * @param data
4250
+ */
4251
+ handleSocks4IncomingConnectionResponse() {
4252
+ const data = this.receiveBuffer.get(8);
4253
+ if (data[1] !== constants_1.Socks4Response.Granted) {
4254
+ this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
4255
+ } else {
4256
+ const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
4257
+ buff.readOffset = 2;
4258
+ const remoteHost = {
4259
+ port: buff.readUInt16BE(),
4260
+ host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
4261
+ };
4262
+ this.setState(constants_1.SocksClientState.Established);
4263
+ this.removeInternalSocketHandlers();
4264
+ this.emit("established", { remoteHost, socket: this.socket });
4265
+ }
4266
+ }
4267
+ /**
4268
+ * Sends initial Socks v5 handshake request.
4269
+ */
4270
+ sendSocks5InitialHandshake() {
4271
+ const buff = new smart_buffer_1.SmartBuffer();
4272
+ const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
4273
+ if (this.options.proxy.userId || this.options.proxy.password) {
4274
+ supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
4275
+ }
4276
+ if (this.options.proxy.custom_auth_method !== void 0) {
4277
+ supportedAuthMethods.push(this.options.proxy.custom_auth_method);
4278
+ }
4279
+ buff.writeUInt8(5);
4280
+ buff.writeUInt8(supportedAuthMethods.length);
4281
+ for (const authMethod of supportedAuthMethods) {
4282
+ buff.writeUInt8(authMethod);
4283
+ }
4284
+ this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
4285
+ this.socket.write(buff.toBuffer());
4286
+ this.setState(constants_1.SocksClientState.SentInitialHandshake);
4287
+ }
4288
+ /**
4289
+ * Handles initial Socks v5 handshake response.
4290
+ * @param data
4291
+ */
4292
+ handleInitialSocks5HandshakeResponse() {
4293
+ const data = this.receiveBuffer.get(2);
4294
+ if (data[0] !== 5) {
4295
+ this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
4296
+ } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
4297
+ this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
4298
+ } else {
4299
+ if (data[1] === constants_1.Socks5Auth.NoAuth) {
4300
+ this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
4301
+ this.sendSocks5CommandRequest();
4302
+ } else if (data[1] === constants_1.Socks5Auth.UserPass) {
4303
+ this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
4304
+ this.sendSocks5UserPassAuthentication();
4305
+ } else if (data[1] === this.options.proxy.custom_auth_method) {
4306
+ this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
4307
+ this.sendSocks5CustomAuthentication();
4308
+ } else {
4309
+ this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
4310
+ }
4311
+ }
4312
+ }
4313
+ /**
4314
+ * Sends Socks v5 user & password auth handshake.
4315
+ *
4316
+ * Note: No auth and user/pass are currently supported.
4317
+ */
4318
+ sendSocks5UserPassAuthentication() {
4319
+ const userId = this.options.proxy.userId || "";
4320
+ const password = this.options.proxy.password || "";
4321
+ const buff = new smart_buffer_1.SmartBuffer();
4322
+ buff.writeUInt8(1);
4323
+ buff.writeUInt8(Buffer.byteLength(userId));
4324
+ buff.writeString(userId);
4325
+ buff.writeUInt8(Buffer.byteLength(password));
4326
+ buff.writeString(password);
4327
+ this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
4328
+ this.socket.write(buff.toBuffer());
4329
+ this.setState(constants_1.SocksClientState.SentAuthentication);
4330
+ }
4331
+ sendSocks5CustomAuthentication() {
4332
+ return __awaiter(this, void 0, void 0, function* () {
4333
+ this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size;
4334
+ this.socket.write(yield this.options.proxy.custom_auth_request_handler());
4335
+ this.setState(constants_1.SocksClientState.SentAuthentication);
4336
+ });
4337
+ }
4338
+ handleSocks5CustomAuthHandshakeResponse(data) {
4339
+ return __awaiter(this, void 0, void 0, function* () {
4340
+ return yield this.options.proxy.custom_auth_response_handler(data);
4341
+ });
4342
+ }
4343
+ handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
4344
+ return __awaiter(this, void 0, void 0, function* () {
4345
+ return data[1] === 0;
4346
+ });
4347
+ }
4348
+ handleSocks5AuthenticationUserPassHandshakeResponse(data) {
4349
+ return __awaiter(this, void 0, void 0, function* () {
4350
+ return data[1] === 0;
4351
+ });
4352
+ }
4353
+ /**
4354
+ * Handles Socks v5 auth handshake response.
4355
+ * @param data
4356
+ */
4357
+ handleInitialSocks5AuthenticationHandshakeResponse() {
4358
+ return __awaiter(this, void 0, void 0, function* () {
4359
+ this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
4360
+ let authResult = false;
4361
+ if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
4362
+ authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
4363
+ } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
4364
+ authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
4365
+ } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
4366
+ authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
4367
+ }
4368
+ if (!authResult) {
4369
+ this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
4370
+ } else {
4371
+ this.sendSocks5CommandRequest();
4372
+ }
4373
+ });
4374
+ }
4375
+ /**
4376
+ * Sends Socks v5 final handshake request.
4377
+ */
4378
+ sendSocks5CommandRequest() {
4379
+ const buff = new smart_buffer_1.SmartBuffer();
4380
+ buff.writeUInt8(5);
4381
+ buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
4382
+ buff.writeUInt8(0);
4383
+ if (net2.isIPv4(this.options.destination.host)) {
4384
+ buff.writeUInt8(constants_1.Socks5HostType.IPv4);
4385
+ buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
4386
+ } else if (net2.isIPv6(this.options.destination.host)) {
4387
+ buff.writeUInt8(constants_1.Socks5HostType.IPv6);
4388
+ buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
4389
+ } else {
4390
+ buff.writeUInt8(constants_1.Socks5HostType.Hostname);
4391
+ buff.writeUInt8(this.options.destination.host.length);
4392
+ buff.writeString(this.options.destination.host);
4393
+ }
4394
+ buff.writeUInt16BE(this.options.destination.port);
4395
+ this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
4396
+ this.socket.write(buff.toBuffer());
4397
+ this.setState(constants_1.SocksClientState.SentFinalHandshake);
4398
+ }
4399
+ /**
4400
+ * Handles Socks v5 final handshake response.
4401
+ * @param data
4402
+ */
4403
+ handleSocks5FinalHandshakeResponse() {
4404
+ const header = this.receiveBuffer.peek(5);
4405
+ if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
4406
+ this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
4407
+ } else {
4408
+ const addressType = header[3];
4409
+ let remoteHost;
4410
+ let buff;
4411
+ if (addressType === constants_1.Socks5HostType.IPv4) {
4412
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
4413
+ if (this.receiveBuffer.length < dataNeeded) {
4414
+ this.nextRequiredPacketBufferSize = dataNeeded;
4415
+ return;
4416
+ }
4417
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
4418
+ remoteHost = {
4419
+ host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
4420
+ port: buff.readUInt16BE()
4421
+ };
4422
+ if (remoteHost.host === "0.0.0.0") {
4423
+ remoteHost.host = this.options.proxy.ipaddress;
4424
+ }
4425
+ } else if (addressType === constants_1.Socks5HostType.Hostname) {
4426
+ const hostLength = header[4];
4427
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
4428
+ if (this.receiveBuffer.length < dataNeeded) {
4429
+ this.nextRequiredPacketBufferSize = dataNeeded;
4430
+ return;
4431
+ }
4432
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
4433
+ remoteHost = {
4434
+ host: buff.readString(hostLength),
4435
+ port: buff.readUInt16BE()
4436
+ };
4437
+ } else if (addressType === constants_1.Socks5HostType.IPv6) {
4438
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
4439
+ if (this.receiveBuffer.length < dataNeeded) {
4440
+ this.nextRequiredPacketBufferSize = dataNeeded;
4441
+ return;
4442
+ }
4443
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
4444
+ remoteHost = {
4445
+ host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
4446
+ port: buff.readUInt16BE()
4447
+ };
4448
+ }
4449
+ this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
4450
+ if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
4451
+ this.setState(constants_1.SocksClientState.Established);
4452
+ this.removeInternalSocketHandlers();
4453
+ this.emit("established", { remoteHost, socket: this.socket });
4454
+ } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
4455
+ this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
4456
+ this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
4457
+ this.emit("bound", { remoteHost, socket: this.socket });
4458
+ } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
4459
+ this.setState(constants_1.SocksClientState.Established);
4460
+ this.removeInternalSocketHandlers();
4461
+ this.emit("established", {
4462
+ remoteHost,
4463
+ socket: this.socket
4464
+ });
4465
+ }
4466
+ }
4467
+ }
4468
+ /**
4469
+ * Handles Socks v5 incoming connection request (BIND).
4470
+ */
4471
+ handleSocks5IncomingConnectionResponse() {
4472
+ const header = this.receiveBuffer.peek(5);
4473
+ if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
4474
+ this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
4475
+ } else {
4476
+ const addressType = header[3];
4477
+ let remoteHost;
4478
+ let buff;
4479
+ if (addressType === constants_1.Socks5HostType.IPv4) {
4480
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
4481
+ if (this.receiveBuffer.length < dataNeeded) {
4482
+ this.nextRequiredPacketBufferSize = dataNeeded;
4483
+ return;
4484
+ }
4485
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
4486
+ remoteHost = {
4487
+ host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
4488
+ port: buff.readUInt16BE()
4489
+ };
4490
+ if (remoteHost.host === "0.0.0.0") {
4491
+ remoteHost.host = this.options.proxy.ipaddress;
4492
+ }
4493
+ } else if (addressType === constants_1.Socks5HostType.Hostname) {
4494
+ const hostLength = header[4];
4495
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
4496
+ if (this.receiveBuffer.length < dataNeeded) {
4497
+ this.nextRequiredPacketBufferSize = dataNeeded;
4498
+ return;
4499
+ }
4500
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
4501
+ remoteHost = {
4502
+ host: buff.readString(hostLength),
4503
+ port: buff.readUInt16BE()
4504
+ };
4505
+ } else if (addressType === constants_1.Socks5HostType.IPv6) {
4506
+ const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
4507
+ if (this.receiveBuffer.length < dataNeeded) {
4508
+ this.nextRequiredPacketBufferSize = dataNeeded;
4509
+ return;
4510
+ }
4511
+ buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
4512
+ remoteHost = {
4513
+ host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
4514
+ port: buff.readUInt16BE()
4515
+ };
4516
+ }
4517
+ this.setState(constants_1.SocksClientState.Established);
4518
+ this.removeInternalSocketHandlers();
4519
+ this.emit("established", { remoteHost, socket: this.socket });
4520
+ }
4521
+ }
4522
+ get socksClientOptions() {
4523
+ return Object.assign({}, this.options);
4524
+ }
4525
+ };
4526
+ exports.SocksClient = SocksClient2;
4527
+ }
4528
+ });
4529
+
4530
+ // ../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/index.js
4531
+ var require_build = __commonJS({
4532
+ "../../node_modules/.pnpm/socks@2.8.10/node_modules/socks/build/index.js"(exports) {
4533
+ "use strict";
4534
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
4535
+ if (k2 === void 0) k2 = k;
4536
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4537
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4538
+ desc = { enumerable: true, get: function() {
4539
+ return m[k];
4540
+ } };
4541
+ }
4542
+ Object.defineProperty(o, k2, desc);
4543
+ }) : (function(o, m, k, k2) {
4544
+ if (k2 === void 0) k2 = k;
4545
+ o[k2] = m[k];
4546
+ }));
4547
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
4548
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
4549
+ };
4550
+ Object.defineProperty(exports, "__esModule", { value: true });
4551
+ __exportStar(require_socksclient(), exports);
4552
+ }
4553
+ });
4554
+
4555
+ // ../../node_modules/.pnpm/socks-proxy-agent@10.1.0/node_modules/socks-proxy-agent/dist/index.js
4556
+ var import_socks = __toESM(require_build(), 1);
4557
+ var import_debug = __toESM(require_src(), 1);
4558
+ import * as dns from "dns";
4559
+ import * as net from "net";
4560
+ import * as tls from "tls";
4561
+ import { URL } from "url";
4562
+ var debug = (0, import_debug.default)("socks-proxy-agent");
4563
+ var setServernameFromNonIpHost = (options) => {
4564
+ if (options.servername === void 0 && options.host && !net.isIP(options.host)) {
4565
+ return {
4566
+ ...options,
4567
+ servername: options.host
4568
+ };
4569
+ }
4570
+ return options;
4571
+ };
4572
+ function parseSocksURL(url) {
4573
+ let lookup2 = false;
4574
+ let type = 5;
4575
+ const host = url.hostname;
4576
+ const port = parseInt(url.port, 10) || 1080;
4577
+ switch (url.protocol.replace(":", "")) {
4578
+ case "socks4":
4579
+ lookup2 = true;
4580
+ type = 4;
4581
+ break;
4582
+ // pass through
4583
+ case "socks4a":
4584
+ type = 4;
4585
+ break;
4586
+ case "socks5":
4587
+ lookup2 = true;
4588
+ type = 5;
4589
+ break;
4590
+ // pass through
4591
+ case "socks":
4592
+ type = 5;
4593
+ break;
4594
+ case "socks5h":
4595
+ type = 5;
4596
+ break;
4597
+ default:
4598
+ throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`);
4599
+ }
4600
+ const proxy = {
4601
+ host,
4602
+ port,
4603
+ type
4604
+ };
4605
+ if (url.username) {
4606
+ Object.defineProperty(proxy, "userId", {
4607
+ value: decodeURIComponent(url.username),
4608
+ enumerable: false
4609
+ });
4610
+ }
4611
+ if (url.password != null) {
4612
+ Object.defineProperty(proxy, "password", {
4613
+ value: decodeURIComponent(url.password),
4614
+ enumerable: false
4615
+ });
4616
+ }
4617
+ return { lookup: lookup2, proxy };
4618
+ }
4619
+ var SocksProxyAgent = class extends Agent {
4620
+ constructor(uri, opts) {
4621
+ super(opts);
4622
+ const url = typeof uri === "string" ? new URL(uri) : uri;
4623
+ const { proxy, lookup: lookup2 } = parseSocksURL(url);
4624
+ this.shouldLookup = lookup2;
4625
+ this.proxy = proxy;
4626
+ this.proxyUrl = url.href;
4627
+ this.timeout = opts?.timeout ?? null;
4628
+ this.socketOptions = opts?.socketOptions ?? null;
4629
+ }
4630
+ /**
4631
+ * Initiates a SOCKS connection to the specified SOCKS proxy server,
4632
+ * which in turn connects to the specified remote host and port.
4633
+ */
4634
+ async connect(req, opts) {
4635
+ const { shouldLookup, proxy, timeout } = this;
4636
+ if (!opts.host) {
4637
+ throw new Error("No `host` defined!");
4638
+ }
4639
+ let { host } = opts;
4640
+ const { port, lookup: lookupFn = dns.lookup } = opts;
4641
+ if (shouldLookup) {
4642
+ host = await new Promise((resolve, reject) => {
4643
+ lookupFn(host, {}, (err, address) => {
4644
+ if (err) {
4645
+ reject(err);
4646
+ } else {
4647
+ resolve(typeof address === "string" ? address : address[0].address);
4648
+ }
4649
+ });
4650
+ });
4651
+ }
4652
+ const socksOpts = {
4653
+ proxy,
4654
+ destination: {
4655
+ host,
4656
+ port: typeof port === "number" ? port : parseInt(port, 10)
4657
+ },
4658
+ command: "connect",
4659
+ timeout: timeout ?? void 0,
4660
+ // @ts-expect-error the type supplied by socks for socket_options is wider
4661
+ // than necessary since socks will always override the host and port
4662
+ socket_options: this.socketOptions ?? void 0
4663
+ };
4664
+ const cleanup = (tlsSocket) => {
4665
+ req.destroy();
4666
+ socket.destroy();
4667
+ if (tlsSocket)
4668
+ tlsSocket.destroy();
4669
+ };
4670
+ debug("Creating socks proxy connection: %o", socksOpts);
4671
+ const { socket } = await import_socks.SocksClient.createConnection(socksOpts);
4672
+ debug("Successfully created socks proxy connection");
4673
+ req.emit("proxy", { proxy: this.proxyUrl, socket });
4674
+ if (timeout !== null) {
4675
+ socket.setTimeout(timeout);
4676
+ socket.on("timeout", () => cleanup());
4677
+ }
4678
+ if (opts.secureEndpoint) {
4679
+ debug("Upgrading socket connection to TLS");
4680
+ const tlsSocket = tls.connect({
4681
+ ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
4682
+ socket
4683
+ });
4684
+ tlsSocket.once("error", (error) => {
4685
+ debug("Socket TLS error", error.message);
4686
+ cleanup(tlsSocket);
4687
+ });
4688
+ return tlsSocket;
4689
+ }
4690
+ return socket;
4691
+ }
4692
+ };
4693
+ SocksProxyAgent.protocols = [
4694
+ "socks",
4695
+ "socks4",
4696
+ "socks4a",
4697
+ "socks5",
4698
+ "socks5h"
4699
+ ];
4700
+ function omit(obj, ...keys) {
4701
+ const ret = {};
4702
+ let key;
4703
+ for (key in obj) {
4704
+ if (!keys.includes(key)) {
4705
+ ret[key] = obj[key];
4706
+ }
4707
+ }
4708
+ return ret;
4709
+ }
4710
+ export {
4711
+ SocksProxyAgent
4712
+ };
4713
+ //# sourceMappingURL=dist-OMWR53J4.js.map