Skip to content

Commit

Permalink
chore: supress linting
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderniebuhr committed Aug 29, 2024
1 parent 4d90e8e commit 4b17094
Show file tree
Hide file tree
Showing 48 changed files with 278 additions and 212 deletions.
2 changes: 1 addition & 1 deletion packages/node/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@
{ darkMode: true },
{
expires: '1 month',
},
}
);
const prefs = Astro.cookies.get<Prefs>('prefs').json();
Expand Down
9 changes: 2 additions & 7 deletions packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@
"url": "https://github.com/withastro/astro.git",
"directory": "packages/integrations/node"
},
"keywords": [
"withastro",
"astro-adapter"
],
"keywords": ["withastro", "astro-adapter"],
"bugs": "https://github.com/withastro/astro/issues",
"homepage": "https://docs.astro.build/en/guides/integrations-guide/node/",
"exports": {
Expand All @@ -23,9 +20,7 @@
"./preview.js": "./dist/preview.js",
"./package.json": "./package.json"
},
"files": [
"dist"
],
"files": ["dist"],
"scripts": {
"build": "tsc",
"test": "astro-scripts test \"test/**/*.test.js\""
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default function createIntegration(userOptions: UserOptions): AstroIntegr

if (config.output === 'static') {
logger.warn(
`\`output: "server"\` or \`output: "hybrid"\` is required to use this adapter.`,
`\`output: "server"\` or \`output: "hybrid"\` is required to use this adapter.`
);
}
},
Expand Down
17 changes: 11 additions & 6 deletions packages/node/src/log-listening-on.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ import type { Options } from './types.js';
export async function logListeningOn(
logger: AstroIntegrationLogger,
server: http.Server | https.Server,
options: Pick<Options, 'host'>,
options: Pick<Options, 'host'>
) {
await new Promise<void>((resolve) => server.once('listening', resolve));
const protocol = server instanceof https.Server ? 'https' : 'http';
// Allow to provide host value at runtime
const host = getResolvedHostForHttpServer(
process.env.HOST !== undefined && process.env.HOST !== '' ? process.env.HOST : options.host,
process.env.HOST !== undefined && process.env.HOST !== '' ? process.env.HOST : options.host
);
const { port } = server.address() as AddressInfo;
const address = getNetworkAddress(protocol, host, port);

if (host === undefined) {
logger.info(
`Server listening on \n local: ${address.local[0]} \t\n network: ${address.network[0]}\n`,
`Server listening on \n local: ${address.local[0]} \t\n network: ${address.network[0]}\n`
);
} else {
logger.info(`Server listening on ${address.local[0]}`);
Expand All @@ -32,9 +32,11 @@ function getResolvedHostForHttpServer(host: string | boolean) {
if (host === false) {
// Use a secure default
return 'localhost';
// biome-ignore lint/style/noUselessElse: <explanation>
} else if (host === true) {
// If passed --host in the CLI without arguments
return undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
// biome-ignore lint/style/noUselessElse: <explanation>
} else {
return host;
}
Expand All @@ -49,29 +51,32 @@ const wildcardHosts = new Set(['0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0

// this code from vite https://github.com/vitejs/vite/blob/d09bbd093a4b893e78f0bbff5b17c7cf7821f403/packages/vite/src/node/utils.ts#L892-L914
export function getNetworkAddress(
// biome-ignore lint/style/useDefaultParameterLast: <explanation>
protocol: 'http' | 'https' = 'http',
hostname: string | undefined,
port: number,
base?: string,
base?: string
) {
const NetworkAddress: NetworkAddressOpt = {
local: [],
network: [],
};
// biome-ignore lint/complexity/noForEach: <explanation>
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
// biome-ignore lint/complexity/useOptionalChain: <explanation>
detail &&
detail.address &&
(detail.family === 'IPv4' ||
// @ts-expect-error Node 18.0 - 18.3 returns number
detail.family === 4),
detail.family === 4)
)
.forEach((detail) => {
let host = detail.address.replace(
'127.0.0.1',
hostname === undefined || wildcardHosts.has(hostname) ? 'localhost' : hostname,
hostname === undefined || wildcardHosts.has(hostname) ? 'localhost' : hostname
);
// ipv6 host
if (host.includes(':')) {
Expand Down
4 changes: 3 additions & 1 deletion packages/node/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ export default function createMiddleware(app: NodeApp): RequestHandler {
const logger = app.getAdapterLogger();
// using spread args because express trips up if the function's
// stringified body includes req, res, next, locals directly
return async function (...args) {
return async (...args) => {
// assume normal invocation at first
const [req, res, next, locals] = args;
// short circuit if it is an error invocation
if (req instanceof Error) {
const error = req;
if (next) {
return next(error);
// biome-ignore lint/style/noUselessElse: <explanation>
} else {
throw error;
}
Expand All @@ -33,6 +34,7 @@ export default function createMiddleware(app: NodeApp): RequestHandler {
logger.error(`Could not render ${req.url}`);
console.error(err);
if (!res.headersSent) {
// biome-ignore lint/style/noUnusedTemplateLiteral: <explanation>
res.writeHead(500, `Server error`);
res.end();
}
Expand Down
10 changes: 6 additions & 4 deletions packages/node/src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,29 @@ import { createServer } from './standalone.js';
type ServerModule = ReturnType<typeof createExports>;
type MaybeServerModule = Partial<ServerModule>;

const createPreviewServer: CreatePreviewServer = async function (preview) {
const createPreviewServer: CreatePreviewServer = async (preview) => {
let ssrHandler: ServerModule['handler'];
let options: ServerModule['options'];
try {
process.env.ASTRO_NODE_AUTOSTART = 'disabled';
const ssrModule: MaybeServerModule = await import(preview.serverEntrypoint.toString());
if (typeof ssrModule.handler === 'function') {
ssrHandler = ssrModule.handler;
// biome-ignore lint/style/noNonNullAssertion: <explanation>
options = ssrModule.options!;
} else {
throw new AstroError(
`The server entrypoint doesn't have a handler. Are you sure this is the right file?`,
`The server entrypoint doesn't have a handler. Are you sure this is the right file?`
);
}
} catch (err) {
if ((err as any).code === 'ERR_MODULE_NOT_FOUND') {
throw new AstroError(
`The server entrypoint ${fileURLToPath(
preview.serverEntrypoint,
)} does not exist. Have you ran a build yet?`,
preview.serverEntrypoint
)} does not exist. Have you ran a build yet?`
);
// biome-ignore lint/style/noUselessElse: <explanation>
} else {
throw err;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/serve-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function createAppHandler(app: NodeApp): RequestHandler {
addCookieHeader: true,
locals,
routeData,
}),
})
);
await NodeApp.writeResponse(response, res);
} else if (next) {
Expand Down
12 changes: 11 additions & 1 deletion packages/node/src/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,41 @@ export function createStaticHandler(app: NodeApp, options: Options) {
let isDirectory = false;
try {
isDirectory = fs.lstatSync(filePath).isDirectory();
} catch {}
} catch { }

const { trailingSlash = 'ignore' } = options;

const hasSlash = urlPath.endsWith('/');
switch (trailingSlash) {
case 'never':
// biome-ignore lint/suspicious/noDoubleEquals: <explanation>
if (isDirectory && urlPath != '/' && hasSlash) {
// biome-ignore lint/style/useTemplate: <explanation>
// biome-ignore lint/suspicious/noFallthroughSwitchClause: <explanation>
pathname = urlPath.slice(0, -1) + (urlQuery ? '?' + urlQuery : '');
res.statusCode = 301;
res.setHeader('Location', pathname);
return res.end();
// biome-ignore lint/style/noUselessElse: <explanation>
} else pathname = urlPath;
// intentionally fall through
case 'ignore':
{
if (isDirectory && !hasSlash) {
// biome-ignore lint/style/useTemplate: <explanation>
pathname = urlPath + '/index.html';
} else pathname = urlPath;
}
break;
case 'always':
// trailing slash is not added to "subresources"
if (!hasSlash && !isSubresourceRegex.test(urlPath)) {
// biome-ignore lint/style/useTemplate: <explanation>
pathname = urlPath + '/' + (urlQuery ? '?' + urlQuery : '');
res.statusCode = 301;
res.setHeader('Location', pathname);
return res.end();
// biome-ignore lint/style/noUselessElse: <explanation>
} else pathname = urlPath;
break;
}
Expand Down Expand Up @@ -110,16 +117,19 @@ function resolveClientDir(options: Options) {
while (!serverEntryFolderURL.endsWith(serverFolder)) {
serverEntryFolderURL = path.dirname(serverEntryFolderURL);
}
// biome-ignore lint/style/useTemplate: <explanation>
const serverEntryURL = serverEntryFolderURL + '/entry.mjs';
const clientURL = new URL(appendForwardSlash(rel), serverEntryURL);
const client = url.fileURLToPath(clientURL);
return client;
}

function prependForwardSlash(pth: string) {
// biome-ignore lint/style/useTemplate: <explanation>
return pth.startsWith('/') ? pth : '/' + pth;
}

function appendForwardSlash(pth: string) {
// biome-ignore lint/style/useTemplate: <explanation>
return pth.endsWith('/') ? pth : pth + '/';
}
3 changes: 2 additions & 1 deletion packages/node/src/standalone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export function createStandaloneHandler(app: NodeApp, options: Options) {
return (req: http.IncomingMessage, res: http.ServerResponse) => {
try {
// validate request path
// biome-ignore lint/style/noNonNullAssertion: <explanation>
decodeURI(req.url!);
} catch {
res.writeHead(400);
Expand All @@ -59,7 +60,7 @@ export function createServer(listener: http.RequestListener, host: string, port:
key: fs.readFileSync(process.env.SERVER_KEY_PATH),
cert: fs.readFileSync(process.env.SERVER_CERT_PATH),
},
listener,
listener
);
} else {
httpServer = http.createServer(listener);
Expand Down
20 changes: 10 additions & 10 deletions packages/node/test/api-route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('API routes', () => {

it('Can get the request body', async () => {
const { handler } = await import('./fixtures/api-route/dist/server/entry.mjs');
let { req, res, done } = createRequestAndResponse({
const { req, res, done } = createRequestAndResponse({
method: 'POST',
url: '/recipes',
});
Expand All @@ -38,9 +38,9 @@ describe('API routes', () => {

handler(req, res);

let [buffer] = await done;
const [buffer] = await done;

let json = JSON.parse(buffer.toString('utf-8'));
const json = JSON.parse(buffer.toString('utf-8'));

assert.equal(json.length, 1);

Expand All @@ -50,7 +50,7 @@ describe('API routes', () => {
it('Can get binary data', async () => {
const { handler } = await import('./fixtures/api-route/dist/server/entry.mjs');

let { req, res, done } = createRequestAndResponse({
const { req, res, done } = createRequestAndResponse({
method: 'POST',
url: '/binary',
});
Expand All @@ -61,15 +61,15 @@ describe('API routes', () => {

handler(req, res);

let [out] = await done;
let arr = Array.from(new Uint8Array(out.buffer));
const [out] = await done;
const arr = Array.from(new Uint8Array(out.buffer));
assert.deepEqual(arr, [5, 4, 3, 2, 1]);
});

it('Can post large binary data', async () => {
const { handler } = await import('./fixtures/api-route/dist/server/entry.mjs');

let { req, res, done } = createRequestAndResponse({
const { req, res, done } = createRequestAndResponse({
method: 'POST',
url: '/hash',
});
Expand All @@ -95,17 +95,17 @@ describe('API routes', () => {
expectedDigest = hash.digest();
});

let [out] = await done;
const [out] = await done;
assert.deepEqual(new Uint8Array(out.buffer), new Uint8Array(expectedDigest));
});

it('Can bail on streaming', async () => {
const { handler } = await import('./fixtures/api-route/dist/server/entry.mjs');
let { req, res, done } = createRequestAndResponse({
const { req, res, done } = createRequestAndResponse({
url: '/streaming',
});

let locals = { cancelledByTheServer: false };
const locals = { cancelledByTheServer: false };

handler(req, res, () => {}, locals);
req.send();
Expand Down
2 changes: 1 addition & 1 deletion packages/node/test/bad-urls.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('Bad URLs', () => {
assert.equal(
statusCodes.includes(fetchResult.status),
true,
`${weirdUrl} returned something else than 400, 404, or 500`,
`${weirdUrl} returned something else than 400, 404, or 500`
);
}
const stillWork = await fixture.fetch('/');
Expand Down
4 changes: 2 additions & 2 deletions packages/node/test/encoded.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('Encoded Pathname', () => {

it('Can get an Astro file', async () => {
const { handler } = await import('./fixtures/encoded/dist/server/entry.mjs');
let { req, res, text } = createRequestAndResponse({
const { req, res, text } = createRequestAndResponse({
url: '/什么',
});

Expand All @@ -32,7 +32,7 @@ describe('Encoded Pathname', () => {
it('Can get a Markdown file', async () => {
const { handler } = await import('./fixtures/encoded/dist/server/entry.mjs');

let { req, res, text } = createRequestAndResponse({
const { req, res, text } = createRequestAndResponse({
url: '/blog/什么',
});

Expand Down
5 changes: 3 additions & 2 deletions packages/node/test/errors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('Errors', () => {
});
let devPreview;

// biome-ignore lint/suspicious/noDuplicateTestHooks: <explanation>
before(async () => {
// The two tests that need the server to run are skipped
// devPreview = await fixture.preview();
Expand Down Expand Up @@ -58,7 +59,7 @@ describe('Errors', () => {
const $ = cheerio.load(html);

assert.equal($('p').text().trim(), 'Internal server error');
},
}
);

it(
Expand Down Expand Up @@ -86,6 +87,6 @@ describe('Errors', () => {
} else {
throw new Error('The response should take at most 2 chunks.');
}
},
}
);
});
2 changes: 1 addition & 1 deletion packages/node/test/headers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ describe('Node Adapter Headers', () => {
async function runTest(url, expectedHeaders) {
const { handler } = await import('./fixtures/headers/dist/server/entry.mjs');

let { req, res, done } = createRequestAndResponse({
const { req, res, done } = createRequestAndResponse({
method: 'GET',
url,
});
Expand Down
Loading

0 comments on commit 4b17094

Please sign in to comment.