isr-engine 3.1.1 → 3.1.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.
Files changed (28) hide show
  1. package/dist/cli/cli.cjs +1 -1
  2. package/dist/cli/cli.js +1 -1
  3. package/dist/{createCacheInspectorMiddleware-DvRhF_-D.cjs → createCacheInspectorMiddleware-Cq1C9TOB.cjs} +2 -2
  4. package/dist/{createCacheInspectorMiddleware-DvRhF_-D.cjs.map → createCacheInspectorMiddleware-Cq1C9TOB.cjs.map} +1 -1
  5. package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js → createCacheInspectorMiddleware-Dhc_2DWt.js} +2 -2
  6. package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js.map → createCacheInspectorMiddleware-Dhc_2DWt.js.map} +1 -1
  7. package/dist/{createISRApp-tRkpdmpp.cjs → createISRApp-CMBRb7yC.cjs} +5 -5
  8. package/dist/{createISRApp-tRkpdmpp.cjs.map → createISRApp-CMBRb7yC.cjs.map} +1 -1
  9. package/dist/{createISRApp-D88Xp0Fb.js → createISRApp-GKE91WpD.js} +5 -5
  10. package/dist/{createISRApp-D88Xp0Fb.js.map → createISRApp-GKE91WpD.js.map} +1 -1
  11. package/dist/{createImagePlugin-Cdz3QfrJ.js → createImagePlugin-BkCgZvI4.js} +2 -2
  12. package/dist/{createImagePlugin-Cdz3QfrJ.js.map → createImagePlugin-BkCgZvI4.js.map} +1 -1
  13. package/dist/{createImagePlugin-DomuzpoI.cjs → createImagePlugin-D3zO2lFv.cjs} +2 -2
  14. package/dist/{createImagePlugin-DomuzpoI.cjs.map → createImagePlugin-D3zO2lFv.cjs.map} +1 -1
  15. package/dist/defaults/runtime/seo-runtime.d.ts +2 -0
  16. package/dist/defaults/runtime/seo-runtime.d.ts.map +1 -1
  17. package/dist/isr-engine.cjs +3 -3
  18. package/dist/isr-engine.cjs.map +1 -1
  19. package/dist/isr-engine.js +3 -3
  20. package/dist/isr-engine.js.map +1 -1
  21. package/dist/runtime/routes.d.ts +18 -2
  22. package/dist/runtime/routes.d.ts.map +1 -1
  23. package/package.json +1 -1
  24. package/src/defaults/runtime/defineClientEntry.tsx +26 -15
  25. package/src/defaults/runtime/defineServerEntry.tsx +47 -44
  26. package/src/defaults/runtime/request.tsx +2 -2
  27. package/src/defaults/runtime/seo-runtime.ts +26 -30
  28. package/src/runtime/routes.tsx +102 -94
@@ -40,7 +40,7 @@
40
40
  import * as React from 'react';
41
41
  import type { PageSeoMeta } from '../defaults/runtime/seo-runtime';
42
42
  declare global {
43
- var __ISR_ENGINE_ROUTE_MANIFESTS__: RouteManifest[] | undefined;
43
+ var __ISR_ENGINE_COMPILED_ROUTE_MANIFESTS__: Map<ResolveRoute, CompiledManifest> | undefined;
44
44
  }
45
45
  /** 路由匹配后传给 page 的 props */
46
46
  export interface PageProps {
@@ -67,7 +67,7 @@ export interface RouteEntry extends RouteModuleRef {
67
67
  }
68
68
  export interface RouteManifest {
69
69
  routes: readonly RouteEntry[];
70
- /** 没匹配到时渲染的 route module;不传 → 返回 null */
70
+ /** 路由未匹配时渲染此模块,使用其 seo 导出并返回 HTTP 404。 */
71
71
  notFound?: RouteModuleRef;
72
72
  }
73
73
  export interface DefinedRoutes {
@@ -78,11 +78,27 @@ export interface PageSeoContext extends PageProps {
78
78
  url: URL;
79
79
  }
80
80
  export type PageSeoExport = PageSeoMeta | null | undefined | ((ctx: PageSeoContext) => PageSeoMeta | null | undefined | Promise<PageSeoMeta | null | undefined>);
81
+ interface PreparedPage {
82
+ ref: RouteModuleRef;
83
+ Component: PageComponent;
84
+ }
85
+ interface CompiledRoute extends PreparedPage {
86
+ re: RegExp;
87
+ keys: string[];
88
+ }
89
+ interface CompiledManifest {
90
+ routes: CompiledRoute[];
91
+ notFound?: PreparedPage;
92
+ }
81
93
  export type ResolveRoute = (ctx: {
82
94
  pathname: string;
83
95
  searchParams: URLSearchParams;
84
96
  }) => React.ReactNode;
85
97
  export declare function defineRoutes(config: RouteManifest): DefinedRoutes;
98
+ export declare function resolvePageRoute(url: URL, routes?: ResolveRoute, includeUnambiguousFallback?: boolean): Promise<{
99
+ notFound: boolean;
100
+ seoMeta: PageSeoMeta | null;
101
+ }>;
86
102
  export declare function resolvePageSeoMeta(url: URL): Promise<PageSeoMeta | null>;
87
103
  export {};
88
104
  //# sourceMappingURL=routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/runtime/routes.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAGH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAEnE,OAAO,CAAC,MAAM,CAAC;IACb,IAAI,8BAA8B,EAAE,aAAa,EAAE,GAAG,SAAS,CAAC;CACjE;AAED,2BAA2B;AAC3B,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,eAAe,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAED;;;;;GAKG;AAEH,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;AAErD,KAAK,WAAW,GAAG,MAAM,CAAC;AAC1B,MAAM,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,CAAC;AAE3D,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,iBAAiB,CAAC;IACxB,wBAAwB;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAW,SAAQ,cAAc;IAChD,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,SAAS,UAAU,EAAE,CAAC;IAC9B,yCAAyC;IACzC,QAAQ,CAAC,EAAE,cAAc,CAAC;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AC;AAiCtB,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAiBjE;AA0BD,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,GAAG,EACR,MAAM,CAAC,EAAE,YAAY,EACrB,0BAA0B,UAAQ,GACjC,OAAO,CAAC;IAAE,QAAQ,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAAA;CAAE,CAAC,CAW7D;AAED,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAE9E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "isr-engine",
3
- "version": "3.1.1",
3
+ "version": "3.1.2",
4
4
  "description": "ISR/SSG/Fallback rendering orchestration on Vite + React 19 RSC.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -54,7 +54,12 @@ import {
54
54
  } from './navigation-history.client';
55
55
  import { installDevRenderInspector } from './dev-render-inspector';
56
56
  import { setClientI18n } from '../../runtime/i18n-store';
57
- import { applySeoToDocument, type IntlPayload, type PageSeoMeta } from './seo-runtime';
57
+ import {
58
+ applySeoToDocument,
59
+ clearInjectedSeo,
60
+ type IntlPayload,
61
+ type PageSeoMeta,
62
+ } from './seo-runtime';
58
63
  import {
59
64
  installBrowserObservability,
60
65
  type BrowserObservabilityHandle,
@@ -134,11 +139,19 @@ async function prepareFetchedDevStyles(
134
139
  result.styleIds = await preparePayloadDevStyles(generation);
135
140
  }
136
141
 
137
- function renderPayloadRoot({
138
- payload,
139
- generation,
140
- styleIds,
141
- }: DefaultRscPayloadState): React.ReactNode {
142
+ function transitionPayload(
143
+ setState: (state: DefaultRscPayloadState) => void,
144
+ state: DefaultRscPayloadState
145
+ ): void {
146
+ // App head nodes must be reconciled without the previous route's injected tags.
147
+ clearInjectedSeo();
148
+ React.startTransition(() => setState(state));
149
+ }
150
+
151
+ function PayloadRoot({ payload, generation, styleIds }: DefaultRscPayloadState): React.ReactNode {
152
+ React.useLayoutEffect(() => {
153
+ applySeoToDocument(payload.seoMeta, payload.siteBaseUrl ?? undefined);
154
+ }, [payload]);
142
155
  if (!import.meta.env.DEV || generation === undefined) return payload.root;
143
156
  return (
144
157
  <DevStyleCommitBoundary key={generation} generation={generation} styleIds={styleIds}>
@@ -339,7 +352,6 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
339
352
  signal.throwIfAborted();
340
353
  syncBrowserUrlToFinalRedirect(response, requestedUrl);
341
354
  setClientI18n(payload.intl);
342
- applySeoToDocument(payload.seoMeta, payload.siteBaseUrl ?? undefined);
343
355
  setPayload(createPayloadState(payload, generation, styleIds));
344
356
  },
345
357
  async (result, generation) => {
@@ -356,7 +368,7 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
356
368
  const [failed, setFailed] = React.useState(false);
357
369
 
358
370
  React.useEffect(() => {
359
- setPayload = v => React.startTransition(() => setPayload_(v));
371
+ setPayload = state => transitionPayload(setPayload_, state);
360
372
  }, [setPayload_]);
361
373
 
362
374
  React.useEffect(() => {
@@ -384,7 +396,7 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
384
396
  )
385
397
  );
386
398
  }
387
- return renderPayloadRoot(payloadState);
399
+ return <PayloadRoot {...payloadState} />;
388
400
  }
389
401
 
390
402
  setServerCallback(async (id: string, args: unknown[]) => {
@@ -403,7 +415,6 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
403
415
  },
404
416
  ({ payload, styleIds }, generation) => {
405
417
  setClientI18n(payload.intl);
406
- applySeoToDocument(payload.seoMeta, payload.siteBaseUrl ?? undefined);
407
418
  setPayload(createPayloadState(payload, generation, styleIds));
408
419
  return payload;
409
420
  },
@@ -464,7 +475,7 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
464
475
  function BrowserRoot(): React.ReactNode {
465
476
  const [payloadState, setPayload_] = React.useState<DefaultRscPayloadState>(initialPayloadState);
466
477
  React.useEffect(() => {
467
- setPayload = v => React.startTransition(() => setPayload_(v));
478
+ setPayload = state => transitionPayload(setPayload_, state);
468
479
  }, [setPayload_]);
469
480
  React.useEffect(() => {
470
481
  const onNavigation = import.meta.env.DEV
@@ -478,7 +489,7 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
478
489
  };
479
490
  return listenNavigation(onNavigation, hooks.onNavigate, observability, hookContext);
480
491
  }, []);
481
- return renderPayloadRoot(payloadState);
492
+ return <PayloadRoot {...payloadState} />;
482
493
  }
483
494
 
484
495
  async function fetchRscPayload(): Promise<void> {
@@ -497,7 +508,6 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
497
508
  signal.throwIfAborted();
498
509
  syncBrowserUrlToFinalRedirect(response, requestedUrl);
499
510
  setClientI18n(payload.intl);
500
- applySeoToDocument(payload.seoMeta, payload.siteBaseUrl ?? undefined);
501
511
  setPayload(createPayloadState(payload, generation, styleIds));
502
512
  },
503
513
  async (result, generation) => {
@@ -525,7 +535,6 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
525
535
  },
526
536
  ({ payload, styleIds }, generation) => {
527
537
  setClientI18n(payload.intl);
528
- applySeoToDocument(payload.seoMeta, payload.siteBaseUrl ?? undefined);
529
538
  setPayload(createPayloadState(payload, generation, styleIds));
530
539
  return payload;
531
540
  },
@@ -554,7 +563,9 @@ async function main(hooks: ClientEntryHooks): Promise<void> {
554
563
  </HydrationShell>
555
564
  );
556
565
 
557
- // 注:csr-shell 路径已在 main 入口处早返回,这里只剩正常水合
566
+ // Reconcile the app's head without adopting injected nodes. PayloadRoot
567
+ // reapplies metadata after hydration.
568
+ clearInjectedSeo();
558
569
  hydrateRoot(document, browserRoot, { formState: initialPayload.formState });
559
570
  installInspector();
560
571
  schedulePostCommitInspectorInstall();
@@ -30,10 +30,12 @@ import type { ReactFormState } from 'react-dom/client';
30
30
 
31
31
  // @ts-expect-error - @app 别名在 createIsrPlugin 注入;指向用户的 src/app.tsx
32
32
  import { App } from '@app/_entry';
33
- // @app 别名在 createIsrPlugin 注入;评估用户 src/routes.tsx 以注册 page-level SEO
34
- import '@app/_routes';
33
+ // @ts-expect-error - App route manifest resolved by createIsrPlugin.
34
+ import * as appRoutes from '@app/_routes';
35
+ // @ts-expect-error - Runtime config resolved by createIsrPlugin.
36
+ import runtimeConfig from 'virtual:isr-engine/runtime-config';
35
37
 
36
- import { parseRenderRequest } from './request';
38
+ import { parseRenderRequest, type RenderRequest } from './request';
37
39
  import {
38
40
  declareDevClientReferenceStyles,
39
41
  runWithDevStyleDeclarationCollection,
@@ -41,7 +43,9 @@ import {
41
43
  import { type IntlPayload, type PageSeoMeta, injectSeoMeta, mergePageSeoMeta } from './seo-runtime';
42
44
  import { injectHeadExtras } from './head-extras-runtime';
43
45
  import { runWithI18n } from './i18n-server';
44
- import { resolvePageSeoMeta } from '../../runtime/routes';
46
+ import { resolvePageRoute, type ResolveRoute } from '../../runtime/routes';
47
+ import { parseLocale, resolveI18nConfig, type I18nConfig } from '../../runtime/i18n';
48
+ import type { RuntimeConfig } from '../../types/ISRConfig';
45
49
  import { getRequestContext } from '../../context/RequestContext';
46
50
 
47
51
  interface DefaultRscPayload {
@@ -111,6 +115,8 @@ export interface ServerEntryHooks<C extends ServerCtx = ServerCtx> {
111
115
  * 不要在这里返回 Response —— 兜底由 engine 处理
112
116
  */
113
117
  onError?: (error: unknown, request: Request, ctx: C) => void | Promise<void>;
118
+ /** URL locale settings exposed by site hooks. */
119
+ intl?: Partial<I18nConfig>;
114
120
  /**
115
121
  * 单页 i18n 数据加载器 —— 返回值经 RSC payload 序列化到客户端
116
122
  *
@@ -162,6 +168,10 @@ function genTraceId(): string {
162
168
  export function defineServerEntry<C extends ServerCtx = ServerCtx>(
163
169
  hooks: ServerEntryHooks<C> = {}
164
170
  ): ServerEntryModule {
171
+ const configuredIntl = hooks.intl?.locales?.length
172
+ ? hooks.intl
173
+ : (runtimeConfig as Partial<RuntimeConfig> | undefined)?.i18n;
174
+ const routeI18n = configuredIntl?.locales?.length ? resolveI18nConfig(configuredIntl) : undefined;
165
175
  return {
166
176
  async fetch(request) {
167
177
  const requestStore = getRequestContext();
@@ -195,44 +205,33 @@ export function defineServerEntry<C extends ServerCtx = ServerCtx>(
195
205
  }
196
206
  }
197
207
 
198
- const seoMeta = await runWithI18n(intl, async () => {
199
- // 双 strip:
200
- // 1) _.rsc 后缀(RSC 客户端导航 URL 携带)—— 不剥的话 /books/1_.rsc
201
- // 永远 match 不到 /books/:id 路由 → seoMeta=null → applySeoToDocument
202
- // no-op,客户端导航后 head 不更新。
203
- // 2) locale 前缀(i18n.prefixDefault=true 时所有 URL 都带)—— pages 注册的
204
- // route 是业务规范路径('/'、'/books/:id'),不含 locale;不剥的话
205
- // /zh-CN/books/1 也匹配不到。
206
- const url = new URL(request.url);
207
- if (url.pathname.endsWith('_.rsc')) {
208
- url.pathname = url.pathname.slice(0, -'_.rsc'.length);
209
- }
210
- let localePrefix = '';
211
- if (intl?.locale) {
212
- localePrefix = `/${intl.locale}`;
213
- if (url.pathname === localePrefix) {
214
- url.pathname = '/';
215
- } else if (url.pathname.startsWith(`${localePrefix}/`)) {
216
- url.pathname = url.pathname.slice(localePrefix.length);
217
- }
218
- }
219
- const [pageSeoMeta, hookSeoMeta] = await Promise.all([
220
- resolvePageSeoMeta(url),
208
+ const renderRequest = parseRenderRequest(request);
209
+ const url = new URL(renderRequest.url);
210
+ const localeConfig =
211
+ routeI18n ?? (intl?.locale && { locales: [intl.locale], defaultLocale: intl.locale });
212
+ const localized = localeConfig ? parseLocale(url.pathname, localeConfig) : undefined;
213
+ if (localized?.hasPrefix) url.pathname = localized.pathname;
214
+
215
+ const routeResolver = (Reflect.get(appRoutes, 'routes') ??
216
+ Reflect.get(appRoutes, 'default')) as ResolveRoute | undefined;
217
+ const { seoMeta, notFound } = await runWithI18n(intl, async () => {
218
+ const [page, hookSeoMeta] = await Promise.all([
219
+ resolvePageRoute(url, routeResolver),
221
220
  hooks.loadSeoMeta
222
221
  ? Promise.resolve(hooks.loadSeoMeta(request, ctx))
223
222
  : Promise.resolve(null),
224
223
  ]);
225
- const merged = mergePageSeoMeta(pageSeoMeta, hookSeoMeta);
226
- // 多语言 canonical 修正:admin 存的 canonical 是规范路径(无 locale),
227
- // 但页面真实 URL 含 locale 前缀。两个 locale 渲染同一个 canonical →
228
- // Google 判跨语言 URL 互为重复,只索引根域那一份,其它 locale SEO 死。
229
- // 这里把当前 locale 前缀重新加回相对 canonical 路径,让每个 locale 的
230
- // 页面声明自己为 canonical(业界标准多语言 SEO 做法)。
231
- if (merged && localePrefix && merged.canonical?.startsWith('/')) {
232
- merged.canonical =
233
- merged.canonical === '/' ? `${localePrefix}/` : `${localePrefix}${merged.canonical}`;
234
- }
235
- return merged;
224
+ const merged = mergePageSeoMeta(page.seoMeta, hookSeoMeta);
225
+ const canonical = merged?.canonical;
226
+ const seoMeta =
227
+ localized?.hasPrefix && canonical?.startsWith('/') && !canonical.startsWith('//')
228
+ ? {
229
+ ...merged,
230
+ canonical:
231
+ canonical === '/' ? `/${localized.locale}` : `/${localized.locale}${canonical}`,
232
+ }
233
+ : merged;
234
+ return { seoMeta, notFound: page.notFound };
236
235
  });
237
236
  if (seoMeta) (ctx as ServerCtx).seoMeta = seoMeta;
238
237
 
@@ -248,7 +247,8 @@ export function defineServerEntry<C extends ServerCtx = ServerCtx>(
248
247
  }
249
248
 
250
249
  const response = await runWithI18n(intl, () =>
251
- runRscPipeline(request, {
250
+ runRscPipeline(renderRequest, {
251
+ routeStatus: notFound && !renderRequest.isAction ? 404 : undefined,
252
252
  intl,
253
253
  seoMeta,
254
254
  siteBaseUrl: hooks.siteBaseUrl,
@@ -282,6 +282,7 @@ export function defineServerEntry<C extends ServerCtx = ServerCtx>(
282
282
  }
283
283
 
284
284
  interface PipelineExtras {
285
+ routeStatus?: 404;
285
286
  intl: IntlPayload | null | undefined;
286
287
  seoMeta: PageSeoMeta | null | undefined;
287
288
  siteBaseUrl?: string;
@@ -291,9 +292,11 @@ interface PipelineExtras {
291
292
  }
292
293
 
293
294
  /** 内部固化的 RSC + SSR 协议流水线 —— 用户不可见 */
294
- async function runRscPipeline(request: Request, extras: PipelineExtras): Promise<Response> {
295
- const renderRequest = parseRenderRequest(request);
296
- request = renderRequest.request;
295
+ async function runRscPipeline(
296
+ renderRequest: RenderRequest,
297
+ extras: PipelineExtras
298
+ ): Promise<Response> {
299
+ const { request } = renderRequest;
297
300
 
298
301
  let returnValue: DefaultRscPayload['returnValue'] | undefined;
299
302
  let formState: ReactFormState | undefined;
@@ -354,7 +357,7 @@ async function runRscPipeline(request: Request, extras: PipelineExtras): Promise
354
357
 
355
358
  if (renderRequest.isRsc) {
356
359
  return new Response(rscStream, {
357
- status: actionStatus,
360
+ status: actionStatus ?? extras.routeStatus,
358
361
  headers: { 'content-type': 'text/x-component;charset=utf-8' },
359
362
  });
360
363
  }
@@ -415,7 +418,7 @@ async function runRscPipeline(request: Request, extras: PipelineExtras): Promise
415
418
  }
416
419
 
417
420
  return new Response(finalStream, {
418
- status: ssrResult.status,
421
+ status: ssrResult.status ?? extras.routeStatus,
419
422
  headers: responseHeaders,
420
423
  });
421
424
  }
@@ -21,7 +21,7 @@ export type RenderRequest = {
21
21
  isAction: boolean;
22
22
  /** Server Action ID(仅 isAction 为 true 时有意义) */
23
23
  actionId?: string;
24
- /** 已去除 `_.rsc` 后缀的规范化请求 */
24
+ /** 原始请求,供读取请求头与 Server Action 正文。 */
25
25
  request: Request;
26
26
  /** 已去除 `_.rsc` 后缀的规范化 URL */
27
27
  url: URL;
@@ -84,7 +84,7 @@ export function parseRenderRequest(request: Request): RenderRequest {
84
84
  isRsc: true,
85
85
  isAction,
86
86
  actionId,
87
- request: new Request(url, request),
87
+ request,
88
88
  url,
89
89
  devStyleGeneration,
90
90
  };
@@ -75,10 +75,8 @@ export function renderPageSeoMeta(meta: PageSeoMeta, baseUrl?: string): string {
75
75
  const esc = (s: string) =>
76
76
  s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
77
77
 
78
- // 所有 engine 注入的 head 节点都打 data-isr-seo 标,客户端导航时按 marker 精准替换,
79
- // 不动业务/插件自己加的 meta(详见 applySeoToDocument 注释)。
80
- // <title> 是单值元素由 document.title 直接管理,不打标。
81
- if (meta.title) tags.push(`<title>${esc(meta.title)}</title>`);
78
+ // Mark injected nodes so navigation can remove them without touching the app's head.
79
+ if (meta.title) tags.push(`<title data-isr-seo>${esc(meta.title)}</title>`);
82
80
  if (meta.description) {
83
81
  tags.push(`<meta data-isr-seo name="description" content="${esc(meta.description)}">`);
84
82
  }
@@ -174,39 +172,37 @@ export function injectSeoMeta(
174
172
  return source.pipeThrough(transform);
175
173
  }
176
174
 
177
- // ─── 客户端导航后同步 <head> ──────────────────────────────────────────────
178
- //
179
- // 首屏 SSR 走 injectSeoMeta(HTML 流注入 <title> / <meta>)。
180
- // 但 RSC 客户端导航(pushState + 拉新 RSC payload)只换 React 树,<head> 不会自动跟。
181
- // Next.js / Remix / Astro 同样的问题,做法都是把页面的 metadata 序列化进 RSC payload,
182
- // 客户端在每次 setPayload 之后把 metadata 应用到 document(title / meta / link / jsonLd)。
183
- //
184
- // 本函数只在浏览器调用:业务侧通常不直接 import,engine 客户端 entry 自动调用。
185
- //
186
- // 关键点:
187
- // - 用 `data-isr-seo` 标记本函数管理的 <head> 节点,避免误删用户/插件加的 meta
188
- // - 先按 `data-isr-seo` 抓出旧节点,再按 meta 重建写回(删→建,避免顺序漂移)
189
- // - jsonLd 也一并管,按 data-isr-seo='jsonld' 标记 + 全删全建
190
- // - 初次调用(即 SSR 注入的初始 head)首先把已有的 <title> / <meta> / <link> / 含
191
- // SSR injection marker 的节点打 data-isr-seo 标,让后续导航能精准替换
192
- export function applySeoToDocument(meta: PageSeoMeta | null | undefined, baseUrl?: string): void {
193
- if (typeof document === 'undefined') return;
194
- if (!meta) return;
195
- const head = document.head;
196
- if (!head) return;
175
+ const managedTitles = new WeakMap<HTMLTitleElement, { base: string; applied: string }>();
197
176
 
198
- // 1. 删除上一次本函数写入的所有 SEO 节点(按 marker)
199
- head.querySelectorAll('[data-isr-seo]').forEach(el => el.remove());
177
+ export function clearInjectedSeo(): void {
178
+ document.head.querySelectorAll('[data-isr-seo]').forEach(el => el.remove());
179
+ }
200
180
 
201
- // 2. title 单独管 —— 只用 document.title 赋值(不创建第二个 <title>)
202
- if (meta.title) document.title = meta.title;
181
+ /** Replace managed head metadata after the route commits. */
182
+ export function applySeoToDocument(meta: PageSeoMeta | null | undefined, baseUrl?: string): void {
183
+ if (typeof document === 'undefined' || !document.head) return;
184
+ const head = document.head;
185
+ clearInjectedSeo();
186
+
187
+ // React owns the app title node and may update or replace it at commit.
188
+ const title = head.querySelector('title');
189
+ const previous = title ? managedTitles.get(title) : undefined;
190
+ const baseTitle = previous?.applied === document.title ? previous.base : document.title;
191
+ if (meta?.title) {
192
+ document.title = meta.title;
193
+ const active = head.querySelector('title');
194
+ if (active) managedTitles.set(active, { base: baseTitle, applied: meta.title });
195
+ } else if (title && previous) {
196
+ document.title = baseTitle;
197
+ managedTitles.delete(title);
198
+ }
199
+ if (!meta) return;
203
200
 
204
- // 3. 用与 renderPageSeoMeta 相同的逻辑重建 head 节点(保持 SSR / 客户端语义一致)
205
201
  const fragments: HTMLElement[] = [];
206
202
  const tag = (name: 'meta' | 'link' | 'script', attrs: Record<string, string>): HTMLElement => {
207
203
  const el = document.createElement(name);
208
204
  el.setAttribute('data-isr-seo', '');
209
- for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
205
+ for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value);
210
206
  return el;
211
207
  };
212
208