@rangojs/router 0.0.0-experimental.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +7 -0
- package/README.md +19 -0
- package/dist/vite/index.js +1298 -0
- package/package.json +140 -0
- package/skills/caching/SKILL.md +319 -0
- package/skills/document-cache/SKILL.md +152 -0
- package/skills/hooks/SKILL.md +359 -0
- package/skills/intercept/SKILL.md +292 -0
- package/skills/layout/SKILL.md +216 -0
- package/skills/loader/SKILL.md +365 -0
- package/skills/middleware/SKILL.md +442 -0
- package/skills/parallel/SKILL.md +255 -0
- package/skills/route/SKILL.md +141 -0
- package/skills/router-setup/SKILL.md +403 -0
- package/skills/theme/SKILL.md +54 -0
- package/skills/typesafety/SKILL.md +352 -0
- package/src/__mocks__/version.ts +6 -0
- package/src/__tests__/component-utils.test.ts +76 -0
- package/src/__tests__/route-definition.test.ts +63 -0
- package/src/__tests__/urls.test.tsx +436 -0
- package/src/browser/event-controller.ts +876 -0
- package/src/browser/index.ts +18 -0
- package/src/browser/link-interceptor.ts +121 -0
- package/src/browser/lru-cache.ts +69 -0
- package/src/browser/merge-segment-loaders.ts +126 -0
- package/src/browser/navigation-bridge.ts +893 -0
- package/src/browser/navigation-client.ts +162 -0
- package/src/browser/navigation-store.ts +823 -0
- package/src/browser/partial-update.ts +559 -0
- package/src/browser/react/Link.tsx +248 -0
- package/src/browser/react/NavigationProvider.tsx +275 -0
- package/src/browser/react/ScrollRestoration.tsx +94 -0
- package/src/browser/react/context.ts +53 -0
- package/src/browser/react/index.ts +52 -0
- package/src/browser/react/location-state-shared.ts +120 -0
- package/src/browser/react/location-state.ts +62 -0
- package/src/browser/react/use-action.ts +240 -0
- package/src/browser/react/use-client-cache.ts +56 -0
- package/src/browser/react/use-handle.ts +178 -0
- package/src/browser/react/use-href.tsx +208 -0
- package/src/browser/react/use-link-status.ts +134 -0
- package/src/browser/react/use-navigation.ts +150 -0
- package/src/browser/react/use-segments.ts +188 -0
- package/src/browser/request-controller.ts +164 -0
- package/src/browser/rsc-router.tsx +353 -0
- package/src/browser/scroll-restoration.ts +324 -0
- package/src/browser/server-action-bridge.ts +747 -0
- package/src/browser/shallow.ts +35 -0
- package/src/browser/types.ts +464 -0
- package/src/cache/__tests__/document-cache.test.ts +522 -0
- package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
- package/src/cache/__tests__/memory-store.test.ts +484 -0
- package/src/cache/cache-scope.ts +565 -0
- package/src/cache/cf/__tests__/cf-cache-store.test.ts +428 -0
- package/src/cache/cf/cf-cache-store.ts +428 -0
- package/src/cache/cf/index.ts +19 -0
- package/src/cache/document-cache.ts +340 -0
- package/src/cache/index.ts +58 -0
- package/src/cache/memory-segment-store.ts +150 -0
- package/src/cache/memory-store.ts +253 -0
- package/src/cache/types.ts +387 -0
- package/src/client.rsc.tsx +88 -0
- package/src/client.tsx +621 -0
- package/src/component-utils.ts +76 -0
- package/src/components/DefaultDocument.tsx +23 -0
- package/src/default-error-boundary.tsx +88 -0
- package/src/deps/browser.ts +8 -0
- package/src/deps/html-stream-client.ts +2 -0
- package/src/deps/html-stream-server.ts +2 -0
- package/src/deps/rsc.ts +10 -0
- package/src/deps/ssr.ts +2 -0
- package/src/errors.ts +259 -0
- package/src/handle.ts +120 -0
- package/src/handles/MetaTags.tsx +193 -0
- package/src/handles/index.ts +6 -0
- package/src/handles/meta.ts +247 -0
- package/src/href-client.ts +128 -0
- package/src/href-context.ts +33 -0
- package/src/href.ts +177 -0
- package/src/index.rsc.ts +79 -0
- package/src/index.ts +87 -0
- package/src/loader.rsc.ts +204 -0
- package/src/loader.ts +47 -0
- package/src/network-error-thrower.tsx +21 -0
- package/src/outlet-context.ts +15 -0
- package/src/root-error-boundary.tsx +277 -0
- package/src/route-content-wrapper.tsx +198 -0
- package/src/route-definition.ts +1371 -0
- package/src/route-map-builder.ts +146 -0
- package/src/route-types.ts +198 -0
- package/src/route-utils.ts +89 -0
- package/src/router/__tests__/match-context.test.ts +104 -0
- package/src/router/__tests__/match-pipelines.test.ts +537 -0
- package/src/router/__tests__/match-result.test.ts +566 -0
- package/src/router/__tests__/on-error.test.ts +935 -0
- package/src/router/__tests__/pattern-matching.test.ts +577 -0
- package/src/router/error-handling.ts +287 -0
- package/src/router/handler-context.ts +158 -0
- package/src/router/loader-resolution.ts +326 -0
- package/src/router/manifest.ts +138 -0
- package/src/router/match-context.ts +264 -0
- package/src/router/match-middleware/background-revalidation.ts +236 -0
- package/src/router/match-middleware/cache-lookup.ts +261 -0
- package/src/router/match-middleware/cache-store.ts +266 -0
- package/src/router/match-middleware/index.ts +81 -0
- package/src/router/match-middleware/intercept-resolution.ts +268 -0
- package/src/router/match-middleware/segment-resolution.ts +174 -0
- package/src/router/match-pipelines.ts +214 -0
- package/src/router/match-result.ts +214 -0
- package/src/router/metrics.ts +62 -0
- package/src/router/middleware.test.ts +1355 -0
- package/src/router/middleware.ts +748 -0
- package/src/router/pattern-matching.ts +272 -0
- package/src/router/revalidation.ts +190 -0
- package/src/router/router-context.ts +299 -0
- package/src/router/types.ts +96 -0
- package/src/router.ts +3876 -0
- package/src/rsc/__tests__/helpers.test.ts +175 -0
- package/src/rsc/handler.ts +1060 -0
- package/src/rsc/helpers.ts +64 -0
- package/src/rsc/index.ts +56 -0
- package/src/rsc/nonce.ts +18 -0
- package/src/rsc/types.ts +237 -0
- package/src/segment-system.tsx +456 -0
- package/src/server/__tests__/request-context.test.ts +171 -0
- package/src/server/context.ts +417 -0
- package/src/server/handle-store.ts +230 -0
- package/src/server/loader-registry.ts +174 -0
- package/src/server/request-context.ts +554 -0
- package/src/server/root-layout.tsx +10 -0
- package/src/server/tsconfig.json +14 -0
- package/src/server.ts +146 -0
- package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
- package/src/ssr/index.tsx +234 -0
- package/src/theme/ThemeProvider.tsx +291 -0
- package/src/theme/ThemeScript.tsx +61 -0
- package/src/theme/__tests__/theme.test.ts +120 -0
- package/src/theme/constants.ts +55 -0
- package/src/theme/index.ts +58 -0
- package/src/theme/theme-context.ts +70 -0
- package/src/theme/theme-script.ts +152 -0
- package/src/theme/types.ts +182 -0
- package/src/theme/use-theme.ts +44 -0
- package/src/types.ts +1561 -0
- package/src/urls.ts +726 -0
- package/src/use-loader.tsx +346 -0
- package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
- package/src/vite/expose-action-id.ts +344 -0
- package/src/vite/expose-handle-id.ts +209 -0
- package/src/vite/expose-loader-id.ts +357 -0
- package/src/vite/expose-location-state-id.ts +177 -0
- package/src/vite/index.ts +787 -0
- package/src/vite/package-resolution.ts +125 -0
- package/src/vite/version.d.ts +12 -0
- package/src/vite/virtual-entries.ts +109 -0
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/// <reference path="../../vite/version.d.ts" />
|
|
2
|
+
|
|
3
|
+
// Extend CacheStorage with Cloudflare's default cache property
|
|
4
|
+
declare global {
|
|
5
|
+
interface CacheStorage {
|
|
6
|
+
readonly default: Cache;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Cloudflare Edge Cache Store
|
|
12
|
+
*
|
|
13
|
+
* Production cache store using Cloudflare's Cache API.
|
|
14
|
+
* Handles SWR atomically - get() checks staleness and marks REVALIDATING in one operation.
|
|
15
|
+
*
|
|
16
|
+
* Features:
|
|
17
|
+
* - Extended TTL for SWR window (max-age = ttl + swr)
|
|
18
|
+
* - Staleness via x-edge-cache-stale-at header
|
|
19
|
+
* - Atomic REVALIDATING status for thundering herd prevention
|
|
20
|
+
* - Non-blocking writes via waitUntil
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type {
|
|
24
|
+
SegmentCacheStore,
|
|
25
|
+
CachedEntryData,
|
|
26
|
+
CacheDefaults,
|
|
27
|
+
CacheGetResult,
|
|
28
|
+
} from "../types.js";
|
|
29
|
+
import {
|
|
30
|
+
getRequestContext,
|
|
31
|
+
type RequestContext,
|
|
32
|
+
} from "../../server/request-context.js";
|
|
33
|
+
import { VERSION } from "@rangojs/router:version";
|
|
34
|
+
|
|
35
|
+
// ============================================================================
|
|
36
|
+
// Constants
|
|
37
|
+
// ============================================================================
|
|
38
|
+
|
|
39
|
+
/** Header storing timestamp when entry becomes stale */
|
|
40
|
+
export const CACHE_STALE_AT_HEADER = "x-edge-cache-stale-at";
|
|
41
|
+
|
|
42
|
+
/** Header storing cache status: HIT | REVALIDATING */
|
|
43
|
+
export const CACHE_STATUS_HEADER = "x-edge-cache-status";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Maximum age in seconds for REVALIDATING status before allowing new revalidation.
|
|
47
|
+
* After this period, a stale entry in REVALIDATING status will trigger revalidation again.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
export const MAX_REVALIDATION_INTERVAL = 30;
|
|
51
|
+
|
|
52
|
+
// ============================================================================
|
|
53
|
+
// Types
|
|
54
|
+
// ============================================================================
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Cloudflare Workers ExecutionContext (subset we need)
|
|
58
|
+
*/
|
|
59
|
+
export interface ExecutionContext {
|
|
60
|
+
waitUntil(promise: Promise<any>): void;
|
|
61
|
+
passThroughOnException(): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface CFCacheStoreOptions<TEnv = unknown> {
|
|
65
|
+
/**
|
|
66
|
+
* Cache namespace. If not provided, uses caches.default (recommended).
|
|
67
|
+
* Only set this if you need isolated cache storage.
|
|
68
|
+
*/
|
|
69
|
+
namespace?: string;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Base URL for cache keys.
|
|
73
|
+
*
|
|
74
|
+
* If not provided, derives from request hostname via requestContext:
|
|
75
|
+
* - Production domains → uses `https://{hostname}/`
|
|
76
|
+
* - Dev/preview (localhost, workers.dev, pages.dev) → uses internal fallback URL
|
|
77
|
+
*/
|
|
78
|
+
baseUrl?: string;
|
|
79
|
+
|
|
80
|
+
/** Default cache options */
|
|
81
|
+
defaults?: CacheDefaults;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Cloudflare ExecutionContext for non-blocking cache writes.
|
|
85
|
+
* Pass the `ctx` from your worker's fetch handler.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* new CFCacheStore({ ctx: env.ctx })
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
ctx: ExecutionContext;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Cache version string override. When this changes, all cached entries are
|
|
96
|
+
* effectively invalidated (new keys won't match old entries).
|
|
97
|
+
*
|
|
98
|
+
* Defaults to the auto-generated VERSION from `rsc-router:version` virtual module.
|
|
99
|
+
* Only set this if you need a custom versioning strategy.
|
|
100
|
+
*/
|
|
101
|
+
version?: string;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Custom key generator applied to all cache operations.
|
|
105
|
+
* Receives the full RequestContext (including env) and the default-generated key.
|
|
106
|
+
* Return value becomes the final cache key (unless route overrides with `key` option).
|
|
107
|
+
*
|
|
108
|
+
* @example Using headers for user segmentation
|
|
109
|
+
* ```typescript
|
|
110
|
+
* keyGenerator: (ctx, defaultKey) => {
|
|
111
|
+
* const segment = ctx.request.headers.get('x-user-segment') || 'default';
|
|
112
|
+
* return `${segment}:${defaultKey}`;
|
|
113
|
+
* }
|
|
114
|
+
* ```
|
|
115
|
+
*
|
|
116
|
+
* @example Using env bindings for multi-region
|
|
117
|
+
* ```typescript
|
|
118
|
+
* keyGenerator: (ctx, defaultKey) => {
|
|
119
|
+
* const region = ctx.env.REGION || 'us';
|
|
120
|
+
* return `${region}:${defaultKey}`;
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*
|
|
124
|
+
* @example Using cookies for locale-aware caching
|
|
125
|
+
* ```typescript
|
|
126
|
+
* keyGenerator: (ctx, defaultKey) => {
|
|
127
|
+
* const locale = ctx.cookie('locale') || 'en';
|
|
128
|
+
* return `${locale}:${defaultKey}`;
|
|
129
|
+
* }
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
keyGenerator?: (
|
|
133
|
+
ctx: RequestContext<TEnv>,
|
|
134
|
+
defaultKey: string,
|
|
135
|
+
) => string | Promise<string>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Cache status values for the x-edge-cache-status header.
|
|
140
|
+
* @internal
|
|
141
|
+
*/
|
|
142
|
+
export type CacheStatus = "HIT" | "REVALIDATING";
|
|
143
|
+
|
|
144
|
+
// ============================================================================
|
|
145
|
+
// CFCacheStore Implementation
|
|
146
|
+
// ============================================================================
|
|
147
|
+
|
|
148
|
+
export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
|
|
149
|
+
readonly defaults?: CacheDefaults;
|
|
150
|
+
readonly keyGenerator?: (
|
|
151
|
+
ctx: RequestContext<TEnv>,
|
|
152
|
+
defaultKey: string,
|
|
153
|
+
) => string | Promise<string>;
|
|
154
|
+
|
|
155
|
+
private readonly namespace?: string;
|
|
156
|
+
private readonly baseUrl: string;
|
|
157
|
+
private readonly waitUntil?: (fn: () => Promise<void>) => void;
|
|
158
|
+
private readonly version?: string;
|
|
159
|
+
|
|
160
|
+
constructor(options: CFCacheStoreOptions<TEnv>) {
|
|
161
|
+
if (!options.ctx) {
|
|
162
|
+
throw new Error(
|
|
163
|
+
"[CFCacheStore] ExecutionContext (ctx) is required. " +
|
|
164
|
+
"Pass the Cloudflare ExecutionContext from your worker's fetch handler: " +
|
|
165
|
+
"new CFCacheStore({ ctx: env.ctx })",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
this.namespace = options.namespace;
|
|
170
|
+
this.baseUrl = options.baseUrl ?? this.deriveBaseUrl();
|
|
171
|
+
this.defaults = options.defaults;
|
|
172
|
+
this.version = options.version ?? VERSION;
|
|
173
|
+
this.keyGenerator = options.keyGenerator;
|
|
174
|
+
this.waitUntil = (fn) => options.ctx.waitUntil(fn());
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Derive base URL from request hostname via requestContext.
|
|
179
|
+
* Uses internal fallback for dev/preview environments.
|
|
180
|
+
* @internal
|
|
181
|
+
*/
|
|
182
|
+
private deriveBaseUrl(): string {
|
|
183
|
+
const fallback = "https://rsc-cache.internal.com/";
|
|
184
|
+
|
|
185
|
+
const ctx = getRequestContext();
|
|
186
|
+
if (!ctx?.request) {
|
|
187
|
+
return fallback;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
const url = new URL(ctx.request.url);
|
|
192
|
+
const hostname = url.hostname;
|
|
193
|
+
|
|
194
|
+
// Use fallback for dev/preview environments
|
|
195
|
+
if (
|
|
196
|
+
hostname === "localhost" ||
|
|
197
|
+
hostname === "127.0.0.1" ||
|
|
198
|
+
hostname.endsWith(".workers.dev") ||
|
|
199
|
+
hostname.endsWith(".pages.dev")
|
|
200
|
+
) {
|
|
201
|
+
return fallback;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Use actual hostname for production
|
|
205
|
+
return `https://${hostname}/`;
|
|
206
|
+
} catch {
|
|
207
|
+
return fallback;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Get the cache instance - uses caches.default unless namespace is specified.
|
|
213
|
+
* @internal
|
|
214
|
+
*/
|
|
215
|
+
private getCache(): Cache | Promise<Cache> {
|
|
216
|
+
if (this.namespace) {
|
|
217
|
+
return caches.open(this.namespace);
|
|
218
|
+
}
|
|
219
|
+
return caches.default;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Get cached entry data by key.
|
|
224
|
+
*
|
|
225
|
+
* Handles SWR atomically:
|
|
226
|
+
* - If stale and not already revalidating, marks as REVALIDATING and returns shouldRevalidate: true
|
|
227
|
+
* - If already REVALIDATING (and recent), returns shouldRevalidate: false
|
|
228
|
+
* - If fresh, returns shouldRevalidate: false
|
|
229
|
+
*
|
|
230
|
+
* The atomic mark prevents thundering herd - only first request triggers revalidation.
|
|
231
|
+
*/
|
|
232
|
+
async get(key: string): Promise<CacheGetResult | null> {
|
|
233
|
+
try {
|
|
234
|
+
const cache = await this.getCache();
|
|
235
|
+
const request = this.keyToRequest(key);
|
|
236
|
+
const response = await cache.match(request);
|
|
237
|
+
|
|
238
|
+
if (!response) {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Read status headers
|
|
243
|
+
const status = response.headers.get(CACHE_STATUS_HEADER);
|
|
244
|
+
const age = Number(response.headers.get("age") ?? "0");
|
|
245
|
+
const staleAt = Number(
|
|
246
|
+
response.headers.get(CACHE_STALE_AT_HEADER) ?? "0",
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
const isStale = staleAt > 0 && Date.now() > staleAt;
|
|
250
|
+
const isRevalidating =
|
|
251
|
+
status === "REVALIDATING" && age < MAX_REVALIDATION_INTERVAL;
|
|
252
|
+
|
|
253
|
+
// Case 1: Fresh or already being revalidated - just return data
|
|
254
|
+
if (!isStale || isRevalidating) {
|
|
255
|
+
const data = (await response.json()) as CachedEntryData;
|
|
256
|
+
return { data, shouldRevalidate: false };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Case 2: Stale and needs revalidation - atomically mark REVALIDATING
|
|
260
|
+
const [b1, b2] = response.body!.tee();
|
|
261
|
+
|
|
262
|
+
const headers = new Headers(response.headers);
|
|
263
|
+
headers.set(CACHE_STATUS_HEADER, "REVALIDATING");
|
|
264
|
+
|
|
265
|
+
// Blocking write - must complete before returning to prevent race
|
|
266
|
+
await cache.put(
|
|
267
|
+
request,
|
|
268
|
+
new Response(b1, { status: response.status, headers }),
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
const data = (await new Response(b2).json()) as CachedEntryData;
|
|
272
|
+
return { data, shouldRevalidate: true };
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.error("[CFCacheStore] get failed:", error);
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Store entry data with TTL and optional SWR window.
|
|
281
|
+
* Uses waitUntil for non-blocking write when available.
|
|
282
|
+
*/
|
|
283
|
+
async set(
|
|
284
|
+
key: string,
|
|
285
|
+
data: CachedEntryData,
|
|
286
|
+
ttl: number,
|
|
287
|
+
swr?: number,
|
|
288
|
+
): Promise<void> {
|
|
289
|
+
try {
|
|
290
|
+
const cache = await this.getCache();
|
|
291
|
+
const request = this.keyToRequest(key);
|
|
292
|
+
|
|
293
|
+
// Extended TTL covers SWR window
|
|
294
|
+
const swrWindow = swr ?? this.defaults?.swr ?? 0;
|
|
295
|
+
const totalTtl = ttl + swrWindow;
|
|
296
|
+
const staleAt = Date.now() + ttl * 1000;
|
|
297
|
+
|
|
298
|
+
const response = new Response(JSON.stringify(data), {
|
|
299
|
+
headers: {
|
|
300
|
+
"Content-Type": "application/json",
|
|
301
|
+
"Cache-Control": `public, max-age=${totalTtl}`,
|
|
302
|
+
[CACHE_STALE_AT_HEADER]: String(staleAt),
|
|
303
|
+
[CACHE_STATUS_HEADER]: "HIT",
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
const putPromise = cache.put(request, response);
|
|
308
|
+
|
|
309
|
+
if (this.waitUntil) {
|
|
310
|
+
// Non-blocking write
|
|
311
|
+
this.waitUntil(async () => {
|
|
312
|
+
await putPromise;
|
|
313
|
+
});
|
|
314
|
+
} else {
|
|
315
|
+
// Blocking fallback
|
|
316
|
+
await putPromise;
|
|
317
|
+
}
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.error("[CFCacheStore] set failed:", error);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Delete a cached entry
|
|
325
|
+
*/
|
|
326
|
+
async delete(key: string): Promise<boolean> {
|
|
327
|
+
try {
|
|
328
|
+
const cache = await this.getCache();
|
|
329
|
+
return await cache.delete(this.keyToRequest(key));
|
|
330
|
+
} catch (error) {
|
|
331
|
+
console.error("[CFCacheStore] delete failed:", error);
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ============================================================================
|
|
337
|
+
// Document Cache Methods
|
|
338
|
+
// ============================================================================
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Get a cached Response by key (for document-level caching).
|
|
342
|
+
* Returns the response and whether it should be revalidated (SWR).
|
|
343
|
+
*/
|
|
344
|
+
async getResponse(
|
|
345
|
+
key: string,
|
|
346
|
+
): Promise<{ response: Response; shouldRevalidate: boolean } | null> {
|
|
347
|
+
try {
|
|
348
|
+
const cache = await this.getCache();
|
|
349
|
+
const request = this.keyToRequest(`doc:${key}`);
|
|
350
|
+
const response = await cache.match(request);
|
|
351
|
+
|
|
352
|
+
if (!response || response.status !== 200) {
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// Check staleness
|
|
357
|
+
const staleAt = Number(response.headers.get(CACHE_STALE_AT_HEADER) || 0);
|
|
358
|
+
const isStale = staleAt > 0 && Date.now() > staleAt;
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
response,
|
|
362
|
+
shouldRevalidate: isStale,
|
|
363
|
+
};
|
|
364
|
+
} catch (error) {
|
|
365
|
+
console.error("[CFCacheStore] getResponse failed:", error);
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Store a Response with TTL and optional SWR window (for document-level caching).
|
|
372
|
+
*/
|
|
373
|
+
async putResponse(
|
|
374
|
+
key: string,
|
|
375
|
+
response: Response,
|
|
376
|
+
ttl: number,
|
|
377
|
+
swr?: number,
|
|
378
|
+
): Promise<void> {
|
|
379
|
+
try {
|
|
380
|
+
const cache = await this.getCache();
|
|
381
|
+
const request = this.keyToRequest(`doc:${key}`);
|
|
382
|
+
|
|
383
|
+
// Extended TTL covers SWR window
|
|
384
|
+
const swrWindow = swr ?? this.defaults?.swr ?? 0;
|
|
385
|
+
const totalTtl = ttl + swrWindow;
|
|
386
|
+
const staleAt = Date.now() + ttl * 1000;
|
|
387
|
+
|
|
388
|
+
// Clone and add cache headers
|
|
389
|
+
const headers = new Headers(response.headers);
|
|
390
|
+
headers.set("Cache-Control", `public, max-age=${totalTtl}`);
|
|
391
|
+
headers.set(CACHE_STALE_AT_HEADER, String(staleAt));
|
|
392
|
+
|
|
393
|
+
const toCache = new Response(response.body, {
|
|
394
|
+
status: response.status,
|
|
395
|
+
statusText: response.statusText,
|
|
396
|
+
headers,
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const putPromise = cache.put(request, toCache);
|
|
400
|
+
|
|
401
|
+
if (this.waitUntil) {
|
|
402
|
+
// Non-blocking write
|
|
403
|
+
this.waitUntil(async () => {
|
|
404
|
+
await putPromise;
|
|
405
|
+
});
|
|
406
|
+
} else {
|
|
407
|
+
// Blocking fallback
|
|
408
|
+
await putPromise;
|
|
409
|
+
}
|
|
410
|
+
} catch (error) {
|
|
411
|
+
console.error("[CFCacheStore] putResponse failed:", error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Convert string key to Request object for CF Cache API.
|
|
417
|
+
* Includes version in URL if specified (for cache invalidation on code changes).
|
|
418
|
+
* @internal
|
|
419
|
+
*/
|
|
420
|
+
private keyToRequest(key: string): Request {
|
|
421
|
+
const encodedKey = encodeURIComponent(key);
|
|
422
|
+
// Include version in URL path to invalidate cache when version changes
|
|
423
|
+
const versionPath = this.version ? `v/${this.version}/` : "";
|
|
424
|
+
return new Request(`${this.baseUrl}${versionPath}${encodedKey}`, {
|
|
425
|
+
method: "GET",
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Cache Store Exports
|
|
3
|
+
*
|
|
4
|
+
* Main export:
|
|
5
|
+
* - CFCacheStore - Production cache store using Cloudflare's Cache API
|
|
6
|
+
*
|
|
7
|
+
* Header constants (for inspection/debugging):
|
|
8
|
+
* - CACHE_STALE_AT_HEADER - Header containing staleness timestamp
|
|
9
|
+
* - CACHE_STATUS_HEADER - Header containing HIT/REVALIDATING status
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// Public API
|
|
13
|
+
export { CFCacheStore, type CFCacheStoreOptions } from "./cf-cache-store.js";
|
|
14
|
+
|
|
15
|
+
// Header constants for debugging and inspection
|
|
16
|
+
export { CACHE_STALE_AT_HEADER, CACHE_STATUS_HEADER } from "./cf-cache-store.js";
|
|
17
|
+
|
|
18
|
+
// Internal exports (re-exported for backwards compatibility, marked @internal in source)
|
|
19
|
+
export { type CacheStatus, MAX_REVALIDATION_INTERVAL } from "./cf-cache-store.js";
|