isr-engine 3.1.0 → 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 (43) hide show
  1. package/dist/cli/cli.cjs +1 -1
  2. package/dist/cli/cli.js +1 -1
  3. package/dist/{createCacheInspectorMiddleware-DG1_VLBS.cjs → createCacheInspectorMiddleware-Cq1C9TOB.cjs} +2 -2
  4. package/dist/{createCacheInspectorMiddleware-DG1_VLBS.cjs.map → createCacheInspectorMiddleware-Cq1C9TOB.cjs.map} +1 -1
  5. package/dist/{createCacheInspectorMiddleware-Bjku5v62.js → createCacheInspectorMiddleware-Dhc_2DWt.js} +2 -2
  6. package/dist/{createCacheInspectorMiddleware-Bjku5v62.js.map → createCacheInspectorMiddleware-Dhc_2DWt.js.map} +1 -1
  7. package/dist/{createISRApp-HX6X8UNb.cjs → createISRApp-CMBRb7yC.cjs} +5 -5
  8. package/dist/createISRApp-CMBRb7yC.cjs.map +1 -0
  9. package/dist/{createISRApp-DYVU8ydT.js → createISRApp-GKE91WpD.js} +5 -5
  10. package/dist/createISRApp-GKE91WpD.js.map +1 -0
  11. package/dist/{createImagePlugin-BZJHOvN9.js → createImagePlugin-BkCgZvI4.js} +2 -2
  12. package/dist/{createImagePlugin-BZJHOvN9.js.map → createImagePlugin-BkCgZvI4.js.map} +1 -1
  13. package/dist/{createImagePlugin-Ca4t_WhM.cjs → createImagePlugin-D3zO2lFv.cjs} +2 -2
  14. package/dist/{createImagePlugin-Ca4t_WhM.cjs.map → createImagePlugin-D3zO2lFv.cjs.map} +1 -1
  15. package/dist/defaults/runtime/defineSiteHooks.cjs +1 -1
  16. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
  17. package/dist/defaults/runtime/defineSiteHooks.js +1 -1
  18. package/dist/defaults/runtime/seo-runtime.d.ts +2 -0
  19. package/dist/defaults/runtime/seo-runtime.d.ts.map +1 -1
  20. package/dist/{defineSiteHooks-w2IrF5-D.cjs → defineSiteHooks-BuhvW5YB.cjs} +45 -36
  21. package/dist/defineSiteHooks-BuhvW5YB.cjs.map +1 -0
  22. package/dist/{defineSiteHooks-CV4tqHvB.js → defineSiteHooks-bHtGQftZ.js} +45 -36
  23. package/dist/defineSiteHooks-bHtGQftZ.js.map +1 -0
  24. package/dist/isr-engine.cjs +4 -4
  25. package/dist/isr-engine.cjs.map +1 -1
  26. package/dist/isr-engine.js +4 -4
  27. package/dist/isr-engine.js.map +1 -1
  28. package/dist/runtime/routes.d.ts +18 -2
  29. package/dist/runtime/routes.d.ts.map +1 -1
  30. package/dist/types/ISRConfig.d.ts +3 -2
  31. package/dist/types/ISRConfig.d.ts.map +1 -1
  32. package/package.json +1 -1
  33. package/src/defaults/runtime/defineClientEntry.tsx +26 -15
  34. package/src/defaults/runtime/defineServerEntry.tsx +47 -44
  35. package/src/defaults/runtime/defineSiteHooks.ts +58 -54
  36. package/src/defaults/runtime/request.tsx +2 -2
  37. package/src/defaults/runtime/seo-runtime.ts +26 -30
  38. package/src/runtime/routes.tsx +102 -94
  39. package/src/types/ISRConfig.ts +3 -2
  40. package/dist/createISRApp-DYVU8ydT.js.map +0 -1
  41. package/dist/createISRApp-HX6X8UNb.cjs.map +0 -1
  42. package/dist/defineSiteHooks-CV4tqHvB.js.map +0 -1
  43. package/dist/defineSiteHooks-w2IrF5-D.cjs.map +0 -1
@@ -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
 
@@ -43,7 +43,7 @@ import * as React from 'react';
43
43
  import type { PageSeoMeta } from '../defaults/runtime/seo-runtime';
44
44
 
45
45
  declare global {
46
- var __ISR_ENGINE_ROUTE_MANIFESTS__: RouteManifest[] | undefined;
46
+ var __ISR_ENGINE_COMPILED_ROUTE_MANIFESTS__: Map<ResolveRoute, CompiledManifest> | undefined;
47
47
  }
48
48
 
49
49
  /** 路由匹配后传给 page 的 props */
@@ -77,7 +77,7 @@ export interface RouteEntry extends RouteModuleRef {
77
77
 
78
78
  export interface RouteManifest {
79
79
  routes: readonly RouteEntry[];
80
- /** 没匹配到时渲染的 route module;不传 → 返回 null */
80
+ /** 路由未匹配时渲染此模块,使用其 seo 导出并返回 HTTP 404。 */
81
81
  notFound?: RouteModuleRef;
82
82
  }
83
83
 
@@ -98,10 +98,25 @@ export type PageSeoExport =
98
98
  ctx: PageSeoContext
99
99
  ) => PageSeoMeta | null | undefined | Promise<PageSeoMeta | null | undefined>);
100
100
 
101
- interface CompiledRoute extends RouteEntry {
101
+ interface PreparedPage {
102
+ ref: RouteModuleRef;
103
+ Component: PageComponent;
104
+ }
105
+
106
+ interface CompiledRoute extends PreparedPage {
102
107
  re: RegExp;
103
108
  keys: string[];
104
- Component: PageComponent;
109
+ }
110
+
111
+ interface CompiledManifest {
112
+ routes: CompiledRoute[];
113
+ notFound?: PreparedPage;
114
+ }
115
+
116
+ interface RouteMatch {
117
+ page: PreparedPage;
118
+ params: Record<string, string>;
119
+ notFound?: true;
105
120
  }
106
121
 
107
122
  function compile(path: string): { re: RegExp; keys: string[] } {
@@ -124,112 +139,105 @@ export type ResolveRoute = (ctx: {
124
139
  searchParams: URLSearchParams;
125
140
  }) => React.ReactNode;
126
141
 
127
- function resolveRouteComponent(
128
- ref: RouteModuleRef,
129
- label: string,
130
- exportName = 'default',
131
- fallbackExport?: string
132
- ): PageComponent {
133
- const requestedExport = ref.export ?? exportName;
134
- return React.lazy(async () => {
135
- const mod = await ref.load();
136
- const exports = mod as Record<string, unknown>;
137
- const component =
138
- exports[requestedExport] ?? (fallbackExport ? exports[fallbackExport] : undefined);
139
- if (!component) {
140
- throw new Error(`Route component "${label}" does not export "${requestedExport}"`);
141
- }
142
- return { default: component as PageComponent };
143
- });
144
- }
145
-
146
- function resolvePageComponent(route: RouteEntry): PageComponent {
147
- return resolveRouteComponent(route, route.path);
148
- }
149
-
150
- function createRouteResolver(
151
- routes: readonly RouteEntry[],
152
- notFound?: RouteModuleRef
153
- ): ResolveRoute {
154
- const compiled: CompiledRoute[] = routes.map(r => ({
155
- ...r,
156
- Component: resolvePageComponent(r),
157
- ...compile(r.path),
158
- }));
159
- const NotFound = notFound ? resolveRouteComponent(notFound, '__not_found__') : undefined;
160
-
161
- return function resolveRoute({ pathname, searchParams }) {
162
- const clean = trimTrailingSlashes(pathname) || '/';
163
- for (const route of compiled) {
164
- const m = route.re.exec(clean);
165
- if (!m) continue;
166
- const params: Record<string, string> = {};
167
- route.keys.forEach((k, i) => {
168
- params[k] = decodeURIComponent(m[i + 1] ?? '');
169
- });
170
- const Page = route.Component;
171
- return <Page pathname={clean} searchParams={searchParams} params={params} />;
172
- }
173
- if (NotFound) {
174
- return <NotFound pathname={clean} searchParams={searchParams} params={{}} />;
175
- }
176
- return null;
177
- };
178
- }
179
-
180
- function createDefinedRoutes(config: RouteManifest): DefinedRoutes {
181
- registerRouteManifest(config);
142
+ function preparePage(ref: RouteModuleRef, label: string): PreparedPage {
143
+ const exportName = ref.export ?? 'default';
182
144
  return {
183
- routes: createRouteResolver(config.routes, config.notFound),
145
+ ref,
146
+ Component: React.lazy(async () => {
147
+ const mod = (await ref.load()) as Record<string, unknown>;
148
+ const component = mod[exportName];
149
+ if (!component) {
150
+ throw new Error(`Route component "${label}" does not export "${exportName}"`);
151
+ }
152
+ return { default: component as PageComponent };
153
+ }),
184
154
  };
185
155
  }
186
156
 
187
- export function defineRoutes(config: RouteManifest): DefinedRoutes;
188
- export function defineRoutes(input: RouteManifest): DefinedRoutes {
189
- return createDefinedRoutes(input);
157
+ function matchRoute(manifest: CompiledManifest, pathname: string): RouteMatch | undefined {
158
+ for (const route of manifest.routes) {
159
+ const match = route.re.exec(pathname);
160
+ if (!match) continue;
161
+ const params = Object.fromEntries(
162
+ route.keys.map((key, index) => [key, decodeURIComponent(match[index + 1] ?? '')])
163
+ );
164
+ return { page: route, params };
165
+ }
166
+ if (manifest.notFound) return { page: manifest.notFound, params: {}, notFound: true };
190
167
  }
191
168
 
192
- function getRouteRegistry(): RouteManifest[] {
193
- globalThis.__ISR_ENGINE_ROUTE_MANIFESTS__ ??= [];
194
- return globalThis.__ISR_ENGINE_ROUTE_MANIFESTS__;
169
+ function getRouteRegistry(): Map<ResolveRoute, CompiledManifest> {
170
+ return (globalThis.__ISR_ENGINE_COMPILED_ROUTE_MANIFESTS__ ??= new Map());
195
171
  }
196
172
 
197
- function registerRouteManifest(config: RouteManifest): void {
198
- getRouteRegistry().push(config);
173
+ export function defineRoutes(config: RouteManifest): DefinedRoutes {
174
+ const manifest: CompiledManifest = {
175
+ routes: config.routes.map(route => ({
176
+ ...compile(route.path),
177
+ ...preparePage(route, route.path),
178
+ })),
179
+ notFound: config.notFound && preparePage(config.notFound, '__not_found__'),
180
+ };
181
+ const routes: ResolveRoute = ({ pathname, searchParams }) => {
182
+ const clean = trimTrailingSlashes(pathname) || '/';
183
+ const match = matchRoute(manifest, clean);
184
+ if (!match) return null;
185
+ const { Component } = match.page;
186
+ return <Component pathname={clean} searchParams={searchParams} params={match.params} />;
187
+ };
188
+ getRouteRegistry().set(routes, manifest);
189
+ return { routes };
199
190
  }
200
191
 
201
- export async function resolvePageSeoMeta(url: URL): Promise<PageSeoMeta | null> {
202
- const pathname = trimTrailingSlashes(url.pathname) || '/';
203
- for (const manifest of getRouteRegistry()) {
204
- for (const route of manifest.routes) {
205
- const matched = matchRoute(pathname, route);
206
- if (!matched) continue;
207
- return await loadPageSeo(route, {
208
- url,
209
- pathname,
210
- searchParams: url.searchParams,
211
- params: matched.params,
212
- });
213
- }
192
+ function matchRegisteredRoute(
193
+ pathname: string,
194
+ routes: ResolveRoute | undefined,
195
+ includeUnambiguousFallback: boolean
196
+ ): RouteMatch | undefined {
197
+ const registry = getRouteRegistry();
198
+ const manifest = routes && registry.get(routes);
199
+ if (manifest) return matchRoute(manifest, pathname);
200
+
201
+ // Registered tables can supply normal page SEO. Only the app's own resolver
202
+ // can establish its HTTP 404 when a nested router also registers a fallback.
203
+ let fallback: RouteMatch | undefined;
204
+ let ambiguous = false;
205
+ for (const candidate of registry.values()) {
206
+ const matched = matchRoute(candidate, pathname);
207
+ if (!matched) continue;
208
+ if (!matched.notFound) return matched;
209
+ if (!includeUnambiguousFallback) continue;
210
+ if (fallback) ambiguous = true;
211
+ else fallback = matched;
214
212
  }
215
- return null;
213
+ return ambiguous ? undefined : fallback;
216
214
  }
217
215
 
218
- function matchRoute(
219
- pathname: string,
220
- route: RouteEntry
221
- ): { params: Record<string, string> } | null {
222
- const compiled = compile(route.path);
223
- const m = compiled.re.exec(pathname);
224
- if (!m) return null;
225
- const params: Record<string, string> = {};
226
- compiled.keys.forEach((k, i) => {
227
- params[k] = decodeURIComponent(m[i + 1] ?? '');
216
+ export async function resolvePageRoute(
217
+ url: URL,
218
+ routes?: ResolveRoute,
219
+ includeUnambiguousFallback = false
220
+ ): Promise<{ notFound: boolean; seoMeta: PageSeoMeta | null }> {
221
+ const pathname = trimTrailingSlashes(url.pathname) || '/';
222
+ const matched = matchRegisteredRoute(pathname, routes, includeUnambiguousFallback);
223
+ if (!matched) return { notFound: false, seoMeta: null };
224
+ const seoMeta = await loadPageSeo(matched.page.ref, {
225
+ url,
226
+ pathname,
227
+ searchParams: url.searchParams,
228
+ params: matched.params,
228
229
  });
229
- return { params };
230
+ return { notFound: matched.notFound === true, seoMeta };
231
+ }
232
+
233
+ export async function resolvePageSeoMeta(url: URL): Promise<PageSeoMeta | null> {
234
+ return (await resolvePageRoute(url, undefined, true)).seoMeta;
230
235
  }
231
236
 
232
- async function loadPageSeo(route: RouteEntry, ctx: PageSeoContext): Promise<PageSeoMeta | null> {
237
+ async function loadPageSeo(
238
+ route: RouteModuleRef,
239
+ ctx: PageSeoContext
240
+ ): Promise<PageSeoMeta | null> {
233
241
  const mod = await route.load();
234
242
  const exports = mod as Record<string, unknown>;
235
243
  const exported = exports.seo ?? exports.generateSeo;
@@ -143,7 +143,7 @@ export interface RuntimeI18nConfig {
143
143
  */
144
144
  export interface DynamicSeoResolver {
145
145
  /**
146
- * 路径 pattern。支持 `:name` 命名参数(贪婪到 `/`)和 `*` 通配后缀。
146
+ * 路径 pattern。支持 `:name` 匹配单段和末尾 `/*` 匹配路径本身及其子路径。
147
147
  * 例:`/books/:id`、`/u/:handle`、`/dashboard/*`
148
148
  */
149
149
  pattern: string;
@@ -151,7 +151,8 @@ export interface DynamicSeoResolver {
151
151
  * 命中后的 resolver。返回 PageSeoMeta(平铺)或 null。
152
152
  * 抛错会被引擎吞掉并写到 onError,不会导致 SSR 失败。
153
153
  *
154
- * input.params 包含 pattern 里 :name 解析出的值。
154
+ * input.params 包含命名参数。末尾 `/*` 还会返回 `wildcard`,
155
+ * 其值为不带起始斜杠的剩余路径,本身命中时为空字符串。
155
156
  * input.locale 是当前请求 locale(可能 undefined,特别是没启 i18n 时)。
156
157
  * input.services / input.runtime 给到完整 runtime context,可拿 api origin。
157
158
  */