Skip to content

Commit

Permalink
chore: move earlyhints to utils, disable purging when unstable_dev is…
Browse files Browse the repository at this point in the history
… truthy (#93)

* chore: move earlyhints to utils, disable purging when unstable_dev is truthy

Signed-off-by: Logan McAnsh <[email protected]>

* Create .changeset/stupid-eggs-shop.md

Signed-off-by: Logan McAnsh <[email protected]>

---------

Signed-off-by: Logan McAnsh <[email protected]>
  • Loading branch information
mcansh authored Apr 11, 2023
1 parent ab24416 commit d92c468
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 38 deletions.
6 changes: 6 additions & 0 deletions .changeset/stupid-eggs-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@mcansh/remix-fastify": patch
"remix-app-template": patch
---

automatically disable require cache purging when unstable_dev is truthy
1 change: 1 addition & 0 deletions example/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ async function start() {
return { loadContextName: "John Doe" };
},
purgeRequireCacheInDevelopment: false,
unstable_earlyHints: true,
});

let port = process.env.PORT ? Number(process.env.PORT) || 3000 : 3000;
Expand Down
45 changes: 10 additions & 35 deletions packages/remix-fastify/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import * as path from "node:path";
import { pathToFileURL, URL } from "node:url";
import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify";
import type { FastifyPluginAsync, FastifyReply } from "fastify";
import fastifyStatic from "@fastify/static";
import type { EarlyHintItem } from "@fastify/early-hints";
import fastifyEarlyHints from "@fastify/early-hints";
import type { ServerBuild } from "@remix-run/node";
import fp from "fastify-plugin";
import fastifyRacing from "fastify-racing";
import invariant from "tiny-invariant";
import { matchRoutes } from "@remix-run/router";

import type { GetLoadContextFunction } from "./server";
import { createRequestHandler } from "./server";
import type { StaticFile } from "./utils";
import { getEarlyHintLinks } from "./utils";
import { getStaticFiles, purgeRequireCache } from "./utils";

interface PluginOptions {
Expand Down Expand Up @@ -42,8 +41,7 @@ interface PluginOptions {
*/
getLoadContext?: GetLoadContextFunction;
/**
* purge the require cache in development
* this should be disabled if you are using `unstable_dev`.
* purge the require cache in development when not using the new dev server
* @default process.env.NODE_ENV === "development"
*/
purgeRequireCacheInDevelopment?: boolean;
Expand Down Expand Up @@ -84,16 +82,20 @@ let remixFastify: FastifyPluginAsync<PluginOptions> = async (
invariant(build, "You must provide a build");
let serverBuild: ServerBuild = await loadBuild(build);

if (mode === "development" && !!serverBuild?.future?.unstable_dev) {
purgeRequireCacheInDevelopment = false;
}

if (!fastify.hasContentTypeParser("*")) {
fastify.addContentTypeParser("*", (_request, payload, done) => {
done(null, payload);
});
}

if (earlyHints) {
fastify.register(fastifyEarlyHints, { warn: true });
await fastify.register(fastifyEarlyHints, { warn: true });
}
fastify.register(fastifyRacing, { handleError: true });
await fastify.register(fastifyRacing, { handleError: true });

let PUBLIC_DIR = path.join(rootDir, "public");

Expand All @@ -102,6 +104,7 @@ let remixFastify: FastifyPluginAsync<PluginOptions> = async (
// this needs to be false so our regular requests can still be served
wildcard: false,
// we handle serving the files ourselves as you cant stack roots (public/build, public)
// and it won't pick up new files in dev
serve: false,
});

Expand Down Expand Up @@ -192,31 +195,3 @@ export let remixFastifyPlugin = fp(remixFastify, {
name: "@mcansh/remix-fastify",
fastify: "^3.29.0 || ^4.0.0",
});

function getEarlyHintLinks(
request: FastifyRequest,
serverBuild: ServerBuild
): EarlyHintItem[] {
let origin = `${request.protocol}://${request.hostname}`;
let url = new URL(`${origin}${request.url}`);

let routes = Object.values(serverBuild.assets.routes);
let matches = matchRoutes(routes, url.pathname);
if (!matches || matches.length === 0) return [];
let links = matches.flatMap((match) => {
let routeImports = match.route.imports || [];
let imports = [
match.route.module,
...routeImports,
serverBuild.assets.url,
serverBuild.assets.entry.module,
...serverBuild.assets.entry.imports,
];

return imports;
});

return links.map((link) => {
return { href: link, as: "script", rel: "preload" };
});
}
35 changes: 32 additions & 3 deletions packages/remix-fastify/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import type { EarlyHintItem } from "@fastify/early-hints";
import type { ServerBuild } from "@remix-run/node";
import { matchRoutes } from "@remix-run/router";
import type { FastifyRequest } from "fastify";
import { globSync } from "glob";

export interface StaticFile {
Expand Down Expand Up @@ -53,12 +57,37 @@ export function purgeRequireCache(BUILD_DIR: string) {
// alternatively you can set up nodemon/pm2-dev to restart the server on
// file changes, but then you'll have to reconnect to databases/etc on each
// change. We prefer the DX of this, so we've included it for you by default
// delete require.cache[BUILDDIR];
// delete require.cache[__filename];

for (let key in require.cache) {
if (key.startsWith(BUILD_DIR)) {
delete require.cache[key];
}
}
}

export function getEarlyHintLinks(
request: FastifyRequest,
serverBuild: ServerBuild
): EarlyHintItem[] {
let origin = `${request.protocol}://${request.hostname}`;
let url = new URL(`${origin}${request.url}`);

let routes = Object.values(serverBuild.assets.routes);
let matches = matchRoutes(routes, url.pathname);
if (!matches || matches.length === 0) return [];
let links = matches.flatMap((match) => {
let routeImports = match.route.imports || [];
let imports = [
match.route.module,
...routeImports,
serverBuild.assets.url,
serverBuild.assets.entry.module,
...serverBuild.assets.entry.imports,
];

return imports;
});

return links.map((link) => {
return { href: link, as: "script", rel: "preload" };
});
}

0 comments on commit d92c468

Please sign in to comment.