bun-torrent 0.0.1-beta

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 (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/package.json +49 -0
  4. package/src/app.ts +65 -0
  5. package/src/client.error.ts +12 -0
  6. package/src/client.test.ts +117 -0
  7. package/src/client.ts +185 -0
  8. package/src/index.test.ts +7 -0
  9. package/src/index.ts +76 -0
  10. package/src/peer/__tests__/peer-id.test.ts +24 -0
  11. package/src/peer/availability.test.ts +50 -0
  12. package/src/peer/availability.ts +88 -0
  13. package/src/peer/consts.ts +11 -0
  14. package/src/peer/handshake/handshake.error.ts +15 -0
  15. package/src/peer/handshake/handshake.test.ts +125 -0
  16. package/src/peer/handshake/index.ts +83 -0
  17. package/src/peer/index.ts +31 -0
  18. package/src/peer/messages/error.ts +16 -0
  19. package/src/peer/messages/helpers.ts +36 -0
  20. package/src/peer/messages/index.ts +174 -0
  21. package/src/peer/messages/messages.test.ts +231 -0
  22. package/src/peer/messages/types.ts +76 -0
  23. package/src/peer/peer-id.ts +9 -0
  24. package/src/peer/pool/index.ts +301 -0
  25. package/src/peer/pool/pool.error.ts +17 -0
  26. package/src/peer/pool/pool.test.ts +305 -0
  27. package/src/peer/session/index.ts +276 -0
  28. package/src/peer/session/session.error.ts +19 -0
  29. package/src/peer/session/session.test.ts +110 -0
  30. package/src/peer/types.ts +6 -0
  31. package/src/torrent/bencode/__tests__/decoder.test.ts +212 -0
  32. package/src/torrent/bencode/__tests__/encoder.test.ts +138 -0
  33. package/src/torrent/bencode/__tests__/encoder.unit.test.ts +24 -0
  34. package/src/torrent/bencode/__tests__/integration.test.ts +64 -0
  35. package/src/torrent/bencode/decoder.error.ts +36 -0
  36. package/src/torrent/bencode/decoder.ts +180 -0
  37. package/src/torrent/bencode/encoder.error.ts +14 -0
  38. package/src/torrent/bencode/encoder.ts +86 -0
  39. package/src/torrent/bencode/index.ts +9 -0
  40. package/src/torrent/bencode/types.ts +15 -0
  41. package/src/torrent/bencode/utils.ts +17 -0
  42. package/src/torrent/download/index.ts +9 -0
  43. package/src/torrent/download/manager.test.ts +393 -0
  44. package/src/torrent/download/manager.ts +376 -0
  45. package/src/torrent/file-selection.ts +51 -0
  46. package/src/torrent/index.ts +61 -0
  47. package/src/torrent/parser/helpers.ts +44 -0
  48. package/src/torrent/parser/index.ts +197 -0
  49. package/src/torrent/parser/info-hash.test.ts +39 -0
  50. package/src/torrent/parser/info-hash.ts +7 -0
  51. package/src/torrent/parser/parser.error.ts +21 -0
  52. package/src/torrent/parser/parser.test.ts +286 -0
  53. package/src/torrent/pieces/DefaultPlanner.ts +257 -0
  54. package/src/torrent/pieces/index.ts +20 -0
  55. package/src/torrent/pieces/planner.error.ts +18 -0
  56. package/src/torrent/pieces/planner.test.ts +303 -0
  57. package/src/torrent/pieces/planner.ts +16 -0
  58. package/src/torrent/pieces/types.ts +59 -0
  59. package/src/torrent/pieces/utils.ts +85 -0
  60. package/src/torrent/pieces/validation.test.ts +32 -0
  61. package/src/torrent/pieces/validation.ts +27 -0
  62. package/src/torrent/session/index.ts +195 -0
  63. package/src/torrent/session/session.test.ts +279 -0
  64. package/src/torrent/storage/index.ts +161 -0
  65. package/src/torrent/storage/storage.error.ts +18 -0
  66. package/src/torrent/storage/storage.test.ts +326 -0
  67. package/src/torrent/storage/types.ts +13 -0
  68. package/src/torrent/types.ts +16 -0
  69. package/src/tracker/http.test.ts +66 -0
  70. package/src/tracker/http.ts +137 -0
  71. package/src/tracker/index.ts +93 -0
  72. package/src/tracker/tracker.error.ts +26 -0
  73. package/src/tracker/types.ts +17 -0
  74. package/src/tracker/udp.test.ts +155 -0
  75. package/src/tracker/udp.ts +234 -0
  76. package/src/utils/__tests__/sha1.test.ts +16 -0
  77. package/src/utils/buffers.ts +28 -0
  78. package/src/utils/errors.ts +9 -0
  79. package/src/utils/formats.ts +8 -0
  80. package/src/utils/sha1.ts +4 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nikola Nedeljkovic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # bun-torrent
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "bun-torrent",
3
+ "version": "0.0.1-beta",
4
+ "type": "module",
5
+ "module": "src/index.ts",
6
+ "license": "MIT",
7
+ "description": "A minimal Bun-native BitTorrent download-only client.",
8
+ "keywords": [
9
+ "bun",
10
+ "bittorrent",
11
+ "torrent",
12
+ "download",
13
+ "typescript"
14
+ ],
15
+ "scripts": {
16
+ "test": "bun test",
17
+ "typecheck": "tsc --noEmit",
18
+ "lint": "eslint .",
19
+ "lint:fix": "eslint . --fix",
20
+ "format": "prettier . --write",
21
+ "format:check": "prettier . --check",
22
+ "check": "bun run typecheck && bun run lint && bun run format:check && bun test",
23
+ "app": "bun src/app.ts"
24
+ },
25
+ "engines": {
26
+ "bun": ">=1.3.0"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./src/index.ts",
36
+ "default": "./src/index.ts"
37
+ }
38
+ },
39
+ "sideEffects": false,
40
+ "devDependencies": {
41
+ "@eslint/js": "^10.0.1",
42
+ "@types/bun": "latest",
43
+ "eslint": "^10.3.0",
44
+ "globals": "^17.6.0",
45
+ "prettier": "3.8.3",
46
+ "typescript": "^5",
47
+ "typescript-eslint": "^8.59.3"
48
+ }
49
+ }
package/src/app.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { bytesToHex } from '@utils/buffers';
2
+ import type { TorrentMetadata } from '@torrent/index';
3
+ import { Client } from './client';
4
+
5
+ type InspectSummary = {
6
+ announce?: string;
7
+ announceList: string[][];
8
+ infoHash: string;
9
+ name: string;
10
+ pieceLength: number;
11
+ piecesTotal: number;
12
+ length: number;
13
+ files: Array<{
14
+ path: string;
15
+ length: number;
16
+ offset: number;
17
+ }>;
18
+ filesTotal: number;
19
+ };
20
+
21
+ const summarizeTorrent = (metadata: TorrentMetadata): InspectSummary => ({
22
+ announce: metadata.announce,
23
+ announceList: metadata.announceList,
24
+ infoHash: bytesToHex(metadata.infoHash),
25
+ name: metadata.name,
26
+ pieceLength: metadata.pieceLength,
27
+ piecesTotal: metadata.pieces.length,
28
+ length: metadata.length,
29
+ files: metadata.files.map((file) => ({
30
+ path: file.path.join('/'),
31
+ length: file.length,
32
+ offset: file.offset,
33
+ })),
34
+ filesTotal: metadata.files.length,
35
+ });
36
+
37
+ const inspectStdin = async (): Promise<void> => {
38
+ const input = new Uint8Array(await Bun.stdin.arrayBuffer());
39
+
40
+ if (input.byteLength === 0) {
41
+ console.error('Usage: bun src/app.ts < file.torrent');
42
+ process.exitCode = 1;
43
+ return;
44
+ }
45
+
46
+ try {
47
+ const client = new Client();
48
+ const metadata = await client.inspect({ torrentFile: input });
49
+ console.log(JSON.stringify(summarizeTorrent(metadata), null, 2));
50
+ } catch (error) {
51
+ console.error(error instanceof Error ? error.message : String(error));
52
+ process.exitCode = 1;
53
+ }
54
+ };
55
+
56
+ if (import.meta.main) {
57
+ const command = Bun.argv[2];
58
+
59
+ if (command === 'inspect') {
60
+ await inspectStdin();
61
+ } else {
62
+ console.error('Usage: bun src/app.ts inspect < file.torrent');
63
+ process.exitCode = 1;
64
+ }
65
+ }
@@ -0,0 +1,12 @@
1
+ import { BunTorrentError } from '@utils/errors';
2
+
3
+ export enum ClientErrorCode {
4
+ INVALID_FILE_SELECTION = 'CLIENT_INVALID_FILE_SELECTION',
5
+ UNSUPPORTED_TORRENT_FILE_INPUT = 'CLIENT_UNSUPPORTED_TORRENT_FILE_INPUT',
6
+ }
7
+
8
+ export class ClientError extends BunTorrentError {
9
+ constructor(code: ClientErrorCode, message: string) {
10
+ super(message, code);
11
+ }
12
+ }
@@ -0,0 +1,117 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { encodeBencode, toBValue } from '@torrent/index';
4
+ import { Client, DEFAULT_CLIENT_CONFIG } from './client';
5
+ import { ClientError, ClientErrorCode } from './client.error';
6
+
7
+ const makeTorrent = ({ announce }: { announce?: string } = {}): Uint8Array => {
8
+ const root: {
9
+ announce?: string;
10
+ info: {
11
+ length: number;
12
+ name: string;
13
+ 'piece length': number;
14
+ pieces: Uint8Array;
15
+ };
16
+ } = {
17
+ info: {
18
+ length: 12345,
19
+ name: 'file.bin',
20
+ 'piece length': 16384,
21
+ pieces: new Uint8Array(20),
22
+ },
23
+ };
24
+
25
+ if (announce !== undefined) root.announce = announce;
26
+
27
+ return encodeBencode(toBValue(root));
28
+ };
29
+
30
+ describe('Client.inspect', () => {
31
+ test('inspects torrent metadata from Uint8Array input', async () => {
32
+ const client = new Client();
33
+ const metadata = await client.inspect({
34
+ torrentFile: makeTorrent({ announce: 'https://tracker.test/announce' }),
35
+ });
36
+
37
+ expect(metadata.name).toBe('file.bin');
38
+ expect(metadata.length).toBe(12345);
39
+ expect(metadata.files).toEqual([{ path: ['file.bin'], length: 12345, offset: 0 }]);
40
+ });
41
+
42
+ test('inspects torrent metadata from ArrayBuffer input', async () => {
43
+ const client = new Client();
44
+ const torrent = makeTorrent({ announce: 'https://tracker.test/announce' });
45
+ const arrayBuffer = torrent.buffer.slice(
46
+ torrent.byteOffset,
47
+ torrent.byteOffset + torrent.byteLength,
48
+ ) as ArrayBuffer;
49
+ const metadata = await client.inspect({ torrentFile: arrayBuffer });
50
+
51
+ expect(metadata.name).toBe('file.bin');
52
+ expect(metadata.pieces).toHaveLength(1);
53
+ });
54
+
55
+ test('inspects torrent metadata from file path input', async () => {
56
+ const path = '/private/tmp/bun-torrent-client-inspect.torrent';
57
+ await Bun.write(path, makeTorrent({ announce: 'https://tracker.test/announce' }));
58
+
59
+ const client = new Client();
60
+ const metadata = await client.inspect({ torrentFile: path });
61
+
62
+ expect(metadata.name).toBe('file.bin');
63
+ expect(metadata.announce).toBe('https://tracker.test/announce');
64
+ });
65
+
66
+ test('rejects unsupported torrent file input with a client error', async () => {
67
+ const client = new Client();
68
+
69
+ expect(
70
+ client.inspect({ torrentFile: null as unknown as Uint8Array }),
71
+ ).rejects.toMatchObject({
72
+ code: ClientErrorCode.UNSUPPORTED_TORRENT_FILE_INPUT,
73
+ });
74
+ expect(
75
+ client.inspect({ torrentFile: null as unknown as Uint8Array }),
76
+ ).rejects.toBeInstanceOf(ClientError);
77
+ });
78
+ });
79
+
80
+ describe('Client.download', () => {
81
+ test('exposes default download configuration', () => {
82
+ expect(DEFAULT_CLIENT_CONFIG).toEqual({
83
+ maxInFlightRequestsPerPeer: 20,
84
+ progressEvents: 'piece',
85
+ requestTimeoutMs: 15_000,
86
+ speedSampleIntervalMs: 500,
87
+ });
88
+ });
89
+
90
+ test('returns an empty torrent instead of rejecting when no trackers are available', async () => {
91
+ const states: string[] = [];
92
+ const client = new Client();
93
+
94
+ const torrent = await client.download(
95
+ { torrentFile: makeTorrent() },
96
+ { onChangeState: (state) => states.push(state) },
97
+ );
98
+
99
+ expect(states).toEqual(['parsing', 'tracking', 'connecting', 'downloading']);
100
+ expect(torrent.stats).toMatchObject({
101
+ peers: 0,
102
+ connections: 0,
103
+ failedConnections: 0,
104
+ });
105
+ await torrent.done;
106
+ });
107
+
108
+ test('rejects unknown selected files', async () => {
109
+ const client = new Client();
110
+
111
+ await expect(
112
+ client.download({ torrentFile: makeTorrent() }, { files: ['missing.bin'] }),
113
+ ).rejects.toMatchObject({
114
+ code: ClientErrorCode.INVALID_FILE_SELECTION,
115
+ });
116
+ });
117
+ });
package/src/client.ts ADDED
@@ -0,0 +1,185 @@
1
+ import { createPeerId } from '@peer/peer-id';
2
+ import { openPeerPool } from '@peer/pool';
3
+ import { DownloadManager, type DownloadProgressEventMode } from '@torrent/download';
4
+ import { parseTorrent } from '@torrent/parser/';
5
+ import { Torrent } from '@torrent/session/index';
6
+ import type { TorrentMetadata } from '@torrent/types';
7
+ import { ClientError, ClientErrorCode } from './client.error';
8
+ import { trackPeers, TrackerError, TrackerErrorCode } from './tracker';
9
+ import type { TorrentFileSelection } from '@torrent/file-selection';
10
+ import { getUnknownSelectedFiles, normalizeTorrentFileSelection } from '@torrent/file-selection';
11
+
12
+ export enum DownloadState {
13
+ PARSING = 'parsing',
14
+ TRACKING = 'tracking',
15
+ CONNECTING = 'connecting',
16
+ DOWNLOADING = 'downloading',
17
+ }
18
+
19
+ export type ClientConfig = {
20
+ files?: TorrentFileSelection;
21
+ maxInFlightRequestsPerPeer?: number;
22
+ outputDirectory?: string;
23
+ progressEvents?: DownloadProgressEventMode;
24
+ requestTimeoutMs?: number;
25
+ speedSampleIntervalMs?: number;
26
+ };
27
+
28
+ export const DEFAULT_CLIENT_CONFIG = {
29
+ maxInFlightRequestsPerPeer: 20,
30
+ progressEvents: 'piece',
31
+ requestTimeoutMs: 15_000,
32
+ speedSampleIntervalMs: 500,
33
+ } as const satisfies Required<
34
+ Pick<
35
+ ClientConfig,
36
+ | 'maxInFlightRequestsPerPeer'
37
+ | 'progressEvents'
38
+ | 'requestTimeoutMs'
39
+ | 'speedSampleIntervalMs'
40
+ >
41
+ >;
42
+
43
+ export class Client {
44
+ private readonly peerId: Uint8Array;
45
+
46
+ constructor(private readonly config: ClientConfig = {}) {
47
+ this.peerId = createPeerId();
48
+ }
49
+
50
+ public async download(
51
+ input: {
52
+ torrentFile: string | Uint8Array | ArrayBuffer;
53
+ },
54
+ options: DownloadOptions = {},
55
+ ): Promise<Torrent> {
56
+ options.onChangeState?.(DownloadState.PARSING);
57
+ const meta = await this.inspect(input);
58
+ const downloadConfig = resolveDownloadConfig(this.config, options);
59
+ assertValidFileSelection(meta, downloadConfig.files);
60
+
61
+ options.onChangeState?.(DownloadState.TRACKING);
62
+ const peers = await this.trackPeers(meta, options);
63
+
64
+ options.onChangeState?.(DownloadState.CONNECTING);
65
+ const pool = await openPeerPool(peers, {
66
+ infoHash: meta.infoHash,
67
+ peerId: this.peerId,
68
+ targetConnections: 20,
69
+ totalPieces: meta.pieces.length,
70
+ minConnections: options.minConnections ?? 0,
71
+ maxConnecting: 30,
72
+ timeoutMs: 5_000,
73
+ });
74
+
75
+ options.onChangeState?.(DownloadState.DOWNLOADING);
76
+ return new Torrent(
77
+ meta,
78
+ pool,
79
+ new DownloadManager({
80
+ metadata: meta,
81
+ files: downloadConfig.files,
82
+ outputDirectory: downloadConfig.outputDirectory,
83
+ peerPool: pool,
84
+ maxInFlightRequestsPerPeer: downloadConfig.maxInFlightRequestsPerPeer,
85
+ progressEvents: downloadConfig.progressEvents,
86
+ requestTimeoutMs: downloadConfig.requestTimeoutMs,
87
+ speedSampleIntervalMs: downloadConfig.speedSampleIntervalMs,
88
+ }),
89
+ normalizeTorrentFileSelection(downloadConfig.files),
90
+ );
91
+ }
92
+
93
+ public async inspect(input: {
94
+ torrentFile: string | Uint8Array | ArrayBuffer;
95
+ }): Promise<TorrentMetadata> {
96
+ const bytes = await readTorrentFile(input.torrentFile);
97
+ return parseTorrent(bytes);
98
+ }
99
+
100
+ private async trackPeers(meta: TorrentMetadata, options: DownloadOptions): Promise<PeerInfo[]> {
101
+ try {
102
+ return await trackPeers({
103
+ meta,
104
+ peerId: this.peerId,
105
+ announcePort: options.announcePort,
106
+ timeoutMs: 5_000,
107
+ });
108
+ } catch (error) {
109
+ if (isNonFatalTrackerError(error)) return [];
110
+ throw error;
111
+ }
112
+ }
113
+ }
114
+
115
+ export type DownloadOptions = {
116
+ announcePort?: number;
117
+ files?: TorrentFileSelection;
118
+ maxInFlightRequestsPerPeer?: number;
119
+ minConnections?: number;
120
+ onChangeState?: (state: DownloadState) => unknown;
121
+ outputDirectory?: string;
122
+ progressEvents?: DownloadProgressEventMode;
123
+ requestTimeoutMs?: number;
124
+ speedSampleIntervalMs?: number;
125
+ };
126
+
127
+ type ResolvedDownloadConfig = Required<ClientConfig>;
128
+
129
+ type PeerInfo = Awaited<ReturnType<typeof trackPeers>>[number];
130
+
131
+ const isNonFatalTrackerError = (error: unknown): error is TrackerError =>
132
+ error instanceof TrackerError &&
133
+ (error.code === TrackerErrorCode.ANNOUNCE_FAILED ||
134
+ error.code === TrackerErrorCode.NO_PEERS ||
135
+ error.code === TrackerErrorCode.NO_SUPPORTED_TRACKERS);
136
+
137
+ const resolveDownloadConfig = (
138
+ config: ClientConfig,
139
+ options: DownloadOptions,
140
+ ): ResolvedDownloadConfig => ({
141
+ files: options.files ?? config.files ?? null,
142
+ maxInFlightRequestsPerPeer:
143
+ options.maxInFlightRequestsPerPeer ??
144
+ config.maxInFlightRequestsPerPeer ??
145
+ DEFAULT_CLIENT_CONFIG.maxInFlightRequestsPerPeer,
146
+ outputDirectory: options.outputDirectory ?? config.outputDirectory ?? process.cwd(),
147
+ progressEvents:
148
+ options.progressEvents ?? config.progressEvents ?? DEFAULT_CLIENT_CONFIG.progressEvents,
149
+ requestTimeoutMs:
150
+ options.requestTimeoutMs ??
151
+ config.requestTimeoutMs ??
152
+ DEFAULT_CLIENT_CONFIG.requestTimeoutMs,
153
+ speedSampleIntervalMs:
154
+ options.speedSampleIntervalMs ??
155
+ config.speedSampleIntervalMs ??
156
+ DEFAULT_CLIENT_CONFIG.speedSampleIntervalMs,
157
+ });
158
+
159
+ const assertValidFileSelection = (
160
+ metadata: TorrentMetadata,
161
+ files: TorrentFileSelection | undefined,
162
+ ): void => {
163
+ const unknownFiles = getUnknownSelectedFiles(metadata, files);
164
+ if (unknownFiles.length === 0) return;
165
+
166
+ throw new ClientError(
167
+ ClientErrorCode.INVALID_FILE_SELECTION,
168
+ `Unknown torrent file selection: ${unknownFiles.join(', ')}`,
169
+ );
170
+ };
171
+
172
+ export type TorrentFileInput = string | Uint8Array | ArrayBuffer;
173
+
174
+ export const readTorrentFile = async (input: TorrentFileInput): Promise<Uint8Array> => {
175
+ if (typeof input === 'string') return await Bun.file(input).bytes();
176
+ if (input instanceof Uint8Array) return input;
177
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
178
+
179
+ throw new ClientError(
180
+ ClientErrorCode.UNSUPPORTED_TORRENT_FILE_INPUT,
181
+ 'Unsupported torrent file input',
182
+ );
183
+ };
184
+
185
+ export { Client as TorrentClient };
@@ -0,0 +1,7 @@
1
+ import { expect, test } from 'bun:test';
2
+
3
+ import * as api from './index';
4
+
5
+ test('public entrypoint loads', () => {
6
+ expect(api).toBeDefined();
7
+ });
package/src/index.ts ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Copyright (c) 2026 Nikola Nedeljkovic
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ export * from './client';
7
+ export { ClientError, ClientErrorCode } from './client.error';
8
+
9
+ export {
10
+ BencodeDecodeError,
11
+ BencodeDecodeErrorCode,
12
+ BencodeEncodeError,
13
+ BencodeEncodeErrorCode,
14
+ computeInfoHash,
15
+ decodeBencode,
16
+ encodeBencode,
17
+ parseTorrent,
18
+ Torrent,
19
+ TorrentState,
20
+ toBValue,
21
+ TorrentParseError,
22
+ TorrentParseErrorCode,
23
+ type TorrentFileSelection,
24
+ type TorrentMetadata,
25
+ } from '@torrent/index';
26
+ export {
27
+ connectToPeers,
28
+ createPeerId,
29
+ decodeHandshake,
30
+ decodePeerMessage,
31
+ encodePeerMessage,
32
+ encodeHandshake,
33
+ HandshakeErrorCode,
34
+ PeerMessageError,
35
+ PeerMessageErrorCode,
36
+ PeerMessageId,
37
+ PeerHandshakeError,
38
+ PeerPoolError,
39
+ PeerPoolErrorCode,
40
+ PeerPool,
41
+ PeerSession,
42
+ PeerSessionError,
43
+ PeerSessionErrorCode,
44
+ openPeerPool,
45
+ type PeerHandshake,
46
+ } from '@peer/index';
47
+ export { TrackerError, TrackerErrorCode } from './tracker';
48
+ export type {
49
+ BitfieldMessage,
50
+ CancelMessage,
51
+ ChokeMessage,
52
+ HaveMessage,
53
+ InterestedMessage,
54
+ KeepAliveMessage,
55
+ NotInterestedMessage,
56
+ PeerMessage,
57
+ PieceMessage,
58
+ RequestMessage,
59
+ UnchokeMessage,
60
+ PeerConnectionSession,
61
+ PeerPoolOptions,
62
+ PeerSessionConnectOptions,
63
+ } from '@peer/index';
64
+
65
+ export { BunTorrentError } from '@utils/errors';
66
+ export type {
67
+ BBytes,
68
+ BDict,
69
+ BInteger,
70
+ BList,
71
+ BValue,
72
+ BencodeInput,
73
+ TorrentFiles,
74
+ TorrentStats,
75
+ TorrentStateChange,
76
+ } from '@torrent/index';
@@ -0,0 +1,24 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { PEER_ID_LENGTH, PEER_ID_PREFIX } from '../consts';
4
+ import { createPeerId } from '../peer-id';
5
+
6
+ const textDecoder = new TextDecoder();
7
+
8
+ describe('createPeerId', () => {
9
+ test('creates a 20-byte peer id', () => {
10
+ expect(createPeerId().byteLength).toBe(PEER_ID_LENGTH);
11
+ });
12
+
13
+ test('uses the bun-torrent peer id prefix', () => {
14
+ expect(textDecoder.decode(createPeerId()).startsWith(PEER_ID_PREFIX)).toBe(true);
15
+ });
16
+
17
+ test('uses an alphanumeric suffix', () => {
18
+ const peerId = textDecoder.decode(createPeerId());
19
+ const suffix = peerId.slice(PEER_ID_PREFIX.length);
20
+
21
+ expect(suffix).toMatch(/^[A-Za-z0-9]+$/);
22
+ expect(suffix.length).toBe(PEER_ID_LENGTH - PEER_ID_PREFIX.length);
23
+ });
24
+ });
@@ -0,0 +1,50 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { createPeerPieceAvailability, PeerPieceAvailability } from './availability';
4
+
5
+ describe('PeerPieceAvailability', () => {
6
+ test('starts with no pieces when no bitfield is provided', () => {
7
+ const availability = new PeerPieceAvailability(3);
8
+
9
+ expect(availability.hasPiece(0)).toBe(false);
10
+ expect(availability.hasPiece(1)).toBe(false);
11
+ expect(availability.hasPiece(2)).toBe(false);
12
+ expect(availability.toPieceIndexes()).toEqual([]);
13
+ });
14
+
15
+ test('reads peer bitfields using most-significant-bit ordering', () => {
16
+ const availability = new PeerPieceAvailability(10, {
17
+ bitfield: new Uint8Array([0b1010_0001, 0b1000_0000]),
18
+ });
19
+
20
+ expect(availability.toPieceIndexes()).toEqual([0, 2, 7, 8]);
21
+ expect(availability.hasPiece(9)).toBe(false);
22
+ });
23
+
24
+ test('ignores spare bits beyond totalPieces', () => {
25
+ const availability = createPeerPieceAvailability(3, new Uint8Array([0xff]));
26
+
27
+ expect(availability.toPieceIndexes()).toEqual([0, 1, 2]);
28
+ expect(availability.hasPiece(3)).toBe(false);
29
+ });
30
+
31
+ test('marks pieces from have messages', () => {
32
+ const availability = new PeerPieceAvailability(4);
33
+
34
+ availability.markHave(2);
35
+ availability.markHave(10);
36
+ availability.markHave(-1);
37
+
38
+ expect(availability.toPieceIndexes()).toEqual([2]);
39
+ });
40
+
41
+ test('replaces availability from a new bitfield', () => {
42
+ const availability = new PeerPieceAvailability(4, {
43
+ bitfield: new Uint8Array([0b1000_0000]),
44
+ });
45
+
46
+ availability.setBitfield(new Uint8Array([0b0101_0000]));
47
+
48
+ expect(availability.toPieceIndexes()).toEqual([1, 3]);
49
+ });
50
+ });