-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
executable file
·861 lines (703 loc) · 23.4 KB
/
index.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
import { posix } from 'path'
import { Readable, pipelinePromise } from 'streamx'
import Hyperdrive from 'hyperdrive'
import { makeRoutedFetch } from 'make-fetch'
import mime from 'mime/index.js'
import parseRange from 'range-parser'
import { EventIterator } from 'event-iterator'
const DEFAULT_TIMEOUT = 5000
const SPECIAL_DOMAIN = 'localhost'
const SPECIAL_FOLDER = '$'
const EXTENSIONS_FOLDER_NAME = 'extensions'
const EXTENSION_EVENT = 'extension-message'
const VERSION_FOLDER_NAME = 'version'
const PEER_OPEN = 'peer-open'
const PEER_REMOVE = 'peer-remove'
const MIME_TEXT_PLAIN = 'text/plain; charset=utf-8'
const MIME_APPLICATION_JSON = 'application/json'
const MIME_TEXT_HTML = 'text/html; charset=utf-8'
const MIME_EVENT_STREAM = 'text/event-stream; charset=utf-8'
const HEADER_CONTENT_TYPE = 'Content-Type'
const HEADER_LAST_MODIFIED = 'Last-Modified'
const WRITABLE_METHODS = [
'PUT',
'DELETE'
]
const BASIC_METHODS = [
'HEAD',
'GET'
]
export const ERROR_KEY_NOT_CREATED = 'Must create key with POST before reading'
export const ERROR_DRIVE_EMPTY = 'Could not find data in drive, make sure your key is correct and that there are peers online to load data from'
const INDEX_FILES = [
'index.html',
'index.md',
'index.gmi',
'index.gemini',
'index.org',
'README.md',
'README.org'
]
async function DEFAULT_RENDER_INDEX (url, files, fetch) {
return `
<!DOCTYPE html>
<title>Index of ${url.pathname}</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<h1>Index of ${url.pathname}</h1>
<ul>
<li><a href="../">../</a></li>
${files.map((file) => `<li><a href="${file}">./${file}</a></li>`).join('\n')}
</ul>
`
}
// Support gemini files
mime.define({
'text/gemini': ['gmi', 'gemini']
}, true)
export default async function makeHyperFetch ({
sdk,
writable = false,
extensionMessages = writable,
timeout = DEFAULT_TIMEOUT,
renderIndex = DEFAULT_RENDER_INDEX
}) {
const { fetch, router } = makeRoutedFetch({
onError
})
// Map loaded drive hostnames to their keys
// TODO: Track LRU + cache clearing
const drives = new Map()
const extensions = new Map()
const cores = new Map()
if (extensionMessages) {
router.get(`hyper://*/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/`, listExtensions)
router.get(`hyper://*/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/*`, listenExtension)
router.post(`hyper://*/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/*`, broadcastExtension)
router.post(`hyper://*/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/*/*`, extensionToPeer)
}
if (writable) {
router.get(`hyper://${SPECIAL_DOMAIN}/`, getKey)
router.post(`hyper://${SPECIAL_DOMAIN}/`, createKey)
router.put(`hyper://*/${SPECIAL_FOLDER}/${VERSION_FOLDER_NAME}/**`, putFilesVersioned)
router.put('hyper://*/**', putFiles)
router.delete('hyper://*/', deleteDrive)
router.delete(`hyper://*/${SPECIAL_FOLDER}/${VERSION_FOLDER_NAME}/**`, deleteFilesVersioned)
router.delete('hyper://*/**', deleteFiles)
}
router.head(`hyper://*/${SPECIAL_FOLDER}/${VERSION_FOLDER_NAME}/**`, headFilesVersioned)
router.get(`hyper://*/${SPECIAL_FOLDER}/${VERSION_FOLDER_NAME}/**`, getFilesVersioned)
router.get('hyper://*/**', getFiles)
router.head('hyper://*/**', headFiles)
async function onError (e, request) {
return {
status: e.statusCode || 500,
headers: {
'Content-Type': 'text/plain; charset=utf-8'
},
body: e.stack
}
}
async function getCore (hostname) {
if (cores.has(hostname)) {
return cores.get(hostname)
}
const core = await sdk.get(hostname)
await core.ready()
cores.set(core.id, core)
cores.set(core.url, core)
return core
}
async function getDBCoreForName (name) {
const corestore = sdk.namespace(name)
const dbCore = corestore.get({ name: 'db' })
await dbCore.ready()
if (!dbCore.discovery) {
const discovery = sdk.join(dbCore.discoveryKey)
dbCore.discovery = discovery
dbCore.once('close', () => {
discovery.destroy()
})
await discovery.flushed()
}
return dbCore
}
async function getDrive (hostname, errorOnNew = false) {
if (drives.has(hostname)) {
return drives.get(hostname)
}
const core = await getCore(hostname)
if (!core.length && errorOnNew) {
await core.close()
const e = new Error(ERROR_DRIVE_EMPTY)
e.statusCode = 404
throw e
}
const corestore = sdk.namespace(core.id)
const drive = new Hyperdrive(corestore, core.key)
await drive.ready()
drive.once('close', () => {
drives.delete(drive.core.id)
drives.delete(hostname)
})
drives.set(drive.core.id, drive)
drives.set(drive.core.url, drive)
drives.set(hostname, drive)
return drive
}
async function getDriveFromKey (key, errorOnNew = false) {
if (drives.has(key)) {
return drives.get(key)
}
const core = await getDBCoreForName(key)
if (!core.length && errorOnNew) {
const e = new Error(ERROR_KEY_NOT_CREATED)
e.statusCode = 404
throw e
}
const corestore = sdk.namespace(key)
const drive = new Hyperdrive(corestore)
await drive.ready()
drive.once('close', () => {
drives.delete(key)
drives.delete(drive.url)
drives.delete(drive.core.id)
})
drives.set(key, drive)
drives.set(drive.url, drive)
drives.set(drive.core.id, drive)
return drive
}
async function getExtension (core, name) {
const key = core.url + name
if (extensions.has(key)) {
return extensions.get(key)
}
const existing = core.extensions.get(name)
if (existing) {
extensions.set(key, existing)
return existing
}
const extension = core.registerExtension(name, {
encoding: 'utf8',
onmessage: (content, peer) => {
core.emit(EXTENSION_EVENT, name, content, peer)
}
})
extensions.set(key, extension)
return extension
}
async function getExtensionPeers (core, name) {
// List peers with this extension
const allPeers = core.peers
return allPeers.filter((peer) => {
return peer?.extensions?.has(name)
})
}
function listExtensionNames (core) {
return [...core.extensions.keys()]
}
async function listExtensions (request) {
const { hostname } = new URL(request.url)
const accept = request.headers.get('Accept') || ''
const core = await getCore(`hyper://${hostname}/`)
if (accept.includes('text/event-stream')) {
const events = new EventIterator(({ push }) => {
function onMessage (name, content, peer) {
const id = peer.remotePublicKey.toString('hex')
// TODO: Fancy verification on the `name`?
// Send each line of content separately on a `data` line
const data = content.split('\n').map((line) => `data:${line}\n`).join('')
push(`id:${id}\nevent:${name}\n${data}\n`)
}
function onPeerOpen (peer) {
const id = peer.remotePublicKey.toString('hex')
push(`id:${id}\nevent:${PEER_OPEN}\n\n`)
}
function onPeerRemove (peer) {
// Whatever, probably an uninitialized peer
if (!peer.remotePublicKey) return
const id = peer.remotePublicKey.toString('hex')
push(`id:${id}\nevent:${PEER_REMOVE}\n\n`)
}
core.on(EXTENSION_EVENT, onMessage)
core.on(PEER_OPEN, onPeerOpen)
core.on(PEER_REMOVE, onPeerRemove)
return () => {
core.removeListener(EXTENSION_EVENT, onMessage)
core.removeListener(PEER_OPEN, onPeerOpen)
core.removeListener(PEER_REMOVE, onPeerRemove)
}
})
return {
statusCode: 200,
headers: {
[HEADER_CONTENT_TYPE]: MIME_EVENT_STREAM
},
body: events
}
}
const extensions = listExtensionNames(core)
return {
status: 200,
headers: { [HEADER_CONTENT_TYPE]: MIME_APPLICATION_JSON },
body: JSON.stringify(extensions, null, '\t')
}
}
async function listenExtension (request) {
const { hostname, pathname: rawPathname } = new URL(request.url)
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const name = pathname.slice(`/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/`.length)
const core = await getCore(`hyper://${hostname}/`)
await getExtension(core, name)
const peers = await getExtensionPeers(core, name)
const finalPeers = formatPeers(peers)
const body = JSON.stringify(finalPeers, null, '\t')
return {
status: 200,
body,
headers: {
[HEADER_CONTENT_TYPE]: MIME_APPLICATION_JSON
}
}
}
async function broadcastExtension (request) {
const { hostname, pathname: rawPathname } = new URL(request.url)
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const name = pathname.slice(`/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/`.length)
const core = await getCore(`hyper://${hostname}/`)
const extension = await getExtension(core, name)
const data = await request.text()
extension.broadcast(data)
return { status: 200 }
}
async function extensionToPeer (request) {
const { hostname, pathname: rawPathname } = new URL(request.url)
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const subFolder = pathname.slice(`/${SPECIAL_FOLDER}/${EXTENSIONS_FOLDER_NAME}/`.length)
const [name, extensionPeer] = subFolder.split('/')
const core = await getCore(`hyper://${hostname}/`)
const extension = await getExtension(core, name)
const peers = await getExtensionPeers(core, name)
const peer = peers.find(({ remotePublicKey }) => remotePublicKey.toString('hex') === extensionPeer)
if (!peer) {
return {
status: 404,
headers: {
[HEADER_CONTENT_TYPE]: MIME_TEXT_PLAIN
},
body: 'Peer Not Found'
}
}
const data = await request.arrayBuffer()
extension.send(data, peer)
return { status: 200 }
}
async function getKey (request) {
const key = new URL(request.url).searchParams.get('key')
if (!key) {
return { status: 400, body: 'Must specify key parameter to resolve' }
}
try {
const drive = await getDriveFromKey(key, true)
return { body: drive.url }
} catch (e) {
if (e.message === ERROR_KEY_NOT_CREATED) {
return {
status: 400,
body: e.message,
headers: {
[HEADER_CONTENT_TYPE]: MIME_TEXT_PLAIN
}
}
} else throw e
}
}
async function createKey (request) {
// TODO: Allow importing secret keys here
// Maybe specify a seed to use for generating the blobs?
// Else we'd need to specify the blobs keys and metadata keys
const key = new URL(request.url).searchParams.get('key')
if (!key) {
return { status: 400, body: 'Must specify key parameter to resolve' }
}
const drive = await getDriveFromKey(key, false)
return { body: drive.url }
}
async function putFiles (request) {
const { hostname, pathname: rawPathname } = new URL(request.url)
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const contentType = request.headers.get('Content-Type') || ''
const mtime = Date.parse(request.headers.get('Last-Modified')) || Date.now()
const isFormData = contentType.includes('multipart/form-data')
const drive = await getDrive(`hyper://${hostname}/`, true)
if (!drive.db.feed.writable) {
return { status: 403, body: `Cannot PUT file to read-only drive: ${drive.url}`, headers: { Location: request.url } }
}
if (isFormData) {
// It's a form! Get the files out and process them
const formData = await request.formData()
for (const [name, data] of formData) {
if (name !== 'file') continue
const filePath = posix.join(pathname, data.name)
await pipelinePromise(
Readable.from(data.stream()),
drive.createWriteStream(filePath, {
metadata: {
mtime
}
})
)
}
} else {
if (pathname.endsWith('/')) {
return { status: 405, body: 'Cannot PUT file with trailing slash', headers: { Location: request.url } }
} else {
await pipelinePromise(
Readable.from(request.body),
drive.createWriteStream(pathname, {
metadata: {
mtime
}
})
)
}
}
const fullURL = new URL(pathname, drive.url).href
const headers = {
Location: request.url,
ETag: `${drive.version}`,
Link: `<${fullURL}>; rel="canonical"`,
[HEADER_LAST_MODIFIED]: isFormData ? undefined : new Date(mtime).toUTCString()
}
return { status: 201, headers }
}
function putFilesVersioned (request) {
return {
status: 405,
body: 'Cannot PUT file to old version',
headers: { Location: request.url }
}
}
async function deleteDrive (request) {
const { hostname } = new URL(request.url)
const drive = await getDrive(`hyper://${hostname}/`, true)
await drive.purge()
return { status: 200 }
}
async function deleteFiles (request) {
const { hostname, pathname: rawPathname } = new URL(request.url)
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const drive = await getDrive(`hyper://${hostname}/`, true)
if (!drive.db.feed.writable) {
return { status: 403, body: `Cannot DELETE file in read-only drive: ${drive.url}`, headers: { Location: request.url } }
}
if (pathname.endsWith('/')) {
let didDelete = false
for await (const entry of drive.list(pathname)) {
await drive.del(entry.key)
didDelete = true
}
if (!didDelete) {
return { status: 404, body: 'Not Found', headers: { [HEADER_CONTENT_TYPE]: MIME_TEXT_PLAIN } }
}
return { status: 200 }
}
const entry = await drive.entry(pathname)
if (!entry) {
return { status: 404, body: 'Not Found', headers: { [HEADER_CONTENT_TYPE]: MIME_TEXT_PLAIN } }
}
await drive.del(pathname)
const fullURL = new URL(pathname, drive.url).href
const headers = {
ETag: `${drive.version}`,
Link: `<${fullURL}>; rel="canonical"`
}
return { status: 200, headers }
}
function deleteFilesVersioned (request) {
return { status: 405, body: 'Cannot DELETE old version', headers: { Location: request.url } }
}
async function headFilesVersioned (request) {
const url = new URL(request.url)
const { hostname, pathname: rawPathname, searchParams } = url
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const accept = request.headers.get('Accept') || ''
const isRanged = request.headers.get('Range') || ''
const noResolve = searchParams.has('noResolve')
const parts = pathname.split('/')
const version = parts[3]
const realPath = ensureLeadingSlash(parts.slice(4).join('/'))
const drive = await getDrive(`hyper://${hostname}/`, true)
const snapshot = await drive.checkout(version)
return serveHead(snapshot, realPath, { accept, isRanged, noResolve })
}
async function headFiles (request) {
const url = new URL(request.url)
const { hostname, pathname: rawPathname, searchParams } = url
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const accept = request.headers.get('Accept') || ''
const isRanged = request.headers.get('Range') || ''
const noResolve = searchParams.has('noResolve')
const drive = await getDrive(`hyper://${hostname}/`, true)
return serveHead(drive, pathname, { accept, isRanged, noResolve })
}
async function serveHead (drive, pathname, { accept, isRanged, noResolve }) {
const isDirectory = pathname.endsWith('/')
const fullURL = new URL(pathname, drive.url).href
const isWritable = writable && drive.db.feed.writable
const Allow = isWritable ? BASIC_METHODS.concat(WRITABLE_METHODS) : BASIC_METHODS
const resHeaders = {
ETag: `${drive.version}`,
'Accept-Ranges': 'bytes',
Link: `<${fullURL}>; rel="canonical"`,
Allow
}
if (isDirectory) {
const entries = await listEntries(drive, pathname)
const hasItems = entries.length
if (!hasItems && pathname !== '/') {
return {
status: 404,
headers: {
[HEADER_CONTENT_TYPE]: MIME_TEXT_PLAIN
}
}
}
if (!noResolve) {
for (const indexFile of INDEX_FILES) {
if (entries.includes(indexFile)) {
const mimeType = getMimeType(indexFile)
return {
status: 204,
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: mimeType
}
}
}
}
}
// TODO: Add range header calculation
if (accept.includes('text/html')) {
return {
status: 204,
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: MIME_TEXT_HTML
}
}
}
return {
status: 204,
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: MIME_APPLICATION_JSON
}
}
}
const { entry, path } = await resolvePath(drive, pathname, noResolve)
if (!entry) {
return { status: 404, body: 'Not Found' }
}
resHeaders.ETag = `${entry.seq + 1}`
resHeaders['Content-Length'] = `${entry.value.blob.byteLength}`
const contentType = getMimeType(path)
resHeaders[HEADER_CONTENT_TYPE] = contentType
if (entry?.value?.metadata?.mtime) {
const date = new Date(entry.value.metadata.mtime)
resHeaders[HEADER_LAST_MODIFIED] = date.toUTCString()
}
const size = entry.value.blob.byteLength
if (isRanged) {
const ranges = parseRange(size, isRanged)
if (ranges && ranges.length && ranges.type === 'bytes') {
const [{ start, end }] = ranges
const length = (end - start + 1)
return {
status: 204,
headers: {
...resHeaders,
'Content-Length': `${length}`,
'Content-Range': `bytes ${start}-${end}/${size}`
}
}
}
}
return {
status: 204,
headers: resHeaders
}
}
async function getFilesVersioned (request) {
const url = new URL(request.url)
const { hostname, pathname: rawPathname, searchParams } = url
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const accept = request.headers.get('Accept') || ''
const isRanged = request.headers.get('Range') || ''
const noResolve = searchParams.has('noResolve')
const parts = pathname.split('/')
const version = parts[3]
const realPath = ensureLeadingSlash(parts.slice(4).join('/'))
const drive = await getDrive(`hyper://${hostname}/`, true)
const snapshot = await drive.checkout(version)
return serveGet(snapshot, realPath, { accept, isRanged, noResolve })
}
// TODO: Redirect on directories without trailing slash
async function getFiles (request) {
const url = new URL(request.url)
const { hostname, pathname: rawPathname, searchParams } = url
const pathname = decodeURI(ensureLeadingSlash(rawPathname))
const accept = request.headers.get('Accept') || ''
const isRanged = request.headers.get('Range') || ''
const noResolve = searchParams.has('noResolve')
const drive = await getDrive(`hyper://${hostname}/`, true)
return serveGet(drive, pathname, { accept, isRanged, noResolve })
}
async function serveGet (drive, pathname, { accept, isRanged, noResolve }) {
const isDirectory = pathname.endsWith('/')
const fullURL = new URL(pathname, drive.url).href
if (isDirectory) {
const resHeaders = {
ETag: `${drive.version}`,
Link: `<${fullURL}>; rel="canonical"`
}
const entries = await listEntries(drive, pathname)
if (!entries.length && pathname !== '/') {
return {
status: 404,
body: '[]',
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: MIME_APPLICATION_JSON
}
}
}
if (!noResolve) {
for (const indexFile of INDEX_FILES) {
if (entries.includes(indexFile)) {
return serveFile(drive, posix.join(pathname, indexFile), isRanged)
}
}
}
if (accept.includes('text/html')) {
const body = await renderIndex(new URL(fullURL), entries, fetch)
return {
status: 200,
body,
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: MIME_TEXT_HTML
}
}
}
return {
status: 200,
body: JSON.stringify(entries, null, '\t'),
headers: {
...resHeaders,
[HEADER_CONTENT_TYPE]: MIME_APPLICATION_JSON
}
}
}
const { entry, path } = await resolvePath(drive, pathname, noResolve)
if (!entry) {
return { status: 404, body: 'Not Found' }
}
return serveFile(drive, path, isRanged)
}
return fetch
}
async function serveFile (drive, pathname, isRanged) {
const contentType = getMimeType(pathname)
const fullURL = new URL(pathname, drive.url).href
const entry = await drive.entry(pathname)
const resHeaders = {
ETag: `${entry.seq + 1}`,
[HEADER_CONTENT_TYPE]: contentType,
'Accept-Ranges': 'bytes',
Link: `<${fullURL}>; rel="canonical"`
}
if (entry?.value?.metadata?.mtime) {
const date = new Date(entry.value.metadata.mtime)
resHeaders[HEADER_LAST_MODIFIED] = date.toUTCString()
}
const size = entry.value.blob.byteLength
if (isRanged) {
const ranges = parseRange(size, isRanged)
if (ranges && ranges.length && ranges.type === 'bytes') {
const [{ start, end }] = ranges
const length = (end - start + 1)
return {
status: 200,
body: drive.createReadStream(pathname, {
start,
end
}),
headers: {
...resHeaders,
'Content-Length': `${length}`,
'Content-Range': `bytes ${start}-${end}/${size}`
}
}
}
}
return {
status: 200,
headers: {
...resHeaders,
'Content-Length': `${size}`
},
body: drive.createReadStream(pathname)
}
}
function makeToTry (pathname) {
return [
pathname,
pathname + '.html',
pathname + '.md'
]
}
async function resolvePath (drive, pathname, noResolve) {
if (noResolve) {
const entry = await drive.entry(pathname)
return { entry, path: pathname }
}
for (const path of makeToTry(pathname)) {
const entry = await drive.entry(path)
if (entry) {
return { entry, path }
}
}
return { entry: null, path: null }
}
async function listEntries (drive, pathname = '/') {
const entries = []
for await (const path of drive.readdir(pathname)) {
const fullPath = posix.join(pathname, path)
const stat = await drive.entry(fullPath)
if (stat === null) {
entries.push(path + '/')
} else {
entries.push(path)
}
}
return entries
}
function formatPeers (peers) {
return peers.map((peer) => {
const remotePublicKey = peer.remotePublicKey.toString('hex')
const remoteHost = peer.stream?.rawStream?.remoteHost
return {
remotePublicKey,
remoteHost
}
})
}
function getMimeType (path) {
let mimeType = mime.getType(path) || 'text/plain; charset=utf-8'
if (mimeType.startsWith('text/')) mimeType = `${mimeType}; charset=utf-8`
return mimeType
}
function ensureLeadingSlash (path) {
return path.startsWith('/') ? path : '/' + path
}