isr-engine 4.1.0 → 4.3.0

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.
Files changed (104) hide show
  1. package/README.md +9 -0
  2. package/dist/CacheTagContext-Btmq8KCD.js +69 -0
  3. package/dist/CacheTagContext-Btmq8KCD.js.map +1 -0
  4. package/dist/{abVariantContext-CGBlCt0q.js → abVariantContext-yWZOqscY.js} +118 -38
  5. package/dist/abVariantContext-yWZOqscY.js.map +1 -0
  6. package/dist/cache/RedisInvalidationBus.d.ts.map +1 -1
  7. package/dist/cache/RedisResponseCacheBackend.d.ts +1 -0
  8. package/dist/cache/RedisResponseCacheBackend.d.ts.map +1 -1
  9. package/dist/cache/ResponseCacheBackend.d.ts +6 -0
  10. package/dist/cache/ResponseCacheBackend.d.ts.map +1 -1
  11. package/dist/cli/cli.js +1 -1
  12. package/dist/config/defineConfig.js +1 -1
  13. package/dist/context/CacheTagContext.d.ts +10 -0
  14. package/dist/context/CacheTagContext.d.ts.map +1 -0
  15. package/dist/{createCacheInspectorMiddleware-D6c-CINz.js → createCacheInspectorMiddleware-glgtcBcQ.js} +2 -2
  16. package/dist/{createCacheInspectorMiddleware-D6c-CINz.js.map → createCacheInspectorMiddleware-glgtcBcQ.js.map} +1 -1
  17. package/dist/createCachedFetcher-CgJscexq.js +186 -0
  18. package/dist/createCachedFetcher-CgJscexq.js.map +1 -0
  19. package/dist/{createISRApp-DTlZvKBm.js → createISRApp-BG-s3uuL.js} +356 -162
  20. package/dist/createISRApp-BG-s3uuL.js.map +1 -0
  21. package/dist/defaults/runtime/contentRevalidation.d.ts +26 -0
  22. package/dist/defaults/runtime/contentRevalidation.d.ts.map +1 -0
  23. package/dist/defaults/runtime/createCachedFetcher.d.ts +8 -2
  24. package/dist/defaults/runtime/createCachedFetcher.d.ts.map +1 -1
  25. package/dist/defaults/runtime/defineSiteHooks.d.ts +4 -7
  26. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
  27. package/dist/defaults/runtime/defineSiteHooks.js +655 -2
  28. package/dist/defaults/runtime/defineSiteHooks.js.map +1 -0
  29. package/dist/defaults/runtime/locale-links.client.d.ts.map +1 -1
  30. package/dist/defaults/runtime/renderCancellation.d.ts +3 -0
  31. package/dist/defaults/runtime/renderCancellation.d.ts.map +1 -0
  32. package/dist/engine/ISREngine.d.ts.map +1 -1
  33. package/dist/engine/seo/SEOEngine.d.ts +3 -0
  34. package/dist/engine/seo/SEOEngine.d.ts.map +1 -1
  35. package/dist/engine/seo/resolveSeoConfig.d.ts +6 -0
  36. package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -1
  37. package/dist/{i18n-B2mWmifk.js → i18n-BZpAOZeO.js} +3 -2
  38. package/dist/{i18n-B2mWmifk.js.map → i18n-BZpAOZeO.js.map} +1 -1
  39. package/dist/index.d.ts +2 -2
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/isr/ISRRoutes.d.ts +2 -0
  42. package/dist/isr/ISRRoutes.d.ts.map +1 -1
  43. package/dist/isr-engine.js +7 -7
  44. package/dist/middlewares/LocaleRedirect.d.ts +4 -3
  45. package/dist/middlewares/LocaleRedirect.d.ts.map +1 -1
  46. package/dist/plugin/coherentCacheStore.d.ts.map +1 -1
  47. package/dist/plugin/isrCacheMiddleware.d.ts +7 -6
  48. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  49. package/dist/plugin/isrCacheStore.d.ts +2 -0
  50. package/dist/plugin/isrCacheStore.d.ts.map +1 -1
  51. package/dist/rsc/browser.d.ts +3 -0
  52. package/dist/rsc/browser.d.ts.map +1 -1
  53. package/dist/rsc/browser.js +4 -9
  54. package/dist/rsc/browser.js.map +1 -1
  55. package/dist/rsc/cacheTag.d.ts +1 -8
  56. package/dist/rsc/cacheTag.d.ts.map +1 -1
  57. package/dist/rsc/index.d.ts +1 -1
  58. package/dist/rsc/index.d.ts.map +1 -1
  59. package/dist/rsc/index.js +4 -3
  60. package/dist/rsc/revalidate.d.ts +18 -9
  61. package/dist/rsc/revalidate.d.ts.map +1 -1
  62. package/dist/{rsc-DWwcqD4W.js → rsc-BYq2vvnh.js} +2 -2
  63. package/dist/{rsc-DWwcqD4W.js.map → rsc-BYq2vvnh.js.map} +1 -1
  64. package/dist/runtime/LocaleLink.d.ts.map +1 -1
  65. package/dist/runtime/i18n.d.ts +3 -0
  66. package/dist/runtime/i18n.d.ts.map +1 -1
  67. package/dist/runtime/localePreference.d.ts +7 -0
  68. package/dist/runtime/localePreference.d.ts.map +1 -0
  69. package/dist/server/contentRevalidationRoute.d.ts +4 -0
  70. package/dist/server/contentRevalidationRoute.d.ts.map +1 -0
  71. package/dist/server/manager.d.ts.map +1 -1
  72. package/dist/server/opsConfig.d.ts +6 -1
  73. package/dist/server/opsConfig.d.ts.map +1 -1
  74. package/dist/server/productionRuntime.d.ts +2 -0
  75. package/dist/server/productionRuntime.d.ts.map +1 -1
  76. package/dist/server/publishedSitemap.d.ts +8 -0
  77. package/dist/server/publishedSitemap.d.ts.map +1 -0
  78. package/dist/types/ISRConfig.d.ts +27 -0
  79. package/dist/types/ISRConfig.d.ts.map +1 -1
  80. package/dist/utils/cookie.d.ts +2 -2
  81. package/dist/utils/cookie.d.ts.map +1 -1
  82. package/dist/utils/isrPath.d.ts +6 -0
  83. package/dist/utils/isrPath.d.ts.map +1 -0
  84. package/package.json +2 -2
  85. package/src/context/CacheTagContext.ts +20 -0
  86. package/src/defaults/entry.server.ssr.tsx +10 -0
  87. package/src/defaults/runtime/contentRevalidation.ts +96 -0
  88. package/src/defaults/runtime/createCachedFetcher.ts +76 -20
  89. package/src/defaults/runtime/defineServerEntry.tsx +30 -29
  90. package/src/defaults/runtime/defineSiteHooks.ts +117 -80
  91. package/src/defaults/runtime/locale-links.client.ts +14 -4
  92. package/src/defaults/runtime/renderCancellation.ts +10 -0
  93. package/src/runtime/LocaleLink.tsx +8 -2
  94. package/src/runtime/i18n.ts +4 -0
  95. package/src/runtime/localePreference.ts +36 -0
  96. package/src/types/ISRConfig.ts +29 -0
  97. package/src/utils/cookie.ts +11 -4
  98. package/src/utils/isrPath.ts +24 -0
  99. package/dist/abVariantContext-CGBlCt0q.js.map +0 -1
  100. package/dist/cookie-DcUeYm6E.js +0 -42
  101. package/dist/cookie-DcUeYm6E.js.map +0 -1
  102. package/dist/createISRApp-DTlZvKBm.js.map +0 -1
  103. package/dist/defineSiteHooks-iwLiVChy.js +0 -716
  104. package/dist/defineSiteHooks-iwLiVChy.js.map +0 -1
@@ -0,0 +1,96 @@
1
+ /** Data and response cache scopes to invalidate after a content write commits. */
2
+ export interface ContentRevalidationOptions {
3
+ /** Exact site paths, including any locale prefix. */
4
+ paths?: readonly string[];
5
+ /** Business pathnames expanded using the runtime's routing config and the supplied locales. */
6
+ localizedPaths?: readonly string[];
7
+ tags?: readonly string[];
8
+ locales?: readonly string[];
9
+ sitemap?: boolean;
10
+ }
11
+
12
+ export interface ContentPublication {
13
+ id: string;
14
+ scopes: Readonly<Omit<Required<ContentRevalidationOptions>, 'localizedPaths'>>;
15
+ }
16
+
17
+ type ContentInvalidation = ContentPublication['scopes'] & { allPageMetadata?: true };
18
+ type ContentInvalidator = (scopes: ContentInvalidation) => void;
19
+
20
+ // Node, the RSC bundle, and the published site-hooks entry have separate module graphs.
21
+ const KEY = Symbol.for('isr-engine:content-invalidators');
22
+ const runtime = globalThis as typeof globalThis & {
23
+ [KEY]?: Set<ContentInvalidator | WeakRef<ContentInvalidator>>;
24
+ };
25
+
26
+ export function registerContentInvalidator(
27
+ invalidate: ContentInvalidator,
28
+ { weak = false } = {}
29
+ ): () => void {
30
+ const registry = (runtime[KEY] ??= new Set());
31
+ for (const entry of registry) {
32
+ if (typeof entry !== 'function' && !entry.deref()) registry.delete(entry);
33
+ }
34
+ const entry = weak ? new WeakRef(invalidate) : invalidate;
35
+ registry.add(entry);
36
+ return () => {
37
+ registry.delete(entry);
38
+ };
39
+ }
40
+
41
+ /** The default scope recovers page metadata after a missed Redis notification. */
42
+ export function invalidateContentCaches(
43
+ scopes: ContentInvalidation = {
44
+ paths: [],
45
+ tags: [],
46
+ locales: [],
47
+ sitemap: false,
48
+ allPageMetadata: true,
49
+ }
50
+ ): void {
51
+ const errors: unknown[] = [];
52
+ const registry = runtime[KEY];
53
+ if (!registry) return;
54
+ for (const entry of registry) {
55
+ const invalidate = typeof entry === 'function' ? entry : entry.deref();
56
+ if (!invalidate) {
57
+ registry.delete(entry);
58
+ continue;
59
+ }
60
+ try {
61
+ invalidate(scopes);
62
+ } catch (error) {
63
+ errors.push(error);
64
+ }
65
+ }
66
+ if (errors.length) throw new AggregateError(errors, 'Content metadata invalidation failed');
67
+ }
68
+
69
+ export function normalizeContentScopes(
70
+ input: unknown
71
+ ): ContentPublication['scopes'] & Pick<ContentRevalidationOptions, 'localizedPaths'> {
72
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
73
+ throw new TypeError('Invalid content revalidation scopes');
74
+ }
75
+ const { paths, localizedPaths, tags, locales, sitemap } = input as ContentRevalidationOptions;
76
+ function read(values: unknown): string[] {
77
+ if (values === undefined) return [];
78
+ if (
79
+ !Array.isArray(values) ||
80
+ Array.from(values).some(value => typeof value !== 'string' || !value.trim())
81
+ ) {
82
+ throw new TypeError('Content revalidation scopes must contain non-empty strings');
83
+ }
84
+ return values;
85
+ }
86
+ if (sitemap !== undefined && typeof sitemap !== 'boolean') {
87
+ throw new TypeError('Content revalidation sitemap must be a boolean');
88
+ }
89
+ return {
90
+ paths: [...new Set(read(paths))],
91
+ ...(localizedPaths !== undefined && { localizedPaths: [...new Set(read(localizedPaths))] }),
92
+ tags: [...new Set(read(tags))],
93
+ locales: [...new Set(read(locales).map(locale => locale.trim().toLowerCase()))],
94
+ sitemap: sitemap ?? false,
95
+ };
96
+ }
@@ -46,50 +46,101 @@ class TinyLRU<K, V> {
46
46
  if (oldest !== undefined) this.store.delete(oldest);
47
47
  }
48
48
  }
49
+
50
+ deleteWhere(matches: (value: V) => boolean): void {
51
+ for (const [key, value] of this.store) {
52
+ if (matches(value)) this.store.delete(key);
53
+ }
54
+ }
49
55
  }
50
56
 
51
57
  export interface CachedFetcherOptions<TArg, TValue> {
52
58
  /** 从入参生成缓存 key */
53
59
  key: (arg: TArg) => string;
54
60
  /** 实际加载逻辑(network / fs / dynamic import 都可) */
55
- fetch: (arg: TArg) => Promise<TValue>;
61
+ fetch: (arg: TArg, markDegraded?: () => void) => Promise<TValue>;
56
62
  /** 缓存 TTL(毫秒),默认 60s */
57
63
  ttl?: number;
58
64
  /** LRU 容量,默认 500 */
59
65
  max?: number;
60
66
  /** 启用 stale-while-revalidate:过期仍返回旧值,后台异步刷新(默认 false) */
61
67
  swr?: boolean;
68
+ /** Maximum time after expiry to reuse the last successful value on refresh errors. */
69
+ staleIfErrorMs?: number;
70
+ /** Called in each consumer's context when it receives a stale or degraded result. */
71
+ onDegraded?: () => void;
62
72
  /** 拉取失败时的回退值(如不提供则抛错) */
63
73
  fallback?: (arg: TArg, error: unknown) => TValue | Promise<TValue>;
64
74
  }
65
75
 
66
- interface Entry<T> {
67
- value: T;
76
+ interface Entry<TArg, TValue> {
77
+ arg: TArg;
78
+ value: TValue;
68
79
  expiresAt: number;
69
80
  }
70
81
 
82
+ interface LoadResult<TValue> {
83
+ value: TValue;
84
+ degraded: boolean;
85
+ }
86
+
71
87
  export type CachedFetcher<TArg, TValue> = (arg: TArg) => Promise<TValue>;
72
88
 
73
89
  export function createCachedFetcher<TArg, TValue>(
74
90
  opts: CachedFetcherOptions<TArg, TValue>
75
- ): CachedFetcher<TArg, TValue> {
91
+ ): CachedFetcher<TArg, TValue> & { invalidate(matches?: (arg: TArg) => boolean): void } {
76
92
  const ttl = opts.ttl ?? 60_000;
77
93
  const max = opts.max ?? 500;
78
- const cache = new TinyLRU<string, Entry<TValue>>(max);
79
- const inflight = new Map<string, Promise<TValue>>();
94
+ const staleIfErrorMs = opts.staleIfErrorMs ?? 0;
95
+ if (!Number.isSafeInteger(staleIfErrorMs) || staleIfErrorMs < 0) {
96
+ throw new RangeError('staleIfErrorMs must be a non-negative safe integer');
97
+ }
98
+ type Flight = { arg: TArg; promise?: Promise<LoadResult<TValue>> };
99
+ const cache = new TinyLRU<string, Entry<TArg, TValue>>(max);
100
+ const inflight = new Map<string, Flight>();
80
101
 
81
- async function load(arg: TArg): Promise<TValue> {
102
+ async function load(
103
+ key: string,
104
+ flight: Flight,
105
+ previous?: Entry<TArg, TValue>
106
+ ): Promise<LoadResult<TValue>> {
82
107
  try {
83
- const v = await opts.fetch(arg);
84
- cache.set(opts.key(arg), { value: v, expiresAt: Date.now() + ttl });
85
- return v;
108
+ let degraded = false;
109
+ const value = await opts.fetch(flight.arg, () => {
110
+ degraded = true;
111
+ });
112
+ if (!degraded && inflight.get(key) === flight) {
113
+ cache.set(key, { arg: flight.arg, value, expiresAt: Date.now() + ttl });
114
+ }
115
+ return { value, degraded };
86
116
  } catch (err) {
87
- if (opts.fallback) return await opts.fallback(arg, err);
117
+ if (
118
+ previous &&
119
+ staleIfErrorMs > 0 &&
120
+ inflight.get(key) === flight &&
121
+ Date.now() - previous.expiresAt < staleIfErrorMs
122
+ ) {
123
+ return { value: previous.value, degraded: true };
124
+ }
125
+ if (opts.fallback) return { value: await opts.fallback(flight.arg, err), degraded: true };
88
126
  throw err;
89
127
  }
90
128
  }
91
129
 
92
- return async function cachedFetcher(arg: TArg): Promise<TValue> {
130
+ function startLoad(
131
+ key: string,
132
+ arg: TArg,
133
+ previous?: Entry<TArg, TValue>
134
+ ): Promise<LoadResult<TValue>> {
135
+ const flight: Flight = { arg };
136
+ inflight.set(key, flight);
137
+ flight.promise = load(key, flight, previous).finally(() => {
138
+ if (inflight.get(key) === flight) inflight.delete(key);
139
+ });
140
+ return flight.promise;
141
+ }
142
+
143
+ async function cachedFetcher(arg: TArg): Promise<TValue> {
93
144
  const key = opts.key(arg);
94
145
  const entry = cache.get(key);
95
146
  const now = Date.now();
@@ -101,21 +152,26 @@ export function createCachedFetcher<TArg, TValue>(
101
152
  if (entry && opts.swr) {
102
153
  // SWR:返回旧值,后台刷新(不阻塞);如已有 in-flight 则不重复触发
103
154
  if (!inflight.has(key)) {
104
- const p = load(arg).finally(() => inflight.delete(key));
105
- inflight.set(key, p);
106
- p.catch(() => {
155
+ startLoad(key, arg).catch(() => {
107
156
  /* 后台刷新失败保留旧值 */
108
157
  });
109
158
  }
159
+ opts.onDegraded?.();
110
160
  return entry.value;
111
161
  }
112
162
 
113
163
  // miss 或非 SWR 过期:合并并发到同一个 promise
114
- const existing = inflight.get(key);
115
- if (existing) return existing;
164
+ const result = await (inflight.get(key)?.promise ?? startLoad(key, arg, entry));
165
+ if (result.degraded) opts.onDegraded?.();
166
+ return result.value;
167
+ }
116
168
 
117
- const p = load(arg).finally(() => inflight.delete(key));
118
- inflight.set(key, p);
119
- return p;
169
+ cachedFetcher.invalidate = (matches: (arg: TArg) => boolean = () => true): void => {
170
+ cache.deleteWhere(entry => matches(entry.arg));
171
+ for (const [key, flight] of inflight) {
172
+ if (matches(flight.arg)) inflight.delete(key);
173
+ }
120
174
  };
175
+
176
+ return cachedFetcher;
121
177
  }
@@ -52,6 +52,8 @@ import {
52
52
  } from '../../runtime/i18n';
53
53
  import type { RuntimeConfig } from '../../types/ISRConfig';
54
54
  import { getRequestContext } from '../../context/RequestContext';
55
+ import { markUncacheable } from '../../context/CacheTagContext';
56
+ import { createRenderErrorHandler, isRenderCancellation } from './renderCancellation';
55
57
 
56
58
  interface DefaultRscPayload {
57
59
  root: React.ReactNode;
@@ -194,6 +196,7 @@ export function defineServerEntry<C extends ServerCtx = ServerCtx>(
194
196
  let ctx: C = { ...(requestStore ?? {}), ...engineCtx } as C;
195
197
 
196
198
  try {
199
+ request.signal.throwIfAborted();
197
200
  if (hooks.beforeRequest) {
198
201
  const userExt = (await hooks.beforeRequest(request, engineCtx)) ?? {};
199
202
  ctx = { ...(requestStore ?? {}), ...engineCtx, ...userExt } as C;
@@ -274,8 +277,12 @@ export function defineServerEntry<C extends ServerCtx = ServerCtx>(
274
277
  }
275
278
  return response;
276
279
  } catch (err) {
280
+ if (isRenderCancellation(request.signal, err)) return new Response(null, { status: 204 });
277
281
  if (isNoAcceptableLocaleError(err)) {
278
- return new Response(null, { status: 406, headers: { vary: 'Accept-Language, Cookie' } });
282
+ return new Response(null, {
283
+ status: 406,
284
+ headers: { vary: 'Accept-Language, Cookie', 'cache-control': 'no-store' },
285
+ });
279
286
  }
280
287
  if (hooks.onError) {
281
288
  try {
@@ -307,6 +314,18 @@ async function runRscPipeline(
307
314
  ): Promise<Response> {
308
315
  const { request } = renderRequest;
309
316
  const responseRouteStatus = renderRequest.isAction ? undefined : extras.routeStatus;
317
+ const signal = request.signal;
318
+ signal.throwIfAborted();
319
+ const responseHeaders = new Headers({
320
+ 'content-type': renderRequest.isRsc
321
+ ? 'text/x-component;charset=utf-8'
322
+ : 'text/html; charset=utf-8',
323
+ });
324
+ if (request.method === 'HEAD') {
325
+ // The header-only response has no dependency tags from the component tree.
326
+ markUncacheable();
327
+ return new Response(null, { status: responseRouteStatus, headers: responseHeaders });
328
+ }
310
329
 
311
330
  let returnValue: DefaultRscPayload['returnValue'] | undefined;
312
331
  let formState: ReactFormState | undefined;
@@ -351,45 +370,28 @@ async function runRscPipeline(
351
370
  formState,
352
371
  returnValue,
353
372
  };
373
+ const renderOptions = { temporaryReferences, signal, onError: createRenderErrorHandler(signal) };
354
374
  const rscStream = import.meta.env.DEV
355
375
  ? runWithDevStyleDeclarationCollection(
356
376
  devStyleDeclarations!,
357
377
  () =>
358
- renderToReadableStream<DefaultRscPayload>(
359
- rscPayload,
360
- { temporaryReferences },
361
- {
362
- onClientReference: declareDevClientReferenceStyles,
363
- }
364
- ),
378
+ renderToReadableStream<DefaultRscPayload>(rscPayload, renderOptions, {
379
+ onClientReference: declareDevClientReferenceStyles,
380
+ }),
365
381
  { transportGeneration: renderRequest.devStyleGeneration }
366
382
  )
367
- : renderToReadableStream<DefaultRscPayload>(rscPayload, { temporaryReferences });
383
+ : renderToReadableStream<DefaultRscPayload>(rscPayload, renderOptions);
368
384
 
369
385
  if (renderRequest.isRsc) {
370
386
  return new Response(rscStream, {
371
387
  status: actionStatus ?? responseRouteStatus,
372
- headers: { 'content-type': 'text/x-component;charset=utf-8' },
388
+ headers: responseHeaders,
373
389
  });
374
390
  }
375
391
 
376
- interface SsrModule {
377
- renderHTML: (
378
- rscStream: ReadableStream<Uint8Array>,
379
- options: {
380
- formState?: ReactFormState;
381
- nonce?: string;
382
- debugNojs?: boolean;
383
- forceCsrShell?: boolean;
384
- apiBaseUrl?: string;
385
- }
386
- ) => Promise<{
387
- stream: ReadableStream<Uint8Array>;
388
- status?: number;
389
- csrShellFallback?: boolean;
390
- }>;
391
- }
392
- const ssrEntry = await import.meta.viteRsc.loadModule<SsrModule>('ssr', 'index');
392
+ const ssrEntry = await import.meta.viteRsc.loadModule<
393
+ Pick<typeof import('../entry.server.ssr'), 'renderHTML'>
394
+ >('ssr', 'index');
393
395
 
394
396
  // CSP nonce —— 由上游 createCspNonceMiddleware 生成并写到 req header 'x-csp-nonce'。
395
397
  // React 19 renderToReadableStream 接 nonce 选项后,自动给所有内联 script (RSC payload、
@@ -403,10 +405,9 @@ async function runRscPipeline(
403
405
  debugNojs: renderRequest.url.searchParams.has('__nojs'),
404
406
  forceCsrShell: renderRequest.url.searchParams.has('__csr-shell'),
405
407
  apiBaseUrl: extras.apiBaseUrl,
408
+ signal,
406
409
  });
407
410
 
408
- const responseHeaders = new Headers();
409
- responseHeaders.set('content-type', 'text/html; charset=utf-8');
410
411
  responseHeaders.set('x-render-strategy', ssrResult.csrShellFallback ? 'csr-shell' : 'rsc-ssr');
411
412
  responseHeaders.set('x-fallback-used', ssrResult.csrShellFallback ? 'true' : 'false');
412
413
  if (ssrResult.csrShellFallback) {