The best way to control Claude Code, Codex and more from any computer or phone

main
ts 251 lines 8.53 KB
Raw
1 import fs from "node:fs";
2 import nodePath from "node:path";
3 import { pathToFileURL } from "node:url";
4 import { keySpace as makeKeySpace } from "./cache/shared.ts";
5
6 export const VINEXT_KV_CACHE_BINDING = "VINEXT_KV_CACHE";
7 export const VINEXT_CACHE_BINDING = "VINEXT_CACHE";
8
9 const DEFAULT_KV_TTL_SECONDS = 30 * 24 * 3600;
10
11 type CacheControlMetadata = {
12 revalidate: number;
13 expire?: number;
14 stale?: number;
15 };
16
17 export type VinextPrerenderKVPair = {
18 key: string;
19 value: string;
20 expirationTtl?: number;
21 metadata?: Record<string, unknown>;
22 };
23
24 export const vinextCacheNamespaceFromEnv = (
25 env: Record<string, unknown>,
26 ): { namespaceId: string; accountId?: string } | undefined => {
27 const raw = env[VINEXT_KV_CACHE_BINDING] ?? env[VINEXT_CACHE_BINDING];
28 if (!raw || typeof raw !== "object") {
29 return undefined;
30 }
31 const namespaceId = (raw as { namespaceId?: unknown }).namespaceId;
32 const accountId = (raw as { accountId?: unknown }).accountId;
33 if (typeof namespaceId !== "string") {
34 return undefined;
35 }
36 return {
37 namespaceId,
38 accountId: typeof accountId === "string" ? accountId : undefined,
39 };
40 };
41
42 /**
43 * Walk prerender artifacts with Node fs. vinext's internals are Promise
44 * APIs; the walk stays async and reports skip warnings for the Effect
45 * caller to log.
46 */
47 export const buildVinextPrerenderKVPairs = async (
48 vinextRoot: string,
49 serverDir: string,
50 ): Promise<{
51 routeCount: number;
52 pairs: VinextPrerenderKVPair[];
53 warnings: string[];
54 }> => {
55 const importVinextDist = (rel: string) =>
56 import(pathToFileURL(nodePath.join(vinextRoot, rel)).href);
57
58 const [
59 { readPrerenderManifest, getRenderedAppRoutes, getRenderedMetadataRoutes },
60 { appIsrCacheKey },
61 { buildAppPageCacheTags, buildAppRouteCacheTags },
62 { normalizePregeneratedPathname },
63 { getAppRouteOutputPath, getOutputPath, getRscOutputPath },
64 ] = await Promise.all([
65 importVinextDist("dist/server/prerender-manifest.js"),
66 importVinextDist("dist/server/isr-cache.js"),
67 importVinextDist("dist/server/app-page-cache.js"),
68 importVinextDist("dist/server/pregenerated-concrete-paths.js"),
69 importVinextDist("dist/utils/prerender-output-paths.js"),
70 ]);
71
72 const manifestPath = nodePath.join(serverDir, "vinext-prerender.json");
73 const manifest = readPrerenderManifest(manifestPath);
74 if (!manifest?.buildId || !Array.isArray(manifest.routes)) {
75 return { routeCount: 0, pairs: [], warnings: [] };
76 }
77
78 const prerenderDir = nodePath.join(serverDir, "prerendered-routes");
79 if (!fs.existsSync(prerenderDir)) {
80 return { routeCount: 0, pairs: [], warnings: [] };
81 }
82
83 const pairs: VinextPrerenderKVPair[] = [];
84 const warnings: string[] = [];
85 const now = Date.now();
86 const trailingSlash = manifest.trailingSlash ?? false;
87 const keySpace = makeKeySpace(undefined);
88 let routeCount = 0;
89
90 for (const route of getRenderedAppRoutes(manifest.routes)) {
91 const artifactPathname = route.path ?? route.route;
92 const cachePathname = normalizePregeneratedPathname(artifactPathname);
93 let htmlPath: string;
94 let rscPath: string;
95 try {
96 htmlPath = resolveContainedFile(prerenderDir, getOutputPath(artifactPathname, trailingSlash));
97 rscPath = resolveContainedFile(prerenderDir, getRscOutputPath(artifactPathname));
98 } catch (error) {
99 warnings.push(
100 `[vinext] Skipping prerender KV seed for ${artifactPathname}: ${formatUnknownError(error)}`,
101 );
102 continue;
103 }
104 if (!fs.existsSync(htmlPath)) continue;
105
106 if (typeof route.revalidate === "number" && route.revalidate <= 0) continue;
107 const revalidateSeconds = typeof route.revalidate === "number" ? route.revalidate : undefined;
108 const expireSeconds = typeof route.expire === "number" ? route.expire : undefined;
109 const staleSeconds =
110 typeof route.stale === "number" && route.stale >= 0 ? route.stale : undefined;
111 const expirationTtl = revalidateSeconds === undefined ? undefined : DEFAULT_KV_TTL_SECONDS;
112 const tags = buildAppPageCacheTags(cachePathname, route.tags ?? []);
113 const metadata = buildMetadata(tags);
114 const htmlKey = appIsrCacheKey(cachePathname, "html", manifest.buildId);
115 const rscKey = appIsrCacheKey(cachePathname, "rsc", manifest.buildId);
116
117 pairs.push({
118 key: keySpace.entryKey(htmlKey),
119 value: buildCacheEntry(
120 {
121 kind: "APP_PAGE",
122 html: fs.readFileSync(htmlPath, "utf-8"),
123 headers: route.headers,
124 },
125 tags,
126 now,
127 revalidateSeconds,
128 expireSeconds,
129 staleSeconds,
130 ),
131 ...(expirationTtl !== undefined ? { expirationTtl } : {}),
132 ...(metadata ? { metadata } : {}),
133 });
134
135 if (fs.existsSync(rscPath)) {
136 const rscData = fs.readFileSync(rscPath, "base64");
137 pairs.push({
138 key: keySpace.entryKey(rscKey),
139 value: buildCacheEntry(
140 {
141 kind: "APP_PAGE",
142 html: "",
143 rscData,
144 },
145 tags,
146 now,
147 revalidateSeconds,
148 expireSeconds,
149 staleSeconds,
150 ),
151 ...(expirationTtl !== undefined ? { expirationTtl } : {}),
152 ...(metadata ? { metadata } : {}),
153 });
154 }
155
156 routeCount++;
157 }
158
159 for (const route of getRenderedMetadataRoutes(manifest.routes)) {
160 const pathname = route.path ?? route.route;
161 let artifactPath: string;
162 try {
163 artifactPath = resolveContainedFile(prerenderDir, getAppRouteOutputPath(pathname));
164 } catch (error) {
165 warnings.push(
166 `[vinext] Skipping metadata prerender KV seed for ${pathname}: ${formatUnknownError(error)}`,
167 );
168 continue;
169 }
170 if (!fs.existsSync(artifactPath)) continue;
171
172 const cachePathname = normalizePregeneratedPathname(pathname);
173 if (typeof route.revalidate === "number" && route.revalidate <= 0) continue;
174 const revalidateSeconds = typeof route.revalidate === "number" ? route.revalidate : undefined;
175 const expireSeconds = typeof route.expire === "number" ? route.expire : undefined;
176 const staleSeconds =
177 typeof route.stale === "number" && route.stale >= 0 ? route.stale : undefined;
178 const expirationTtl = revalidateSeconds === undefined ? undefined : DEFAULT_KV_TTL_SECONDS;
179 const tags = buildAppRouteCacheTags(cachePathname, route.tags ?? [], route.routeSegments ?? []);
180 const metadata = buildMetadata(tags);
181 const routeKey = appIsrCacheKey(cachePathname, "route", manifest.buildId);
182 pairs.push({
183 key: keySpace.entryKey(routeKey),
184 value: buildCacheEntry(
185 {
186 kind: "APP_ROUTE",
187 body: fs.readFileSync(artifactPath, "base64"),
188 headers: route.headers ?? {},
189 status: route.responseStatus ?? 200,
190 },
191 tags,
192 now,
193 revalidateSeconds,
194 expireSeconds,
195 staleSeconds,
196 ),
197 ...(expirationTtl !== undefined ? { expirationTtl } : {}),
198 ...(metadata ? { metadata } : {}),
199 });
200 routeCount++;
201 }
202
203 return { routeCount, pairs, warnings };
204 };
205
206 const resolveContainedFile = (rootDir: string, relativePath: string): string => {
207 const resolvedRoot = nodePath.resolve(rootDir);
208 const resolvedFile = nodePath.resolve(resolvedRoot, relativePath);
209 const relative = nodePath.relative(resolvedRoot, resolvedFile);
210 if (relative === "" || relative.startsWith("..") || nodePath.isAbsolute(relative)) {
211 throw new Error(`[vinext] Refusing to read prerender artifact outside ${resolvedRoot}`);
212 }
213 return resolvedFile;
214 };
215
216 const buildCacheEntry = (
217 value: Record<string, unknown>,
218 tags: string[],
219 now: number,
220 revalidateSeconds: number | undefined,
221 expireSeconds: number | undefined,
222 staleSeconds: number | undefined,
223 ): string => {
224 const cacheControl: CacheControlMetadata | undefined =
225 revalidateSeconds === undefined
226 ? undefined
227 : {
228 revalidate: revalidateSeconds,
229 ...(expireSeconds === undefined ? {} : { expire: expireSeconds }),
230 ...(staleSeconds === undefined ? {} : { stale: staleSeconds }),
231 };
232
233 return JSON.stringify({
234 value,
235 tags,
236 lastModified: now,
237 revalidateAt: revalidateSeconds === undefined ? null : now + revalidateSeconds * 1000,
238 expireAt: expireSeconds === undefined ? null : now + expireSeconds * 1000,
239 ...(cacheControl ? { cacheControl } : {}),
240 });
241 };
242
243 const buildMetadata = (tags: string[]): Record<string, unknown> | undefined => {
244 const metadata = { tags };
245 return JSON.stringify(metadata).length <= 1024 ? metadata : undefined;
246 };
247
248 const formatUnknownError = (error: unknown): string => {
249 if (error instanceof Error && error.message) return error.message;
250 return String(error);
251 };