This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 545
/
dat-archive-web-api-test.js
2120 lines (1852 loc) · 64.6 KB
/
dat-archive-web-api-test.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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import test from 'ava'
import os from 'os'
import path from 'path'
import fs from 'fs'
import tempy from 'tempy'
import electron from '../node_modules/electron'
import * as browserdriver from './lib/browser-driver'
import {shareDat, createDat} from './lib/dat-helpers'
import {toUnixPath} from './lib/test-helpers'
const app = browserdriver.start({
path: electron,
args: ['../app'],
env: {
NODE_ENV: 'test',
beaker_no_welcome_tab: 1,
beaker_user_data_path: fs.mkdtempSync(os.tmpdir() + path.sep + 'beaker-test-'),
beaker_dat_quota_default_bytes_allowed: '90kb'
}
})
var mainTab
var testStaticDat, testStaticDatURL
var testRunnerDat, testRunnerDatURL
var createdDatURL // url of the dat which is created by testRunnerDat, which gives it write access
var createdDatKey
var beakerPng = fs.readFileSync(__dirname + '/scaffold/test-static-dat/beaker.png')
var tmpDirPath1 = tempy.directory()
test.before(async t => {
console.log('starting dat-archive-web-api-test')
await app.isReady
mainTab = app.getTab(0)
// share the test static dat
testStaticDat = await shareDat(__dirname + '/scaffold/test-static-dat')
testStaticDatURL = 'dat://' + testStaticDat.archive.key.toString('hex') + '/'
// share the test runner dat
testRunnerDat = await shareDat(__dirname + '/scaffold/test-runner-dat')
testRunnerDatURL = 'dat://' + testRunnerDat.archive.key.toString('hex') + '/'
// save the test-runner dat to the library
var res = await app.executeJavascript(`
beaker.archives.add("${testRunnerDatURL}")
`)
t.deepEqual(res.isSaved, true)
// open the test-runner dat
await app.getTab(0).navigateTo(testRunnerDatURL)
})
test.after.always('cleanup', async t => {
await app.stop()
})
// some custom wrappers around async calls
// (the remove execution can be a little janky, these wrappers solve that)
function stat (url, path, opts) {
return mainTab.executeJavascript(`
var archive = new DatArchive("${url}")
archive.stat("${path}", ${JSON.stringify(opts)}).then(v => {
v.isFile = v.isFile()
v.isDirectory = v.isDirectory()
return v
})
`)
}
function readdir (url, path, opts) {
return mainTab.executeJavascript(`
var archive = new DatArchive("${url}")
archive.readdir("${path}", ${JSON.stringify(opts)})
`)
}
function readFile (url, path, opts) {
return mainTab.executeJavascript(`
var archive = new DatArchive("${url}")
archive.readFile("${path}", ${JSON.stringify(opts)}).then(v => {
if (v instanceof ArrayBuffer) {
v = new Uint8Array(v)
}
return v
})
`)
}
async function writeFile (url, path, content, opts, where) {
where = where || mainTab
if (opts === 'binary' || opts.encoding === 'binary') {
content = content.toString('base64')
return where.executeJavascript(`
var content = Uint8Array.from(atob("${content}"), c => c.charCodeAt(0))
var archive = new DatArchive("${url}")
archive.writeFile("${path}", content, ${JSON.stringify(opts)})
`)
} else {
return where.executeJavascript(`
var archive = new DatArchive("${url}")
archive.writeFile("${path}", "${content}", ${JSON.stringify(opts)})
`)
}
}
// tests
//
test('archive.readdir', async t => {
// root dir
let listing1 = await readdir(testStaticDatURL, '/')
t.deepEqual(listing1.sort(), ['beaker.png', 'hello.txt', 'subdir'])
// subdir
let listing2 = await readdir(testStaticDatURL, '/subdir')
t.deepEqual(listing2.sort(), ['hello.txt', 'space in the name.txt'])
// root dir stat=true
let listing3 = await readdir(testStaticDatURL, '/', {stat: true})
listing3 = listing3.sort()
t.is(listing3[0].name, 'beaker.png')
t.truthy(listing3[0].stat)
t.is(listing3[1].name, 'hello.txt')
t.truthy(listing3[1].stat)
t.is(listing3[2].name, 'subdir')
t.truthy(listing3[2].stat)
// subdir stat=true
let listing4 = await readdir(testStaticDatURL, '/subdir', {stat: true})
listing4 = listing4.sort()
t.is(listing4[0].name, 'hello.txt')
t.truthy(listing4[0].stat)
t.is(listing4[1].name, 'space in the name.txt')
t.truthy(listing4[1].stat)
})
test('archive.readFile', async t => {
// read utf8
var helloTxt = await readFile(testStaticDatURL, 'hello.txt', {})
t.deepEqual(helloTxt, 'hello world')
// read utf8 2
var helloTxt2 = await readFile(testStaticDatURL, '/subdir/hello.txt', 'utf8')
t.deepEqual(helloTxt2, 'hello world')
// read utf8 when spaces are in the name
var helloTxt2 = await readFile(testStaticDatURL, '/subdir/space in the name.txt', 'utf8')
t.deepEqual(helloTxt2, 'hello world')
// read hex
var beakerPngHex = await readFile(testStaticDatURL, 'beaker.png', 'hex')
t.deepEqual(beakerPngHex, beakerPng.toString('hex'))
// read base64
var beakerPngBase64 = await readFile(testStaticDatURL, 'beaker.png', 'base64')
t.deepEqual(beakerPngBase64, beakerPng.toString('base64'))
// read binary
var beakerPngBinary = await readFile(testStaticDatURL, 'beaker.png', 'binary')
t.truthy(beakerPng.equals(Buffer.from(beakerPngBinary)))
// timeout: read an archive that does not exist
var fakeUrl = 'dat://' + ('f'.repeat(64)) + '/'
try {
await readFile(fakeUrl, 'hello.txt', { timeout: 500 })
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'TimeoutError')
}
})
test('archive.stat', async t => {
// stat root file
var entry = await stat(testStaticDatURL, 'hello.txt', {})
t.deepEqual(entry.isFile, true, 'root file')
t.deepEqual(entry.downloaded, entry.blocks)
// stat subdir file
var entry = await stat(testStaticDatURL, 'subdir/hello.txt', {})
t.deepEqual(entry.isFile, true, 'subdir file')
// stat subdir
var entry = await stat(testStaticDatURL, 'subdir', {})
t.deepEqual(entry.isDirectory, true, 'subdir')
// stat non-existent file
try {
var entry = await stat(testStaticDatURL, 'notfound', {})
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'NotFoundError')
}
// stat alt-formed path
var entry = await stat(testStaticDatURL, '/hello.txt', {})
t.deepEqual(entry.isFile, true, 'alt-formed path')
// stat path w/spaces in it
var entry = await stat(testStaticDatURL, '/subdir/space in the name.txt', {})
t.deepEqual(entry.isFile, true, 'path w/spaces in it')
// stat path w/spaces in it
var entry = await stat(testStaticDatURL, '/subdir/space%20in%20the%20name.txt', {})
t.deepEqual(entry.isFile, true, 'path w/spaces in it')
// timeout: stat an archive that does not exist
try {
var fakeUrl = 'dat://' + ('f'.repeat(64)) + '/'
var entry = await stat(fakeUrl, 'hello.txt', { timeout: 500 })
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'TimeoutError')
}
})
test('dat:// HEAD and GET', async t => {
// GET
var res = await mainTab.executeJavascript(`
window.fetch("${testStaticDatURL + 'hello.txt'}").then(res => {
return res.text().then(data => ({data, headers: Array.from(res.headers.entries())}))
})
`)
t.deepEqual(res.data, 'hello world')
t.deepEqual((res.headers.filter(h => h[0] === 'content-type'))[0][1], 'text/plain; charset=utf8')
// HEAD
var res = await mainTab.executeJavascript(`
window.fetch("${testStaticDatURL + 'hello.txt'}", {method: 'HEAD'}).then(res => {
return res.text().then(data => ({data, headers: Array.from(res.headers.entries())}))
})
`)
t.deepEqual(res.data, '')
t.deepEqual((res.headers.filter(h => h[0] === 'content-type'))[0][1], 'text/plain; charset=utf8')
})
test('DatArchive.load', async t => {
// good url
var res = await mainTab.executeJavascript(`
DatArchive.load("${testStaticDatURL}").then(a => a.url)
`)
t.deepEqual(res, testStaticDatURL.slice(0, -1))
// bad url
try {
var res = await mainTab.executeJavascript(`
DatArchive.load('dat://badurl')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'InvalidDomainName')
}
})
test('DatArchive.create prompt=false', async t => {
// start the permission prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.create({ title: 'The Title', description: 'The Description', links: {foo: 'https://bar.com'}, prompt: false }).then(
res => window.res = res,
err => window.res = err
)
`)
// accept the permission prompt
await app.waitForElement('.prompt-accept')
await app.click('.prompt-accept')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
var datUrl = res.url
t.truthy(datUrl.startsWith('dat://'))
var datKey = datUrl.slice('dat://'.length)
// check the dat.json
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${datUrl}")
archive.readFile('dat.json')
`)
var manifest
try {
var manifest = JSON.parse(res)
} catch (e) {
console.log('unexpected error parsing manifest', res)
}
t.deepEqual(manifest.title, 'The Title')
t.deepEqual(manifest.description, 'The Description')
t.deepEqual(manifest.links, {foo: [{href: 'https://bar.com'}]})
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${datKey}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.isSaved, true)
})
test('DatArchive.create prompt=true rejection', async t => {
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.create({ title: 'The Title', description: 'The Description', prompt: true }).then(
res => window.res = res,
err => window.res = err
)
`)
// reject the prompt
await app.waitForElement('.cancel')
await app.click('.cancel')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
t.deepEqual(res.name, 'UserDeniedError')
})
test('DatArchive.create prompt=true', async t => {
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.create({ title: 'The Title', description: 'The Description', prompt: true }).then(
res => window.res = res,
err => window.res = err
)
`)
// accept the prompt
await app.waitForElement('button[type="submit"]')
await app.click('button[type="submit"]')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
createdDatURL = res.url
t.truthy(createdDatURL.startsWith('dat://'))
createdDatKey = createdDatURL.slice('dat://'.length)
// check the dat.json
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.readFile('dat.json')
`)
var manifest
try {
var manifest = JSON.parse(res)
} catch (e) {
console.log('unexpected error parsing manifest', res)
}
t.deepEqual(manifest.title, 'The Title')
t.deepEqual(manifest.description, 'The Description')
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${createdDatKey}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.isSaved, true)
})
test('DatArchive.fork prompt=false', async t => {
// create a dat
var res = await app.executeJavascript(`
DatArchive.create({ title: 'The Title', description: 'The Description', prompt: false })
`)
var datUrl = res.url
t.truthy(datUrl.startsWith('dat://'))
await app.executeJavascript(`
var archive = new DatArchive("${datUrl}")
archive.writeFile('foo.txt', 'bar', 'utf8')
`)
// start the permission prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.fork("${datUrl}", { description: 'The Description 2', prompt: false }).then(
res => window.res = res,
err => window.res = err
)
`)
// accept the permission prompt
await app.waitForElement('.prompt-accept')
await app.click('.prompt-accept')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
var forkedDatURL = res.url
t.truthy(forkedDatURL.startsWith('dat://'))
// check the content
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${forkedDatURL}")
archive.readFile('foo.txt')
`)
t.deepEqual(res, 'bar')
// check the dat.json
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${forkedDatURL}")
archive.readFile('dat.json')
`)
var manifest
try {
var manifest = JSON.parse(res)
} catch (e) {
console.log('unexpected error parsing manifest', res)
}
t.deepEqual(manifest.title, 'The Title')
t.deepEqual(manifest.description, 'The Description 2')
})
test('DatArchive.fork prompt=true', async t => {
// create a dat
var res = await app.executeJavascript(`
DatArchive.create({ title: 'The Title', description: 'The Description', prompt: false })
`)
var datUrl = res.url
t.truthy(datUrl.startsWith('dat://'))
await app.executeJavascript(`
var archive = new DatArchive("${datUrl}")
archive.writeFile('foo.txt', 'bar', 'utf8')
`)
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.fork("${datUrl}", { description: 'The Description 2', prompt: true }).then(
res => window.res = res,
err => window.res = err
)
`)
// accept the prompt
await app.waitForElement('button[type="submit"]')
await app.click('button[type="submit"]')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
var forkedDatURL = res.url
t.truthy(forkedDatURL.startsWith('dat://'))
// check the content
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${forkedDatURL}")
archive.readFile('foo.txt')
`)
t.deepEqual(res, 'bar')
// check the dat.json
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${forkedDatURL}")
archive.readFile('dat.json')
`)
var manifest
try {
var manifest = JSON.parse(res)
} catch (e) {
console.log('unexpected error parsing manifest', res)
}
t.deepEqual(manifest.title, 'The Title')
t.deepEqual(manifest.description, 'The Description 2')
})
test('DatArchive.unlink', async t => {
// create a dat
var res = await app.executeJavascript(`
DatArchive.create({ title: 'The Title', description: 'The Description', prompt: false })
`)
var datUrl = res.url
t.truthy(datUrl.startsWith('dat://'))
var datKey = datUrl.slice('dat://'.length)
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = 'unset'
DatArchive.unlink("${datUrl}").then(
res => window.res = res,
err => window.res = err
)
`)
// accept the permission prompt
await app.waitForElement('.prompt-accept')
await app.click('.prompt-accept')
// fetch & test the res
await mainTab.waitFor(`(window.res !== 'unset')`)
var res = await mainTab.executeJavascript(`window.res`)
t.falsy(res)
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${datKey}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.isSaved, false)
// dont allow writes
try {
var res = await writeFile(datUrl, '/foo.txt', 'bar', 'utf8')
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ArchiveNotWritableError')
}
})
test('DatArchive.selectArchive rejection', async t => {
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.selectArchive({ message: 'Help message', buttonLabel: 'button' }).then(
res => window.res = res,
err => window.res = err
)
`)
// reject the prompt
await app.waitForElement('.cancel')
await app.click('.cancel')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
t.deepEqual(res.name, 'UserDeniedError')
})
test('DatArchive.selectArchive: create', async t => {
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.selectArchive({ message: 'Custom title', buttonLabel: 'button' }).then(
res => window.res = res.url,
err => window.res = err
)
`)
// open the create archive view
await app.waitForElement('.btn[data-content="newArchive"]')
await app.click('.btn[data-content="newArchive"]')
// input a title for a now archive
await app.waitForElement('input[name="title"]')
await app.setValue('input[name="title"]', 'The Title')
// accept the prompt
await app.click('button[type="submit"]')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
var newArchiveURL = res
t.truthy(res.startsWith('dat://'))
// check the dat.json
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${newArchiveURL}")
archive.readFile('dat.json')
`)
var manifest
try {
var manifest = JSON.parse(res)
} catch (e) {
console.log('unexpected error parsing manifest', res)
}
t.deepEqual(manifest.title, 'The Title')
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${newArchiveURL}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.isSaved, true)
})
test('DatArchive.selectArchive: select', async t => {
// start the prompt
mainTab.executeJavascript(`
// put the result on the window, for checking later
window.res = null
DatArchive.selectArchive().then(
res => window.res = res.url,
err => window.res = err
)
`)
// click one of the archives
var testRunnerDatKey = testRunnerDat.archive.key.toString('hex')
await app.waitForElement(`li[data-key="${testRunnerDatKey}"]`)
await app.click(`li[data-key="${testRunnerDatKey}"]`)
// accept the prompt
await app.click('button[type="submit"]')
// fetch & test the res
await mainTab.waitFor(`window.res`)
var res = await mainTab.executeJavascript(`window.res`)
t.truthy(res.startsWith('dat://'))
t.is(res, testRunnerDatURL.slice(0, -1))
})
test('archive.configure', async t => {
// write the manifest
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.configure({
title: 'The Changed Title',
description: 'The Changed Description',
links: {
foo: ['https://bar.com', {href: 'https://baz.com'}],
home: 'dat://beakerbrowser.com'
}
})
`)
t.falsy(res)
// read it back
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.getInfo()
`)
t.deepEqual(res.title, 'The Changed Title')
t.deepEqual(res.description, 'The Changed Description')
t.deepEqual(res.links, {
foo: [{href: 'https://bar.com'}, {href: 'https://baz.com'}],
home: [{href: 'dat://beakerbrowser.com'}]
})
})
test('offline archives', async t => {
// create a dat (prompt=false)
var res = await app.executeJavascript(`
DatArchive.create({ networked: false, prompt: false })
`)
var datUrl = res.url
t.truthy(datUrl.startsWith('dat://'))
var datKey = datUrl.slice('dat://'.length)
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${datKey}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.networked, false)
// change the settings
var res = await app.executeJavascript(`
var archive = new DatArchive("${datUrl}")
archive.configure({networked: true})
`)
t.falsy(res)
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${datKey}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.networked, true)
// fork a dat (prompt=false)
var res = await app.executeJavascript(`
DatArchive.fork("${datUrl}", { networked: false, prompt: false })
`)
var datUrl3 = res.url
t.truthy(datUrl3.startsWith('dat://'))
var datKey3 = datUrl3.slice('dat://'.length)
// check the settings
var details = await app.executeJavascript(`
var archive = new DatArchive("${datKey3}")
archive.getInfo()
`)
t.deepEqual(details.userSettings.networked, false)
})
test('archive.writeFile', async t => {
async function dotest (filename, content, encoding) {
// write the file
var res = await writeFile(createdDatURL, filename, content, encoding)
t.falsy(res)
// read it back
var res = await readFile(createdDatURL, filename, encoding)
if (encoding === 'binary') {
t.truthy(content.equals(Buffer.from(res)))
} else {
t.deepEqual(res, content)
}
}
var beakerPng = fs.readFileSync(__dirname + '/scaffold/test-static-dat/beaker.png')
await dotest('hello.txt', 'hello world', 'utf8')
await dotest('beaker1.png', beakerPng, 'binary')
await dotest('beaker2.png', beakerPng.toString('base64'), 'base64')
await dotest('beaker3.png', beakerPng.toString('hex'), 'hex')
})
test('archive.writeFile does not write to nonexistent directories', async t => {
try {
// write to a subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('subdir/hello.txt', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ParentFolderDoesntExistError')
}
})
test('archive.writeFile gives an error for malformed names', async t => {
try {
// write to the root dir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('/', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'InvalidPathError')
}
try {
// write to a subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('/subdir/hello.txt/', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'InvalidPathError')
}
try {
// write with a bad char
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('hello#.txt', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'InvalidPathError')
}
})
test('archive.writeFile protects the manifest', async t => {
try {
// write to the manifest
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('dat.json', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ProtectedFileNotWritableError')
}
})
test('archive.mkdir', async t => {
// create the directory
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.mkdir('subdir')
`)
t.falsy(res)
// read it back
var res = await stat(createdDatURL, 'subdir', {})
t.deepEqual(res.isDirectory, true)
})
test('archive.writeFile writes to subdirectories', async t => {
// write to a subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('subdir/hello.txt', 'hello world', 'utf8')
`)
t.falsy(res)
// read it back
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.readFile('subdir/hello.txt', 'utf8')
`)
t.deepEqual(res, 'hello world')
})
test('archive.writeFile doesnt overwrite folders', async t => {
try {
// write to the subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('/subdir', 'hello world', 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'EntryAlreadyExistsError')
}
})
test('archive.mkdir doesnt overwrite files or folders', async t => {
try {
// write to the subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.mkdir('/')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'EntryAlreadyExistsError')
}
try {
// write to the subdir
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.mkdir('/subdir')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'EntryAlreadyExistsError')
}
try {
// write to the file
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.mkdir('/hello.txt')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'EntryAlreadyExistsError')
}
})
test('archive.mkdir gives an error for malformed names', async t => {
try {
// write with a bad char
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.mkdir('hello#world')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'InvalidPathError')
}
})
test('archive.writeFile doesnt allow writes that exceed the quota', async t => {
try {
// write a too-big file
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.writeFile('/denythis.txt', 'x'.repeat(1024 * 100), 'utf8')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'QuotaExceededError')
}
})
test('versioned reads and writes', async t => {
// create a fresh dat
var res = await app.executeJavascript(`
DatArchive.create({title: 'Another Test Dat', prompt: false})
`)
t.falsy(res.name, 'create didnt fail')
var newTestDatURL = res.url
// do some writes
await writeFile(newTestDatURL, '/one.txt', 'a', 'utf8', app)
await writeFile(newTestDatURL, '/two.txt', 'b', 'utf8', app)
await sleep(1e3) // have to make sure 1s passes for the change to be detected
await writeFile(newTestDatURL, '/one.txt', 'c', 'utf8', app)
// check history
var history = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
archive.history()
`)
if (history.length !== 5) {
console.log('Weird history', history)
}
t.deepEqual(history.length, 5)
var history2 = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
archive.history({reverse: true})
`)
t.deepEqual(history2[0].version, history[4].version)
var history2 = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
archive.history({start: 0, end: 5, reverse: true})
`)
t.deepEqual(history2[0].version, history[4].version)
var history2 = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
archive.history({start: 2, end: 4})
`)
t.deepEqual(history2[0].version, history[1].version)
t.deepEqual(history2[1].version, history[2].version)
var history2 = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
archive.history({start: 2, end: 4, reverse: true})
`)
t.deepEqual(history2[0].version, history[2].version)
t.deepEqual(history2[1].version, history[1].version)
// read back versions
t.deepEqual((await readdir(newTestDatURL + '+1', '/')).length, 1)
t.deepEqual((await readdir(newTestDatURL + '+2', '/')).length, 2)
t.deepEqual((await readdir(newTestDatURL + '+3', '/')).length, 3)
t.deepEqual((await readFile(newTestDatURL + '+3', '/one.txt')), 'a')
t.deepEqual((await readFile(newTestDatURL + '+5', '/one.txt')), 'c')
var statRev2 = await stat(newTestDatURL + '+3', '/one.txt')
var statRev4 = await stat(newTestDatURL + '+5', '/one.txt')
t.truthy(statRev2.offset < statRev4.offset)
// try again with checkout()
var reads = await mainTab.executeJavascript(`
var archive = new DatArchive("${newTestDatURL}")
Promise.all([
archive.checkout(1).readdir('/'),
archive.checkout(2).readdir('/'),
archive.checkout(3).readdir('/'),
archive.checkout(3).readFile('/one.txt'),
archive.checkout(5).readFile('/one.txt'),
archive.checkout(3).stat('/one.txt'),
archive.checkout(5).stat('/one.txt'),
])
`)
t.deepEqual(reads[0].length, 1)
t.deepEqual(reads[1].length, 2)
t.deepEqual(reads[2].length, 3)
t.deepEqual(reads[3], 'a')
t.deepEqual(reads[4], 'c')
t.truthy(reads[5].offset < reads[6].offset)
// dont allow writes to old versions
// writeFile
try {
var res = await writeFile(newTestDatURL + '+1', '/three.txt', 'foo', 'utf8', app)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ArchiveNotWritableError')
}
// mkdir
try {
var res = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL + '+1'}")
archive.mkdir('/foo')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ArchiveNotWritableError')
}
// unlink
try {
var res = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL + '+1'}")
archive.unlink('/one.txt')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ArchiveNotWritableError')
}
// rmdir
try {
var res = await app.executeJavascript(`
var archive = new DatArchive("${newTestDatURL + '+1'}")
archive.rmdir('/there-is-no-dir-but-it-doesnt-matter')
`)
t.fail('Failed to throw')
} catch (e) {
t.deepEqual(e.name, 'ArchiveNotWritableError')
}
})
test('archive.copy', async t => {
// file 1
var res = await mainTab.executeJavascript(`
var archive = new DatArchive("${createdDatURL}")
archive.copy('/hello.txt', '/hello2.txt')
`)
t.falsy(res)
await t.deepEqual(
(await readFile(createdDatURL, '/hello.txt')),
(await readFile(createdDatURL, '/hello2.txt'))
)
// file 2