1 | import _fetch, { Response, FetchError } from "node-fetch";
|
2 | import { resolve } from 'path';
|
3 | import { promises as fsp } from 'fs';
|
4 | import { readDir } from "../utils/fs.js";
|
5 | const cwd = import.meta.url.slice('file:/'.length).split('microsite')[0].slice(0, -1);
|
6 | async function fetch(url, init) {
|
7 | if (typeof url === 'string' && !url.startsWith('http')) {
|
8 | url = resolve(cwd, `../.${url}`);
|
9 | try {
|
10 | const stat = await fsp.stat(url);
|
11 | if (stat.isFile()) {
|
12 | const content = await fsp.readFile(url, 'utf-8');
|
13 | return new Response(content);
|
14 | }
|
15 | else if (stat.isDirectory()) {
|
16 | let contents = await readDir(url);
|
17 | contents = contents.map(path => path.slice(url.length));
|
18 | const res = new Response(JSON.stringify(contents));
|
19 | res.headers.set('Content-Type', 'application/json');
|
20 | return res;
|
21 | }
|
22 | }
|
23 | catch (e) {
|
24 | const err = new FetchError(`Unable to fetch ${url}. ${e.message}`);
|
25 | err.code = 'ERR_NOT_FOUND';
|
26 | err.errno = '404';
|
27 | throw err;
|
28 | }
|
29 | }
|
30 | return _fetch(url, init);
|
31 | }
|
32 | export default fetch;
|