datachannel-file-transfer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/index.d.ts +44 -0
  4. package/index.js +213 -0
  5. package/package.json +40 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BESI
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 CHANGED
@@ -1,3 +1,124 @@
1
- # Temporary Holding Version
1
+ # datachannel-file-transfer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send files between two browsers over a WebRTC `RTCDataChannel`.
4
+
5
+ - Works in both directions on the same channel
6
+ - Splits big files into chunks and reads them from disk a piece at a time
7
+ - Backpressure: waits when the channel's buffer is full, so large files don't crash the tab
8
+ - Progress events for sending and receiving
9
+ - `sendFile()` resolves only when the other side has the whole file
10
+ - Zero dependencies, about 250 lines, ES module with TypeScript types
11
+
12
+ It does **not** connect the two browsers for you. Use whatever you already use for that
13
+ (your own signaling, [PeerJS](https://peerjs.com), simple-peer, …) and hand the
14
+ resulting data channel to this library.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install datachannel-file-transfer
20
+ ```
21
+
22
+ Or without a build step:
23
+
24
+ ```html
25
+ <script type="module">
26
+ import { createFileTransfer } from 'https://cdn.jsdelivr.net/npm/datachannel-file-transfer@0.1.0/index.js';
27
+ </script>
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```js
33
+ import { createFileTransfer } from 'datachannel-file-transfer';
34
+
35
+ // `channel` is an RTCDataChannel you already created (open or still opening)
36
+ const transfer = createFileTransfer(channel, {
37
+ onIncoming(info) {
38
+ console.log('receiving', info.name, info.size, 'bytes');
39
+ },
40
+ onProgress({ name, direction, bytes, total }) {
41
+ console.log(direction, name, Math.round(bytes / total * 100) + '%');
42
+ },
43
+ onFile(file, info) {
44
+ // file is a File: save it, show it, upload it…
45
+ const a = document.createElement('a');
46
+ a.href = URL.createObjectURL(file);
47
+ a.download = info.name;
48
+ a.textContent = 'Save ' + info.name;
49
+ document.body.append(a);
50
+ },
51
+ onError(err, info) {
52
+ console.warn('transfer failed', info && info.name, err.message);
53
+ }
54
+ });
55
+
56
+ // Send files picked by the user
57
+ input.addEventListener('change', async () => {
58
+ for (const file of input.files) {
59
+ await transfer.sendFile(file); // resolves once the other side has it
60
+ }
61
+ });
62
+ ```
63
+
64
+ ### With PeerJS
65
+
66
+ ```js
67
+ const peer = new Peer();
68
+ const conn = peer.connect(otherId, { reliable: true, serialization: 'raw' });
69
+ conn.on('open', () => {
70
+ const transfer = createFileTransfer(conn.dataChannel, { onFile: save });
71
+ });
72
+ ```
73
+
74
+ Use `serialization: 'raw'` so PeerJS doesn't re-encode the messages, and attach the
75
+ library on **both** sides.
76
+
77
+ ## API
78
+
79
+ ### `createFileTransfer(channel, options?)`
80
+
81
+ | option | default | |
82
+ |---|---|---|
83
+ | `onIncoming(info)` | | a file started arriving: `{ id, name, size, type }` |
84
+ | `onFile(file, info)` | | a file fully arrived |
85
+ | `onProgress(p)` | | `{ id, name, direction: 'send' \| 'receive', bytes, total }` |
86
+ | `onError(err, info?)` | | a send or receive failed |
87
+ | `chunkSize` | 64 KiB | bytes per channel message |
88
+ | `readSize` | 1 MiB | bytes read from disk at once |
89
+ | `bufferHigh` | 8 MiB | pause sending above this many queued bytes |
90
+ | `bufferLow` | 1 MiB | resume below this |
91
+
92
+ Returns:
93
+
94
+ - `sendFile(file)` → `Promise<void>`: queues a `File` or `Blob`; files go one at a time in order
95
+ - `sendFiles(files)` → `Promise<void[]>`
96
+ - `busy`: `true` while anything is sending or arriving
97
+ - `destroy()`: stop listening (does not close the channel)
98
+
99
+ ## Limits
100
+
101
+ - A received file is kept in memory until the transfer ends, so very large files
102
+ (above roughly 1 GB) can be too much for phones.
103
+ - Channels must be **reliable and ordered** (the WebRTC default).
104
+ - Both sides must use this library: it uses a small message format of JSON control
105
+ messages (`meta`, `end`, `got`, `abort`) plus binary chunks.
106
+
107
+ ## Example
108
+
109
+ [`example/index.html`](example/index.html) sends files between two browser tabs on the
110
+ same computer, with no server at all.
111
+
112
+ ## Tests
113
+
114
+ ```bash
115
+ npm install --no-save playwright
116
+ npm test
117
+ ```
118
+
119
+ Runs a real WebRTC connection in headless Chromium, sends files both ways and checks every
120
+ byte arrived unchanged.
121
+
122
+ ## License
123
+
124
+ MIT
package/index.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ export interface FileInfo {
2
+ id: number;
3
+ name: string;
4
+ size: number;
5
+ type: string;
6
+ }
7
+
8
+ export interface Progress {
9
+ id: number;
10
+ name: string;
11
+ direction: 'send' | 'receive';
12
+ bytes: number;
13
+ total: number;
14
+ }
15
+
16
+ export interface TransferOptions {
17
+ /** A file has started arriving. */
18
+ onIncoming?: (info: FileInfo) => void;
19
+ /** A file has fully arrived. */
20
+ onFile?: (file: File | Blob, info: FileInfo) => void;
21
+ onProgress?: (progress: Progress) => void;
22
+ onError?: (error: Error, info?: { id: number; name: string; direction: 'send' | 'receive' }) => void;
23
+ /** Bytes per data-channel message. Default 65536. */
24
+ chunkSize?: number;
25
+ /** Bytes read from disk at once. Default 1 MiB. */
26
+ readSize?: number;
27
+ /** Pause sending above this many queued bytes. Default 8 MiB. */
28
+ bufferHigh?: number;
29
+ /** Resume sending below this many queued bytes. Default 1 MiB. */
30
+ bufferLow?: number;
31
+ }
32
+
33
+ export interface FileTransfer {
34
+ /** Resolves once the other side has received the whole file. */
35
+ sendFile(file: File | Blob): Promise<void>;
36
+ sendFiles(files: Iterable<File | Blob> | ArrayLike<File | Blob>): Promise<void[]>;
37
+ /** True while files are being sent or received. */
38
+ readonly busy: boolean;
39
+ /** Stop listening to the channel. Does not close the channel. */
40
+ destroy(): void;
41
+ }
42
+
43
+ export function createFileTransfer(channel: RTCDataChannel, options?: TransferOptions): FileTransfer;
44
+ export default createFileTransfer;
package/index.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * datachannel-file-transfer
3
+ * Send files over a WebRTC RTCDataChannel, in both directions, with
4
+ * chunking, backpressure, progress events and delivery confirmation.
5
+ *
6
+ * MIT License
7
+ */
8
+
9
+ const DEFAULTS = {
10
+ chunkSize: 64 * 1024, // bytes per data-channel message
11
+ readSize: 1024 * 1024, // bytes read from disk at once
12
+ bufferHigh: 8 * 1024 * 1024, // pause sending above this many queued bytes
13
+ bufferLow: 1024 * 1024 // resume sending below this
14
+ };
15
+
16
+ /**
17
+ * Attach file transfer to an open (or opening) RTCDataChannel.
18
+ *
19
+ * @param {RTCDataChannel} channel
20
+ * @param {object} [options]
21
+ * @param {(info: {id:number, name:string, size:number, type:string}) => void} [options.onIncoming]
22
+ * A file has started arriving.
23
+ * @param {(file: File|Blob, info: {id:number, name:string, size:number, type:string}) => void} [options.onFile]
24
+ * A file has fully arrived.
25
+ * @param {(p: {id:number, name:string, direction:'send'|'receive', bytes:number, total:number}) => void} [options.onProgress]
26
+ * @param {(err: Error, info?: {id:number, name:string, direction:'send'|'receive'}) => void} [options.onError]
27
+ * @param {number} [options.chunkSize]
28
+ * @param {number} [options.readSize]
29
+ * @param {number} [options.bufferHigh]
30
+ * @param {number} [options.bufferLow]
31
+ */
32
+ export function createFileTransfer(channel, options = {}) {
33
+ const opt = Object.assign({}, DEFAULTS, options);
34
+ const noop = () => {};
35
+ const onIncoming = opt.onIncoming || noop;
36
+ const onFile = opt.onFile || noop;
37
+ const onProgress = opt.onProgress || noop;
38
+ const onError = opt.onError || noop;
39
+
40
+ channel.binaryType = 'arraybuffer';
41
+ channel.bufferedAmountLowThreshold = opt.bufferLow;
42
+
43
+ let nextId = 1;
44
+ let incoming = null; // file currently arriving
45
+ const queue = []; // files waiting to be sent
46
+ const waiting = new Map(); // id -> {resolve, reject} until the receiver confirms
47
+ let sending = false;
48
+ let closed = false;
49
+
50
+ function sendJSON(obj) {
51
+ if (channel.readyState === 'open') channel.send(JSON.stringify(obj));
52
+ }
53
+
54
+ function waitForBuffer() {
55
+ return new Promise((resolve, reject) => {
56
+ const done = () => { clearInterval(timer); channel.removeEventListener('bufferedamountlow', check); };
57
+ const check = () => {
58
+ if (channel.readyState !== 'open') { done(); reject(new Error('Channel closed')); }
59
+ else if (channel.bufferedAmount <= opt.bufferLow) { done(); resolve(); }
60
+ };
61
+ const timer = setInterval(check, 200); // some browsers miss the event
62
+ channel.addEventListener('bufferedamountlow', check);
63
+ });
64
+ }
65
+
66
+ function waitForOpen() {
67
+ if (channel.readyState === 'open') return Promise.resolve();
68
+ return new Promise((resolve, reject) => {
69
+ channel.addEventListener('open', () => resolve(), { once: true });
70
+ channel.addEventListener('close', () => reject(new Error('Channel closed')), { once: true });
71
+ });
72
+ }
73
+
74
+ async function pump() {
75
+ if (sending) return;
76
+ sending = true;
77
+ try {
78
+ await waitForOpen();
79
+ while (queue.length) {
80
+ const job = queue.shift();
81
+ const { id, file } = job;
82
+ const name = file.name || 'file';
83
+ const total = file.size;
84
+ try {
85
+ channel.send(JSON.stringify({ t: 'meta', id, name, size: total, type: file.type || 'application/octet-stream' }));
86
+ waiting.set(id, job);
87
+ let offset = 0;
88
+ while (offset < total) {
89
+ const buf = await file.slice(offset, offset + opt.readSize).arrayBuffer();
90
+ for (let i = 0; i < buf.byteLength; i += opt.chunkSize) {
91
+ if (channel.readyState !== 'open') throw new Error('Channel closed');
92
+ if (channel.bufferedAmount > opt.bufferHigh) await waitForBuffer();
93
+ channel.send(buf.slice(i, i + opt.chunkSize));
94
+ }
95
+ offset += buf.byteLength;
96
+ onProgress({ id, name, direction: 'send', bytes: Math.max(0, offset - channel.bufferedAmount), total });
97
+ }
98
+ channel.send(JSON.stringify({ t: 'end', id }));
99
+ onProgress({ id, name, direction: 'send', bytes: total, total });
100
+ } catch (err) {
101
+ waiting.delete(id);
102
+ job.reject(err);
103
+ onError(err, { id, name, direction: 'send' });
104
+ if (channel.readyState !== 'open') break;
105
+ sendJSON({ t: 'abort', id });
106
+ }
107
+ }
108
+ } catch (err) {
109
+ // channel never opened
110
+ } finally {
111
+ sending = false;
112
+ if (channel.readyState !== 'open') failAll(new Error('Channel closed'));
113
+ }
114
+ }
115
+
116
+ function failAll(err) {
117
+ queue.splice(0).forEach((job) => job.reject(err));
118
+ waiting.forEach((job) => job.reject(err));
119
+ waiting.clear();
120
+ if (incoming) {
121
+ onError(err, { id: incoming.id, name: incoming.name, direction: 'receive' });
122
+ incoming = null;
123
+ }
124
+ }
125
+
126
+ function onMessage(ev) {
127
+ const data = ev.data;
128
+ if (typeof data !== 'string') {
129
+ if (!incoming) return;
130
+ incoming.chunks.push(data);
131
+ incoming.bytes += data.byteLength;
132
+ onProgress({ id: incoming.id, name: incoming.name, direction: 'receive', bytes: incoming.bytes, total: incoming.size });
133
+ return;
134
+ }
135
+ let msg;
136
+ try { msg = JSON.parse(data); } catch (e) { return; }
137
+
138
+ if (msg.t === 'meta') {
139
+ const info = {
140
+ id: msg.id,
141
+ name: String(msg.name || 'file').replace(/[\/\\]/g, '_').slice(0, 255),
142
+ size: Number(msg.size) || 0,
143
+ type: String(msg.type || 'application/octet-stream')
144
+ };
145
+ incoming = Object.assign({ chunks: [], bytes: 0 }, info);
146
+ onIncoming(info);
147
+ } else if (msg.t === 'end' && incoming && incoming.id === msg.id) {
148
+ const f = incoming;
149
+ incoming = null;
150
+ const info = { id: f.id, name: f.name, size: f.size, type: f.type };
151
+ if (f.bytes !== f.size) {
152
+ onError(new Error('File arrived incomplete'), Object.assign({ direction: 'receive' }, info));
153
+ return;
154
+ }
155
+ let file;
156
+ try { file = new File(f.chunks, f.name, { type: f.type }); }
157
+ catch (e) { file = new Blob(f.chunks, { type: f.type }); }
158
+ f.chunks = null;
159
+ sendJSON({ t: 'got', id: f.id });
160
+ onFile(file, info);
161
+ } else if (msg.t === 'abort' && incoming && incoming.id === msg.id) {
162
+ onError(new Error('Sender cancelled the file'), { id: incoming.id, name: incoming.name, direction: 'receive' });
163
+ incoming = null;
164
+ } else if (msg.t === 'got') {
165
+ const job = waiting.get(msg.id);
166
+ if (job) { waiting.delete(msg.id); job.resolve(); }
167
+ }
168
+ }
169
+
170
+ function onClose() {
171
+ closed = true;
172
+ failAll(new Error('Channel closed'));
173
+ }
174
+
175
+ channel.addEventListener('message', onMessage);
176
+ channel.addEventListener('close', onClose);
177
+
178
+ return {
179
+ /**
180
+ * Queue a File or Blob for sending. Resolves when the other side has
181
+ * received the whole file, rejects if it could not be delivered.
182
+ * @param {File|Blob} file
183
+ * @returns {Promise<void>}
184
+ */
185
+ sendFile(file) {
186
+ if (closed) return Promise.reject(new Error('Channel closed'));
187
+ return new Promise((resolve, reject) => {
188
+ queue.push({ id: nextId++, file, resolve, reject });
189
+ pump();
190
+ });
191
+ },
192
+
193
+ /** Send several files one after another. */
194
+ sendFiles(files) {
195
+ return Promise.all(Array.from(files, (f) => this.sendFile(f)));
196
+ },
197
+
198
+ /** True while files are being sent or received. */
199
+ get busy() {
200
+ return sending || queue.length > 0 || waiting.size > 0 || incoming !== null;
201
+ },
202
+
203
+ /** Stop listening to the channel. Does not close the channel itself. */
204
+ destroy() {
205
+ channel.removeEventListener('message', onMessage);
206
+ channel.removeEventListener('close', onClose);
207
+ closed = true;
208
+ failAll(new Error('Transfer destroyed'));
209
+ }
210
+ };
211
+ }
212
+
213
+ export default createFileTransfer;
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "datachannel-file-transfer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Send files between browsers over a WebRTC RTCDataChannel, with chunking, backpressure, progress and delivery confirmation. No dependencies.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "module": "index.js",
8
+ "types": "index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts"
18
+ ],
19
+ "scripts": {
20
+ "test": "node test/run.js"
21
+ },
22
+ "keywords": [
23
+ "webrtc",
24
+ "datachannel",
25
+ "rtcdatachannel",
26
+ "file-transfer",
27
+ "p2p",
28
+ "peer-to-peer",
29
+ "file-sharing",
30
+ "browser"
31
+ ],
32
+ "author": "BESI",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/besimobai/datachannel-file-transfer.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/besimobai/datachannel-file-transfer/issues"
40
+ },
41
+ "homepage": "https://github.com/besimobai/datachannel-file-transfer#readme"
42
+ }