@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 199 lines 7.18 KB
Raw
1 import { pathToFileURL } from "node:url";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import {
6 loadProjectModule,
7 resolveProjectPackageDirectory,
8 type ModuleLoadError,
9 } from "../core/Loader.ts";
10 import { loadVinextBuildConfig, type VinextBuildConfig } from "./BuildConfig.ts";
11
12 export type VinextPrerenderResult = {
13 readonly ran: boolean;
14 /** Absolute path of the RSC worker entry after path-table injection. */
15 readonly entryPath?: string;
16 };
17
18 const PATH_TABLE_START = "/* __VINEXT_PREGENERATED_CONCRETE_PATHS_START__ */";
19 const PATH_TABLE_END = "/* __VINEXT_PREGENERATED_CONCRETE_PATHS_END__ */";
20
21 const exists = (fs: FileSystem.FileSystem, filePath: string) =>
22 fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
23
24 /**
25 * The KV data-cache adapter throws during local prerender (no Worker
26 * `env`) and vinext may log a wrangler.jsonc snippet. That hint is
27 * wrong on the Alchemy path — drop those lines so deploy logs do not
28 * look like a missing Wrangler file.
29 */
30 const isWranglerKvHint = (text: string) =>
31 text.includes("failed to initialize the configured data cache adapter") ||
32 text.includes("Add it to wrangler.jsonc") ||
33 (text.includes("KV data cache adapter requires") && text.includes("KV namespace binding")) ||
34 text.includes('"kv_namespaces"');
35
36 const withLocalPrerenderLogs = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
37 Effect.acquireUseRelease(
38 Effect.sync(() => {
39 const original = {
40 log: console.log,
41 warn: console.warn,
42 error: console.error,
43 info: console.info,
44 };
45 const filter =
46 (write: typeof console.log) =>
47 (...args: Array<unknown>) => {
48 const text = args.map((arg) => String(arg)).join(" ");
49 if (isWranglerKvHint(text)) return;
50 write(...args);
51 };
52 console.log = filter(original.log);
53 console.warn = filter(original.warn);
54 console.error = filter(original.error);
55 console.info = filter(original.info);
56 return original;
57 }),
58 () => effect,
59 (original) =>
60 Effect.sync(() => {
61 console.log = original.log;
62 console.warn = original.warn;
63 console.error = original.error;
64 console.info = original.info;
65 }),
66 );
67
68 /**
69 * After `vite build`, run vinext's prerender phase when the project
70 * configured `vinext({ prerender: true })` (or `{ routes: "*" }`).
71 *
72 * Alchemy's Website Vite path only runs `vite build`, which vinext does
73 * not prerender by itself — that step lives in `vinext build`. This hook
74 * is not a reimplementation: it resolves the project's `vinext` and calls
75 * `runPrerender` / `emitPrerenderPathManifest`. The path-table injection
76 * is the only Alchemy-owned glue.
77 */
78 export const runVinextPrerenderIfConfigured = Effect.fn(function* (
79 rootDir: string,
80 cache: "kv" | "redis" | "s3" = "kv",
81 buildConfig?: VinextBuildConfig,
82 ) {
83 const path = yield* Path.Path;
84 const root = path.resolve(rootDir);
85 const vinextRoot = yield* resolveVinextRoot(root);
86
87 const importVinextDist = (rel: string) =>
88 Effect.promise(() => import(pathToFileURL(path.join(vinextRoot, rel)).href));
89
90 const { resolveVinextPrerenderDecision, formatVinextPrerenderLabel } = yield* importVinextDist(
91 "dist/config/prerender.js",
92 );
93 const loadBuildConfig = Effect.gen(function* () {
94 const vite = yield* loadProjectModule<typeof import("vite")>(root, "vite");
95 const loaded = yield* Effect.tryPromise(() =>
96 vite.loadConfigFromFile({ command: "build", mode: "production" }, undefined, root),
97 );
98 return yield* loadVinextBuildConfig(root, loaded?.config.plugins);
99 });
100 const config = buildConfig ?? (yield* loadBuildConfig);
101 const decision = resolveVinextPrerenderDecision({
102 vinextPrerenderConfig: config.prerenderConfig,
103 nextOutput: config.nextConfig.output,
104 });
105 if (!decision) {
106 return { ran: false } satisfies VinextPrerenderResult;
107 }
108
109 yield* Effect.logInfo(` ${formatVinextPrerenderLabel(decision)}`);
110 if (cache === "kv") {
111 yield* Effect.logInfo(
112 " Local prerender has no Worker bindings. VINEXT_KV_CACHE is provisioned and seeded on deploy; do not add wrangler.jsonc.",
113 );
114 }
115
116 const { runPrerender, assertNoFatalPrerenderRoutes } = (yield* importVinextDist(
117 "dist/build/run-prerender.js",
118 )) as {
119 runPrerender: (options: {
120 root: string;
121 concurrency?: number;
122 nextConfig: unknown;
123 routeRootConfig: unknown;
124 }) => Promise<{ routes?: readonly unknown[] } | null>;
125 assertNoFatalPrerenderRoutes: (routes: readonly unknown[]) => void;
126 };
127 const prerenderResult = yield* withLocalPrerenderLogs(
128 Effect.promise(() =>
129 runPrerender({
130 root,
131 concurrency: config.prerenderConfig?.concurrency,
132 nextConfig: config.nextConfig,
133 routeRootConfig: config.routeRootConfig,
134 }),
135 ),
136 );
137 if (prerenderResult?.routes) {
138 assertNoFatalPrerenderRoutes(prerenderResult.routes);
139 }
140
141 const { emitPrerenderPathManifest } = yield* importVinextDist("dist/build/prerender-paths.js");
142 yield* Effect.promise(() =>
143 emitPrerenderPathManifest({
144 root,
145 nextConfig: config.nextConfig,
146 routeRootConfig: config.routeRootConfig,
147 buildIdentity: config.buildIdentity,
148 responseVary: config.responseVary,
149 requestRouting: config.requestRouting,
150 isResponsePolicyHeader: config.isResponsePolicyHeader,
151 }),
152 );
153 yield* injectPregeneratedConcretePaths(root);
154
155 const fs = yield* FileSystem.FileSystem;
156 const entryPath = path.join(root, "dist", "server", "index.js");
157 return {
158 ran: true,
159 entryPath: (yield* exists(fs, entryPath)) ? entryPath : undefined,
160 } satisfies VinextPrerenderResult;
161 });
162
163 /** Absolute path to the project's `vinext` package root. */
164 export const resolveVinextRoot = (root: string): Effect.Effect<string, ModuleLoadError> =>
165 resolveProjectPackageDirectory(root, "vinext");
166
167 const injectPregeneratedConcretePaths = (root: string) =>
168 Effect.gen(function* () {
169 const path = yield* Path.Path;
170 const fs = yield* FileSystem.FileSystem;
171 const workerEntry = path.join(root, "dist", "server", "index.js");
172 if (!(yield* exists(fs, workerEntry))) {
173 return;
174 }
175
176 const escapedStart = PATH_TABLE_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
177 const escapedEnd = PATH_TABLE_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
178 const re = new RegExp(`${escapedStart}[\\s\\S]*?${escapedEnd}\\n?`, "g");
179
180 let code = (yield* fs.readFileString(workerEntry)).replace(re, "");
181 const manifestPath = path.join(root, "dist", "server", "vinext-prerender.json");
182 if (!(yield* exists(fs, manifestPath))) {
183 yield* fs.writeFileString(workerEntry, code);
184 return;
185 }
186
187 const manifest = JSON.parse(yield* fs.readFileString(manifestPath)) as {
188 pregeneratedConcretePaths?: unknown;
189 };
190 const table = manifest.pregeneratedConcretePaths ?? [];
191 if (Array.isArray(table) && table.length > 0) {
192 code =
193 `${PATH_TABLE_START}\n` +
194 `globalThis.__VINEXT_PREGENERATED_CONCRETE_PATHS = ${JSON.stringify(table)};\n` +
195 `${PATH_TABLE_END}\n` +
196 code;
197 }
198 yield* fs.writeFileString(workerEntry, code);
199 });