summaryrefslogtreecommitdiffstats
path: root/client.js
blob: 77dd88b5d3971f75feb82a6087e9245eb4794a78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict'

const connect = require('./connect')
const createParser = require('./lib/response-parser')
const {
	DEFAULT_PORT,
	ALPN_ID,
} = require('./lib/util')

const sendGeminiRequest = (pathOrUrl, opt, cb) => {
	if (typeof pathOrUrl !== 'string' || !pathOrUrl) {
		throw new Error('pathOrUrl must be a string & not empty')
	}
	if (typeof opt === 'function') {
		cb = opt
		opt = {}
	}
	const {
		port,
		tlsOpt,
	} = {
		port: DEFAULT_PORT,
		tlsOpt: {},
		...opt,
	}

	connect({
		port, tlsOpt,
	}, (err, socket) => {
		if (err) return cb(err)

		if (socket.alpnProtocol !== ALPN_ID) {
			socket.destroy()
			return cb(new Error('invalid or missing ALPN protocol'))
		}

		const res = createParser()
		socket.pipe(res)
		socket.once('error', (err) => {
			socket.unpipe(res)
			res.destroy(err)
		})

		const close = () => {
			socket.destroy()
			res.destroy()
		}
		let timeout = setTimeout(close, 20 * 1000)

		res.once('header', (header) => {
			clearTimeout(timeout)

			// prepare res
			res.socket = socket
			res.statusCode = header.statusCode
			res.statusMessage = header.statusMsg
			res.meta = header.meta // todo: change name
			// todo: res.abort(), res.destroy()

			cb(null, res)
			socket.emit('response', res)
		})

		// send request
		socket.end(encodeURI(pathOrUrl) + ' \r\n')
	})
}

module.exports = sendGeminiRequest