Skip to content

Commit

Permalink
rearrange lib
Browse files Browse the repository at this point in the history
  • Loading branch information
LiviaMedeiros committed Aug 26, 2023
1 parent 9a8321a commit 67f492d
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 78 deletions.
6 changes: 0 additions & 6 deletions lib/generic.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import { sep } from 'node:path';
import { cwd } from 'node:process';
import { pathToFileURL } from 'node:url';

const requestConstructor = Reflect.construct.bind(Reflect, Request);
const responseConstructor = Reflect.construct.bind(Reflect, Response);
const getCwdURL = () => pathToFileURL(cwd() + sep).href;

export {
getCwdURL,
requestConstructor,
responseConstructor,
};
26 changes: 24 additions & 2 deletions lib/http.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { readlink } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';

const _params = Object.fromEntries(new URL(import.meta.url).searchParams.entries());
const PREFIX = `X-${_params.prefix ?? 'Poteto'}-`;

const errorAsUndefined = () => {};

const HEADERS_ALLOW = Object.freeze(new Headers({
Expand Down Expand Up @@ -73,6 +76,26 @@ const genericResponse = (status = 200, {
...opts,
});

const adjustHeaders = ({ headers }) =>
new Headers([
...getGenericHeaders(),
...Object.entries(headers).map(([$, _]) => [
`${PREFIX}${$}`,
_ instanceof Date ? _.toISOString() : `${_}`,
]),

// TODO: Etag?
// TODO: Content-Type?
['Content-Length', headers.size],
['Last-Modified', headers.mtime?.toUTCString()],
].filter(([, $]) => $ !== undefined));

const statsAsOptions = async (statsOrError, { status } = {}) =>
Promise.resolve(statsOrError)
.catch($ => $)
.then(headers => ({ ...errAsStatus(headers, status), headers }))
.then($ => Object.assign($, { headers: adjustHeaders($) }));

const blockingHooks = [
// if request.redirect is not follow,
async (url, { redirect }) => {
Expand Down Expand Up @@ -100,9 +123,8 @@ const getRanges = headers =>
headers.get('Range')?.split(';')[0].split('=')[1]?.split(',').map($ => $.trim()) ?? [];

export {
errAsStatus,
genericResponse,
getGenericHeaders,
getRanges,
preHooks,
statsAsOptions,
};
75 changes: 5 additions & 70 deletions lib/poteto.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ import fs from 'node:fs/promises';
import { Writable } from 'node:stream';

import {
errAsStatus,
genericResponse,
getGenericHeaders,
getRanges,
preHooks,
statsAsOptions,
} from './http.mjs';
import {
STAT_OPTS,
READDIR_OPTS,
} from './constants.mjs';
import {
getCwdURL,
responseConstructor,
} from './generic.mjs';
import {
Expand All @@ -23,74 +21,11 @@ import {
readRange,
writeRange,
} from './fs.mjs';
import {
PotetoRequest,
ProxyRequest,
} from './request.mjs';

const _params = Object.fromEntries(new URL(import.meta.url).searchParams.entries());
const cwdURL = _params.persistCwd
? getCwdURL()
: { [Symbol.toPrimitive]: getCwdURL };
const PREFIX = `X-${_params.prefix ?? 'Poteto'}-`;

const adjustHeaders = ({ headers }) =>
new Headers([
...getGenericHeaders(),
...Object.entries(headers).map(([$, _]) => [
`${PREFIX}${$}`,
_ instanceof Date ? _.toISOString() : `${_}`,
]),

// TODO: Etag?
// TODO: Content-Type?
['Content-Length', headers.size],
['Last-Modified', headers.mtime?.toUTCString()],
].filter(([, $]) => $ !== undefined));

const statsAsOptions = async (statsOrError, { status } = {}) =>
Promise.resolve(statsOrError)
.catch($ => $)
.then(headers => ({ ...errAsStatus(headers, status), headers }))
.then($ => Object.assign($, { headers: adjustHeaders($) }));

const requestInitOptions = new Set([
'method',
'headers',
'body',
'referrer',
'referrerPolicy',
'mode',
'credentials',
'cache',
'redirect',
'integrity',
'keepalive',
'signal',
'duplex',
'priority',
'window',
]);

const potetoRequestInit = ([ resource, options ], requestInit = {}, url = null) => {
if (resource instanceof Request) {
requestInitOptions.forEach($ => requestInit[$] = resource[$]);
resource = resource.url;
}
return [
(url = new URL(resource, cwdURL)).protocol === 'file:'
? url
: resource,
{ ...requestInit, ...options },
];
};

class PotetoRequest extends Request {
constructor(...$) {
super(...potetoRequestInit($));
}
}

const ProxyRequest = new Proxy(Request, {
construct: (target, argumentsList) =>
Reflect.construct(target, potetoRequestInit(argumentsList))
});

const DELETE = async url =>
fs.rm(url).then(() => genericResponse(204));
Expand Down
57 changes: 57 additions & 0 deletions lib/request.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { sep } from 'node:path';
import { cwd } from 'node:process';
import { pathToFileURL } from 'node:url';

const getCwdURL = () => pathToFileURL(cwd() + sep).href;

const _params = Object.fromEntries(new URL(import.meta.url).searchParams.entries());
const cwdURL = _params.persistCwd
? getCwdURL()
: { [Symbol.toPrimitive]: getCwdURL };

const requestInitOptions = new Set([
'method',
'headers',
'body',
'referrer',
'referrerPolicy',
'mode',
'credentials',
'cache',
'redirect',
'integrity',
'keepalive',
'signal',
'duplex',
'priority',
'window',
]);

const potetoRequestInit = ([ resource, options ], requestInit = {}, url = null) => {
if (resource instanceof Request) {
requestInitOptions.forEach($ => requestInit[$] = resource[$]);
resource = resource.url;
}
return [
(url = new URL(resource, cwdURL)).protocol === 'file:'
? url
: resource,
{ ...requestInit, ...options },
];
};

class PotetoRequest extends Request {
constructor(...$) {
super(...potetoRequestInit($));
}
}

const ProxyRequest = new Proxy(Request, {
construct: (target, argumentsList) =>
Reflect.construct(target, potetoRequestInit(argumentsList))
});

export {
PotetoRequest,
ProxyRequest,
};

0 comments on commit 67f492d

Please sign in to comment.