@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 230 lines 7.57 KB
Raw
1 /**
2 * Shared ISR / `"use cache"` entry codec for vinext Node adapters.
3 *
4 * Mirrors `@vinext/cloudflare` KV data-cache serialization so Redis and
5 * S3 store the same JSON shape (ArrayBuffers as base64, tag invalidation
6 * timestamps, stale-while-revalidate).
7 */
8 const PATH_TAG_PREFIX = "_N_T_";
9 const MAX_TAG_LENGTH = 256;
10 const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
11 const VALID_KINDS = new Set(["FETCH", "APP_PAGE", "PAGES", "APP_ROUTE", "REDIRECT", "IMAGE"]);
12
13 export const ENTRY_PREFIX = "cache:";
14 export const TAG_PREFIX = "__tag:";
15 /** Marker for logical keys hashed to fit Cloudflare KV's 512-byte limit. */
16 export const HASHED_KEY_PREFIX = "__hash:";
17 const KV_KEY_MAX_BYTES = 512;
18 const KEY_ENCODER = new TextEncoder();
19
20 /** FNV-1a 64-bit (two 32-bit rounds). Same algorithm vinext uses for KV keys. */
21 export const fnv1a64 = (input: string): string => {
22 let h1 = 2166136261;
23 for (let i = 0; i < input.length; i++) {
24 h1 ^= input.charCodeAt(i);
25 h1 = (h1 * 16777619) >>> 0;
26 }
27 let h2 = 84696351;
28 for (let i = 0; i < input.length; i++) {
29 h2 ^= input.charCodeAt(i);
30 h2 = (h2 * 16777619) >>> 0;
31 }
32 return h1.toString(16).padStart(8, "0") + h2.toString(16).padStart(8, "0");
33 };
34
35 const normalizeAppPrefix = (appPrefix: string | undefined): string => {
36 if (!appPrefix) return "";
37 const prefix = `${appPrefix}:`;
38 const sample = `${prefix}${ENTRY_PREFIX}${HASHED_KEY_PREFIX}${fnv1a64("")}`;
39 if (KEY_ENCODER.encode(sample).length <= KV_KEY_MAX_BYTES) return prefix;
40 return `__app:${fnv1a64(appPrefix)}:`;
41 };
42
43 const buildStorageKey = (prefix: string, categoryPrefix: string, logicalKey: string): string => {
44 const key = `${prefix}${categoryPrefix}${logicalKey}`;
45 if (KEY_ENCODER.encode(key).length <= KV_KEY_MAX_BYTES) return key;
46 return `${prefix}${categoryPrefix}${HASHED_KEY_PREFIX}${fnv1a64(logicalKey)}`;
47 };
48
49 export const validateTag = (tag: string): string | null => {
50 if (typeof tag !== "string" || tag.length === 0 || tag.length > MAX_TAG_LENGTH) {
51 return null;
52 }
53 // oxlint-disable-next-line no-control-regex -- rejects control characters on purpose
54 if (/[\x00-\x1f\\:]/.test(tag)) return null;
55 return tag;
56 };
57
58 export const validUniqueTags = (tags: ReadonlyArray<string>): Array<string> => {
59 const result: Array<string> = [];
60 const seen = new Set<string>();
61 for (const tag of tags) {
62 const valid = validateTag(tag);
63 if (!valid || seen.has(valid)) continue;
64 seen.add(valid);
65 result.push(valid);
66 }
67 return result;
68 };
69
70 export const isPathChildOf = (path: string, prefix: string): boolean => {
71 if (prefix === "/") return path.startsWith("/");
72 if (path === prefix) return true;
73 return path.startsWith(`${prefix}/`);
74 };
75
76 export const pathFromTag = (tag: string): string | undefined => {
77 const raw = tag.startsWith(PATH_TAG_PREFIX) ? tag.slice(PATH_TAG_PREFIX.length) : tag;
78 return raw.startsWith("/") ? raw : undefined;
79 };
80
81 export const readStringArrayField = (
82 ctx: Record<string, unknown> | undefined,
83 field: string,
84 ): Array<string> => {
85 const value = ctx?.[field];
86 if (!Array.isArray(value)) return [];
87 return value.filter((item): item is string => typeof item === "string");
88 };
89
90 export const readPositiveNumberField = (
91 ctx: Record<string, unknown> | undefined,
92 field: string,
93 ): number | undefined => {
94 const value = ctx?.[field];
95 return typeof value === "number" && value > 0 ? value : undefined;
96 };
97
98 export const readCacheControlNumberField = (
99 ctx: Record<string, unknown> | undefined,
100 field: string,
101 ): number | undefined => {
102 const control = ctx?.cacheControl;
103 if (control !== undefined && typeof control === "object" && control !== null) {
104 const nested = (control as Record<string, unknown>)[field];
105 if (typeof nested === "number") return nested;
106 }
107 const value = ctx?.[field];
108 return typeof value === "number" ? value : undefined;
109 };
110
111 export interface StoredCacheControl {
112 readonly revalidate: number;
113 readonly expire?: number;
114 readonly stale?: number;
115 }
116
117 export interface StoredCacheEntry {
118 value: unknown;
119 tags: Array<string>;
120 lastModified: number;
121 revalidateAt: number | null;
122 expireAt: number | null;
123 cacheControl?: StoredCacheControl;
124 }
125
126 export const isUnknownRecord = (value: unknown): value is Record<string, unknown> =>
127 typeof value === "object" && value !== null;
128
129 export const validateCacheEntry = (raw: unknown): StoredCacheEntry | null => {
130 if (!isUnknownRecord(raw)) return null;
131 if (typeof raw.lastModified !== "number") return null;
132 if (!Array.isArray(raw.tags)) return null;
133 if (raw.revalidateAt !== null && typeof raw.revalidateAt !== "number") {
134 return null;
135 }
136 if (raw.expireAt !== undefined && raw.expireAt !== null && typeof raw.expireAt !== "number") {
137 return null;
138 }
139 if (raw.cacheControl !== undefined) {
140 if (!isUnknownRecord(raw.cacheControl)) return null;
141 if (typeof raw.cacheControl.revalidate !== "number") return null;
142 }
143 if (raw.value !== null) {
144 if (!isUnknownRecord(raw.value)) return null;
145 if (typeof raw.value.kind !== "string" || !VALID_KINDS.has(raw.value.kind)) {
146 return null;
147 }
148 }
149 return raw as unknown as StoredCacheEntry;
150 };
151
152 const arrayBufferToBase64 = (buffer: ArrayBuffer): string => Buffer.from(buffer).toString("base64");
153
154 const safeBase64ToArrayBuffer = (base64: string): ArrayBuffer | null => {
155 if (!BASE64_RE.test(base64) || base64.length % 4 !== 0) return null;
156 try {
157 const buf = Buffer.from(base64, "base64");
158 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
159 } catch {
160 return null;
161 }
162 };
163
164 export const serializeForJSON = (value: Record<string, unknown>): unknown => {
165 if (value.kind === "APP_PAGE") {
166 return {
167 ...value,
168 rscData:
169 value.rscData instanceof ArrayBuffer ? arrayBufferToBase64(value.rscData) : value.rscData,
170 };
171 }
172 if (value.kind === "APP_ROUTE") {
173 return {
174 ...value,
175 body: value.body instanceof ArrayBuffer ? arrayBufferToBase64(value.body) : value.body,
176 };
177 }
178 if (value.kind === "IMAGE") {
179 return {
180 ...value,
181 buffer:
182 value.buffer instanceof ArrayBuffer ? arrayBufferToBase64(value.buffer) : value.buffer,
183 };
184 }
185 return value;
186 };
187
188 export const restoreArrayBuffers = (
189 value: Record<string, unknown>,
190 ): Record<string, unknown> | null => {
191 const restore = (field: string) => {
192 const raw = value[field];
193 if (typeof raw !== "string") return value;
194 const decoded = safeBase64ToArrayBuffer(raw);
195 if (!decoded) return null;
196 return { ...value, [field]: decoded };
197 };
198 if (value.kind === "APP_PAGE") return restore("rscData");
199 if (value.kind === "APP_ROUTE") return restore("body");
200 if (value.kind === "IMAGE") return restore("buffer");
201 return value;
202 };
203
204 export const keySpace = (appPrefix: string | undefined) => {
205 const prefix = normalizeAppPrefix(appPrefix);
206 return {
207 entryPrefix: `${prefix}${ENTRY_PREFIX}`,
208 entryKey: (key: string) => buildStorageKey(prefix, ENTRY_PREFIX, key),
209 tagKey: (tag: string) => buildStorageKey(prefix, TAG_PREFIX, tag),
210 };
211 };
212
213 /**
214 * Read a non-empty string from the adapter `env` bag, then `process.env`.
215 * Node `startProdServer` passes `process.env`; Pages Router registration
216 * sometimes calls the factory with no env at all.
217 */
218 export const readEnvString = (
219 env: Record<string, unknown> | undefined,
220 key: string,
221 ): string | undefined => {
222 const fromEnv = env?.[key];
223 if (typeof fromEnv === "string" && fromEnv.length > 0) return fromEnv;
224 if (typeof process === "undefined") return undefined;
225 const fromProcess = process.env?.[key];
226 if (typeof fromProcess === "string" && fromProcess.length > 0) {
227 return fromProcess;
228 }
229 return undefined;
230 };