@fortedigital/nextjs-cache-handler
Version:
Next.js cache handlers
366 lines (361 loc) • 11.9 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/instrumentation/instrumentation.ts
var instrumentation_exports = {};
__export(instrumentation_exports, {
registerInitialCache: () => registerInitialCache
});
module.exports = __toCommonJS(instrumentation_exports);
// src/instrumentation/register-initial-cache.ts
var import_node_fs = require("fs");
var import_node_path = __toESM(require("path"), 1);
var import_constants = require("next/constants");
var import_constants2 = require("next/dist/lib/constants");
// src/helpers/getTagsFromHeaders.ts
function getTagsFromHeaders(headers) {
const tagsHeader = headers["x-next-cache-tags"];
if (Array.isArray(tagsHeader)) {
return tagsHeader;
}
if (typeof tagsHeader === "string") {
return tagsHeader.split(",");
}
return [];
}
// src/instrumentation/register-initial-cache.ts
var PRERENDER_MANIFEST_VERSION = 4;
async function registerInitialCache(CacheHandler, options = {}) {
const debug = typeof process.env.NEXT_PRIVATE_DEBUG_CACHE !== "undefined";
const nextJsPath = import_node_path.default.join(process.cwd(), ".next");
const prerenderManifestPath = import_node_path.default.join(nextJsPath, import_constants.PRERENDER_MANIFEST);
const serverDistDir = import_node_path.default.join(nextJsPath, import_constants.SERVER_DIRECTORY);
const fetchCacheDir = import_node_path.default.join(nextJsPath, "cache", "fetch-cache");
const populateFetch = options.fetch ?? true;
const populatePages = options.pages ?? true;
const populateRoutes = options.routes ?? true;
let prerenderManifest;
try {
const prerenderManifestData = await import_node_fs.promises.readFile(
prerenderManifestPath,
"utf-8"
);
prerenderManifest = JSON.parse(prerenderManifestData);
if (prerenderManifest.version !== PRERENDER_MANIFEST_VERSION) {
throw new Error(
`Invalid prerender manifest version. Expected version ${PRERENDER_MANIFEST_VERSION}. Please check if the Next.js version is compatible with the CacheHandler version.`
);
}
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read prerender manifest",
`Error: ${error}`
);
}
return;
}
const context = {
serverDistDir,
dev: process.env.NODE_ENV === "development"
};
let cacheHandler;
try {
cacheHandler = new CacheHandler(
context
);
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to create CacheHandler instance",
`Error: ${error}`
);
}
return;
}
async function setRouteCache(cachePath, router, revalidate) {
const pathToRouteFiles = import_node_path.default.join(serverDistDir, router, cachePath);
let lastModified;
try {
const stats = await import_node_fs.promises.stat(`${pathToRouteFiles}.body`);
lastModified = stats.mtimeMs;
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read route body file",
`Error: ${error}`
);
}
return;
}
let body;
let meta;
try {
[body, meta] = await Promise.all([
import_node_fs.promises.readFile(`${pathToRouteFiles}.body`),
import_node_fs.promises.readFile(`${pathToRouteFiles}.meta`, "utf-8").then((data) => JSON.parse(data))
]);
if (!(meta.headers && meta.status)) {
throw new Error("Invalid route metadata. Missing headers or status.");
}
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read route body or metadata file, or parse metadata",
`Error: ${error}`
);
}
return;
}
try {
const value = {
kind: "APP_ROUTE",
body,
headers: meta.headers,
status: meta.status
};
await cacheHandler.set(cachePath, value, {
revalidate,
internal_lastModified: lastModified,
tags: getTagsFromHeaders(meta.headers)
});
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to set route cache. Please check if the CacheHandler is configured correctly",
`Error: ${error}`
);
}
return;
}
}
async function setPageCache(cachePath, router, revalidate) {
const isAppRouter = router === "app";
if (isAppRouter && cachePath === "/") {
cachePath = "/index";
}
const pathToRouteFiles = import_node_path.default.join(serverDistDir, router, cachePath);
let lastModified;
try {
const stats = await import_node_fs.promises.stat(`${pathToRouteFiles}.html`);
lastModified = stats.mtimeMs;
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read page html file",
`Error: ${error}`
);
}
return;
}
let html;
let pageData;
let meta;
let rscData;
if (debug) {
console.info(
"[CacheHandler] [%s] %s",
"registerInitialCache",
"Reading file system cache"
);
}
try {
[html, pageData, rscData, meta] = await Promise.all([
import_node_fs.promises.readFile(`${pathToRouteFiles}.html`, "utf-8"),
import_node_fs.promises.readFile(
`${pathToRouteFiles}.${isAppRouter ? "rsc" : "json"}`,
"utf-8"
).then((data) => isAppRouter ? data : JSON.parse(data)).catch((error) => {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read page data, assuming it does not exist",
`Error: ${error}`
);
return void 0;
}),
isAppRouter ? import_node_fs.promises.readFile(`${pathToRouteFiles}.prefetch.rsc`, "utf-8").then((data) => data).catch((error) => {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read page prefetch data, assuming it does not exist",
`Error: ${error}`
);
return void 0;
}) : void 0,
isAppRouter ? import_node_fs.promises.readFile(`${pathToRouteFiles}.meta`, "utf-8").then((data) => JSON.parse(data)) : void 0
]);
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read page html, page data, or metadata file, or parse metadata",
`Error: ${error}`
);
}
return;
}
if (debug) {
console.info(
"[CacheHandler] [%s] %s",
"registerInitialCache",
"Saving file system cache to cache handler"
);
}
try {
const value = {
kind: isAppRouter ? "APP_PAGE" : "PAGES",
html,
pageData,
postponed: meta?.postponed,
headers: meta?.headers,
status: meta?.status,
rscData: isAppRouter && rscData ? Buffer.from(rscData, "utf-8") : void 0,
segmentData: void 0
// TODO: Add segment data
};
await cacheHandler.set(cachePath, value, {
revalidate,
internal_lastModified: lastModified
});
if (debug) {
console.info(
"[CacheHandler] [%s] %s",
"registerInitialCache",
"Saved file system cache to cache handler"
);
}
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to set page cache. Please check if the CacheHandler is configured correctly",
`Error: ${error}`
);
}
return;
}
}
for (const [
cachePath,
{ dataRoute, initialRevalidateSeconds }
] of Object.entries(prerenderManifest.routes)) {
if (populatePages && dataRoute?.endsWith(".json")) {
await setPageCache(cachePath, "pages", initialRevalidateSeconds);
} else if (populatePages && dataRoute?.endsWith(".rsc")) {
await setPageCache(cachePath, "app", initialRevalidateSeconds);
} else if (populateRoutes && dataRoute === null) {
await setRouteCache(cachePath, "app", initialRevalidateSeconds);
}
}
if (!populateFetch) {
return;
}
let fetchFiles;
try {
fetchFiles = await import_node_fs.promises.readdir(fetchCacheDir);
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read cache/fetch-cache directory",
`Error: ${error}`
);
}
return;
}
for (const fetchCacheKey of fetchFiles) {
const filePath = import_node_path.default.join(fetchCacheDir, fetchCacheKey);
let lastModified;
try {
const stats = await import_node_fs.promises.stat(filePath);
lastModified = stats.mtimeMs;
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to read fetch cache file",
`Error: ${error}`
);
}
return;
}
let fetchCache;
try {
fetchCache = await import_node_fs.promises.readFile(filePath, "utf-8").then((data) => JSON.parse(data));
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to parse fetch cache file",
`Error: ${error}`
);
}
return;
}
const revalidateValue = fetchCache.revalidate;
const revalidate = revalidateValue === import_constants2.CACHE_ONE_YEAR ? false : revalidateValue;
try {
await cacheHandler.set(fetchCacheKey, fetchCache, {
revalidate,
internal_lastModified: lastModified,
tags: fetchCache.tags
});
} catch (error) {
if (debug) {
console.warn(
"[CacheHandler] [%s] %s %s",
"registerInitialCache",
"Failed to set fetch cache. Please check if the CacheHandler is configured correctly",
`Error: ${error}`
);
}
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
registerInitialCache
});