1 | const debug = require('debug')('upward-js:IOAdapter');
|
2 | const containsPath = require('contains-path');
|
3 | const { resolve, dirname } = require('path');
|
4 | const { readFile: fsReadFile } = require('fs');
|
5 | const { promisify } = require('util');
|
6 |
|
7 | const readFile = promisify(fsReadFile);
|
8 | class IOAdapter {
|
9 | static default(upwardPath) {
|
10 | debug(`creating default IO from ${upwardPath}`);
|
11 | const baseDir = dirname(upwardPath);
|
12 | debug(`baseDir ${baseDir}`);
|
13 | return new IOAdapter({
|
14 | networkFetch: require('node-fetch'),
|
15 | readFile: (filePath, enc) => {
|
16 |
|
17 | const resolvedPath = resolve(baseDir, filePath);
|
18 | if (!containsPath(resolvedPath, baseDir)) {
|
19 | throw new Error(
|
20 | `Cannot read ${resolvedPath} because it is outside ${baseDir}`
|
21 | );
|
22 | }
|
23 |
|
24 | |
25 |
|
26 |
|
27 |
|
28 |
|
29 | if (enc === 'binary') enc = null;
|
30 |
|
31 | return readFile(resolvedPath, enc);
|
32 | }
|
33 | });
|
34 | }
|
35 | constructor(implementations) {
|
36 | const missingImpls = ['readFile', 'networkFetch'].reduce(
|
37 | (missing, method) =>
|
38 | method in implementations
|
39 | ? missing
|
40 | : missing +
|
41 | `Must provide an implementation of '${method}\n`,
|
42 | ''
|
43 | );
|
44 | if (missingImpls) {
|
45 | throw new Error(`Error creating IOAdapter:\n${missingImpls}`);
|
46 | }
|
47 | Object.assign(this, implementations);
|
48 | }
|
49 | |
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | async readFile(filePath, encoding) {}
|
57 |
|
58 | |
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | async networkFetch(url, options) {}
|
65 | }
|
66 |
|
67 | module.exports = IOAdapter;
|