isr-engine 3.1.1 → 3.1.3
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/dist/cli/cli.js +1 -1
- package/dist/config/loadConfig.d.ts.map +1 -1
- package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js → createCacheInspectorMiddleware-GgzKVkq2.js} +2 -2
- package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js.map → createCacheInspectorMiddleware-GgzKVkq2.js.map} +1 -1
- package/dist/{createISRApp-D88Xp0Fb.js → createISRApp-DPD3Er4F.js} +25 -33
- package/dist/createISRApp-DPD3Er4F.js.map +1 -0
- package/dist/{createImagePlugin-Cdz3QfrJ.js → createImagePlugin-QNvY9vPB.js} +2 -2
- package/dist/{createImagePlugin-Cdz3QfrJ.js.map → createImagePlugin-QNvY9vPB.js.map} +1 -1
- package/dist/defaults/runtime/seo-runtime.d.ts +2 -0
- package/dist/defaults/runtime/seo-runtime.d.ts.map +1 -1
- package/dist/isr-engine.js +3 -3
- package/dist/isr-engine.js.map +1 -1
- package/dist/runtime/routes.d.ts +18 -2
- package/dist/runtime/routes.d.ts.map +1 -1
- package/package.json +20 -28
- package/src/defaults/runtime/defineClientEntry.tsx +26 -15
- package/src/defaults/runtime/defineServerEntry.tsx +47 -44
- package/src/defaults/runtime/request.tsx +2 -2
- package/src/defaults/runtime/seo-runtime.ts +26 -30
- package/src/runtime/routes.tsx +102 -94
- package/dist/Logger-DqBS_3v8.cjs +0 -184
- package/dist/Logger-DqBS_3v8.cjs.map +0 -1
- package/dist/abVariantContext-BvAMuhjj.cjs +0 -510
- package/dist/abVariantContext-BvAMuhjj.cjs.map +0 -1
- package/dist/adapters/observability/index.cjs +0 -152
- package/dist/adapters/observability/index.cjs.map +0 -1
- package/dist/adapters/runtime/index.cjs +0 -100
- package/dist/adapters/runtime/index.cjs.map +0 -1
- package/dist/cli/cli.cjs +0 -372
- package/dist/cli/cli.cjs.map +0 -1
- package/dist/config/defineConfig.cjs +0 -26
- package/dist/config/defineConfig.cjs.map +0 -1
- package/dist/createCacheInspectorMiddleware-DvRhF_-D.cjs +0 -112
- package/dist/createCacheInspectorMiddleware-DvRhF_-D.cjs.map +0 -1
- package/dist/createISRApp-D88Xp0Fb.js.map +0 -1
- package/dist/createISRApp-tRkpdmpp.cjs +0 -8232
- package/dist/createISRApp-tRkpdmpp.cjs.map +0 -1
- package/dist/createImagePlugin-DomuzpoI.cjs +0 -487
- package/dist/createImagePlugin-DomuzpoI.cjs.map +0 -1
- package/dist/defaults/auto-observability.cjs +0 -147
- package/dist/defaults/auto-observability.cjs.map +0 -1
- package/dist/defaults/runtime/defineSiteHooks.cjs +0 -11
- package/dist/defineSiteHooks-BuhvW5YB.cjs +0 -770
- package/dist/defineSiteHooks-BuhvW5YB.cjs.map +0 -1
- package/dist/error500-template-BvZmvKoa.cjs +0 -63
- package/dist/error500-template-BvZmvKoa.cjs.map +0 -1
- package/dist/i18n-CS5QhOO0.cjs +0 -221
- package/dist/i18n-CS5QhOO0.cjs.map +0 -1
- package/dist/image/index.cjs +0 -93
- package/dist/image/index.cjs.map +0 -1
- package/dist/isr-engine.cjs +0 -3332
- package/dist/isr-engine.cjs.map +0 -1
- package/dist/rolldown-runtime-DakpK96I.cjs +0 -43
- package/dist/rsc/browser.cjs +0 -109
- package/dist/rsc/browser.cjs.map +0 -1
- package/dist/rsc/index.cjs +0 -32
- package/dist/rsc-CYT6B6bf.cjs +0 -237
- package/dist/rsc-CYT6B6bf.cjs.map +0 -1
package/dist/isr-engine.cjs
DELETED
|
@@ -1,3332 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("./rolldown-runtime-DakpK96I.cjs");
|
|
3
|
-
const require_createISRApp = require("./createISRApp-tRkpdmpp.cjs");
|
|
4
|
-
const require_abVariantContext = require("./abVariantContext-BvAMuhjj.cjs");
|
|
5
|
-
const require_Logger = require("./Logger-DqBS_3v8.cjs");
|
|
6
|
-
const require_i18n = require("./i18n-CS5QhOO0.cjs");
|
|
7
|
-
const require_config_defineConfig = require("./config/defineConfig.cjs");
|
|
8
|
-
const require_createImagePlugin = require("./createImagePlugin-DomuzpoI.cjs");
|
|
9
|
-
const require_defineSiteHooks = require("./defineSiteHooks-BuhvW5YB.cjs");
|
|
10
|
-
const require_rsc = require("./rsc-CYT6B6bf.cjs");
|
|
11
|
-
let node_fs = require("node:fs");
|
|
12
|
-
node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
|
|
13
|
-
let node_path = require("node:path");
|
|
14
|
-
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
15
|
-
let path = require("path");
|
|
16
|
-
let fs = require("fs");
|
|
17
|
-
let typescript = require("typescript");
|
|
18
|
-
typescript = require_rolldown_runtime.__toESM(typescript, 1);
|
|
19
|
-
let vite = require("vite");
|
|
20
|
-
let node_crypto = require("node:crypto");
|
|
21
|
-
let node_url = require("node:url");
|
|
22
|
-
let css_tree = require("css-tree");
|
|
23
|
-
let node_zlib = require("node:zlib");
|
|
24
|
-
let node_module = require("node:module");
|
|
25
|
-
let _vitejs_plugin_rsc = require("@vitejs/plugin-rsc");
|
|
26
|
-
_vitejs_plugin_rsc = require_rolldown_runtime.__toESM(_vitejs_plugin_rsc, 1);
|
|
27
|
-
let react_dom = require("react-dom");
|
|
28
|
-
react_dom = require_rolldown_runtime.__toESM(react_dom, 1);
|
|
29
|
-
//#region src/defaults/runtime/seo-runtime.ts
|
|
30
|
-
/**
|
|
31
|
-
* 把相对 URL 用 baseUrl 解析成绝对 URL
|
|
32
|
-
* og:image / canonical / twitter:image / alternates.href 必须是绝对 URL
|
|
33
|
-
* —— 社交爬虫(Facebook/Twitter/微信/LinkedIn)不会基于页面 URL resolve 相对路径
|
|
34
|
-
*/
|
|
35
|
-
function toAbsolute(href, baseUrl) {
|
|
36
|
-
if (!href) return href;
|
|
37
|
-
if (/^(https?:)?\/\//i.test(href)) return href;
|
|
38
|
-
if (!baseUrl) return href;
|
|
39
|
-
try {
|
|
40
|
-
return new URL(href, baseUrl).toString();
|
|
41
|
-
} catch {
|
|
42
|
-
return href;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
function renderPageSeoMeta(meta, baseUrl) {
|
|
46
|
-
const tags = [];
|
|
47
|
-
const esc = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
48
|
-
if (meta.title) tags.push(`<title>${esc(meta.title)}</title>`);
|
|
49
|
-
if (meta.description) tags.push(`<meta data-isr-seo name="description" content="${esc(meta.description)}">`);
|
|
50
|
-
if (meta.keywords?.length) tags.push(`<meta data-isr-seo name="keywords" content="${esc(meta.keywords.join(", "))}">`);
|
|
51
|
-
if (meta.noindex) tags.push(`<meta data-isr-seo name="robots" content="noindex, nofollow">`);
|
|
52
|
-
if (meta.canonical || baseUrl) {
|
|
53
|
-
const href = toAbsolute(meta.canonical || "", baseUrl) || baseUrl || "";
|
|
54
|
-
if (href) tags.push(`<link data-isr-seo rel="canonical" href="${esc(href)}">`);
|
|
55
|
-
}
|
|
56
|
-
if (meta.alternates?.length) for (const a of meta.alternates) tags.push(`<link data-isr-seo rel="alternate" hreflang="${esc(a.hreflang)}" href="${esc(toAbsolute(a.href, baseUrl))}">`);
|
|
57
|
-
if (meta.title) tags.push(`<meta data-isr-seo property="og:title" content="${esc(meta.title)}">`);
|
|
58
|
-
if (meta.description) tags.push(`<meta data-isr-seo property="og:description" content="${esc(meta.description)}">`);
|
|
59
|
-
tags.push(`<meta data-isr-seo property="og:type" content="${meta.ogType ?? "website"}">`);
|
|
60
|
-
if (meta.image) {
|
|
61
|
-
const abs = toAbsolute(meta.image, baseUrl);
|
|
62
|
-
tags.push(`<meta data-isr-seo property="og:image" content="${esc(abs)}">`);
|
|
63
|
-
tags.push(`<meta data-isr-seo name="twitter:image" content="${esc(abs)}">`);
|
|
64
|
-
}
|
|
65
|
-
if (meta.jsonLd) {
|
|
66
|
-
const arr = Array.isArray(meta.jsonLd) ? meta.jsonLd : [meta.jsonLd];
|
|
67
|
-
for (const obj of arr) {
|
|
68
|
-
const json = JSON.stringify(obj).replace(/<\/script/gi, "<\\/script");
|
|
69
|
-
tags.push(`<script data-isr-seo="jsonld" type="application/ld+json">${json}<\/script>`);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
return tags.join("\n ");
|
|
73
|
-
}
|
|
74
|
-
var HEAD_OPEN_RE = /<head\b[^>]*>/i;
|
|
75
|
-
function injectSeoMeta(source, meta, baseUrl) {
|
|
76
|
-
const encoder = new TextEncoder();
|
|
77
|
-
const decoder = new TextDecoder("utf-8", { fatal: false });
|
|
78
|
-
const injection = "\n " + renderPageSeoMeta(meta, baseUrl) + "\n";
|
|
79
|
-
let buffer = "";
|
|
80
|
-
let injected = false;
|
|
81
|
-
const SAFE_KEEP = 256;
|
|
82
|
-
const transform = new TransformStream({
|
|
83
|
-
transform(chunk, controller) {
|
|
84
|
-
if (injected) {
|
|
85
|
-
controller.enqueue(chunk);
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
buffer += decoder.decode(chunk, { stream: true });
|
|
89
|
-
const m = HEAD_OPEN_RE.exec(buffer);
|
|
90
|
-
if (m) {
|
|
91
|
-
const cutAt = m.index + m[0].length;
|
|
92
|
-
const before = buffer.slice(0, cutAt);
|
|
93
|
-
const after = buffer.slice(cutAt);
|
|
94
|
-
controller.enqueue(encoder.encode(before + injection + after));
|
|
95
|
-
buffer = "";
|
|
96
|
-
injected = true;
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
if (buffer.length > SAFE_KEEP) {
|
|
100
|
-
const emit = buffer.slice(0, buffer.length - SAFE_KEEP);
|
|
101
|
-
buffer = buffer.slice(buffer.length - SAFE_KEEP);
|
|
102
|
-
controller.enqueue(encoder.encode(emit));
|
|
103
|
-
}
|
|
104
|
-
},
|
|
105
|
-
flush(controller) {
|
|
106
|
-
const tail = buffer + decoder.decode();
|
|
107
|
-
if (tail) controller.enqueue(encoder.encode(tail));
|
|
108
|
-
}
|
|
109
|
-
});
|
|
110
|
-
return source.pipeThrough(transform);
|
|
111
|
-
}
|
|
112
|
-
//#endregion
|
|
113
|
-
//#region src/manifest/ManifestLoader.ts
|
|
114
|
-
/**
|
|
115
|
-
* Vite Manifest 加载器
|
|
116
|
-
*
|
|
117
|
-
* @description 加载 Vite 构建产出的 Manifest 文件,用于生产环境 SSR 资源注入
|
|
118
|
-
*
|
|
119
|
-
* @example
|
|
120
|
-
* ```typescript
|
|
121
|
-
* const manifest = ManifestLoader.load({ rootDir: process.cwd() });
|
|
122
|
-
* if (manifest) {
|
|
123
|
-
* const assets = ManifestLoader.getEntryAssets('src/entry.tsx');
|
|
124
|
-
* console.log(assets.js); // '/assets/entry.a1b2c3.js'
|
|
125
|
-
* }
|
|
126
|
-
* ```
|
|
127
|
-
*/
|
|
128
|
-
/** Vite Manifest 默认路径 (按优先级排列) */
|
|
129
|
-
var MANIFEST_PATHS = [
|
|
130
|
-
"dist/.vite/manifest.json",
|
|
131
|
-
"dist/client/.vite/manifest.json",
|
|
132
|
-
"dist/manifest.json"
|
|
133
|
-
];
|
|
134
|
-
var MANIFEST_ENTRY_CANDIDATES = [
|
|
135
|
-
"src/entry.tsx",
|
|
136
|
-
"src/entry.ts",
|
|
137
|
-
"src/main.tsx",
|
|
138
|
-
"src/main.ts",
|
|
139
|
-
"src/index.tsx",
|
|
140
|
-
"src/index.ts",
|
|
141
|
-
"src/App.tsx",
|
|
142
|
-
"src/App.ts"
|
|
143
|
-
];
|
|
144
|
-
/**
|
|
145
|
-
* Vite Manifest 加载器
|
|
146
|
-
*/
|
|
147
|
-
var ManifestLoader = class {
|
|
148
|
-
static logger = require_Logger.Logger.getInstance();
|
|
149
|
-
static manifest = null;
|
|
150
|
-
static publicPath = "/";
|
|
151
|
-
constructor() {}
|
|
152
|
-
/**
|
|
153
|
-
* 加载 Manifest
|
|
154
|
-
* @returns 解析后的 Manifest,失败返回 null
|
|
155
|
-
*/
|
|
156
|
-
static load(config) {
|
|
157
|
-
const { rootDir, manifestPath, publicPath = "/" } = config;
|
|
158
|
-
this.publicPath = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
|
|
159
|
-
const absolutePath = manifestPath ? (0, path.resolve)(rootDir, manifestPath) : this.detectManifestPath(rootDir);
|
|
160
|
-
if (!absolutePath) return null;
|
|
161
|
-
return this.loadFromPath(absolutePath);
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* 检测 Manifest 路径
|
|
165
|
-
*/
|
|
166
|
-
static detectManifestPath(rootDir) {
|
|
167
|
-
for (const relativePath of MANIFEST_PATHS) {
|
|
168
|
-
const absolutePath = (0, path.resolve)(rootDir, relativePath);
|
|
169
|
-
if ((0, fs.existsSync)(absolutePath)) {
|
|
170
|
-
this.logger.info(`📦 检测到 Manifest: ${relativePath}`);
|
|
171
|
-
return absolutePath;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
this.logger.warn(`⚠️ 未找到 Manifest 文件,请确保已执行 vite build 并设置 build.manifest: true`);
|
|
175
|
-
return null;
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* 从路径加载 Manifest
|
|
179
|
-
*/
|
|
180
|
-
static loadFromPath(absolutePath) {
|
|
181
|
-
if (!(0, fs.existsSync)(absolutePath)) {
|
|
182
|
-
this.logger.error(`Manifest 文件不存在: ${absolutePath}`);
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
185
|
-
try {
|
|
186
|
-
const content = (0, fs.readFileSync)(absolutePath, "utf-8");
|
|
187
|
-
const raw = JSON.parse(content);
|
|
188
|
-
const parsed = this.parse(raw, absolutePath);
|
|
189
|
-
this.manifest = parsed;
|
|
190
|
-
this.logger.info(`✅ Manifest 加载成功: ${parsed.entries.size} 个入口,${parsed.modules.size} 个模块`);
|
|
191
|
-
return parsed;
|
|
192
|
-
} catch (error) {
|
|
193
|
-
this.logger.error(`Manifest 解析失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
194
|
-
return null;
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* 解析 Vite Manifest
|
|
199
|
-
*/
|
|
200
|
-
static parse(raw, filePath) {
|
|
201
|
-
const entries = /* @__PURE__ */ new Map();
|
|
202
|
-
const modules = /* @__PURE__ */ new Map();
|
|
203
|
-
for (const [modulePath, chunk] of Object.entries(raw)) {
|
|
204
|
-
const assetInfo = this.toAssetInfo(chunk);
|
|
205
|
-
modules.set(modulePath, assetInfo);
|
|
206
|
-
if (chunk.isEntry) entries.set(modulePath, assetInfo);
|
|
207
|
-
}
|
|
208
|
-
return {
|
|
209
|
-
filePath,
|
|
210
|
-
entries,
|
|
211
|
-
modules,
|
|
212
|
-
raw
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* 转换为 AssetInfo
|
|
217
|
-
*/
|
|
218
|
-
static toAssetInfo(chunk) {
|
|
219
|
-
const preloadModules = this.collectPreloadModules(chunk);
|
|
220
|
-
return {
|
|
221
|
-
js: this.normalizePath(chunk.file),
|
|
222
|
-
css: this.uniqueValues((chunk.css ?? []).map((css) => this.normalizePath(css))),
|
|
223
|
-
preloadModules: this.uniqueValues(preloadModules),
|
|
224
|
-
assets: this.uniqueValues((chunk.assets ?? []).map((asset) => this.normalizePath(asset))),
|
|
225
|
-
isEntry: chunk.isEntry ?? false
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* 收集预加载模块(包含静态与动态导入),并统一为 manifest key 风格
|
|
230
|
-
*/
|
|
231
|
-
static collectPreloadModules(chunk) {
|
|
232
|
-
const imports = chunk.imports ?? [];
|
|
233
|
-
const dynamicImports = chunk.dynamicImports ?? [];
|
|
234
|
-
return [...imports, ...dynamicImports].map((entry) => this.normalizeManifestPath(entry)).filter((entry) => Boolean(entry));
|
|
235
|
-
}
|
|
236
|
-
static uniqueValues(values) {
|
|
237
|
-
return Array.from(new Set(values.filter(Boolean)));
|
|
238
|
-
}
|
|
239
|
-
/**
|
|
240
|
-
* 标准化 manifest 路径(便于跨环境匹配)
|
|
241
|
-
*/
|
|
242
|
-
static normalizeManifestPath(path$6) {
|
|
243
|
-
return path$6.split("?")[0].split("#")[0].replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
|
|
244
|
-
}
|
|
245
|
-
/**
|
|
246
|
-
* 构建匹配候选(含带/不带前导斜杠、去扩展名)
|
|
247
|
-
*/
|
|
248
|
-
static buildMatchVariants(raw) {
|
|
249
|
-
const normalized = this.normalizeManifestPath(raw);
|
|
250
|
-
if (!normalized) return [];
|
|
251
|
-
const noExt = normalized.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/i, "");
|
|
252
|
-
return Array.from(/* @__PURE__ */ new Set([
|
|
253
|
-
normalized,
|
|
254
|
-
`/${normalized}`,
|
|
255
|
-
noExt,
|
|
256
|
-
`/${noExt}`
|
|
257
|
-
]));
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* 在 manifest 映射中查找候选匹配 key
|
|
261
|
-
*/
|
|
262
|
-
static findModuleKeyByCandidates(source, candidates) {
|
|
263
|
-
const normalizedCandidates = /* @__PURE__ */ new Set();
|
|
264
|
-
for (const candidate of candidates) for (const variant of this.buildMatchVariants(candidate)) normalizedCandidates.add(variant);
|
|
265
|
-
for (const key of source.keys()) for (const variant of this.buildMatchVariants(key)) if (normalizedCandidates.has(variant)) return key;
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* 解析依赖 key(imports)
|
|
269
|
-
*/
|
|
270
|
-
static normalizeImportId(importId) {
|
|
271
|
-
return this.normalizeManifestPath(importId);
|
|
272
|
-
}
|
|
273
|
-
/**
|
|
274
|
-
* 规范化路径
|
|
275
|
-
*/
|
|
276
|
-
static normalizePath(path$7) {
|
|
277
|
-
if (path$7.startsWith("/") || path$7.startsWith("http")) return path$7;
|
|
278
|
-
return `${this.publicPath}${path$7}`;
|
|
279
|
-
}
|
|
280
|
-
/**
|
|
281
|
-
* 获取已加载的 Manifest
|
|
282
|
-
*/
|
|
283
|
-
static getManifest() {
|
|
284
|
-
return this.manifest;
|
|
285
|
-
}
|
|
286
|
-
/**
|
|
287
|
-
* 获取入口资源信息
|
|
288
|
-
*/
|
|
289
|
-
static getEntryAssets(entryPath) {
|
|
290
|
-
if (!this.manifest) return null;
|
|
291
|
-
const directKey = this.findModuleKeyByCandidates(this.manifest.entries, [entryPath]);
|
|
292
|
-
if (directKey) return this.manifest.entries.get(directKey) ?? null;
|
|
293
|
-
const normalizedPath = this.normalizeManifestPath(entryPath);
|
|
294
|
-
if (normalizedPath) {
|
|
295
|
-
const normalizedKey = this.findModuleKeyByCandidates(this.manifest.entries, [normalizedPath]);
|
|
296
|
-
if (normalizedKey) return this.manifest.entries.get(normalizedKey) ?? null;
|
|
297
|
-
}
|
|
298
|
-
return null;
|
|
299
|
-
}
|
|
300
|
-
/**
|
|
301
|
-
* 生成入口候选 key(兼容 build 产物和路径写法差异)
|
|
302
|
-
*/
|
|
303
|
-
static buildEntryCandidates(entryPath) {
|
|
304
|
-
const candidates = /* @__PURE__ */ new Set();
|
|
305
|
-
const collect = (rawPath) => {
|
|
306
|
-
const normalized = rawPath.replace(/^\/+/, "").trim();
|
|
307
|
-
if (!normalized) return;
|
|
308
|
-
candidates.add(normalized);
|
|
309
|
-
candidates.add(`/${normalized}`);
|
|
310
|
-
const noExt = normalized.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/i, "");
|
|
311
|
-
candidates.add(noExt);
|
|
312
|
-
candidates.add(`/${noExt}`);
|
|
313
|
-
if (noExt.includes(".")) candidates.add(noExt.replace(/\.([^.]+)$/, ""));
|
|
314
|
-
};
|
|
315
|
-
if (entryPath) collect(entryPath);
|
|
316
|
-
else for (const candidate of MANIFEST_ENTRY_CANDIDATES) collect(candidate);
|
|
317
|
-
return Array.from(candidates);
|
|
318
|
-
}
|
|
319
|
-
/**
|
|
320
|
-
* 按候选路径解析入口资源,找不到时回退到最接近入口的 chunk
|
|
321
|
-
*/
|
|
322
|
-
static resolveEntryAssets(entryPath) {
|
|
323
|
-
if (!this.manifest) return null;
|
|
324
|
-
for (const candidate of this.buildEntryCandidates(entryPath)) {
|
|
325
|
-
const matched = this.getEntryAssets(candidate);
|
|
326
|
-
if (matched) return matched;
|
|
327
|
-
}
|
|
328
|
-
for (const [key, asset] of this.manifest.entries) if (asset.js && !/vendor|router|polyfill/i.test(key)) return asset;
|
|
329
|
-
for (const [, asset] of this.manifest.entries) if (asset.js) return asset;
|
|
330
|
-
return null;
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* 获取模块资源信息
|
|
334
|
-
*/
|
|
335
|
-
static getModuleAssets(modulePath) {
|
|
336
|
-
if (!this.manifest) return null;
|
|
337
|
-
const candidates = this.buildMatchVariants(modulePath);
|
|
338
|
-
const direct = this.findModuleKeyByCandidates(this.manifest.modules, candidates);
|
|
339
|
-
if (direct) return this.manifest.modules.get(direct) ?? null;
|
|
340
|
-
return this.manifest.modules.get(this.normalizeManifestPath(modulePath)) ?? null;
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* 生成 HTML 资源标签
|
|
344
|
-
*/
|
|
345
|
-
static generateHtmlTags(entryPath) {
|
|
346
|
-
if (!this.manifest) return {
|
|
347
|
-
head: "",
|
|
348
|
-
scripts: ""
|
|
349
|
-
};
|
|
350
|
-
const headTagSet = /* @__PURE__ */ new Set();
|
|
351
|
-
const scriptTagSet = /* @__PURE__ */ new Set();
|
|
352
|
-
const { modules, entries } = this.manifest;
|
|
353
|
-
const processAsset = (asset) => {
|
|
354
|
-
for (const css of asset.css) headTagSet.add(`<link rel="stylesheet" href="${css}" />`);
|
|
355
|
-
for (const preload of asset.preloadModules) {
|
|
356
|
-
const preloadModuleKey = this.findModuleKeyByCandidates(modules, [preload]);
|
|
357
|
-
const module = preloadModuleKey ? modules.get(preloadModuleKey) : null;
|
|
358
|
-
if (module?.js) headTagSet.add(`<link rel="modulepreload" href="${module.js}" />`);
|
|
359
|
-
}
|
|
360
|
-
if (asset.isEntry) scriptTagSet.add(`<script type="module" src="${asset.js}"><\/script>`);
|
|
361
|
-
};
|
|
362
|
-
const entryAsset = this.resolveEntryAssets(entryPath);
|
|
363
|
-
if (entryAsset) processAsset(entryAsset);
|
|
364
|
-
else for (const asset of entries.values()) processAsset(asset);
|
|
365
|
-
return {
|
|
366
|
-
head: Array.from(headTagSet).join("\n "),
|
|
367
|
-
scripts: Array.from(scriptTagSet).join("\n ")
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
};
|
|
371
|
-
//#endregion
|
|
372
|
-
//#region src/route/RouteManager.ts
|
|
373
|
-
/** 统一提取 RouteRule 的 mode */
|
|
374
|
-
function toMode(rule) {
|
|
375
|
-
return typeof rule === "string" ? rule : rule.mode;
|
|
376
|
-
}
|
|
377
|
-
var RouteManager = class {
|
|
378
|
-
globalMode;
|
|
379
|
-
overrides;
|
|
380
|
-
defaultRevalidate;
|
|
381
|
-
constructor(config) {
|
|
382
|
-
this.globalMode = config.renderMode;
|
|
383
|
-
this.overrides = config.routes || {};
|
|
384
|
-
this.defaultRevalidate = config.revalidate;
|
|
385
|
-
}
|
|
386
|
-
getRenderMode(path) {
|
|
387
|
-
return require_createISRApp.resolveRenderMode(path, this.globalMode, this.overrides);
|
|
388
|
-
}
|
|
389
|
-
hasOverride(path) {
|
|
390
|
-
if (this.overrides[path] !== void 0) return true;
|
|
391
|
-
for (const pattern of Object.keys(this.overrides)) if (require_createISRApp.matchRoutePattern(path, pattern)) return true;
|
|
392
|
-
return false;
|
|
393
|
-
}
|
|
394
|
-
getSSGRoutes() {
|
|
395
|
-
return Object.entries(this.overrides).filter(([pattern, rule]) => toMode(rule) === "ssg" && !pattern.includes("*") && !pattern.includes(":")).map(([pattern]) => pattern);
|
|
396
|
-
}
|
|
397
|
-
getISRRoutes() {
|
|
398
|
-
const result = {};
|
|
399
|
-
for (const [pattern, rule] of Object.entries(this.overrides)) if (toMode(rule) === "isr") result[pattern] = {
|
|
400
|
-
revalidate: typeof rule === "object" && typeof rule.ttl === "number" ? rule.ttl : this.defaultRevalidate,
|
|
401
|
-
priority: .5
|
|
402
|
-
};
|
|
403
|
-
return result;
|
|
404
|
-
}
|
|
405
|
-
shouldCache(path) {
|
|
406
|
-
return this.getRenderMode(path) !== "ssr";
|
|
407
|
-
}
|
|
408
|
-
getPriority(path) {
|
|
409
|
-
if (path === "/") return 1;
|
|
410
|
-
switch (this.getRenderMode(path)) {
|
|
411
|
-
case "ssg": return .8;
|
|
412
|
-
case "isr": return .6;
|
|
413
|
-
case "ssr": return .4;
|
|
414
|
-
default: return .5;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
getChangeFreq(path) {
|
|
418
|
-
switch (this.getRenderMode(path)) {
|
|
419
|
-
case "ssg": return "monthly";
|
|
420
|
-
case "isr": return "daily";
|
|
421
|
-
case "ssr": return "hourly";
|
|
422
|
-
default: return "weekly";
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
};
|
|
426
|
-
//#endregion
|
|
427
|
-
//#region src/cache/CacheManager.ts
|
|
428
|
-
var DEFAULT_CONFIG = { strategy: "memory" };
|
|
429
|
-
/**
|
|
430
|
-
* 缓存管理器
|
|
431
|
-
* 统一管理缓存后端,支持 Memory / Redis 策略切换
|
|
432
|
-
*
|
|
433
|
-
* 使用工厂模式创建缓存适配器:
|
|
434
|
-
* - memory: 基于 LRU + TTL 的高性能内存缓存
|
|
435
|
-
* - redis: 基于 ioredis 的分布式缓存,自动降级到内存
|
|
436
|
-
*/
|
|
437
|
-
var CacheManager = class {
|
|
438
|
-
adapter;
|
|
439
|
-
logger;
|
|
440
|
-
config;
|
|
441
|
-
constructor(config = {}) {
|
|
442
|
-
this.config = {
|
|
443
|
-
...DEFAULT_CONFIG,
|
|
444
|
-
...config
|
|
445
|
-
};
|
|
446
|
-
this.logger = require_Logger.Logger.getInstance();
|
|
447
|
-
this.adapter = this.createAdapter();
|
|
448
|
-
this.logger.info(`缓存后端已初始化: ${this.adapter.name}`);
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* 工厂方法:根据策略创建适配器
|
|
452
|
-
*/
|
|
453
|
-
createAdapter() {
|
|
454
|
-
switch (this.config.strategy) {
|
|
455
|
-
case "redis": return new require_createISRApp.RedisCacheAdapter(this.config.redis);
|
|
456
|
-
default: return new require_createISRApp.MemoryCacheAdapter(this.config.memory);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
/**
|
|
460
|
-
* 获取底层适配器
|
|
461
|
-
*/
|
|
462
|
-
getAdapter() {
|
|
463
|
-
return this.adapter;
|
|
464
|
-
}
|
|
465
|
-
/**
|
|
466
|
-
* 获取缓存内容
|
|
467
|
-
*/
|
|
468
|
-
async get(key) {
|
|
469
|
-
return this.adapter.get(key);
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* 设置缓存内容
|
|
473
|
-
*/
|
|
474
|
-
async set(key, value, options) {
|
|
475
|
-
return this.adapter.set(key, value, options);
|
|
476
|
-
}
|
|
477
|
-
/**
|
|
478
|
-
* 检查是否存在
|
|
479
|
-
*/
|
|
480
|
-
async has(key) {
|
|
481
|
-
return this.adapter.has(key);
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* 删除缓存
|
|
485
|
-
*/
|
|
486
|
-
async delete(key) {
|
|
487
|
-
return this.adapter.delete(key);
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* 清空缓存
|
|
491
|
-
*/
|
|
492
|
-
async clear() {
|
|
493
|
-
await this.adapter.clear();
|
|
494
|
-
this.logger.debug("缓存已清空");
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* 批量获取
|
|
498
|
-
*/
|
|
499
|
-
async getMany(keys) {
|
|
500
|
-
return this.adapter.getMany(keys);
|
|
501
|
-
}
|
|
502
|
-
/**
|
|
503
|
-
* 批量设置
|
|
504
|
-
*/
|
|
505
|
-
async setMany(entries) {
|
|
506
|
-
return this.adapter.setMany(entries);
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* 按标签批量失效
|
|
510
|
-
*/
|
|
511
|
-
async invalidateByTag(tag) {
|
|
512
|
-
return this.adapter.invalidateByTag(tag);
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* 连接状态
|
|
516
|
-
*/
|
|
517
|
-
isConnected() {
|
|
518
|
-
return this.adapter.isConnected();
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* 销毁缓存管理器
|
|
522
|
-
*/
|
|
523
|
-
async destroy() {
|
|
524
|
-
await this.adapter.destroy();
|
|
525
|
-
this.logger.debug("缓存管理器已销毁");
|
|
526
|
-
}
|
|
527
|
-
};
|
|
528
|
-
//#endregion
|
|
529
|
-
//#region src/plugin/googleFontAssets.ts
|
|
530
|
-
var MAX_CSS_BYTES = 2 * 1024 * 1024;
|
|
531
|
-
var MAX_FONT_BYTES = 16 * 1024 * 1024;
|
|
532
|
-
var MAX_DECODED_BYTES = 32 * 1024 * 1024;
|
|
533
|
-
var MAX_TOTAL_BYTES = 64 * 1024 * 1024;
|
|
534
|
-
var MAX_ASSETS = 512;
|
|
535
|
-
var MAX_FACES = 512;
|
|
536
|
-
var REQUEST_TIMEOUT = 1e4;
|
|
537
|
-
var BATCH_TIMEOUT = 6e4;
|
|
538
|
-
function invalid(message) {
|
|
539
|
-
throw new Error(`Google font ${message}`);
|
|
540
|
-
}
|
|
541
|
-
function isControlCharacter(character) {
|
|
542
|
-
const code = character.charCodeAt(0);
|
|
543
|
-
return code < 32 || code >= 127 && code <= 159;
|
|
544
|
-
}
|
|
545
|
-
function normalizeFontOutDir(value) {
|
|
546
|
-
const directory = value.replace(/\/$/, "");
|
|
547
|
-
if (!directory || directory.length > 256 || directory.split("/").some((part) => !/^[A-Za-z0-9_.-]+$/.test(part) || part === "." || part === "..")) invalid("outDir must be a relative asset directory without traversal");
|
|
548
|
-
return directory;
|
|
549
|
-
}
|
|
550
|
-
function validateOptions(families, weights) {
|
|
551
|
-
if (families.length > 32 || families.some((family) => !family || family.length > 128 || family.trim() !== family || Array.from(family).some(isControlCharacter))) invalid("family list is invalid or too large");
|
|
552
|
-
if (!weights.length || weights.length > 16 || weights.some((weight) => {
|
|
553
|
-
const match = /^([1-9]\d{0,3})(?:\.\.([1-9]\d{0,3}))?$/.exec(weight);
|
|
554
|
-
return !match || Number(match[1]) > 1e3 || match[2] !== void 0 && (Number(match[2]) > 1e3 || Number(match[2]) < Number(match[1]));
|
|
555
|
-
})) invalid("weights must be bounded numeric weights or ranges");
|
|
556
|
-
}
|
|
557
|
-
/** Fixed trusted host selection is separate from the untrusted stylesheet's URL components. */
|
|
558
|
-
function googleTarget(source, kind) {
|
|
559
|
-
const host = kind === "css" ? "fonts.googleapis.com" : "fonts.gstatic.com";
|
|
560
|
-
let url;
|
|
561
|
-
try {
|
|
562
|
-
url = new URL(source);
|
|
563
|
-
} catch {
|
|
564
|
-
return invalid("URL is invalid");
|
|
565
|
-
}
|
|
566
|
-
if (url.protocol !== "https:" || url.hostname !== host || url.port || url.username || url.password || url.hash) invalid("origin is not allowed");
|
|
567
|
-
return url;
|
|
568
|
-
}
|
|
569
|
-
async function download(source, kind, parent) {
|
|
570
|
-
const controller = new AbortController();
|
|
571
|
-
const abort = () => controller.abort(parent.reason);
|
|
572
|
-
if (parent.aborted) abort();
|
|
573
|
-
else parent.addEventListener("abort", abort, { once: true });
|
|
574
|
-
const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Google font request timed out")), REQUEST_TIMEOUT);
|
|
575
|
-
const limit = kind === "css" ? MAX_CSS_BYTES : MAX_FONT_BYTES;
|
|
576
|
-
const allow = /* @__PURE__ */ new Set([kind === "css" ? "fonts.googleapis.com:443" : "fonts.gstatic.com:443"]);
|
|
577
|
-
try {
|
|
578
|
-
let url = googleTarget(source, kind);
|
|
579
|
-
for (let hop = 0; hop <= 5; hop++) {
|
|
580
|
-
controller.signal.throwIfAborted();
|
|
581
|
-
const response = await require_createImagePlugin.requestPinnedImage(url, allow, controller.signal, kind === "css" ? "text/css" : "font/woff2", kind === "css" ? "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36" : void 0);
|
|
582
|
-
try {
|
|
583
|
-
if ([
|
|
584
|
-
301,
|
|
585
|
-
302,
|
|
586
|
-
303,
|
|
587
|
-
307,
|
|
588
|
-
308
|
|
589
|
-
].includes(response.statusCode ?? 0)) {
|
|
590
|
-
if (!response.headers.location || hop === 5) invalid("redirect limit exceeded");
|
|
591
|
-
url = googleTarget(new URL(response.headers.location, url).href, kind);
|
|
592
|
-
continue;
|
|
593
|
-
}
|
|
594
|
-
if ((response.statusCode ?? 0) < 200 || (response.statusCode ?? 0) >= 300) invalid("download failed");
|
|
595
|
-
if (response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity") invalid("unexpected response encoding");
|
|
596
|
-
if (Number(response.headers["content-length"]) > limit) invalid("response is too large");
|
|
597
|
-
const chunks = [];
|
|
598
|
-
let size = 0;
|
|
599
|
-
for await (const chunk of response) {
|
|
600
|
-
controller.signal.throwIfAborted();
|
|
601
|
-
const bytes = Buffer.from(chunk);
|
|
602
|
-
size += bytes.length;
|
|
603
|
-
if (size > limit) invalid("response is too large");
|
|
604
|
-
chunks.push(bytes);
|
|
605
|
-
}
|
|
606
|
-
if (!response.complete) invalid("response is incomplete");
|
|
607
|
-
return Buffer.concat(chunks, size);
|
|
608
|
-
} finally {
|
|
609
|
-
response.destroy();
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
return invalid("redirect limit exceeded");
|
|
613
|
-
} catch (error) {
|
|
614
|
-
if (controller.signal.aborted) throw controller.signal.reason;
|
|
615
|
-
throw error;
|
|
616
|
-
} finally {
|
|
617
|
-
clearTimeout(timeout);
|
|
618
|
-
parent.removeEventListener("abort", abort);
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
function declarations(rule) {
|
|
622
|
-
const values = /* @__PURE__ */ new Map();
|
|
623
|
-
const allowed = /* @__PURE__ */ new Set([
|
|
624
|
-
"font-family",
|
|
625
|
-
"font-style",
|
|
626
|
-
"font-weight",
|
|
627
|
-
"font-stretch",
|
|
628
|
-
"font-display",
|
|
629
|
-
"src",
|
|
630
|
-
"unicode-range"
|
|
631
|
-
]);
|
|
632
|
-
if (rule.prelude || !rule.block) invalid("stylesheet contains an invalid font-face rule");
|
|
633
|
-
rule.block.children.forEach((declaration) => {
|
|
634
|
-
if (declaration.type !== "Declaration" || declaration.important || declaration.value.type !== "Value") invalid("stylesheet contains an invalid font descriptor");
|
|
635
|
-
const property = declaration.property.toLowerCase();
|
|
636
|
-
if (!allowed.has(property) || values.has(property)) invalid("stylesheet contains an unsupported font descriptor");
|
|
637
|
-
values.set(property, declaration.value);
|
|
638
|
-
});
|
|
639
|
-
return values;
|
|
640
|
-
}
|
|
641
|
-
function unicodeRange(value) {
|
|
642
|
-
const ranges = value.toUpperCase().split(",");
|
|
643
|
-
if (ranges.length > 256 || ranges.some((part) => {
|
|
644
|
-
const match = /^U\+([0-9A-F?]{1,6})(?:-([0-9A-F]{1,6}))?$/.exec(part.trim());
|
|
645
|
-
if (!match) return true;
|
|
646
|
-
if (match[1].includes("?") && (match[2] || !/^[0-9A-F]*\?+$/.test(match[1]))) return true;
|
|
647
|
-
const low = Number.parseInt(match[1].replaceAll("?", "0"), 16);
|
|
648
|
-
const high = Number.parseInt(match[2] ?? match[1].replaceAll("?", "F"), 16);
|
|
649
|
-
return high > 1114111 || low > high;
|
|
650
|
-
})) return invalid("unicode range is invalid");
|
|
651
|
-
return ranges.map((part) => part.trim()).join(", ");
|
|
652
|
-
}
|
|
653
|
-
function parseFaces(css, family) {
|
|
654
|
-
let stylesheet;
|
|
655
|
-
try {
|
|
656
|
-
stylesheet = (0, css_tree.parse)(css, { onParseError: () => invalid("stylesheet cannot be parsed") });
|
|
657
|
-
} catch {
|
|
658
|
-
return invalid("stylesheet cannot be parsed");
|
|
659
|
-
}
|
|
660
|
-
if (stylesheet.type !== "StyleSheet") return invalid("stylesheet is invalid");
|
|
661
|
-
const faces = [];
|
|
662
|
-
stylesheet.children.forEach((rule) => {
|
|
663
|
-
if (rule.type !== "Atrule" || rule.name.toLowerCase() !== "font-face") invalid("stylesheet contains a non-font rule");
|
|
664
|
-
const values = declarations(rule);
|
|
665
|
-
const familyNode = values.get("font-family");
|
|
666
|
-
if (familyNode?.type !== "Value" || familyNode.children.size !== 1) invalid("family descriptor is invalid");
|
|
667
|
-
const name = familyNode.children.first;
|
|
668
|
-
if (name?.type !== "String" || name.value !== family) invalid("family descriptor does not match the requested family");
|
|
669
|
-
const style = values.has("font-style") ? (0, css_tree.generate)(values.get("font-style")).toLowerCase() : "normal";
|
|
670
|
-
if (![
|
|
671
|
-
"normal",
|
|
672
|
-
"italic",
|
|
673
|
-
"oblique"
|
|
674
|
-
].includes(style)) invalid("style descriptor is invalid");
|
|
675
|
-
let weight = values.has("font-weight") ? (0, css_tree.generate)(values.get("font-weight")) : "400";
|
|
676
|
-
if (weight === "normal") weight = "400";
|
|
677
|
-
if (weight === "bold") weight = "700";
|
|
678
|
-
const weights = weight.split(/\s+/);
|
|
679
|
-
if (weights.length > 2 || weights.some((value) => !/^\d{1,4}$/.test(value) || Number(value) < 1 || Number(value) > 1e3) || weights.length === 2 && Number(weights[0]) > Number(weights[1])) invalid("weight descriptor is invalid");
|
|
680
|
-
const stretch = values.has("font-stretch") ? (0, css_tree.generate)(values.get("font-stretch")).toLowerCase() : void 0;
|
|
681
|
-
if (stretch !== void 0 && !/^(?:normal|(?:ultra-|extra-|semi-)?(?:condensed|expanded)|\d{1,3}(?:\.\d+)?%(?: \d{1,3}(?:\.\d+)?%)?)$/.test(stretch)) invalid("stretch descriptor is invalid");
|
|
682
|
-
const display = values.get("font-display");
|
|
683
|
-
if (display && ![
|
|
684
|
-
"auto",
|
|
685
|
-
"block",
|
|
686
|
-
"swap",
|
|
687
|
-
"fallback",
|
|
688
|
-
"optional"
|
|
689
|
-
].includes((0, css_tree.generate)(display))) invalid("display descriptor is invalid");
|
|
690
|
-
const src = values.get("src");
|
|
691
|
-
if (src?.type !== "Value") invalid("source descriptor is missing");
|
|
692
|
-
const parts = src.children.toArray();
|
|
693
|
-
const url = parts[0];
|
|
694
|
-
const format = parts[1];
|
|
695
|
-
if (url?.type !== "Url" || parts.length > 2 || format && (format.type !== "Function" || format.name.toLowerCase() !== "format" || format.children.size !== 1 || format.children.first?.type !== "String" || format.children.first.value !== "woff2")) invalid("source descriptor must contain one WOFF2 URL");
|
|
696
|
-
const source = googleTarget(url.value, "font").href;
|
|
697
|
-
const range = values.get("unicode-range");
|
|
698
|
-
faces.push({
|
|
699
|
-
family,
|
|
700
|
-
style,
|
|
701
|
-
weight,
|
|
702
|
-
stretch,
|
|
703
|
-
unicodeRange: range ? unicodeRange((0, css_tree.generate)(range)) : void 0,
|
|
704
|
-
source
|
|
705
|
-
});
|
|
706
|
-
});
|
|
707
|
-
if (!faces.length || faces.length > MAX_FACES) invalid("stylesheet has an invalid number of font faces");
|
|
708
|
-
return faces;
|
|
709
|
-
}
|
|
710
|
-
function decompress(bytes, limit) {
|
|
711
|
-
return new Promise((resolve, reject) => {
|
|
712
|
-
(0, node_zlib.brotliDecompress)(bytes, { maxOutputLength: limit }, (error, result) => {
|
|
713
|
-
if (error) reject(/* @__PURE__ */ new Error("Google font WOFF2 compressed data is invalid"));
|
|
714
|
-
else resolve(result);
|
|
715
|
-
});
|
|
716
|
-
});
|
|
717
|
-
}
|
|
718
|
-
var TABLE_TAGS = [
|
|
719
|
-
"cmap",
|
|
720
|
-
"head",
|
|
721
|
-
"hhea",
|
|
722
|
-
"hmtx",
|
|
723
|
-
"maxp",
|
|
724
|
-
"name",
|
|
725
|
-
"OS/2",
|
|
726
|
-
"post",
|
|
727
|
-
"cvt ",
|
|
728
|
-
"fpgm",
|
|
729
|
-
"glyf",
|
|
730
|
-
"loca",
|
|
731
|
-
"prep",
|
|
732
|
-
"CFF ",
|
|
733
|
-
"VORG",
|
|
734
|
-
"EBDT",
|
|
735
|
-
"EBLC",
|
|
736
|
-
"gasp",
|
|
737
|
-
"hdmx",
|
|
738
|
-
"kern",
|
|
739
|
-
"LTSH",
|
|
740
|
-
"PCLT",
|
|
741
|
-
"VDMX",
|
|
742
|
-
"vhea",
|
|
743
|
-
"vmtx",
|
|
744
|
-
"BASE",
|
|
745
|
-
"GDEF",
|
|
746
|
-
"GPOS",
|
|
747
|
-
"GSUB",
|
|
748
|
-
"EBSC",
|
|
749
|
-
"JSTF",
|
|
750
|
-
"MATH",
|
|
751
|
-
"CBDT",
|
|
752
|
-
"CBLC",
|
|
753
|
-
"COLR",
|
|
754
|
-
"CPAL",
|
|
755
|
-
"SVG ",
|
|
756
|
-
"sbix",
|
|
757
|
-
"acnt",
|
|
758
|
-
"avar",
|
|
759
|
-
"bdat",
|
|
760
|
-
"bloc",
|
|
761
|
-
"bsln",
|
|
762
|
-
"cvar",
|
|
763
|
-
"fdsc",
|
|
764
|
-
"feat",
|
|
765
|
-
"fmtx",
|
|
766
|
-
"fvar",
|
|
767
|
-
"gvar",
|
|
768
|
-
"hsty",
|
|
769
|
-
"just",
|
|
770
|
-
"lcar",
|
|
771
|
-
"mort",
|
|
772
|
-
"morx",
|
|
773
|
-
"opbd",
|
|
774
|
-
"prop",
|
|
775
|
-
"trak",
|
|
776
|
-
"Zapf",
|
|
777
|
-
"Silf",
|
|
778
|
-
"Glat",
|
|
779
|
-
"Gloc",
|
|
780
|
-
"Feat",
|
|
781
|
-
"Sill"
|
|
782
|
-
];
|
|
783
|
-
/**
|
|
784
|
-
* Admit bounded single-font WOFF2 containers, not arbitrary network bytes or collections.
|
|
785
|
-
* Directory/Brotli validation follows https://www.w3.org/TR/WOFF2/ sections 3–5.
|
|
786
|
-
* This does not replace the browser's semantic OpenType/glyph validation.
|
|
787
|
-
*/
|
|
788
|
-
async function validateWoff2(font) {
|
|
789
|
-
const fail = () => invalid("WOFF2 container is invalid or too large");
|
|
790
|
-
if (font.length < 50 || font.length > MAX_FONT_BYTES || font.readUInt32BE(0) !== 2001684018) fail();
|
|
791
|
-
const flavor = font.readUInt32BE(4);
|
|
792
|
-
const tables = font.readUInt16BE(12);
|
|
793
|
-
const sfntSize = font.readUInt32BE(16);
|
|
794
|
-
const compressedSize = font.readUInt32BE(20);
|
|
795
|
-
if (![65536, 1330926671].includes(flavor) || font.readUInt32BE(8) !== font.length || !tables || tables > 256 || font.readUInt16BE(14) !== 0 || sfntSize < 12 + tables * 16 || sfntSize > MAX_DECODED_BYTES || !compressedSize) fail();
|
|
796
|
-
let cursor = 48;
|
|
797
|
-
const byte = () => {
|
|
798
|
-
if (cursor >= font.length) return fail();
|
|
799
|
-
return font[cursor++];
|
|
800
|
-
};
|
|
801
|
-
const base128 = () => {
|
|
802
|
-
let value = 0;
|
|
803
|
-
for (let index = 0; index < 5; index++) {
|
|
804
|
-
const next = byte();
|
|
805
|
-
if (index === 0 && next === 128 || value > 33554431) return fail();
|
|
806
|
-
value = value * 128 + (next & 127);
|
|
807
|
-
if (!(next & 128)) return value;
|
|
808
|
-
}
|
|
809
|
-
return fail();
|
|
810
|
-
};
|
|
811
|
-
const tags = /* @__PURE__ */ new Set();
|
|
812
|
-
let decodedSize = 0;
|
|
813
|
-
let originalSize = 12 + tables * 16;
|
|
814
|
-
let previousTransformedGlyf = false;
|
|
815
|
-
for (let index = 0; index < tables; index++) {
|
|
816
|
-
const flags = byte();
|
|
817
|
-
const tag = (flags & 63) === 63 ? String.fromCharCode(byte(), byte(), byte(), byte()) : TABLE_TAGS[flags & 63];
|
|
818
|
-
if (!tag || tags.has(tag) || !/^[\x20-\x7e]{4}$/.test(tag)) fail();
|
|
819
|
-
tags.add(tag);
|
|
820
|
-
const version = flags >> 6;
|
|
821
|
-
const glyfOrLoca = tag === "glyf" || tag === "loca";
|
|
822
|
-
if (glyfOrLoca ? version !== 0 && version !== 3 : version !== 0 && !(tag === "hmtx" && version === 1)) fail();
|
|
823
|
-
const transformed = glyfOrLoca ? version === 0 : version !== 0;
|
|
824
|
-
const original = base128();
|
|
825
|
-
const length = transformed ? base128() : original;
|
|
826
|
-
if (tag === "loca" && transformed && length !== 0) fail();
|
|
827
|
-
if (previousTransformedGlyf !== (tag === "loca" && transformed)) fail();
|
|
828
|
-
previousTransformedGlyf = tag === "glyf" && transformed;
|
|
829
|
-
decodedSize += length;
|
|
830
|
-
originalSize += Math.ceil(original / 4) * 4;
|
|
831
|
-
if (decodedSize > MAX_DECODED_BYTES || originalSize > MAX_DECODED_BYTES) fail();
|
|
832
|
-
}
|
|
833
|
-
if (previousTransformedGlyf || !decodedSize || ![
|
|
834
|
-
"cmap",
|
|
835
|
-
"head",
|
|
836
|
-
"hhea",
|
|
837
|
-
"hmtx",
|
|
838
|
-
"maxp",
|
|
839
|
-
"name",
|
|
840
|
-
"OS/2",
|
|
841
|
-
"post"
|
|
842
|
-
].every((tag) => tags.has(tag))) fail();
|
|
843
|
-
const compressedStart = cursor;
|
|
844
|
-
cursor += compressedSize;
|
|
845
|
-
if (cursor > font.length) fail();
|
|
846
|
-
const metaOffset = font.readUInt32BE(28);
|
|
847
|
-
const metaLength = font.readUInt32BE(32);
|
|
848
|
-
const metaOriginal = font.readUInt32BE(36);
|
|
849
|
-
const privateOffset = font.readUInt32BE(40);
|
|
850
|
-
const privateLength = font.readUInt32BE(44);
|
|
851
|
-
const advance = (offset, length) => {
|
|
852
|
-
if (!length || offset % 4 || offset < cursor || offset - cursor > 3 || offset + length > font.length) fail();
|
|
853
|
-
while (cursor < offset) if (font[cursor++] !== 0) fail();
|
|
854
|
-
cursor += length;
|
|
855
|
-
};
|
|
856
|
-
if (metaOffset) {
|
|
857
|
-
if (!metaOriginal || metaOriginal > 1024 * 1024 || metaLength > 1024 * 1024) fail();
|
|
858
|
-
advance(metaOffset, metaLength);
|
|
859
|
-
} else if (metaLength || metaOriginal) fail();
|
|
860
|
-
if (privateOffset) {
|
|
861
|
-
if (privateLength > 1024 * 1024) fail();
|
|
862
|
-
advance(privateOffset, privateLength);
|
|
863
|
-
} else if (privateLength) fail();
|
|
864
|
-
if (font.length - cursor > 3) fail();
|
|
865
|
-
while (cursor < font.length) if (font[cursor++] !== 0) fail();
|
|
866
|
-
if ((await decompress(font.subarray(compressedStart, compressedStart + compressedSize), MAX_DECODED_BYTES)).length !== decodedSize) fail();
|
|
867
|
-
if (metaOffset && (await decompress(font.subarray(metaOffset, metaOffset + metaLength), 1024 * 1024)).length !== metaOriginal) fail();
|
|
868
|
-
}
|
|
869
|
-
async function loadGoogleFontAssets(families, weights, outDir, shutdown) {
|
|
870
|
-
validateOptions(families, weights);
|
|
871
|
-
const directory = normalizeFontOutDir(outDir);
|
|
872
|
-
const controller = new AbortController();
|
|
873
|
-
const abort = () => controller.abort(shutdown.reason);
|
|
874
|
-
if (shutdown.aborted) abort();
|
|
875
|
-
else shutdown.addEventListener("abort", abort, { once: true });
|
|
876
|
-
const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Google font batch timed out")), BATCH_TIMEOUT);
|
|
877
|
-
const bundle = {
|
|
878
|
-
assets: /* @__PURE__ */ new Map(),
|
|
879
|
-
faces: []
|
|
880
|
-
};
|
|
881
|
-
const downloaded = /* @__PURE__ */ new Map();
|
|
882
|
-
let total = 0;
|
|
883
|
-
try {
|
|
884
|
-
for (const family of [...new Set(families)]) {
|
|
885
|
-
controller.signal.throwIfAborted();
|
|
886
|
-
const bytes = await download("https://fonts.googleapis.com/css2?family=" + encodeURIComponent(family).replace(/%20/g, "+") + `:wght@${weights.join(";")}&display=swap`, "css", controller.signal);
|
|
887
|
-
total += bytes.length;
|
|
888
|
-
if (total > MAX_TOTAL_BYTES) invalid("total download byte budget exceeded");
|
|
889
|
-
let css;
|
|
890
|
-
try {
|
|
891
|
-
css = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
892
|
-
} catch {
|
|
893
|
-
return invalid("stylesheet encoding is invalid");
|
|
894
|
-
}
|
|
895
|
-
const faces = parseFaces(css, family);
|
|
896
|
-
if (bundle.faces.length + faces.length > MAX_FACES) invalid("face budget exceeded");
|
|
897
|
-
for (const face of faces) {
|
|
898
|
-
controller.signal.throwIfAborted();
|
|
899
|
-
let fileName = downloaded.get(face.source);
|
|
900
|
-
if (!fileName) {
|
|
901
|
-
if (downloaded.size >= MAX_ASSETS) invalid("asset count budget exceeded");
|
|
902
|
-
const font = await download(face.source, "font", controller.signal);
|
|
903
|
-
total += font.length;
|
|
904
|
-
if (total > MAX_TOTAL_BYTES) invalid("total download byte budget exceeded");
|
|
905
|
-
await validateWoff2(font);
|
|
906
|
-
controller.signal.throwIfAborted();
|
|
907
|
-
fileName = `${directory}/${(0, node_crypto.createHash)("sha256").update(font).digest("hex")}.woff2`;
|
|
908
|
-
if (!bundle.assets.has(fileName)) bundle.assets.set(fileName, font);
|
|
909
|
-
downloaded.set(face.source, fileName);
|
|
910
|
-
}
|
|
911
|
-
bundle.faces.push({
|
|
912
|
-
family: face.family,
|
|
913
|
-
style: face.style,
|
|
914
|
-
weight: face.weight,
|
|
915
|
-
stretch: face.stretch,
|
|
916
|
-
unicodeRange: face.unicodeRange,
|
|
917
|
-
fileName
|
|
918
|
-
});
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
return bundle;
|
|
922
|
-
} finally {
|
|
923
|
-
clearTimeout(timeout);
|
|
924
|
-
shutdown.removeEventListener("abort", abort);
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
/** CSS strings are escaped for both the CSS parser and an HTML raw-text style element. */
|
|
928
|
-
function cssString(value) {
|
|
929
|
-
let output = "\"";
|
|
930
|
-
for (const character of value) if (isControlCharacter(character) || "\\\"<>".includes(character)) output += `\\${character.charCodeAt(0).toString(16)} `;
|
|
931
|
-
else output += character;
|
|
932
|
-
return output + "\"";
|
|
933
|
-
}
|
|
934
|
-
function renderGoogleFontCss(bundle, assetUrl) {
|
|
935
|
-
return bundle.faces.map((face) => `@font-face {
|
|
936
|
-
font-family: ${cssString(face.family)};\n font-style: ${face.style};\n font-weight: ${face.weight};\n` + (face.stretch ? ` font-stretch: ${face.stretch};\n` : "") + ` font-display: swap;\n src: url(${cssString(assetUrl(face.fileName))}) format("woff2");\n` + (face.unicodeRange ? ` unicode-range: ${face.unicodeRange};\n` : "") + "}").join("\n");
|
|
937
|
-
}
|
|
938
|
-
//#endregion
|
|
939
|
-
//#region src/plugin/createFontPlugin.ts
|
|
940
|
-
/**
|
|
941
|
-
* createFontPlugin —— 字体优化 Vite 插件(构建时 + dev)
|
|
942
|
-
*
|
|
943
|
-
* 解决三个真实问题:
|
|
944
|
-
* 1. **FOUT/FOIT**:所有 @font-face 强制注入 `font-display: swap`
|
|
945
|
-
* (没设的浏览器会 block ~3s 不渲染文本,严重伤 LCP)
|
|
946
|
-
* 2. **CLS**:自上而下扫 CSS 的 @font-face 链接,注入 <link rel="preload">
|
|
947
|
-
* 到 transformIndexHtml(让浏览器在 HTML parse 时就拉字体)
|
|
948
|
-
* 3. **Google Fonts → 自托管**:可选 `google: ['Inter', 'Noto Sans SC']`
|
|
949
|
-
* 构建时输出字体资源、开发时从内存提供,避免运行时第三方阻塞
|
|
950
|
-
*
|
|
951
|
-
* 业界对标:next/font 的子集(不做 size-adjust 推算 fallback metrics —— 那是
|
|
952
|
-
* Capsize 的活,可作为后续增强;当前覆盖 80% 收益场景)。
|
|
953
|
-
*/
|
|
954
|
-
function escapeHtmlAttribute(value) {
|
|
955
|
-
return value.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
956
|
-
}
|
|
957
|
-
/** 字体格式 → preload 的 type 属性 */
|
|
958
|
-
function fontTypeFromUrl(url) {
|
|
959
|
-
const ext = url.split("?")[0].split("#")[0].split(".").pop()?.toLowerCase();
|
|
960
|
-
return ext ? {
|
|
961
|
-
woff2: "font/woff2",
|
|
962
|
-
woff: "font/woff",
|
|
963
|
-
ttf: "font/ttf",
|
|
964
|
-
otf: "font/otf"
|
|
965
|
-
}[ext] : void 0;
|
|
966
|
-
}
|
|
967
|
-
function createSession(config) {
|
|
968
|
-
return {
|
|
969
|
-
config,
|
|
970
|
-
preloadUrls: /* @__PURE__ */ new Set(),
|
|
971
|
-
shutdown: new AbortController(),
|
|
972
|
-
devAssets: /* @__PURE__ */ new Map(),
|
|
973
|
-
starts: /* @__PURE__ */ new Map()
|
|
974
|
-
};
|
|
975
|
-
}
|
|
976
|
-
function createFontPlugin(options = {}) {
|
|
977
|
-
const injectSwap = options.injectSwap !== false;
|
|
978
|
-
const injectPreload = options.injectPreload !== false;
|
|
979
|
-
const weights = [...options.weights ?? ["400", "700"]];
|
|
980
|
-
const families = [...options.google ?? []];
|
|
981
|
-
const outRel = normalizeFontOutDir(options.outDir ?? "_/fonts");
|
|
982
|
-
const sessions = /* @__PURE__ */ new WeakMap();
|
|
983
|
-
let current = createSession();
|
|
984
|
-
function sessionFor(config) {
|
|
985
|
-
return (config ? sessions.get(config) : void 0) ?? current;
|
|
986
|
-
}
|
|
987
|
-
function environmentSession(environment) {
|
|
988
|
-
return sessionFor(environment?.getTopLevelConfig?.());
|
|
989
|
-
}
|
|
990
|
-
function assetUrl(session, fileName, htmlPath = "/index.html") {
|
|
991
|
-
const base = session.config?.base ?? "/";
|
|
992
|
-
if (base === "./" || base === "") {
|
|
993
|
-
let entry = htmlPath.split(/[?#]/, 1)[0].replace(/^\/+/, "");
|
|
994
|
-
if (!entry || entry.endsWith("/")) entry += "index.html";
|
|
995
|
-
const relative = node_path.default.posix.relative(node_path.default.posix.dirname(entry), fileName);
|
|
996
|
-
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
997
|
-
}
|
|
998
|
-
return `${base.endsWith("/") ? base : `${base}/`}${fileName}`;
|
|
999
|
-
}
|
|
1000
|
-
function ensureAssets(session) {
|
|
1001
|
-
session.shutdown.signal.throwIfAborted();
|
|
1002
|
-
return session.downloading ??= loadGoogleFontAssets(families, weights, outRel, session.shutdown.signal).then((bundle) => {
|
|
1003
|
-
session.shutdown.signal.throwIfAborted();
|
|
1004
|
-
session.assets = bundle;
|
|
1005
|
-
if (session.config?.command === "serve") for (const [fileName, bytes] of bundle.assets) session.devAssets.set(new URL(assetUrl(session, fileName), "http://font-assets.invalid").pathname, bytes);
|
|
1006
|
-
return bundle;
|
|
1007
|
-
}).catch((error) => {
|
|
1008
|
-
session.downloading = void 0;
|
|
1009
|
-
throw error;
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
function dispose(session) {
|
|
1013
|
-
session.shutdown.abort(/* @__PURE__ */ new Error("Google font asset session closed"));
|
|
1014
|
-
session.assets = void 0;
|
|
1015
|
-
session.downloading = void 0;
|
|
1016
|
-
session.devAssets.clear();
|
|
1017
|
-
session.starts.clear();
|
|
1018
|
-
session.preloadUrls.clear();
|
|
1019
|
-
}
|
|
1020
|
-
return {
|
|
1021
|
-
name: "isr-engine:font-optimization",
|
|
1022
|
-
enforce: "post",
|
|
1023
|
-
sharedDuringBuild: true,
|
|
1024
|
-
configResolved(c) {
|
|
1025
|
-
current = createSession(c);
|
|
1026
|
-
sessions.set(c, current);
|
|
1027
|
-
},
|
|
1028
|
-
/** Share validated downloads across environments; only client outputs own browser assets. */
|
|
1029
|
-
async buildStart() {
|
|
1030
|
-
const session = environmentSession(this.environment);
|
|
1031
|
-
if (!families.length || session.config?.command === "build" && this.environment?.config.consumer === "server") return;
|
|
1032
|
-
const key = this.environment ?? this;
|
|
1033
|
-
let pending = session.starts.get(key);
|
|
1034
|
-
if (!pending) {
|
|
1035
|
-
pending = (async () => {
|
|
1036
|
-
const bundle = await ensureAssets(session);
|
|
1037
|
-
session.shutdown.signal.throwIfAborted();
|
|
1038
|
-
if (session.config?.command === "build") for (const [fileName, source] of bundle.assets) this.emitFile({
|
|
1039
|
-
type: "asset",
|
|
1040
|
-
fileName,
|
|
1041
|
-
source
|
|
1042
|
-
});
|
|
1043
|
-
})();
|
|
1044
|
-
session.starts.set(key, pending);
|
|
1045
|
-
}
|
|
1046
|
-
try {
|
|
1047
|
-
await pending;
|
|
1048
|
-
} finally {
|
|
1049
|
-
if (session.starts.get(key) === pending) session.starts.delete(key);
|
|
1050
|
-
}
|
|
1051
|
-
},
|
|
1052
|
-
configureServer(server) {
|
|
1053
|
-
const session = sessionFor(server.config);
|
|
1054
|
-
server.httpServer?.once("close", () => dispose(session));
|
|
1055
|
-
server.middlewares.use((req, res, next) => {
|
|
1056
|
-
const bytes = session.devAssets.get((req.url ?? "").split(/[?#]/, 1)[0]);
|
|
1057
|
-
if (!bytes) return next();
|
|
1058
|
-
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
1059
|
-
res.statusCode = 405;
|
|
1060
|
-
res.setHeader("allow", "GET, HEAD");
|
|
1061
|
-
res.end();
|
|
1062
|
-
return;
|
|
1063
|
-
}
|
|
1064
|
-
res.setHeader("content-type", "font/woff2");
|
|
1065
|
-
res.setHeader("x-content-type-options", "nosniff");
|
|
1066
|
-
res.setHeader("content-length", bytes.length);
|
|
1067
|
-
res.setHeader("cache-control", "public, max-age=31536000, immutable");
|
|
1068
|
-
res.end(req.method === "HEAD" ? void 0 : bytes);
|
|
1069
|
-
});
|
|
1070
|
-
},
|
|
1071
|
-
closeBundle() {
|
|
1072
|
-
const session = environmentSession(this.environment);
|
|
1073
|
-
if (session.config?.command === "serve") dispose(session);
|
|
1074
|
-
},
|
|
1075
|
-
closeWatcher() {
|
|
1076
|
-
const session = environmentSession(this.environment);
|
|
1077
|
-
if (session.config?.command === "build" && this.environment?.config.consumer !== "server") dispose(session);
|
|
1078
|
-
},
|
|
1079
|
-
/** 任何 CSS 文件经过 transform:注入 swap + 收集 preload url */
|
|
1080
|
-
transform(code, id) {
|
|
1081
|
-
const session = environmentSession(this.environment);
|
|
1082
|
-
if (!/\.(css|scss|less|sass|styl)(\?|$)/.test(id)) return null;
|
|
1083
|
-
let stylesheet;
|
|
1084
|
-
try {
|
|
1085
|
-
stylesheet = (0, css_tree.parse)(code, { positions: true });
|
|
1086
|
-
} catch {
|
|
1087
|
-
return null;
|
|
1088
|
-
}
|
|
1089
|
-
const insertions = [];
|
|
1090
|
-
(0, css_tree.walk)(stylesheet, {
|
|
1091
|
-
visit: "Atrule",
|
|
1092
|
-
enter(rule) {
|
|
1093
|
-
if (rule.name.toLowerCase() !== "font-face" || !rule.block) return;
|
|
1094
|
-
let hasDisplay = false;
|
|
1095
|
-
let firstUrl;
|
|
1096
|
-
rule.block.children.forEach((declaration) => {
|
|
1097
|
-
if (declaration.type !== "Declaration") return;
|
|
1098
|
-
const property = declaration.property.toLowerCase();
|
|
1099
|
-
if (property === "font-display") hasDisplay = true;
|
|
1100
|
-
if (property === "src" && firstUrl === void 0) (0, css_tree.walk)(declaration.value, {
|
|
1101
|
-
visit: "Url",
|
|
1102
|
-
enter(url) {
|
|
1103
|
-
firstUrl ??= url.value;
|
|
1104
|
-
}
|
|
1105
|
-
});
|
|
1106
|
-
});
|
|
1107
|
-
if (firstUrl && injectPreload) session.preloadUrls.add(firstUrl);
|
|
1108
|
-
const close = rule.block.loc ? rule.block.loc.end.offset - 1 : -1;
|
|
1109
|
-
if (injectSwap && !hasDisplay && code[close] === "}") insertions.push(close);
|
|
1110
|
-
}
|
|
1111
|
-
});
|
|
1112
|
-
if (insertions.length === 0) return null;
|
|
1113
|
-
const parts = [];
|
|
1114
|
-
let cursor = 0;
|
|
1115
|
-
for (const offset of insertions.sort((a, b) => a - b)) {
|
|
1116
|
-
parts.push(code.slice(cursor, offset), "; font-display: swap;\n");
|
|
1117
|
-
cursor = offset;
|
|
1118
|
-
}
|
|
1119
|
-
parts.push(code.slice(cursor));
|
|
1120
|
-
return {
|
|
1121
|
-
code: parts.join(""),
|
|
1122
|
-
map: null
|
|
1123
|
-
};
|
|
1124
|
-
},
|
|
1125
|
-
/** HTML 注入:preload 标签 + 自托管 google fonts 的 @font-face 块 */
|
|
1126
|
-
transformIndexHtml(html, context) {
|
|
1127
|
-
const session = sessionFor(context?.server?.config);
|
|
1128
|
-
const render = () => {
|
|
1129
|
-
const generatedCss = session.assets ? renderGoogleFontCss(session.assets, (fileName) => assetUrl(session, fileName, context?.path)) : "";
|
|
1130
|
-
const tags = [];
|
|
1131
|
-
if (generatedCss) tags.push({
|
|
1132
|
-
tag: "style",
|
|
1133
|
-
attrs: { "data-isr-engine-font": "google" },
|
|
1134
|
-
injectTo: "head"
|
|
1135
|
-
});
|
|
1136
|
-
for (const url of session.preloadUrls) tags.push({
|
|
1137
|
-
tag: "link",
|
|
1138
|
-
attrs: {
|
|
1139
|
-
rel: "preload",
|
|
1140
|
-
href: url,
|
|
1141
|
-
as: "font",
|
|
1142
|
-
type: fontTypeFromUrl(url) ?? "font/woff2",
|
|
1143
|
-
crossorigin: "anonymous"
|
|
1144
|
-
},
|
|
1145
|
-
injectTo: "head"
|
|
1146
|
-
});
|
|
1147
|
-
if (tags.length === 0) return html;
|
|
1148
|
-
const inject = `${tags.filter((t) => t.tag === "link").map((t) => `<link ${Object.entries(t.attrs ?? {}).map(([k, v]) => `${k}="${escapeHtmlAttribute(v)}"`).join(" ")}>`).join("\n ")}\n ${generatedCss ? `<style data-isr-engine-font="google">${generatedCss}</style>` : ""}\n`;
|
|
1149
|
-
return html.replace("</head>", ` ${inject}</head>`);
|
|
1150
|
-
};
|
|
1151
|
-
if (families.length && !session.assets) return ensureAssets(session).then(render);
|
|
1152
|
-
return render();
|
|
1153
|
-
}
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
//#endregion
|
|
1157
|
-
//#region src/runtime/telemetry.ts
|
|
1158
|
-
var currentHandle = null;
|
|
1159
|
-
var pendingCalls = [];
|
|
1160
|
-
function __setBrowserTelemetryHandle(handle) {
|
|
1161
|
-
currentHandle = handle;
|
|
1162
|
-
const calls = pendingCalls;
|
|
1163
|
-
pendingCalls = [];
|
|
1164
|
-
for (const call of calls) try {
|
|
1165
|
-
call(handle);
|
|
1166
|
-
} catch {}
|
|
1167
|
-
}
|
|
1168
|
-
function __clearBrowserTelemetryHandle(handle) {
|
|
1169
|
-
if (currentHandle === handle) currentHandle = null;
|
|
1170
|
-
}
|
|
1171
|
-
//#endregion
|
|
1172
|
-
//#region src/defaults/runtime/browserObservability.ts
|
|
1173
|
-
/**
|
|
1174
|
-
* Browser observability bridge.
|
|
1175
|
-
*
|
|
1176
|
-
* isr-engine owns the browser lifecycle points: app boot, page navigation,
|
|
1177
|
-
* Web Vitals, global browser errors and Server Action failures. It deliberately
|
|
1178
|
-
* does not import a vendor SDK or a project-specific SDK. The only integration
|
|
1179
|
-
* contract is HTTP endpoints resolved from ssr.config.ts runtime.telemetry.
|
|
1180
|
-
* Rendering, hydration and navigation must never depend on observability.
|
|
1181
|
-
*/
|
|
1182
|
-
/** Dev-runtime 噪声 —— 由开发工具链自身产生的错误,并非业务问题。
|
|
1183
|
-
* Sentry 风格 inbound filter,industry-standard。 */
|
|
1184
|
-
var DEFAULT_IGNORE_SOURCE_PATTERNS = [
|
|
1185
|
-
/@vite\/client/,
|
|
1186
|
-
/@react-refresh/,
|
|
1187
|
-
/__vite_ping/,
|
|
1188
|
-
/webpack-internal:\/\//,
|
|
1189
|
-
/webpack-hmr/,
|
|
1190
|
-
/^chrome-extension:\/\//,
|
|
1191
|
-
/^moz-extension:\/\//,
|
|
1192
|
-
/^safari-extension:\/\//
|
|
1193
|
-
];
|
|
1194
|
-
async function installBrowserObservability(options) {
|
|
1195
|
-
const cleanups = [];
|
|
1196
|
-
let currentUser = options.user;
|
|
1197
|
-
const getUser = () => currentUser;
|
|
1198
|
-
const analytics = options.analytics === false ? null : createEndpointAnalyticsClient(options, getUser);
|
|
1199
|
-
const errorReporter = options.errorReporting === false ? null : createEndpointErrorReporter(options, getUser);
|
|
1200
|
-
if (analytics && options.analytics !== false && options.analytics?.webVitals && typeof analytics.installWebVitals === "function") cleanups.push(analytics.installWebVitals());
|
|
1201
|
-
if (analytics && options.analytics !== false && options.analytics?.trackInitialPage !== false) analytics.page();
|
|
1202
|
-
const globalCleanup = errorReporter?.installGlobalHandlers?.({ captureResourceErrors: options.errorReporting !== false ? options.errorReporting?.captureResourceErrors : void 0 });
|
|
1203
|
-
if (globalCleanup) cleanups.push(globalCleanup);
|
|
1204
|
-
const handle = {
|
|
1205
|
-
track(name, properties, trackOptions) {
|
|
1206
|
-
analytics?.track(name, properties, trackOptions);
|
|
1207
|
-
},
|
|
1208
|
-
capture(error, context) {
|
|
1209
|
-
errorReporter?.captureException(error, context);
|
|
1210
|
-
},
|
|
1211
|
-
measure(name, value, measureOptions) {
|
|
1212
|
-
analytics?.measure(name, value, measureOptions);
|
|
1213
|
-
},
|
|
1214
|
-
page(url) {
|
|
1215
|
-
if (!analytics) return;
|
|
1216
|
-
analytics.page(typeof url === "string" ? sanitizeUrl(url, options.includeQueryString) : url ? toPagePath(url, options.includeQueryString) : void 0);
|
|
1217
|
-
},
|
|
1218
|
-
captureActionError(error, actionId) {
|
|
1219
|
-
errorReporter?.captureException(error, {
|
|
1220
|
-
source: "server-action",
|
|
1221
|
-
tags: { actionId }
|
|
1222
|
-
});
|
|
1223
|
-
},
|
|
1224
|
-
setUser(user) {
|
|
1225
|
-
currentUser = user ?? void 0;
|
|
1226
|
-
},
|
|
1227
|
-
flush() {
|
|
1228
|
-
return Promise.all([analytics?.flush?.(), errorReporter?.flush?.()]).then(() => void 0);
|
|
1229
|
-
},
|
|
1230
|
-
shutdown() {
|
|
1231
|
-
__clearBrowserTelemetryHandle(handle);
|
|
1232
|
-
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
1233
|
-
analytics?.shutdown?.();
|
|
1234
|
-
errorReporter?.shutdown?.();
|
|
1235
|
-
}
|
|
1236
|
-
};
|
|
1237
|
-
__setBrowserTelemetryHandle(handle);
|
|
1238
|
-
return handle;
|
|
1239
|
-
}
|
|
1240
|
-
function toPagePath(url, includeQueryString) {
|
|
1241
|
-
return includeQueryString ? `${url.pathname}${url.search}` : url.pathname;
|
|
1242
|
-
}
|
|
1243
|
-
function createEndpointAnalyticsClient(options, getUser) {
|
|
1244
|
-
const analyticsOptions = options.analytics === false ? void 0 : options.analytics;
|
|
1245
|
-
const endpoint = analyticsOptions?.endpoint;
|
|
1246
|
-
if (!endpoint) return null;
|
|
1247
|
-
const base = createEndpointQueue(options, {
|
|
1248
|
-
endpoint,
|
|
1249
|
-
batchSize: analyticsOptions?.batchSize ?? 20,
|
|
1250
|
-
flushIntervalMs: analyticsOptions?.flushIntervalMs ?? 3e3,
|
|
1251
|
-
maxQueueSize: analyticsOptions?.maxQueueSize ?? 500,
|
|
1252
|
-
retryBaseDelayMs: analyticsOptions?.retryBaseDelayMs ?? 1e3,
|
|
1253
|
-
retryMaxDelayMs: analyticsOptions?.retryMaxDelayMs ?? 3e4,
|
|
1254
|
-
sampleRate: analyticsOptions?.sampleRate ?? 1,
|
|
1255
|
-
key: "isr_engine_builtin_analytics"
|
|
1256
|
-
}, getUser);
|
|
1257
|
-
if (!base) return null;
|
|
1258
|
-
return {
|
|
1259
|
-
track(name, properties, trackOptions) {
|
|
1260
|
-
base.enqueue({
|
|
1261
|
-
name,
|
|
1262
|
-
properties: properties ?? {},
|
|
1263
|
-
tags: normalizeTags(trackOptions?.tags)
|
|
1264
|
-
});
|
|
1265
|
-
},
|
|
1266
|
-
page(path) {
|
|
1267
|
-
base.enqueue({
|
|
1268
|
-
name: "page_view",
|
|
1269
|
-
properties: {
|
|
1270
|
-
path: path ?? currentPath(options.includeQueryString),
|
|
1271
|
-
title: isBrowser() && typeof document.title === "string" ? document.title : void 0,
|
|
1272
|
-
referrer: isBrowser() && typeof document.referrer === "string" ? document.referrer : void 0
|
|
1273
|
-
}
|
|
1274
|
-
});
|
|
1275
|
-
},
|
|
1276
|
-
measure(name, value, measureOptions) {
|
|
1277
|
-
if (!Number.isFinite(value)) return;
|
|
1278
|
-
base.enqueue({
|
|
1279
|
-
name: "metric",
|
|
1280
|
-
properties: {
|
|
1281
|
-
metric: name,
|
|
1282
|
-
value,
|
|
1283
|
-
unit: measureOptions?.unit,
|
|
1284
|
-
...measureOptions?.properties ?? {}
|
|
1285
|
-
},
|
|
1286
|
-
tags: normalizeTags(measureOptions?.tags)
|
|
1287
|
-
});
|
|
1288
|
-
},
|
|
1289
|
-
installWebVitals() {
|
|
1290
|
-
return installFallbackWebVitals(base, options.includeQueryString);
|
|
1291
|
-
},
|
|
1292
|
-
flush() {
|
|
1293
|
-
return base.flush();
|
|
1294
|
-
},
|
|
1295
|
-
shutdown() {
|
|
1296
|
-
base.shutdown();
|
|
1297
|
-
}
|
|
1298
|
-
};
|
|
1299
|
-
}
|
|
1300
|
-
function createEndpointErrorReporter(options, getUser) {
|
|
1301
|
-
const errorOptions = options.errorReporting === false ? void 0 : options.errorReporting;
|
|
1302
|
-
const endpoint = errorOptions?.endpoint;
|
|
1303
|
-
if (!endpoint) return null;
|
|
1304
|
-
const base = createEndpointQueue(options, {
|
|
1305
|
-
endpoint,
|
|
1306
|
-
batchSize: errorOptions?.batchSize ?? 10,
|
|
1307
|
-
flushIntervalMs: errorOptions?.flushIntervalMs ?? 3e3,
|
|
1308
|
-
maxQueueSize: errorOptions?.maxQueueSize ?? 200,
|
|
1309
|
-
retryBaseDelayMs: errorOptions?.retryBaseDelayMs ?? 1e3,
|
|
1310
|
-
retryMaxDelayMs: errorOptions?.retryMaxDelayMs ?? 3e4,
|
|
1311
|
-
sampleRate: errorOptions?.sampleRate ?? 1,
|
|
1312
|
-
key: "isr_engine_builtin_errors"
|
|
1313
|
-
}, getUser);
|
|
1314
|
-
if (!base) return null;
|
|
1315
|
-
const captureException = (error, context = {}) => {
|
|
1316
|
-
const normalized = normalizeError(error);
|
|
1317
|
-
base.enqueue({
|
|
1318
|
-
message: normalized.message,
|
|
1319
|
-
name: normalized.name,
|
|
1320
|
-
stack: normalized.stack,
|
|
1321
|
-
level: typeof context.level === "string" ? context.level : "error",
|
|
1322
|
-
source: typeof context.source === "string" ? context.source : void 0,
|
|
1323
|
-
tags: normalizeTags(context.tags),
|
|
1324
|
-
extra: isRecord(context.extra) ? context.extra : void 0,
|
|
1325
|
-
fingerprint: Array.isArray(context.fingerprint) ? context.fingerprint : void 0
|
|
1326
|
-
});
|
|
1327
|
-
};
|
|
1328
|
-
const ignorePatterns = resolveIgnorePatterns(errorOptions?.ignoreSourcePatterns);
|
|
1329
|
-
return {
|
|
1330
|
-
captureException,
|
|
1331
|
-
installGlobalHandlers(globalOptions = {}) {
|
|
1332
|
-
if (!isBrowser()) return () => {};
|
|
1333
|
-
const captureResourceErrors = globalOptions.captureResourceErrors !== false;
|
|
1334
|
-
const onError = (event) => {
|
|
1335
|
-
if (event instanceof ErrorEvent) {
|
|
1336
|
-
if (shouldIgnore(ignorePatterns, event.filename, event.error)) return;
|
|
1337
|
-
captureException(event.error ?? event.message, {
|
|
1338
|
-
source: event.filename,
|
|
1339
|
-
extra: {
|
|
1340
|
-
lineno: event.lineno,
|
|
1341
|
-
colno: event.colno
|
|
1342
|
-
}
|
|
1343
|
-
});
|
|
1344
|
-
return;
|
|
1345
|
-
}
|
|
1346
|
-
if (!captureResourceErrors) return;
|
|
1347
|
-
const target = event.target;
|
|
1348
|
-
if (target instanceof HTMLElement) {
|
|
1349
|
-
const url = target instanceof HTMLImageElement || target instanceof HTMLScriptElement ? target.src : target instanceof HTMLLinkElement ? target.href : void 0;
|
|
1350
|
-
if (shouldIgnore(ignorePatterns, url, void 0)) return;
|
|
1351
|
-
captureException("Resource load failed", {
|
|
1352
|
-
level: "warning",
|
|
1353
|
-
source: target.tagName.toLowerCase(),
|
|
1354
|
-
extra: { url: sanitizeUrl(url, options.includeQueryString) }
|
|
1355
|
-
});
|
|
1356
|
-
}
|
|
1357
|
-
};
|
|
1358
|
-
const onRejection = (event) => {
|
|
1359
|
-
if (shouldIgnore(ignorePatterns, void 0, event.reason)) return;
|
|
1360
|
-
captureException(event.reason, { source: "unhandledrejection" });
|
|
1361
|
-
};
|
|
1362
|
-
window.addEventListener("error", onError, true);
|
|
1363
|
-
window.addEventListener("unhandledrejection", onRejection);
|
|
1364
|
-
return () => {
|
|
1365
|
-
window.removeEventListener("error", onError, true);
|
|
1366
|
-
window.removeEventListener("unhandledrejection", onRejection);
|
|
1367
|
-
};
|
|
1368
|
-
},
|
|
1369
|
-
flush() {
|
|
1370
|
-
return base.flush();
|
|
1371
|
-
},
|
|
1372
|
-
shutdown() {
|
|
1373
|
-
base.shutdown();
|
|
1374
|
-
}
|
|
1375
|
-
};
|
|
1376
|
-
}
|
|
1377
|
-
function createEndpointQueue(options, baseOptions, getUser) {
|
|
1378
|
-
const queue = [];
|
|
1379
|
-
const sessionId = readOrCreateBrowserId(`${baseOptions.key}_session`);
|
|
1380
|
-
const anonymousId = readOrCreateBrowserId(`${baseOptions.key}_anonymous`);
|
|
1381
|
-
if (!sessionId || !anonymousId) return null;
|
|
1382
|
-
let timer = null;
|
|
1383
|
-
let retryTimer = null;
|
|
1384
|
-
let inFlight = false;
|
|
1385
|
-
let consecutiveFailures = 0;
|
|
1386
|
-
let disposeLifecycleListeners = null;
|
|
1387
|
-
const flush = async (flushOptions = {}) => {
|
|
1388
|
-
if (queue.length === 0) return;
|
|
1389
|
-
if (!flushOptions.beacon && (inFlight || retryTimer !== null)) return;
|
|
1390
|
-
const payloads = queue.splice(0);
|
|
1391
|
-
const isError = baseOptions.key.includes("errors");
|
|
1392
|
-
const body = JSON.stringify({
|
|
1393
|
-
app: options.app,
|
|
1394
|
-
sentAt: Date.now(),
|
|
1395
|
-
[isError ? "reports" : "events"]: payloads
|
|
1396
|
-
});
|
|
1397
|
-
let shouldDrainAfterSuccess = false;
|
|
1398
|
-
inFlight = true;
|
|
1399
|
-
try {
|
|
1400
|
-
await postJson(baseOptions.endpoint, body, flushOptions.beacon);
|
|
1401
|
-
consecutiveFailures = 0;
|
|
1402
|
-
shouldDrainAfterSuccess = !flushOptions.beacon && queue.length >= baseOptions.batchSize;
|
|
1403
|
-
if (queue.length === 0) clearRetryTimer();
|
|
1404
|
-
} catch {
|
|
1405
|
-
queue.unshift(...payloads);
|
|
1406
|
-
queue.splice(baseOptions.maxQueueSize);
|
|
1407
|
-
consecutiveFailures += 1;
|
|
1408
|
-
scheduleRetry();
|
|
1409
|
-
} finally {
|
|
1410
|
-
inFlight = false;
|
|
1411
|
-
if (shouldDrainAfterSuccess) flush();
|
|
1412
|
-
}
|
|
1413
|
-
};
|
|
1414
|
-
const enqueue = (payload) => {
|
|
1415
|
-
if (baseOptions.sampleRate <= 0) return;
|
|
1416
|
-
if (baseOptions.sampleRate < 1 && Math.random() > baseOptions.sampleRate) return;
|
|
1417
|
-
const id = createId(baseOptions.key.includes("errors") ? "err" : "evt");
|
|
1418
|
-
if (!id) return;
|
|
1419
|
-
queue.push({
|
|
1420
|
-
id,
|
|
1421
|
-
app: options.app,
|
|
1422
|
-
ts: Date.now(),
|
|
1423
|
-
release: options.release,
|
|
1424
|
-
environment: options.environment,
|
|
1425
|
-
sessionId,
|
|
1426
|
-
anonymousId,
|
|
1427
|
-
user: getUser(),
|
|
1428
|
-
url: currentPath(options.includeQueryString),
|
|
1429
|
-
...payload
|
|
1430
|
-
});
|
|
1431
|
-
if (queue.length > baseOptions.maxQueueSize) queue.splice(0, queue.length - baseOptions.maxQueueSize);
|
|
1432
|
-
if (queue.length >= baseOptions.batchSize) flush();
|
|
1433
|
-
};
|
|
1434
|
-
const shutdown = () => {
|
|
1435
|
-
if (timer !== null) {
|
|
1436
|
-
clearInterval(timer);
|
|
1437
|
-
timer = null;
|
|
1438
|
-
}
|
|
1439
|
-
clearRetryTimer();
|
|
1440
|
-
disposeLifecycleListeners?.();
|
|
1441
|
-
disposeLifecycleListeners = null;
|
|
1442
|
-
flush({ beacon: true });
|
|
1443
|
-
};
|
|
1444
|
-
const scheduleRetry = () => {
|
|
1445
|
-
if (!isBrowser() || retryTimer !== null || queue.length === 0) return;
|
|
1446
|
-
const base = Math.max(100, baseOptions.retryBaseDelayMs);
|
|
1447
|
-
const max = Math.max(base, baseOptions.retryMaxDelayMs);
|
|
1448
|
-
const backoff = Math.min(max, base * 2 ** Math.max(0, consecutiveFailures - 1));
|
|
1449
|
-
const jitter = Math.floor(backoff * .2 * Math.random());
|
|
1450
|
-
retryTimer = window.setTimeout(() => {
|
|
1451
|
-
retryTimer = null;
|
|
1452
|
-
flush();
|
|
1453
|
-
}, backoff + jitter);
|
|
1454
|
-
};
|
|
1455
|
-
const clearRetryTimer = () => {
|
|
1456
|
-
if (retryTimer !== null && isBrowser()) window.clearTimeout(retryTimer);
|
|
1457
|
-
retryTimer = null;
|
|
1458
|
-
};
|
|
1459
|
-
if (isBrowser()) {
|
|
1460
|
-
if (baseOptions.flushIntervalMs > 0) timer = window.setInterval(() => void flush(), baseOptions.flushIntervalMs);
|
|
1461
|
-
const flushOnPageHide = () => void flush({ beacon: true });
|
|
1462
|
-
const onHidden = () => {
|
|
1463
|
-
if (document.visibilityState === "hidden") flush({ beacon: true });
|
|
1464
|
-
};
|
|
1465
|
-
const onOnline = () => void flush();
|
|
1466
|
-
window.addEventListener("pagehide", flushOnPageHide);
|
|
1467
|
-
window.addEventListener("online", onOnline);
|
|
1468
|
-
document.addEventListener("visibilitychange", onHidden);
|
|
1469
|
-
disposeLifecycleListeners = () => {
|
|
1470
|
-
window.removeEventListener("pagehide", flushOnPageHide);
|
|
1471
|
-
window.removeEventListener("online", onOnline);
|
|
1472
|
-
document.removeEventListener("visibilitychange", onHidden);
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
return {
|
|
1476
|
-
enqueue,
|
|
1477
|
-
flush,
|
|
1478
|
-
shutdown
|
|
1479
|
-
};
|
|
1480
|
-
}
|
|
1481
|
-
function installFallbackWebVitals(base, includeQueryString) {
|
|
1482
|
-
if (!isBrowser() || typeof PerformanceObserver === "undefined") return () => {};
|
|
1483
|
-
const cleanups = [];
|
|
1484
|
-
let cls = 0;
|
|
1485
|
-
let lcp = 0;
|
|
1486
|
-
let inp = 0;
|
|
1487
|
-
let inpEntry;
|
|
1488
|
-
const observe = (type, callback, options = {}) => {
|
|
1489
|
-
try {
|
|
1490
|
-
const observer = new PerformanceObserver((list) => {
|
|
1491
|
-
for (const entry of list.getEntries()) callback(entry);
|
|
1492
|
-
});
|
|
1493
|
-
observer.observe({
|
|
1494
|
-
type,
|
|
1495
|
-
buffered: true,
|
|
1496
|
-
...options
|
|
1497
|
-
});
|
|
1498
|
-
cleanups.push(() => observer.disconnect());
|
|
1499
|
-
} catch {}
|
|
1500
|
-
};
|
|
1501
|
-
observe("paint", (entry) => {
|
|
1502
|
-
if (entry.name === "first-contentful-paint") base.enqueue({
|
|
1503
|
-
name: "web_vital",
|
|
1504
|
-
properties: createWebVitalPayload("FCP", entry.startTime, includeQueryString, entry)
|
|
1505
|
-
});
|
|
1506
|
-
});
|
|
1507
|
-
observe("largest-contentful-paint", (entry) => {
|
|
1508
|
-
lcp = entry.startTime;
|
|
1509
|
-
});
|
|
1510
|
-
observe("layout-shift", (entry) => {
|
|
1511
|
-
if (entry.hadRecentInput !== true && typeof entry.value === "number") cls += entry.value;
|
|
1512
|
-
});
|
|
1513
|
-
observe("event", (entry) => {
|
|
1514
|
-
if (typeof entry.duration === "number" && typeof entry.interactionId === "number" && entry.interactionId > 0) {
|
|
1515
|
-
if (entry.duration >= inp) {
|
|
1516
|
-
inp = entry.duration;
|
|
1517
|
-
inpEntry = entry;
|
|
1518
|
-
}
|
|
1519
|
-
}
|
|
1520
|
-
}, { durationThreshold: 40 });
|
|
1521
|
-
const flushFinalVitals = () => {
|
|
1522
|
-
if (lcp > 0) base.enqueue({
|
|
1523
|
-
name: "web_vital",
|
|
1524
|
-
properties: createWebVitalPayload("LCP", lcp, includeQueryString)
|
|
1525
|
-
});
|
|
1526
|
-
if (inp > 0) base.enqueue({
|
|
1527
|
-
name: "web_vital",
|
|
1528
|
-
properties: createWebVitalPayload("INP", inp, includeQueryString, inpEntry)
|
|
1529
|
-
});
|
|
1530
|
-
if (cls > 0) base.enqueue({
|
|
1531
|
-
name: "web_vital",
|
|
1532
|
-
properties: createWebVitalPayload("CLS", cls, includeQueryString)
|
|
1533
|
-
});
|
|
1534
|
-
};
|
|
1535
|
-
const nav = performance.getEntriesByType("navigation")[0];
|
|
1536
|
-
if (nav) base.enqueue({
|
|
1537
|
-
name: "web_vital",
|
|
1538
|
-
properties: createWebVitalPayload("TTFB", nav.responseStart, includeQueryString, nav)
|
|
1539
|
-
});
|
|
1540
|
-
const flushIfHidden = () => {
|
|
1541
|
-
if (document.visibilityState === "hidden") flushFinalVitals();
|
|
1542
|
-
};
|
|
1543
|
-
window.addEventListener("pagehide", flushFinalVitals);
|
|
1544
|
-
document.addEventListener("visibilitychange", flushIfHidden);
|
|
1545
|
-
cleanups.push(() => {
|
|
1546
|
-
window.removeEventListener("pagehide", flushFinalVitals);
|
|
1547
|
-
document.removeEventListener("visibilitychange", flushIfHidden);
|
|
1548
|
-
});
|
|
1549
|
-
return () => cleanups.splice(0).forEach((cleanup) => cleanup());
|
|
1550
|
-
}
|
|
1551
|
-
function createWebVitalPayload(name, value, includeQueryString, entry) {
|
|
1552
|
-
const payload = {
|
|
1553
|
-
name,
|
|
1554
|
-
value,
|
|
1555
|
-
href: currentHref(includeQueryString),
|
|
1556
|
-
path: currentPath(includeQueryString),
|
|
1557
|
-
route: currentRoute(),
|
|
1558
|
-
title: isBrowser() && typeof document.title === "string" ? document.title : void 0,
|
|
1559
|
-
navigationType: currentNavigationType(),
|
|
1560
|
-
visibilityState: isBrowser() && typeof document.visibilityState === "string" ? document.visibilityState : void 0,
|
|
1561
|
-
device: currentDevice(),
|
|
1562
|
-
viewport: currentViewport(),
|
|
1563
|
-
connection: currentConnection(),
|
|
1564
|
-
entryType: entry?.entryType,
|
|
1565
|
-
startTime: typeof entry?.startTime === "number" ? entry.startTime : void 0
|
|
1566
|
-
};
|
|
1567
|
-
const target = pickPerformanceTarget(entry);
|
|
1568
|
-
if (target) payload.target = target;
|
|
1569
|
-
if (typeof entry?.interactionId === "number") payload.interactionId = entry.interactionId;
|
|
1570
|
-
return payload;
|
|
1571
|
-
}
|
|
1572
|
-
async function postJson(endpoint, body, beacon) {
|
|
1573
|
-
if (beacon && isBrowser() && typeof navigator.sendBeacon === "function") {
|
|
1574
|
-
const payload = typeof Blob !== "undefined" ? new Blob([body], { type: "application/json" }) : body;
|
|
1575
|
-
if (navigator.sendBeacon(endpoint, payload)) return;
|
|
1576
|
-
}
|
|
1577
|
-
if (typeof fetch !== "function") return;
|
|
1578
|
-
const response = await fetch(endpoint, {
|
|
1579
|
-
method: "POST",
|
|
1580
|
-
headers: { "content-type": "application/json" },
|
|
1581
|
-
body,
|
|
1582
|
-
keepalive: beacon
|
|
1583
|
-
});
|
|
1584
|
-
if (!response.ok) throw new Error(`observability upload failed: ${response.status}`);
|
|
1585
|
-
}
|
|
1586
|
-
function currentPath(includeQueryString) {
|
|
1587
|
-
if (!isBrowser()) return "/";
|
|
1588
|
-
const { pathname, search } = window.location;
|
|
1589
|
-
return includeQueryString ? `${pathname}${search}` : pathname;
|
|
1590
|
-
}
|
|
1591
|
-
function currentHref(includeQueryString) {
|
|
1592
|
-
if (!isBrowser()) return void 0;
|
|
1593
|
-
try {
|
|
1594
|
-
const url = new URL(window.location.href);
|
|
1595
|
-
return includeQueryString ? `${url.origin}${url.pathname}${url.search}` : `${url.origin}${url.pathname}`;
|
|
1596
|
-
} catch {
|
|
1597
|
-
return;
|
|
1598
|
-
}
|
|
1599
|
-
}
|
|
1600
|
-
function currentRoute() {
|
|
1601
|
-
if (!isBrowser()) return void 0;
|
|
1602
|
-
const explicit = document.documentElement?.getAttribute("data-route") ?? document.body?.getAttribute("data-route") ?? void 0;
|
|
1603
|
-
if (explicit) return explicit;
|
|
1604
|
-
const globalRoute = window.__ISR_ENGINE_ROUTE__;
|
|
1605
|
-
return typeof globalRoute === "string" && globalRoute.trim() ? globalRoute : void 0;
|
|
1606
|
-
}
|
|
1607
|
-
function currentNavigationType() {
|
|
1608
|
-
if (!isBrowser() || typeof performance.getEntriesByType !== "function") return void 0;
|
|
1609
|
-
const nav = performance.getEntriesByType("navigation")[0];
|
|
1610
|
-
return typeof nav?.type === "string" ? nav.type : void 0;
|
|
1611
|
-
}
|
|
1612
|
-
function currentDevice() {
|
|
1613
|
-
if (!isBrowser()) return void 0;
|
|
1614
|
-
const uaData = navigator.userAgentData;
|
|
1615
|
-
if (typeof uaData?.mobile === "boolean") return uaData.mobile ? "mobile" : "desktop";
|
|
1616
|
-
const width = window.innerWidth;
|
|
1617
|
-
if (width < 768) return "mobile";
|
|
1618
|
-
if (width < 1180) return "tablet";
|
|
1619
|
-
return "desktop";
|
|
1620
|
-
}
|
|
1621
|
-
function currentViewport() {
|
|
1622
|
-
if (!isBrowser()) return void 0;
|
|
1623
|
-
if (!Number.isFinite(window.innerWidth) || !Number.isFinite(window.innerHeight)) return;
|
|
1624
|
-
return `${window.innerWidth}x${window.innerHeight}`;
|
|
1625
|
-
}
|
|
1626
|
-
function currentConnection() {
|
|
1627
|
-
if (!isBrowser()) return void 0;
|
|
1628
|
-
const connection = navigator.connection;
|
|
1629
|
-
if (!connection?.effectiveType) return void 0;
|
|
1630
|
-
return connection.saveData ? `${connection.effectiveType}:save-data` : connection.effectiveType;
|
|
1631
|
-
}
|
|
1632
|
-
function pickPerformanceTarget(entry) {
|
|
1633
|
-
if (typeof Element === "undefined") return void 0;
|
|
1634
|
-
const target = entry?.target;
|
|
1635
|
-
if (!(target instanceof Element)) return void 0;
|
|
1636
|
-
return toElementSelector(target);
|
|
1637
|
-
}
|
|
1638
|
-
function toElementSelector(element) {
|
|
1639
|
-
const tag = element.tagName.toLowerCase();
|
|
1640
|
-
const id = element.id ? `#${cssEscape(element.id)}` : "";
|
|
1641
|
-
const testId = element.getAttribute("data-testid");
|
|
1642
|
-
if (testId) return `${tag}[data-testid="${cssEscape(testId)}"]`;
|
|
1643
|
-
return `${tag}${id}${typeof element.className === "string" ? element.className.split(/\s+/).filter(Boolean).slice(0, 2).map((item) => `.${cssEscape(item)}`).join("") : ""}` || tag;
|
|
1644
|
-
}
|
|
1645
|
-
function cssEscape(value) {
|
|
1646
|
-
if (typeof CSS !== "undefined" && typeof CSS.escape === "function") return CSS.escape(value);
|
|
1647
|
-
return value.replace(/["\\]/g, "\\$&");
|
|
1648
|
-
}
|
|
1649
|
-
function sanitizeUrl(url, includeQueryString) {
|
|
1650
|
-
if (!url) return void 0;
|
|
1651
|
-
if (includeQueryString) return url;
|
|
1652
|
-
try {
|
|
1653
|
-
const parsed = new URL(url, isBrowser() ? window.location.origin : "http://localhost");
|
|
1654
|
-
return parsed.origin === "http://localhost" && !/^https?:\/\//i.test(url) ? parsed.pathname : `${parsed.origin}${parsed.pathname}`;
|
|
1655
|
-
} catch {
|
|
1656
|
-
return url.split("?")[0]?.split("#")[0];
|
|
1657
|
-
}
|
|
1658
|
-
}
|
|
1659
|
-
function isBrowser() {
|
|
1660
|
-
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
1661
|
-
}
|
|
1662
|
-
function createId(prefix) {
|
|
1663
|
-
try {
|
|
1664
|
-
if (typeof globalThis.crypto?.getRandomValues !== "function") return null;
|
|
1665
|
-
const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
1666
|
-
return `${prefix}_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
1667
|
-
} catch {
|
|
1668
|
-
return null;
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
function readOrCreateBrowserId(key) {
|
|
1672
|
-
if (!isBrowser()) return createId("runtime");
|
|
1673
|
-
try {
|
|
1674
|
-
const existing = window.localStorage.getItem(key);
|
|
1675
|
-
if (existing && /^runtime_[0-9a-f]{32}$/.test(existing)) return existing;
|
|
1676
|
-
} catch {}
|
|
1677
|
-
const next = createId("runtime");
|
|
1678
|
-
if (!next) return null;
|
|
1679
|
-
try {
|
|
1680
|
-
window.localStorage.setItem(key, next);
|
|
1681
|
-
} catch {}
|
|
1682
|
-
return next;
|
|
1683
|
-
}
|
|
1684
|
-
/** 解析 ignoreSourcePatterns 选项 —— false 关闭过滤;数组与默认合并;缺省走默认。 */
|
|
1685
|
-
function resolveIgnorePatterns(custom) {
|
|
1686
|
-
if (custom === false) return [];
|
|
1687
|
-
if (Array.isArray(custom)) return [...DEFAULT_IGNORE_SOURCE_PATTERNS, ...custom];
|
|
1688
|
-
return DEFAULT_IGNORE_SOURCE_PATTERNS;
|
|
1689
|
-
}
|
|
1690
|
-
/** 判断错误是否来自 dev-runtime 等噪声源。
|
|
1691
|
-
* 命中 ignorePatterns 任一 → 丢弃。检查 source URL + error.stack 两条。 */
|
|
1692
|
-
function shouldIgnore(ignorePatterns, source, reason) {
|
|
1693
|
-
if (ignorePatterns.length === 0) return false;
|
|
1694
|
-
if (typeof source === "string") {
|
|
1695
|
-
for (const re of ignorePatterns) if (re.test(source)) return true;
|
|
1696
|
-
}
|
|
1697
|
-
if (reason && typeof reason === "object" && "stack" in reason) {
|
|
1698
|
-
const stack = reason.stack;
|
|
1699
|
-
if (typeof stack === "string") {
|
|
1700
|
-
for (const re of ignorePatterns) if (re.test(stack)) return true;
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
if (typeof reason === "string") {
|
|
1704
|
-
for (const re of ignorePatterns) if (re.test(reason)) return true;
|
|
1705
|
-
}
|
|
1706
|
-
return false;
|
|
1707
|
-
}
|
|
1708
|
-
function normalizeError(error) {
|
|
1709
|
-
if (error instanceof Error) return {
|
|
1710
|
-
message: error.message,
|
|
1711
|
-
name: error.name,
|
|
1712
|
-
stack: error.stack
|
|
1713
|
-
};
|
|
1714
|
-
if (typeof error === "string") return { message: error };
|
|
1715
|
-
try {
|
|
1716
|
-
return { message: JSON.stringify(error) };
|
|
1717
|
-
} catch {
|
|
1718
|
-
return { message: String(error) };
|
|
1719
|
-
}
|
|
1720
|
-
}
|
|
1721
|
-
function isRecord(value) {
|
|
1722
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1723
|
-
}
|
|
1724
|
-
function normalizeTags(tags) {
|
|
1725
|
-
if (!tags) return void 0;
|
|
1726
|
-
const normalized = {};
|
|
1727
|
-
for (const [key, value] of Object.entries(tags)) {
|
|
1728
|
-
if (value === void 0 || value === null) continue;
|
|
1729
|
-
normalized[key] = String(value);
|
|
1730
|
-
}
|
|
1731
|
-
return Object.keys(normalized).length > 0 ? normalized : void 0;
|
|
1732
|
-
}
|
|
1733
|
-
//#endregion
|
|
1734
|
-
//#region src/metrics/MetricsCollector.ts
|
|
1735
|
-
/** 滑动窗口大小 (保留最近 N 条请求记录用于百分位计算) */
|
|
1736
|
-
var WINDOW_SIZE = 1e4;
|
|
1737
|
-
var MetricsCollector = class MetricsCollector {
|
|
1738
|
-
static instance;
|
|
1739
|
-
startedAt = Date.now();
|
|
1740
|
-
totalRequests = 0;
|
|
1741
|
-
successRequests = 0;
|
|
1742
|
-
errorRequests = 0;
|
|
1743
|
-
cacheHits = 0;
|
|
1744
|
-
cacheMisses = 0;
|
|
1745
|
-
totalResponseTime = 0;
|
|
1746
|
-
renderModeBreakdown = {};
|
|
1747
|
-
/** 滑动窗口:用于计算百分位 */
|
|
1748
|
-
recentResponseTimes = [];
|
|
1749
|
-
constructor() {}
|
|
1750
|
-
static getInstance() {
|
|
1751
|
-
if (!MetricsCollector.instance) MetricsCollector.instance = new MetricsCollector();
|
|
1752
|
-
return MetricsCollector.instance;
|
|
1753
|
-
}
|
|
1754
|
-
/**
|
|
1755
|
-
* 重置所有指标 (用于测试)
|
|
1756
|
-
*/
|
|
1757
|
-
reset() {
|
|
1758
|
-
this.startedAt = Date.now();
|
|
1759
|
-
this.totalRequests = 0;
|
|
1760
|
-
this.successRequests = 0;
|
|
1761
|
-
this.errorRequests = 0;
|
|
1762
|
-
this.cacheHits = 0;
|
|
1763
|
-
this.cacheMisses = 0;
|
|
1764
|
-
this.totalResponseTime = 0;
|
|
1765
|
-
this.renderModeBreakdown = {};
|
|
1766
|
-
this.recentResponseTimes = [];
|
|
1767
|
-
}
|
|
1768
|
-
/**
|
|
1769
|
-
* 记录一次请求
|
|
1770
|
-
*/
|
|
1771
|
-
record(record) {
|
|
1772
|
-
this.totalRequests++;
|
|
1773
|
-
this.totalResponseTime += record.responseTime;
|
|
1774
|
-
if (record.statusCode >= 200 && record.statusCode < 400) this.successRequests++;
|
|
1775
|
-
else this.errorRequests++;
|
|
1776
|
-
if (record.cacheHit) this.cacheHits++;
|
|
1777
|
-
else this.cacheMisses++;
|
|
1778
|
-
const mode = record.renderMode || "unknown";
|
|
1779
|
-
this.renderModeBreakdown[mode] = (this.renderModeBreakdown[mode] || 0) + 1;
|
|
1780
|
-
this.recentResponseTimes.push(record.responseTime);
|
|
1781
|
-
if (this.recentResponseTimes.length > WINDOW_SIZE) this.recentResponseTimes.shift();
|
|
1782
|
-
}
|
|
1783
|
-
/**
|
|
1784
|
-
* 获取当前指标快照
|
|
1785
|
-
*/
|
|
1786
|
-
getSnapshot() {
|
|
1787
|
-
const now = Date.now();
|
|
1788
|
-
const memUsage = process.memoryUsage();
|
|
1789
|
-
const sorted = [...this.recentResponseTimes].sort((a, b) => a - b);
|
|
1790
|
-
return {
|
|
1791
|
-
startedAt: this.startedAt,
|
|
1792
|
-
uptime: now - this.startedAt,
|
|
1793
|
-
totalRequests: this.totalRequests,
|
|
1794
|
-
successRequests: this.successRequests,
|
|
1795
|
-
errorRequests: this.errorRequests,
|
|
1796
|
-
successRate: this.totalRequests > 0 ? Number((this.successRequests / this.totalRequests * 100).toFixed(1)) : 0,
|
|
1797
|
-
avgResponseTime: this.totalRequests > 0 ? Math.round(this.totalResponseTime / this.totalRequests) : 0,
|
|
1798
|
-
p50ResponseTime: this.percentile(sorted, .5),
|
|
1799
|
-
p95ResponseTime: this.percentile(sorted, .95),
|
|
1800
|
-
p99ResponseTime: this.percentile(sorted, .99),
|
|
1801
|
-
cacheHitRate: this.cacheHits + this.cacheMisses > 0 ? Number((this.cacheHits / (this.cacheHits + this.cacheMisses) * 100).toFixed(1)) : 0,
|
|
1802
|
-
renderModeBreakdown: { ...this.renderModeBreakdown },
|
|
1803
|
-
memoryUsageMB: Number((memUsage.rss / (1024 * 1024)).toFixed(1)),
|
|
1804
|
-
heapUsedMB: Number((memUsage.heapUsed / (1024 * 1024)).toFixed(1))
|
|
1805
|
-
};
|
|
1806
|
-
}
|
|
1807
|
-
/**
|
|
1808
|
-
* 计算百分位值
|
|
1809
|
-
*/
|
|
1810
|
-
percentile(sorted, p) {
|
|
1811
|
-
if (sorted.length === 0) return 0;
|
|
1812
|
-
const index = Math.ceil(sorted.length * p) - 1;
|
|
1813
|
-
return sorted[Math.max(0, index)];
|
|
1814
|
-
}
|
|
1815
|
-
/**
|
|
1816
|
-
* 返回 JSON 格式的指标 (可用于 /metrics API 端点)
|
|
1817
|
-
*/
|
|
1818
|
-
toJSON() {
|
|
1819
|
-
return this.getSnapshot();
|
|
1820
|
-
}
|
|
1821
|
-
};
|
|
1822
|
-
//#endregion
|
|
1823
|
-
//#region src/plugin/createAutomaticImagePlugin.ts
|
|
1824
|
-
function createAutomaticImagePlugin(root, inlineConfig) {
|
|
1825
|
-
let image;
|
|
1826
|
-
return {
|
|
1827
|
-
name: "isr-engine:automatic-images",
|
|
1828
|
-
async configResolved(config) {
|
|
1829
|
-
if (config.plugins.some((plugin) => plugin.name === "isr-engine:image-optimization")) return;
|
|
1830
|
-
image = require_createImagePlugin.createImagePlugin(require_createISRApp.resolveImageOptions((Object.keys(inlineConfig).length ? inlineConfig : await require_createISRApp.loadConfig({ cwd: root })).runtime?.images));
|
|
1831
|
-
const hook = image.configResolved;
|
|
1832
|
-
if (typeof hook === "function") await hook.call(this, config);
|
|
1833
|
-
},
|
|
1834
|
-
configureServer(server) {
|
|
1835
|
-
const hook = image?.configureServer;
|
|
1836
|
-
if (typeof hook === "function") return hook.call(this, server);
|
|
1837
|
-
},
|
|
1838
|
-
configurePreviewServer(server) {
|
|
1839
|
-
const hook = image?.configurePreviewServer;
|
|
1840
|
-
if (typeof hook === "function") return hook.call(this, server);
|
|
1841
|
-
}
|
|
1842
|
-
};
|
|
1843
|
-
}
|
|
1844
|
-
var TRANSPORT_QUERY_KEYS = /* @__PURE__ */ new Set([
|
|
1845
|
-
"direct",
|
|
1846
|
-
"t",
|
|
1847
|
-
"v",
|
|
1848
|
-
"import",
|
|
1849
|
-
"__isr_engine_style_generation"
|
|
1850
|
-
]);
|
|
1851
|
-
var UNRESERVED_PATH_BYTE$1 = /^[A-Za-z\d._~-]$/;
|
|
1852
|
-
function canonicalizePathname(pathname) {
|
|
1853
|
-
return pathname.replace(/%([\da-f]{2})/gi, (_encoded, hex) => {
|
|
1854
|
-
const decoded = String.fromCharCode(Number.parseInt(hex, 16));
|
|
1855
|
-
return UNRESERVED_PATH_BYTE$1.test(decoded) ? decoded : `%${hex.toUpperCase()}`;
|
|
1856
|
-
});
|
|
1857
|
-
}
|
|
1858
|
-
function canonicalUrl(value, baseUrl) {
|
|
1859
|
-
const url = new URL(value, baseUrl);
|
|
1860
|
-
for (const key of TRANSPORT_QUERY_KEYS) url.searchParams.delete(key);
|
|
1861
|
-
url.searchParams.sort();
|
|
1862
|
-
return url;
|
|
1863
|
-
}
|
|
1864
|
-
function canonicalizeDevStyleSemanticQuery(value, baseUrl = "http://isr-engine.local/") {
|
|
1865
|
-
return canonicalUrl(value, baseUrl).search;
|
|
1866
|
-
}
|
|
1867
|
-
function canonicalizeDevStyleId(value, baseUrl = "http://isr-engine.local/") {
|
|
1868
|
-
const url = canonicalUrl(value, baseUrl);
|
|
1869
|
-
return `${canonicalizePathname(url.pathname)}${url.search}`;
|
|
1870
|
-
}
|
|
1871
|
-
//#endregion
|
|
1872
|
-
//#region src/plugin/transformDevCssModule.ts
|
|
1873
|
-
var STYLESHEET_URL$1 = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:[?#]|$)/i;
|
|
1874
|
-
function hasDirectQuery$1(value) {
|
|
1875
|
-
const queryStart = value.indexOf("?");
|
|
1876
|
-
if (queryStart === -1) return false;
|
|
1877
|
-
const hashStart = value.indexOf("#", queryStart);
|
|
1878
|
-
return new URLSearchParams(value.slice(queryStart + 1, hashStart === -1 ? void 0 : hashStart)).has("direct");
|
|
1879
|
-
}
|
|
1880
|
-
function isViteClientSpecifier(value) {
|
|
1881
|
-
return /(?:^|\/)@vite\/client(?:[?#]|$)/.test(value);
|
|
1882
|
-
}
|
|
1883
|
-
function isCallToBinding(node, binding) {
|
|
1884
|
-
return typescript.default.isCallExpression(node) && typescript.default.isIdentifier(node.expression) && node.expression.text === binding;
|
|
1885
|
-
}
|
|
1886
|
-
function isImportMetaHot(node) {
|
|
1887
|
-
return typescript.default.isPropertyAccessExpression(node) && node.name.text === "hot" && typescript.default.isMetaProperty(node.expression) && node.expression.keywordToken === typescript.default.SyntaxKind.ImportKeyword && node.expression.name.text === "meta";
|
|
1888
|
-
}
|
|
1889
|
-
function isImportMetaHotInternalAccess(node) {
|
|
1890
|
-
if (!typescript.default.isPropertyAccessExpression(node) && !typescript.default.isElementAccessExpression(node) || !isImportMetaHot(node.expression)) return false;
|
|
1891
|
-
return typescript.default.isPropertyAccessExpression(node) ? node.name.text === "_internal" : node.argumentExpression !== void 0 && typescript.default.isStringLiteral(node.argumentExpression) && node.argumentExpression.text === "_internal";
|
|
1892
|
-
}
|
|
1893
|
-
function isCanonicalImportMetaHotInternal(node) {
|
|
1894
|
-
return typescript.default.isPropertyAccessExpression(node) && isImportMetaHotInternalAccess(node);
|
|
1895
|
-
}
|
|
1896
|
-
function isNamespaceMutatorAccess(node, namespaceBindings) {
|
|
1897
|
-
if (!typescript.default.isPropertyAccessExpression(node) && !typescript.default.isElementAccessExpression(node) || !typescript.default.isIdentifier(node.expression) || !namespaceBindings.has(node.expression.text)) return false;
|
|
1898
|
-
const propertyName = typescript.default.isPropertyAccessExpression(node) ? node.name.text : typescript.default.isStringLiteral(node.argumentExpression) ? node.argumentExpression.text : void 0;
|
|
1899
|
-
return propertyName === "updateStyle" || propertyName === "removeStyle";
|
|
1900
|
-
}
|
|
1901
|
-
function collectViteStyleBindings(source) {
|
|
1902
|
-
const bindings = {
|
|
1903
|
-
hasEvidence: false,
|
|
1904
|
-
updateStyleBindings: [],
|
|
1905
|
-
removeStyleBindings: [],
|
|
1906
|
-
supportedInternalAccesses: /* @__PURE__ */ new Set(),
|
|
1907
|
-
unsupportedMutatorAccesses: []
|
|
1908
|
-
};
|
|
1909
|
-
const addBinding = (name, declaration) => {
|
|
1910
|
-
bindings.hasEvidence = true;
|
|
1911
|
-
bindings[`${name}Bindings`].push({
|
|
1912
|
-
name: declaration.text,
|
|
1913
|
-
declaration
|
|
1914
|
-
});
|
|
1915
|
-
};
|
|
1916
|
-
const namespaceBindings = /* @__PURE__ */ new Set();
|
|
1917
|
-
for (const statement of source.statements) {
|
|
1918
|
-
if (typescript.default.isImportDeclaration(statement) && typescript.default.isStringLiteral(statement.moduleSpecifier) && isViteClientSpecifier(statement.moduleSpecifier.text)) {
|
|
1919
|
-
const namedBindings = statement.importClause?.namedBindings;
|
|
1920
|
-
if (namedBindings !== void 0 && typescript.default.isNamespaceImport(namedBindings)) {
|
|
1921
|
-
namespaceBindings.add(namedBindings.name.text);
|
|
1922
|
-
continue;
|
|
1923
|
-
}
|
|
1924
|
-
if (namedBindings === void 0 || !typescript.default.isNamedImports(namedBindings)) continue;
|
|
1925
|
-
for (const specifier of namedBindings.elements) {
|
|
1926
|
-
const importedName = specifier.propertyName?.text ?? specifier.name.text;
|
|
1927
|
-
if (importedName === "updateStyle" || importedName === "removeStyle") addBinding(importedName, specifier.name);
|
|
1928
|
-
}
|
|
1929
|
-
continue;
|
|
1930
|
-
}
|
|
1931
|
-
if (!typescript.default.isVariableStatement(statement) || (statement.declarationList.flags & typescript.default.NodeFlags.Const) === 0 || statement.declarationList.declarations.length !== 1) continue;
|
|
1932
|
-
const declaration = statement.declarationList.declarations[0];
|
|
1933
|
-
if (declaration === void 0) continue;
|
|
1934
|
-
const internalAccess = declaration.initializer;
|
|
1935
|
-
if (internalAccess === void 0 || !isCanonicalImportMetaHotInternal(internalAccess)) continue;
|
|
1936
|
-
if (!typescript.default.isObjectBindingPattern(declaration.name) || declaration.name.elements.length !== 2) continue;
|
|
1937
|
-
const extracted = [];
|
|
1938
|
-
for (const element of declaration.name.elements) {
|
|
1939
|
-
if (element.dotDotDotToken !== void 0 || !typescript.default.isIdentifier(element.name)) {
|
|
1940
|
-
extracted.length = 0;
|
|
1941
|
-
break;
|
|
1942
|
-
}
|
|
1943
|
-
extracted.push({
|
|
1944
|
-
importedName: element.propertyName?.getText(source) ?? element.name.text,
|
|
1945
|
-
declaration: element.name
|
|
1946
|
-
});
|
|
1947
|
-
}
|
|
1948
|
-
if (extracted.length !== 2) continue;
|
|
1949
|
-
if (!extracted.some((element) => element.importedName === "updateStyle") || !extracted.some((element) => element.importedName === "removeStyle")) continue;
|
|
1950
|
-
for (const element of extracted) if (element.importedName === "updateStyle" || element.importedName === "removeStyle") addBinding(element.importedName, element.declaration);
|
|
1951
|
-
bindings.supportedInternalAccesses.add(internalAccess);
|
|
1952
|
-
}
|
|
1953
|
-
const visit = (node) => {
|
|
1954
|
-
if (isImportMetaHotInternalAccess(node)) {
|
|
1955
|
-
bindings.hasEvidence = true;
|
|
1956
|
-
if (!bindings.supportedInternalAccesses.has(node)) bindings.unsupportedMutatorAccesses.push(node);
|
|
1957
|
-
}
|
|
1958
|
-
if (isNamespaceMutatorAccess(node, namespaceBindings)) {
|
|
1959
|
-
bindings.hasEvidence = true;
|
|
1960
|
-
bindings.unsupportedMutatorAccesses.push(node);
|
|
1961
|
-
}
|
|
1962
|
-
typescript.default.forEachChild(node, visit);
|
|
1963
|
-
};
|
|
1964
|
-
visit(source);
|
|
1965
|
-
return bindings;
|
|
1966
|
-
}
|
|
1967
|
-
function findPruneCall(statement, removeStyleBinding) {
|
|
1968
|
-
if (!typescript.default.isExpressionStatement(statement) || !typescript.default.isCallExpression(statement.expression)) return void 0;
|
|
1969
|
-
const prune = statement.expression;
|
|
1970
|
-
if (!typescript.default.isPropertyAccessExpression(prune.expression) || prune.expression.name.text !== "prune" || !isImportMetaHot(prune.expression.expression) || prune.arguments.length !== 1) return;
|
|
1971
|
-
const callback = prune.arguments[0];
|
|
1972
|
-
if (!typescript.default.isArrowFunction(callback) || !typescript.default.isCallExpression(callback.body)) return void 0;
|
|
1973
|
-
return isCallToBinding(callback.body, removeStyleBinding) && callback.body.arguments.length === 1 ? callback.body : void 0;
|
|
1974
|
-
}
|
|
1975
|
-
function findUpdateStyleCall(statement, updateStyleBinding) {
|
|
1976
|
-
if (!typescript.default.isExpressionStatement(statement)) return void 0;
|
|
1977
|
-
return isCallToBinding(statement.expression, updateStyleBinding) && statement.expression.arguments.length === 2 ? statement.expression : void 0;
|
|
1978
|
-
}
|
|
1979
|
-
function isNonReferenceIdentifier(node) {
|
|
1980
|
-
const parent = node.parent;
|
|
1981
|
-
return typescript.default.isPropertyAccessExpression(parent) && parent.name === node || typescript.default.isPropertyAssignment(parent) && parent.name === node || typescript.default.isBindingElement(parent) && parent.propertyName === node || typescript.default.isImportSpecifier(parent);
|
|
1982
|
-
}
|
|
1983
|
-
function collectMutatorReferences(source, bindings) {
|
|
1984
|
-
const bindingNames = new Set(bindings.map((binding) => binding.name));
|
|
1985
|
-
const declarations = new Set(bindings.map((binding) => binding.declaration));
|
|
1986
|
-
const references = [];
|
|
1987
|
-
const visit = (node) => {
|
|
1988
|
-
if (typescript.default.isIdentifier(node) && bindingNames.has(node.text) && !declarations.has(node) && !isNonReferenceIdentifier(node)) references.push(node);
|
|
1989
|
-
typescript.default.forEachChild(node, visit);
|
|
1990
|
-
};
|
|
1991
|
-
visit(source);
|
|
1992
|
-
return references;
|
|
1993
|
-
}
|
|
1994
|
-
function compatibilityError(id, detail) {
|
|
1995
|
-
return /* @__PURE__ */ new Error(`Vite development CSS wrapper compatibility error for ${id}: ${detail}`);
|
|
1996
|
-
}
|
|
1997
|
-
function staticStringValue(source, expression) {
|
|
1998
|
-
if (typescript.default.isStringLiteral(expression)) return expression.text;
|
|
1999
|
-
if (!typescript.default.isIdentifier(expression)) return void 0;
|
|
2000
|
-
const matches = [];
|
|
2001
|
-
for (const statement of source.statements) {
|
|
2002
|
-
if (!typescript.default.isVariableStatement(statement) || (statement.declarationList.flags & typescript.default.NodeFlags.Const) === 0) continue;
|
|
2003
|
-
for (const declaration of statement.declarationList.declarations) if (typescript.default.isIdentifier(declaration.name) && declaration.name.text === expression.text) matches.push(declaration);
|
|
2004
|
-
}
|
|
2005
|
-
const declaration = matches.length === 1 ? matches[0] : void 0;
|
|
2006
|
-
return declaration?.initializer && typescript.default.isStringLiteral(declaration.initializer) ? declaration.initializer.text : void 0;
|
|
2007
|
-
}
|
|
2008
|
-
function transformDevCssModule(code, id, registryId, browserStyleId) {
|
|
2009
|
-
if (!STYLESHEET_URL$1.test(id) || hasDirectQuery$1(id)) return void 0;
|
|
2010
|
-
const source = typescript.default.createSourceFile(id, code, typescript.default.ScriptTarget.Latest, true, typescript.default.ScriptKind.JS);
|
|
2011
|
-
const bindings = collectViteStyleBindings(source);
|
|
2012
|
-
if (!bindings.hasEvidence) return void 0;
|
|
2013
|
-
const exactStyleId = browserStyleId ?? (/^\/(?:src|@fs)\//.test(id) ? id : void 0);
|
|
2014
|
-
if (exactStyleId === void 0) throw compatibilityError(id, "missing an exact browser module URL from the Vite module graph.");
|
|
2015
|
-
if (bindings.unsupportedMutatorAccesses.length > 0) throw compatibilityError(id, "contains unsupported Vite DOM-mutator access.");
|
|
2016
|
-
if (bindings.updateStyleBindings.length !== 1 || bindings.removeStyleBindings.length !== 1) throw compatibilityError(id, "expected one updateStyle and one removeStyle binding.");
|
|
2017
|
-
const updateStyleBinding = bindings.updateStyleBindings[0];
|
|
2018
|
-
const removeStyleBinding = bindings.removeStyleBindings[0];
|
|
2019
|
-
if (updateStyleBinding === void 0 || removeStyleBinding === void 0) throw compatibilityError(id, "expected one updateStyle and one removeStyle binding.");
|
|
2020
|
-
if (updateStyleBinding.name === removeStyleBinding.name) throw compatibilityError(id, "updateStyle and removeStyle must use distinct local bindings.");
|
|
2021
|
-
const updateStyleCalls = source.statements.map((statement) => findUpdateStyleCall(statement, updateStyleBinding.name)).filter((call) => call !== void 0);
|
|
2022
|
-
const removeStyleCalls = source.statements.map((statement) => findPruneCall(statement, removeStyleBinding.name)).filter((call) => call !== void 0);
|
|
2023
|
-
if (updateStyleCalls.length !== 1 || removeStyleCalls.length !== 1) throw compatibilityError(id, "expected exactly one top-level updateStyle call and one import.meta.hot.prune removeStyle callback.");
|
|
2024
|
-
const updateStyleCall = updateStyleCalls[0];
|
|
2025
|
-
const removeStyleCall = removeStyleCalls[0];
|
|
2026
|
-
if (updateStyleCall === void 0 || removeStyleCall === void 0) throw compatibilityError(id, "expected exactly one top-level updateStyle call and one import.meta.hot.prune removeStyle callback.");
|
|
2027
|
-
const removeStyleArgument = removeStyleCall.arguments[0];
|
|
2028
|
-
const updateStyleArgument = updateStyleCall.arguments[0];
|
|
2029
|
-
if (removeStyleArgument === void 0 || updateStyleArgument === void 0) throw compatibilityError(id, "expected the removeStyle callback to receive one stylesheet id.");
|
|
2030
|
-
const updateStyleId = staticStringValue(source, updateStyleArgument);
|
|
2031
|
-
const removeStyleId = staticStringValue(source, removeStyleArgument);
|
|
2032
|
-
if (updateStyleId === void 0 || removeStyleId === void 0 || updateStyleId !== removeStyleId) throw compatibilityError(id, "could not prove one exact stylesheet identity in the wrapper.");
|
|
2033
|
-
const wrapperStyleId = canonicalizeDevStyleId(updateStyleId);
|
|
2034
|
-
const transformedStyleId = canonicalizeDevStyleId(id);
|
|
2035
|
-
const canonicalBrowserStyleId = canonicalizeDevStyleId(exactStyleId);
|
|
2036
|
-
const semanticQueries = [
|
|
2037
|
-
updateStyleId,
|
|
2038
|
-
id,
|
|
2039
|
-
exactStyleId
|
|
2040
|
-
].map((value) => canonicalizeDevStyleSemanticQuery(value));
|
|
2041
|
-
if (!semanticQueries.every((query) => query === semanticQueries[0])) throw compatibilityError(id, "stylesheet semantic query does not match across identities.");
|
|
2042
|
-
if (wrapperStyleId !== transformedStyleId && wrapperStyleId !== canonicalBrowserStyleId) throw compatibilityError(id, "stylesheet identity in the wrapper does not match the module.");
|
|
2043
|
-
const expectedReferences = /* @__PURE__ */ new Set([updateStyleCall.expression, removeStyleCall.expression]);
|
|
2044
|
-
const references = collectMutatorReferences(source, [updateStyleBinding, removeStyleBinding]);
|
|
2045
|
-
if (references.length !== expectedReferences.size || references.some((reference) => !expectedReferences.has(reference))) throw compatibilityError(id, "contains unsupported additional Vite DOM-mutator references.");
|
|
2046
|
-
const replacements = [{
|
|
2047
|
-
start: updateStyleCall.getStart(source),
|
|
2048
|
-
end: updateStyleCall.getEnd(),
|
|
2049
|
-
value: `__isr_engine_dev_styles.publish(${JSON.stringify(canonicalBrowserStyleId)}, ${updateStyleCall.arguments[1]?.getText(source)})`
|
|
2050
|
-
}, {
|
|
2051
|
-
start: removeStyleCall.getStart(source),
|
|
2052
|
-
end: removeStyleCall.getEnd(),
|
|
2053
|
-
value: `__isr_engine_dev_styles.prune(${JSON.stringify(canonicalBrowserStyleId)})`
|
|
2054
|
-
}];
|
|
2055
|
-
let transformed = code;
|
|
2056
|
-
for (const replacement of replacements.sort((left, right) => right.start - left.start)) transformed = transformed.slice(0, replacement.start) + replacement.value + transformed.slice(replacement.end);
|
|
2057
|
-
return {
|
|
2058
|
-
code: `import { devStyleRegistry as __isr_engine_dev_styles } from ${JSON.stringify(registryId)};\n${transformed}`,
|
|
2059
|
-
map: null
|
|
2060
|
-
};
|
|
2061
|
-
}
|
|
2062
|
-
//#endregion
|
|
2063
|
-
//#region src/defaults/runtime/dev-style-resource-dispatcher.server.ts
|
|
2064
|
-
var PINNED_REACT_DOM_VERSION = "19.3.1";
|
|
2065
|
-
function pinnedResourceDispatcher() {
|
|
2066
|
-
const module = react_dom;
|
|
2067
|
-
const dispatcher = module.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE?.d;
|
|
2068
|
-
if (module.version !== PINNED_REACT_DOM_VERSION || typeof dispatcher?.S !== "function") throw new Error(`[isr-engine] Development CSS transport requires react-dom ${PINNED_REACT_DOM_VERSION} with the pinned stylesheet resource dispatcher shape.`);
|
|
2069
|
-
return dispatcher;
|
|
2070
|
-
}
|
|
2071
|
-
function assertPinnedDevStyleResourceDispatcher() {
|
|
2072
|
-
pinnedResourceDispatcher();
|
|
2073
|
-
}
|
|
2074
|
-
//#endregion
|
|
2075
|
-
//#region src/plugin/createDevCssHandoffPlugin.ts
|
|
2076
|
-
var VITE_RSC_REMOVE_DUPLICATE_CSS_ID = "virtual:vite-rsc/remove-duplicate-server-css";
|
|
2077
|
-
var DEV_CSS_HANDOFF_RESOLVED_ID = "\0virtual:isr-engine/dev-css-handoff";
|
|
2078
|
-
var DEV_STYLE_REGISTRY_ID = "virtual:isr-engine/dev-style-registry";
|
|
2079
|
-
var DEV_STYLE_REGISTRY_RESOLVED_ID = "\0virtual:isr-engine/dev-style-registry";
|
|
2080
|
-
var VITE_RSC_CSS_RESOLVED_PREFIX = "\0virtual:vite-rsc/css?";
|
|
2081
|
-
var STYLESHEET_URL = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:[?#]|$)/i;
|
|
2082
|
-
var SPECIAL_STYLESHEET_QUERY = /[?&](?:direct|inline|raw|url)(?:[=&]|$)/;
|
|
2083
|
-
var TERMINAL_CLIENT_RESOURCE_QUERY = /[?&](?:worker|sharedworker|raw|url)\b/;
|
|
2084
|
-
var pinnedRscServerRuntimePath;
|
|
2085
|
-
function getPinnedRscServerRuntimePath() {
|
|
2086
|
-
if (pinnedRscServerRuntimePath) return pinnedRscServerRuntimePath;
|
|
2087
|
-
pinnedRscServerRuntimePath = (0, node_fs.realpathSync)((0, node_module.createRequire)(typeof {}.url === "string" ? {}.url : __filename).resolve("@vitejs/plugin-rsc/react/rsc/server"));
|
|
2088
|
-
return pinnedRscServerRuntimePath;
|
|
2089
|
-
}
|
|
2090
|
-
var VITE_HMR_TIMESTAMP_VALUE = /^\d{13}$/;
|
|
2091
|
-
var VITE_DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
|
|
2092
|
-
var DEV_STYLE_GENERATION_VALUE = /^(?:0|[1-9]\d*)$/;
|
|
2093
|
-
var PINNED_VITE_VERSION = "8.1.6";
|
|
2094
|
-
function assertPinnedViteVersion(actualVersion) {
|
|
2095
|
-
if (actualVersion !== PINNED_VITE_VERSION) throw new Error(`[isr-engine] Development CSS lifecycle requires Vite ${PINNED_VITE_VERSION}; detected ${actualVersion}. Install the engine's exact Vite peer version.`);
|
|
2096
|
-
}
|
|
2097
|
-
function applyDevCssLifecycle(_config, environment) {
|
|
2098
|
-
return environment.command === "serve" && environment.isPreview !== true;
|
|
2099
|
-
}
|
|
2100
|
-
function isModuleTransportQueryParameter(parameter) {
|
|
2101
|
-
const separator = parameter.indexOf("=");
|
|
2102
|
-
const key = separator === -1 ? parameter : parameter.slice(0, separator);
|
|
2103
|
-
const value = separator === -1 ? "" : parameter.slice(separator + 1);
|
|
2104
|
-
if (key === "direct" || key === "import") return value === "";
|
|
2105
|
-
if (key === "t") return VITE_HMR_TIMESTAMP_VALUE.test(value);
|
|
2106
|
-
if (key === "v") return VITE_DEP_VERSION_RE.test(`?${parameter}`);
|
|
2107
|
-
if (key !== "__isr_engine_style_generation") return false;
|
|
2108
|
-
if (!DEV_STYLE_GENERATION_VALUE.test(value)) return false;
|
|
2109
|
-
return Number.isSafeInteger(Number(value));
|
|
2110
|
-
}
|
|
2111
|
-
function semanticModuleIdentity(id) {
|
|
2112
|
-
const hashStart = id.indexOf("#");
|
|
2113
|
-
const resource = hashStart === -1 ? id : id.slice(0, hashStart);
|
|
2114
|
-
const hash = hashStart === -1 ? "" : id.slice(hashStart);
|
|
2115
|
-
const queryStart = resource.indexOf("?");
|
|
2116
|
-
if (queryStart === -1) return id;
|
|
2117
|
-
const pathname = resource.slice(0, queryStart);
|
|
2118
|
-
const semanticQuery = resource.slice(queryStart + 1).split("&").filter((parameter) => !isModuleTransportQueryParameter(parameter)).join("&");
|
|
2119
|
-
return `${pathname}${semanticQuery ? `?${semanticQuery}` : ""}${hash}`;
|
|
2120
|
-
}
|
|
2121
|
-
function modulePathname(id) {
|
|
2122
|
-
return id.replace(/[?#].*$/, "");
|
|
2123
|
-
}
|
|
2124
|
-
function moduleSemanticQuery(id) {
|
|
2125
|
-
const semanticId = semanticModuleIdentity(id);
|
|
2126
|
-
const queryStart = semanticId.indexOf("?");
|
|
2127
|
-
if (queryStart === -1) return "";
|
|
2128
|
-
const hashStart = semanticId.indexOf("#", queryStart);
|
|
2129
|
-
return semanticId.slice(queryStart, hashStart === -1 ? void 0 : hashStart);
|
|
2130
|
-
}
|
|
2131
|
-
function browserStyleIdForResolvedModule(server, id) {
|
|
2132
|
-
const moduleGraph = server?.environments.client.moduleGraph;
|
|
2133
|
-
const queryStart = id.indexOf("?");
|
|
2134
|
-
const resolvedPath = queryStart === -1 ? id : id.slice(0, queryStart);
|
|
2135
|
-
const query = queryStart === -1 ? "" : id.slice(queryStart);
|
|
2136
|
-
let mappedId;
|
|
2137
|
-
if (resolvedPath.startsWith("/@fs/") || !server && resolvedPath.startsWith("/src/")) mappedId = canonicalizeDevStyleId(id);
|
|
2138
|
-
else if (server && node_path.default.isAbsolute(resolvedPath)) {
|
|
2139
|
-
const normalizedRoot = (0, vite.normalizePath)(node_path.default.resolve(server.config.root));
|
|
2140
|
-
const normalizedPath = (0, vite.normalizePath)(node_path.default.resolve(resolvedPath));
|
|
2141
|
-
const relative = (0, vite.normalizePath)(node_path.default.relative(normalizedRoot, normalizedPath));
|
|
2142
|
-
mappedId = canonicalizeDevStyleId(`${relative !== ".." && !relative.startsWith("../") ? `/${relative}` : `/@fs/${normalizedPath}`}${query}`);
|
|
2143
|
-
}
|
|
2144
|
-
const exactNode = moduleGraph?.getModuleById(id);
|
|
2145
|
-
if (exactNode?.url && !exactNode.url.startsWith("\0")) return canonicalizeDevStyleId(exactNode.url);
|
|
2146
|
-
if (mappedId === void 0) return void 0;
|
|
2147
|
-
const cleanNode = moduleGraph?.getModuleById(modulePathname(id));
|
|
2148
|
-
if (cleanNode?.url && !cleanNode.url.startsWith("\0")) {
|
|
2149
|
-
if (new URL(canonicalizeDevStyleId(cleanNode.url), "http://isr-engine.local/").pathname !== new URL(mappedId, "http://isr-engine.local/").pathname) return void 0;
|
|
2150
|
-
}
|
|
2151
|
-
return mappedId;
|
|
2152
|
-
}
|
|
2153
|
-
function hasUseClientDirective$1(code, id) {
|
|
2154
|
-
const source = typescript.default.createSourceFile(id, code, typescript.default.ScriptTarget.Latest, true, typescript.default.ScriptKind.TSX);
|
|
2155
|
-
for (const statement of source.statements) {
|
|
2156
|
-
if (!typescript.default.isExpressionStatement(statement) || !typescript.default.isStringLiteral(statement.expression)) return false;
|
|
2157
|
-
if (statement.expression.text === "use client") return true;
|
|
2158
|
-
}
|
|
2159
|
-
return false;
|
|
2160
|
-
}
|
|
2161
|
-
function unsupportedClientProxy(id) {
|
|
2162
|
-
return /* @__PURE__ */ new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc client reference proxy shape in ${id}. Expected the pinned 0.5.39 registerClientReference wrapper.`);
|
|
2163
|
-
}
|
|
2164
|
-
function isPinnedRscServerRuntime(value) {
|
|
2165
|
-
try {
|
|
2166
|
-
const url = new URL(value);
|
|
2167
|
-
if (url.protocol !== "file:") return false;
|
|
2168
|
-
url.search = "";
|
|
2169
|
-
url.hash = "";
|
|
2170
|
-
return (0, node_fs.realpathSync)((0, node_url.fileURLToPath)(url)) === getPinnedRscServerRuntimePath();
|
|
2171
|
-
} catch {
|
|
2172
|
-
return false;
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
function decodePackageProxyTarget(value) {
|
|
2176
|
-
try {
|
|
2177
|
-
return decodeURIComponent(value).replaceAll("\\", "/");
|
|
2178
|
-
} catch {
|
|
2179
|
-
return;
|
|
2180
|
-
}
|
|
2181
|
-
}
|
|
2182
|
-
var UNRESERVED_PATH_BYTE = /^[A-Za-z\d._~-]$/;
|
|
2183
|
-
var WINDOWS_DRIVE_PATH = /^[A-Za-z]:\//;
|
|
2184
|
-
function canonicalPathSegment(segment) {
|
|
2185
|
-
let result = "";
|
|
2186
|
-
for (let index = 0; index < segment.length;) {
|
|
2187
|
-
const codePoint = segment.codePointAt(index);
|
|
2188
|
-
if (codePoint === void 0) return void 0;
|
|
2189
|
-
const character = String.fromCodePoint(codePoint);
|
|
2190
|
-
if (character === "%") {
|
|
2191
|
-
const hex = segment.slice(index + 1, index + 3);
|
|
2192
|
-
if (!/^[\da-f]{2}$/i.test(hex)) return void 0;
|
|
2193
|
-
const decoded = String.fromCharCode(Number.parseInt(hex, 16));
|
|
2194
|
-
result += UNRESERVED_PATH_BYTE.test(decoded) ? decoded : `%${hex.toUpperCase()}`;
|
|
2195
|
-
index += 3;
|
|
2196
|
-
continue;
|
|
2197
|
-
}
|
|
2198
|
-
if (/^[A-Za-z\d._~:@+-]$/.test(character)) result += character;
|
|
2199
|
-
else result += encodeURIComponent(character).replace(/[!'()*]/g, (value) => `%${value.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
2200
|
-
index += character.length;
|
|
2201
|
-
}
|
|
2202
|
-
return result;
|
|
2203
|
-
}
|
|
2204
|
-
function canonicalFilePath(value) {
|
|
2205
|
-
const normalized = value.replaceAll("\\", "/");
|
|
2206
|
-
const hasDrive = WINDOWS_DRIVE_PATH.test(normalized);
|
|
2207
|
-
if (!(normalized.startsWith("/") || hasDrive)) return void 0;
|
|
2208
|
-
const segments = [];
|
|
2209
|
-
for (const rawSegment of normalized.split("/")) {
|
|
2210
|
-
if (rawSegment === "") continue;
|
|
2211
|
-
const segment = canonicalPathSegment(rawSegment);
|
|
2212
|
-
if (segment === void 0) return void 0;
|
|
2213
|
-
if (segment === ".") continue;
|
|
2214
|
-
if (segment === "..") {
|
|
2215
|
-
if (segments.length === 0 || hasDrive && segments.length === 1) return void 0;
|
|
2216
|
-
segments.pop();
|
|
2217
|
-
continue;
|
|
2218
|
-
}
|
|
2219
|
-
segments.push(segment);
|
|
2220
|
-
}
|
|
2221
|
-
const drive = segments[0];
|
|
2222
|
-
if (hasDrive && drive) {
|
|
2223
|
-
segments[0] = `${drive.charAt(0).toLowerCase()}${drive.slice(1)}`;
|
|
2224
|
-
return segments.join("/");
|
|
2225
|
-
}
|
|
2226
|
-
return `/${segments.join("/")}`;
|
|
2227
|
-
}
|
|
2228
|
-
function filePathFromFsUrl(value) {
|
|
2229
|
-
if (!value.startsWith("/@fs/")) return void 0;
|
|
2230
|
-
const filePath = value.slice(5);
|
|
2231
|
-
return canonicalFilePath(WINDOWS_DRIVE_PATH.test(filePath) ? filePath : `/${filePath}`);
|
|
2232
|
-
}
|
|
2233
|
-
function canonicalModuleFilePath(moduleId) {
|
|
2234
|
-
const cleanId = modulePathname(moduleId);
|
|
2235
|
-
return filePathFromFsUrl(cleanId) ?? canonicalFilePath(cleanId);
|
|
2236
|
-
}
|
|
2237
|
-
function rootRelativeFilePath(root, referenceId) {
|
|
2238
|
-
if (!referenceId.startsWith("/") || referenceId.startsWith("//") || referenceId.includes("\\") || referenceId.startsWith("/@")) return;
|
|
2239
|
-
const canonicalRoot = canonicalFilePath(root);
|
|
2240
|
-
const canonicalReference = canonicalFilePath(referenceId);
|
|
2241
|
-
if (!canonicalRoot || !canonicalReference || referenceId.startsWith("/@fs/")) return void 0;
|
|
2242
|
-
return canonicalFilePath(`${canonicalRoot}/${canonicalReference.slice(1)}`);
|
|
2243
|
-
}
|
|
2244
|
-
function referenceMatchesModule(referenceId, moduleId, root) {
|
|
2245
|
-
const normalizedModuleId = semanticModuleIdentity(moduleId.replaceAll("\\", "/"));
|
|
2246
|
-
const normalizedReferenceId = semanticModuleIdentity(referenceId);
|
|
2247
|
-
if (normalizedModuleId.startsWith("\0")) return normalizedReferenceId === `/@id/__x00__${normalizedModuleId.slice(1)}`;
|
|
2248
|
-
const cleanId = modulePathname(normalizedModuleId);
|
|
2249
|
-
if (normalizedReferenceId.startsWith("/@id/__x00__virtual:vite-rsc/client-in-server-package-proxy/")) {
|
|
2250
|
-
const target = decodePackageProxyTarget(normalizedReferenceId.slice(60));
|
|
2251
|
-
const targetPath = target === void 0 ? void 0 : canonicalModuleFilePath(target);
|
|
2252
|
-
const modulePath = canonicalModuleFilePath(cleanId);
|
|
2253
|
-
return targetPath !== void 0 && modulePath !== void 0 && targetPath === modulePath;
|
|
2254
|
-
}
|
|
2255
|
-
if (moduleSemanticQuery(normalizedReferenceId) !== moduleSemanticQuery(normalizedModuleId)) return false;
|
|
2256
|
-
const moduleFilePath = canonicalModuleFilePath(cleanId);
|
|
2257
|
-
if (!moduleFilePath) return false;
|
|
2258
|
-
const cleanReferenceId = modulePathname(normalizedReferenceId);
|
|
2259
|
-
const fsReference = filePathFromFsUrl(cleanReferenceId);
|
|
2260
|
-
if (fsReference) return moduleFilePath === fsReference;
|
|
2261
|
-
const browserReference = rootRelativeFilePath(root, cleanReferenceId);
|
|
2262
|
-
if (!browserReference) return false;
|
|
2263
|
-
if (cleanId.startsWith("/") && !cleanId.startsWith("/@fs/")) {
|
|
2264
|
-
if (canonicalFilePath(cleanId) === canonicalFilePath(cleanReferenceId)) return true;
|
|
2265
|
-
}
|
|
2266
|
-
return moduleFilePath === browserReference;
|
|
2267
|
-
}
|
|
2268
|
-
function registerClientReferenceCall(expression, runtimeBinding, exportName, moduleId, root) {
|
|
2269
|
-
if (!typescript.default.isCallExpression(expression) || expression.questionDotToken !== void 0 || expression.typeArguments !== void 0 || expression.arguments.length !== 3 || !typescript.default.isPropertyAccessExpression(expression.expression) || expression.expression.questionDotToken !== void 0 || !typescript.default.isIdentifier(expression.expression.expression) || expression.expression.expression.text !== runtimeBinding || expression.expression.name.text !== "registerClientReference" || !isPinnedClientReferenceProxy(expression.arguments[0], exportName) || !typescript.default.isStringLiteral(expression.arguments[1]) || !typescript.default.isStringLiteral(expression.arguments[2]) || expression.arguments[2].text !== exportName || !referenceMatchesModule(expression.arguments[1].text, moduleId, root)) return;
|
|
2270
|
-
return expression.arguments[1].text;
|
|
2271
|
-
}
|
|
2272
|
-
function isPinnedClientReferenceError(node, exportName) {
|
|
2273
|
-
if (!typescript.default.isBinaryExpression(node) || node.operatorToken.kind !== typescript.default.SyntaxKind.PlusToken || !typescript.default.isBinaryExpression(node.left) || node.left.operatorToken.kind !== typescript.default.SyntaxKind.PlusToken) return false;
|
|
2274
|
-
return typescript.default.isStringLiteral(node.left.left) && node.left.left.text === "Unexpectedly client reference export '" && typescript.default.isStringLiteral(node.left.right) && node.left.right.text === exportName && typescript.default.isStringLiteral(node.right) && node.right.text === "' is called on server";
|
|
2275
|
-
}
|
|
2276
|
-
function isPinnedClientReferenceProxy(expression, exportName) {
|
|
2277
|
-
if (!expression || !typescript.default.isArrowFunction(expression) || expression.modifiers !== void 0 || expression.typeParameters !== void 0 || expression.parameters.length !== 0 || expression.type !== void 0 || !typescript.default.isBlock(expression.body) || expression.body.statements.length !== 1) return false;
|
|
2278
|
-
const statement = expression.body.statements[0];
|
|
2279
|
-
if (!statement || !typescript.default.isThrowStatement(statement) || !statement.expression) return false;
|
|
2280
|
-
const error = statement.expression;
|
|
2281
|
-
const message = typescript.default.isNewExpression(error) ? error.arguments?.[0] : void 0;
|
|
2282
|
-
return typescript.default.isNewExpression(error) && typescript.default.isIdentifier(error.expression) && error.expression.text === "Error" && error.typeArguments === void 0 && error.arguments?.length === 1 && message !== void 0 && isPinnedClientReferenceError(message, exportName);
|
|
2283
|
-
}
|
|
2284
|
-
function clientReferenceIdFromProxy(code, id, root) {
|
|
2285
|
-
const source = typescript.default.createSourceFile(id, code, typescript.default.ScriptTarget.Latest, true, typescript.default.ScriptKind.JS);
|
|
2286
|
-
if (source.parseDiagnostics.length > 0) throw unsupportedClientProxy(id);
|
|
2287
|
-
const runtimeImports = source.statements.filter((statement) => typescript.default.isImportDeclaration(statement) && typescript.default.isStringLiteral(statement.moduleSpecifier) && isPinnedRscServerRuntime(statement.moduleSpecifier.text) && statement.modifiers === void 0 && statement.importClause?.name === void 0 && statement.importClause?.isTypeOnly === false && statement.importClause?.namedBindings !== void 0 && typescript.default.isNamespaceImport(statement.importClause.namedBindings) && statement.importClause.namedBindings.name.text === "$$ReactServer" && statement.attributes === void 0);
|
|
2288
|
-
if (runtimeImports.length !== 1) throw unsupportedClientProxy(id);
|
|
2289
|
-
const runtimeImport = runtimeImports[0];
|
|
2290
|
-
const runtimeBindings = runtimeImport?.importClause?.namedBindings;
|
|
2291
|
-
if (!runtimeImport || !runtimeBindings || !typescript.default.isNamespaceImport(runtimeBindings)) throw unsupportedClientProxy(id);
|
|
2292
|
-
const runtimeBinding = runtimeBindings.name.text;
|
|
2293
|
-
const referenceIds = /* @__PURE__ */ new Set();
|
|
2294
|
-
const exportNames = /* @__PURE__ */ new Set();
|
|
2295
|
-
for (const statement of source.statements) {
|
|
2296
|
-
if (statement === runtimeImport) continue;
|
|
2297
|
-
if (typescript.default.isExportAssignment(statement) && !statement.isExportEquals) {
|
|
2298
|
-
if (exportNames.has("default")) throw unsupportedClientProxy(id);
|
|
2299
|
-
const referenceId = registerClientReferenceCall(statement.expression, runtimeBinding, "default", id, root);
|
|
2300
|
-
if (!referenceId) throw unsupportedClientProxy(id);
|
|
2301
|
-
referenceIds.add(referenceId);
|
|
2302
|
-
exportNames.add("default");
|
|
2303
|
-
continue;
|
|
2304
|
-
}
|
|
2305
|
-
if (typescript.default.isVariableStatement(statement) && statement.modifiers?.length === 1 && statement.modifiers[0]?.kind === typescript.default.SyntaxKind.ExportKeyword && (statement.declarationList.flags & (typescript.default.NodeFlags.Let | typescript.default.NodeFlags.Const)) === typescript.default.NodeFlags.Const && statement.declarationList.declarations.length === 1) {
|
|
2306
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
2307
|
-
if (!typescript.default.isIdentifier(declaration.name) || exportNames.has(declaration.name.text) || declaration.exclamationToken !== void 0 || declaration.type !== void 0 || !declaration.initializer) throw unsupportedClientProxy(id);
|
|
2308
|
-
const referenceId = registerClientReferenceCall(declaration.initializer, runtimeBinding, declaration.name.text, id, root);
|
|
2309
|
-
if (!referenceId) throw unsupportedClientProxy(id);
|
|
2310
|
-
referenceIds.add(referenceId);
|
|
2311
|
-
exportNames.add(declaration.name.text);
|
|
2312
|
-
}
|
|
2313
|
-
continue;
|
|
2314
|
-
}
|
|
2315
|
-
throw unsupportedClientProxy(id);
|
|
2316
|
-
}
|
|
2317
|
-
const [referenceId] = referenceIds;
|
|
2318
|
-
if (referenceIds.size !== 1 || referenceId === void 0) throw unsupportedClientProxy(id);
|
|
2319
|
-
return referenceId;
|
|
2320
|
-
}
|
|
2321
|
-
async function collectClientReferenceStyles(server, id) {
|
|
2322
|
-
const environment = server.environments.client;
|
|
2323
|
-
const moduleId = semanticModuleIdentity(id);
|
|
2324
|
-
const requestUrl = moduleId.startsWith("\0") ? `/@id/__x00__${moduleId.slice(1)}` : moduleId.startsWith(server.config.root) ? moduleId.slice(server.config.root.length) || "/" : moduleId;
|
|
2325
|
-
await environment.transformRequest(moduleId.startsWith("\0") ? moduleId : requestUrl);
|
|
2326
|
-
const entry = await environment.moduleGraph.getModuleByUrl(requestUrl) ?? environment.moduleGraph.getModuleById(moduleId);
|
|
2327
|
-
if (!entry) throw new Error(`[isr-engine] Could not inspect the client dependency graph for ${id}.`);
|
|
2328
|
-
const visited = /* @__PURE__ */ new Set();
|
|
2329
|
-
const styleIds = /* @__PURE__ */ new Set();
|
|
2330
|
-
const visit = async (module) => {
|
|
2331
|
-
if (visited.has(module)) return;
|
|
2332
|
-
visited.add(module);
|
|
2333
|
-
const transformId = module.id || module.url;
|
|
2334
|
-
if (!transformId) return;
|
|
2335
|
-
await environment.transformRequest(transformId);
|
|
2336
|
-
const transformed = (module.id ? environment.moduleGraph.getModuleById(module.id) : void 0) ?? (module.url ? await environment.moduleGraph.getModuleByUrl(module.url) : void 0) ?? module;
|
|
2337
|
-
for (const dependency of transformed.importedModules) {
|
|
2338
|
-
const dependencyId = dependency.url || dependency.id;
|
|
2339
|
-
if (dependencyId && TERMINAL_CLIENT_RESOURCE_QUERY.test(dependencyId)) continue;
|
|
2340
|
-
if (dependencyId && STYLESHEET_URL.test(dependencyId)) {
|
|
2341
|
-
if (!SPECIAL_STYLESHEET_QUERY.test(dependencyId)) styleIds.add(dependencyId);
|
|
2342
|
-
} else await visit(dependency);
|
|
2343
|
-
}
|
|
2344
|
-
};
|
|
2345
|
-
await visit(entry);
|
|
2346
|
-
return Array.from(styleIds).sort();
|
|
2347
|
-
}
|
|
2348
|
-
function hasDirectQuery(value) {
|
|
2349
|
-
const queryStart = value.indexOf("?");
|
|
2350
|
-
if (queryStart === -1) return false;
|
|
2351
|
-
const hashStart = value.indexOf("#", queryStart);
|
|
2352
|
-
const query = value.slice(queryStart + 1, hashStart === -1 ? void 0 : hashStart);
|
|
2353
|
-
return new URLSearchParams(query).has("direct");
|
|
2354
|
-
}
|
|
2355
|
-
function withDirectQuery(value) {
|
|
2356
|
-
if (!STYLESHEET_URL.test(value) || hasDirectQuery(value)) return value;
|
|
2357
|
-
const hashStart = value.indexOf("#");
|
|
2358
|
-
const resource = hashStart === -1 ? value : value.slice(0, hashStart);
|
|
2359
|
-
const hash = hashStart === -1 ? "" : value.slice(hashStart);
|
|
2360
|
-
return `${resource}${resource.includes("?") ? /[?&]$/.test(resource) ? "" : "&" : "?"}direct${hash}`;
|
|
2361
|
-
}
|
|
2362
|
-
function canonicalizeDevRscStylesheetModule(code, id) {
|
|
2363
|
-
if (!id.startsWith(VITE_RSC_CSS_RESOLVED_PREFIX)) return void 0;
|
|
2364
|
-
const source = typescript.default.createSourceFile(id, code, typescript.default.ScriptTarget.Latest, true, typescript.default.ScriptKind.JS);
|
|
2365
|
-
const replacements = [];
|
|
2366
|
-
const visit = (node) => {
|
|
2367
|
-
if (typescript.default.isStringLiteral(node)) {
|
|
2368
|
-
const value = withDirectQuery(node.text);
|
|
2369
|
-
if (value !== node.text) replacements.push({
|
|
2370
|
-
start: node.getStart(source),
|
|
2371
|
-
end: node.getEnd(),
|
|
2372
|
-
value
|
|
2373
|
-
});
|
|
2374
|
-
}
|
|
2375
|
-
typescript.default.forEachChild(node, visit);
|
|
2376
|
-
};
|
|
2377
|
-
visit(source);
|
|
2378
|
-
if (replacements.length === 0) return void 0;
|
|
2379
|
-
let transformed = code;
|
|
2380
|
-
for (const replacement of replacements.reverse()) transformed = transformed.slice(0, replacement.start) + JSON.stringify(replacement.value) + transformed.slice(replacement.end);
|
|
2381
|
-
return {
|
|
2382
|
-
code: transformed,
|
|
2383
|
-
map: null
|
|
2384
|
-
};
|
|
2385
|
-
}
|
|
2386
|
-
function identifierIs(node, value) {
|
|
2387
|
-
return node !== void 0 && typescript.default.isIdentifier(node) && node.text === value;
|
|
2388
|
-
}
|
|
2389
|
-
function stringIs(node, value) {
|
|
2390
|
-
return node !== void 0 && typescript.default.isStringLiteral(node) && node.text === value;
|
|
2391
|
-
}
|
|
2392
|
-
function propertyName(node) {
|
|
2393
|
-
if (!node) return void 0;
|
|
2394
|
-
return typescript.default.isIdentifier(node) || typescript.default.isStringLiteral(node) ? node.text : void 0;
|
|
2395
|
-
}
|
|
2396
|
-
function isPropertyPath(node, root, ...properties) {
|
|
2397
|
-
let current = node;
|
|
2398
|
-
for (const property of [...properties].reverse()) {
|
|
2399
|
-
if (!typescript.default.isPropertyAccessExpression(current) || current.name.text !== property) return false;
|
|
2400
|
-
current = current.expression;
|
|
2401
|
-
}
|
|
2402
|
-
return identifierIs(current, root);
|
|
2403
|
-
}
|
|
2404
|
-
function isCreateElementCall(node, reactBinding, argumentCount) {
|
|
2405
|
-
return typescript.default.isCallExpression(node) && node.arguments.length === argumentCount && isPropertyPath(node.expression, reactBinding, "createElement");
|
|
2406
|
-
}
|
|
2407
|
-
function isPinnedLinkProps(node, hrefBinding, precedenceBinding) {
|
|
2408
|
-
if (!typescript.default.isObjectLiteralExpression(node) || node.properties.length !== 6) return false;
|
|
2409
|
-
const [key, rel, crossOrigin, precedence, href, dataHref] = node.properties;
|
|
2410
|
-
if (!key || !typescript.default.isPropertyAssignment(key) || propertyName(key.name) !== "key" || !typescript.default.isBinaryExpression(key.initializer) || key.initializer.operatorToken.kind !== typescript.default.SyntaxKind.PlusToken || !stringIs(key.initializer.left, "css:") || !identifierIs(key.initializer.right, hrefBinding)) return false;
|
|
2411
|
-
if (!rel || !typescript.default.isPropertyAssignment(rel) || propertyName(rel.name) !== "rel" || !stringIs(rel.initializer, "stylesheet")) return false;
|
|
2412
|
-
if (!crossOrigin || !typescript.default.isPropertyAssignment(crossOrigin) || propertyName(crossOrigin.name) !== "crossOrigin" || !stringIs(crossOrigin.initializer, "anonymous")) return false;
|
|
2413
|
-
if (!precedence || !typescript.default.isSpreadAssignment(precedence)) return false;
|
|
2414
|
-
const condition = precedence.expression;
|
|
2415
|
-
if (!typescript.default.isConditionalExpression(condition) || !identifierIs(condition.condition, precedenceBinding) || !typescript.default.isObjectLiteralExpression(condition.whenTrue) || condition.whenTrue.properties.length !== 1 || !typescript.default.isShorthandPropertyAssignment(condition.whenTrue.properties[0]) || condition.whenTrue.properties[0].name.text !== precedenceBinding || !typescript.default.isObjectLiteralExpression(condition.whenFalse) || condition.whenFalse.properties.length !== 0) return false;
|
|
2416
|
-
if (!href || !typescript.default.isShorthandPropertyAssignment(href) || href.name.text !== hrefBinding || !dataHref || !typescript.default.isPropertyAssignment(dataHref) || propertyName(dataHref.name) !== "data-rsc-css-href" || !identifierIs(dataHref.initializer, hrefBinding)) return false;
|
|
2417
|
-
return true;
|
|
2418
|
-
}
|
|
2419
|
-
function isPinnedResourcesFactory(factory) {
|
|
2420
|
-
const parameterNames = [
|
|
2421
|
-
"React",
|
|
2422
|
-
"deps",
|
|
2423
|
-
"RemoveDuplicateServerCss",
|
|
2424
|
-
"precedence"
|
|
2425
|
-
];
|
|
2426
|
-
if (factory.parameters.length !== parameterNames.length || !factory.parameters.every((parameter, index) => {
|
|
2427
|
-
const expected = parameterNames[index];
|
|
2428
|
-
return expected !== void 0 && identifierIs(parameter.name, expected);
|
|
2429
|
-
}) || !typescript.default.isBlock(factory.body) || factory.body.statements.length !== 2) return false;
|
|
2430
|
-
const [element, factoryReturn] = factory.body.statements;
|
|
2431
|
-
if (!element || !typescript.default.isVariableStatement(element) || (element.declarationList.flags & typescript.default.NodeFlags.Const) === 0 || element.declarationList.declarations.length !== 1) return false;
|
|
2432
|
-
const declaration = element.declarationList.declarations[0];
|
|
2433
|
-
if (!declaration || !identifierIs(declaration.name, "element")) return false;
|
|
2434
|
-
if (!factoryReturn || !typescript.default.isReturnStatement(factoryReturn) || !factoryReturn.expression || !typescript.default.isFunctionExpression(factoryReturn.expression) || !identifierIs(factoryReturn.expression.name, "Resources") || factoryReturn.expression.parameters.length !== 0 || factoryReturn.expression.body.statements.length !== 1) return false;
|
|
2435
|
-
const resourcesReturn = factoryReturn.expression.body.statements[0];
|
|
2436
|
-
const resourcesCall = declaration.initializer;
|
|
2437
|
-
if (!resourcesReturn || !typescript.default.isReturnStatement(resourcesReturn) || !identifierIs(resourcesReturn.expression, "element") || !resourcesCall || !isCreateElementCall(resourcesCall, "React", 3)) return false;
|
|
2438
|
-
const [fragment, nullValue, children] = resourcesCall.arguments;
|
|
2439
|
-
if (!fragment || !isPropertyPath(fragment, "React", "Fragment") || nullValue?.kind !== typescript.default.SyntaxKind.NullKeyword || !children || !typescript.default.isArrayLiteralExpression(children) || children.elements.length !== 2) return false;
|
|
2440
|
-
const [linksSpread, cleanup] = children.elements;
|
|
2441
|
-
if (!linksSpread || !typescript.default.isSpreadElement(linksSpread) || !typescript.default.isCallExpression(linksSpread.expression)) return false;
|
|
2442
|
-
const mapCall = linksSpread.expression;
|
|
2443
|
-
const mapCallback = mapCall.arguments[0];
|
|
2444
|
-
const linkCall = mapCallback && typescript.default.isArrowFunction(mapCallback) && isCreateElementCall(mapCallback.body, "React", 2) ? mapCallback.body : void 0;
|
|
2445
|
-
if (!isPropertyPath(mapCall.expression, "deps", "css", "map") || mapCall.arguments.length !== 1 || !mapCallback || !typescript.default.isArrowFunction(mapCallback) || mapCallback.parameters.length !== 1 || !identifierIs(mapCallback.parameters[0]?.name, "href") || !linkCall || !stringIs(linkCall.arguments[0], "link") || !linkCall.arguments[1] || !isPinnedLinkProps(linkCall.arguments[1], "href", "precedence")) return false;
|
|
2446
|
-
if (!cleanup || !typescript.default.isBinaryExpression(cleanup) || cleanup.operatorToken.kind !== typescript.default.SyntaxKind.AmpersandAmpersandToken || !identifierIs(cleanup.left, "RemoveDuplicateServerCss") || !isCreateElementCall(cleanup.right, "React", 2) || !identifierIs(cleanup.right.arguments[0], "RemoveDuplicateServerCss") || !typescript.default.isObjectLiteralExpression(cleanup.right.arguments[1]) || cleanup.right.arguments[1].properties.length !== 1) return false;
|
|
2447
|
-
const cleanupKey = cleanup.right.arguments[1].properties[0];
|
|
2448
|
-
return cleanupKey !== void 0 && typescript.default.isPropertyAssignment(cleanupKey) && propertyName(cleanupKey.name) === "key" && stringIs(cleanupKey.initializer, "remove-duplicate-css");
|
|
2449
|
-
}
|
|
2450
|
-
function addTransportMediaToPinnedFactory(source, code, factory) {
|
|
2451
|
-
let linkProps;
|
|
2452
|
-
const visit = (node) => {
|
|
2453
|
-
if (typescript.default.isObjectLiteralExpression(node) && isPinnedLinkProps(node, "href", "precedence")) linkProps = node;
|
|
2454
|
-
typescript.default.forEachChild(node, visit);
|
|
2455
|
-
};
|
|
2456
|
-
visit(factory);
|
|
2457
|
-
const lastParameter = factory.parameters[factory.parameters.length - 1];
|
|
2458
|
-
if (!linkProps || !lastParameter) throw new Error("Pinned Resources factory lost its stylesheet transport binding.");
|
|
2459
|
-
const factoryStart = factory.getStart(source);
|
|
2460
|
-
const replacements = [{
|
|
2461
|
-
position: lastParameter.getEnd() - factoryStart,
|
|
2462
|
-
value: ", __isr_engine_transport_media"
|
|
2463
|
-
}, {
|
|
2464
|
-
position: linkProps.getEnd() - factoryStart - 1,
|
|
2465
|
-
value: ",\n media: __isr_engine_transport_media"
|
|
2466
|
-
}].sort((left, right) => right.position - left.position);
|
|
2467
|
-
let factoryCode = code.slice(factoryStart, factory.getEnd());
|
|
2468
|
-
for (const replacement of replacements) factoryCode = factoryCode.slice(0, replacement.position) + replacement.value + factoryCode.slice(replacement.position);
|
|
2469
|
-
return factoryCode;
|
|
2470
|
-
}
|
|
2471
|
-
function isPinnedDependencies(node) {
|
|
2472
|
-
if (!typescript.default.isObjectLiteralExpression(node) || node.properties.length !== 2) return false;
|
|
2473
|
-
const properties = new Map(node.properties.map((property) => [propertyName(property.name), typescript.default.isPropertyAssignment(property) ? property.initializer : void 0]));
|
|
2474
|
-
const js = properties.get("js");
|
|
2475
|
-
const css = properties.get("css");
|
|
2476
|
-
return properties.size === 2 && js !== void 0 && typescript.default.isArrayLiteralExpression(js) && js.elements.every(typescript.default.isStringLiteral) && css !== void 0 && typescript.default.isArrayLiteralExpression(css) && css.elements.every(typescript.default.isStringLiteral);
|
|
2477
|
-
}
|
|
2478
|
-
function defaultImportBinding(statement, source) {
|
|
2479
|
-
if (statement === void 0 || !typescript.default.isImportDeclaration(statement) || !typescript.default.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== source || !statement.importClause?.name || statement.importClause.namedBindings) return;
|
|
2480
|
-
return statement.importClause.name.text;
|
|
2481
|
-
}
|
|
2482
|
-
function instrumentDevRscStylesheetModule(code, id, declarationsUrl) {
|
|
2483
|
-
if (!id.startsWith(VITE_RSC_CSS_RESOLVED_PREFIX)) return void 0;
|
|
2484
|
-
if (new URLSearchParams(id.slice(id.indexOf("?") + 1)).get("type") !== "rsc") return void 0;
|
|
2485
|
-
const source = typescript.default.createSourceFile(id, code, typescript.default.ScriptTarget.Latest, true, typescript.default.ScriptKind.JS);
|
|
2486
|
-
const resourcesStatement = source.statements.find((statement) => typescript.default.isVariableStatement(statement) && statement.modifiers?.some((modifier) => modifier.kind === typescript.default.SyntaxKind.ExportKeyword) === true && statement.declarationList.declarations.some((declaration) => typescript.default.isIdentifier(declaration.name) && declaration.name.text === "Resources"));
|
|
2487
|
-
const initializer = (resourcesStatement?.declarationList.declarations.find((declaration) => typescript.default.isIdentifier(declaration.name) && declaration.name.text === "Resources"))?.initializer;
|
|
2488
|
-
const factory = initializer && typescript.default.isCallExpression(initializer) ? typescript.default.isParenthesizedExpression(initializer.expression) ? initializer.expression.expression : initializer.expression : void 0;
|
|
2489
|
-
const reactBinding = defaultImportBinding(source.statements[0], "react");
|
|
2490
|
-
const cleanupBinding = defaultImportBinding(source.statements[1], VITE_RSC_REMOVE_DUPLICATE_CSS_ID);
|
|
2491
|
-
const depsArgument = initializer && typescript.default.isCallExpression(initializer) ? initializer.arguments[1] : void 0;
|
|
2492
|
-
if (source.statements.length !== 3 || reactBinding === void 0 || cleanupBinding === void 0 || source.statements[2] !== resourcesStatement || !resourcesStatement || resourcesStatement.modifiers?.length !== 1 || resourcesStatement.modifiers[0]?.kind !== typescript.default.SyntaxKind.ExportKeyword || (resourcesStatement.declarationList.flags & typescript.default.NodeFlags.Const) === 0 || resourcesStatement.declarationList.declarations.length !== 1 || !initializer || !typescript.default.isCallExpression(initializer) || initializer.arguments.length !== 4 || factory === void 0 || !typescript.default.isArrowFunction(factory) && !typescript.default.isFunctionExpression(factory) || !isPinnedResourcesFactory(factory) || !identifierIs(initializer.arguments[0], reactBinding) || !depsArgument || !isPinnedDependencies(depsArgument) || !identifierIs(initializer.arguments[2], cleanupBinding) || !(stringIs(initializer.arguments[3], "vite-rsc/importer-resources") || identifierIs(initializer.arguments[3], "undefined"))) throw new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc server stylesheet resource shape in ${id}. Expected the pinned 0.5.39 Resources factory.`);
|
|
2493
|
-
const reactCode = code.slice(initializer.arguments[0].getStart(source), initializer.arguments[0].getEnd());
|
|
2494
|
-
const depsCode = code.slice(initializer.arguments[1].getStart(source), initializer.arguments[1].getEnd());
|
|
2495
|
-
const replacement = `
|
|
2496
|
-
const __isr_engine_create_RscResources = ${addTransportMediaToPinnedFactory(source, code, factory)};
|
|
2497
|
-
export function Resources() {
|
|
2498
|
-
const __isr_engine_RscResources = __isr_engine_create_RscResources(
|
|
2499
|
-
${reactCode},
|
|
2500
|
-
__isr_engine_prepare_styles(${depsCode}),
|
|
2501
|
-
${code.slice(initializer.arguments[2].getStart(source), initializer.arguments[2].getEnd())},
|
|
2502
|
-
${code.slice(initializer.arguments[3].getStart(source), initializer.arguments[3].getEnd())},
|
|
2503
|
-
__isr_engine_get_transport_media(),
|
|
2504
|
-
);
|
|
2505
|
-
return ${reactCode}.createElement(__isr_engine_RscResources);
|
|
2506
|
-
}`;
|
|
2507
|
-
return {
|
|
2508
|
-
code: `import { getDevStyleTransportMedia as __isr_engine_get_transport_media, prepareDevStyleDependencies as __isr_engine_prepare_styles } from ${JSON.stringify(declarationsUrl)};\n` + code.slice(0, resourcesStatement.getStart(source)) + replacement + code.slice(resourcesStatement.getEnd()),
|
|
2509
|
-
map: null
|
|
2510
|
-
};
|
|
2511
|
-
}
|
|
2512
|
-
function createDevCssLifecyclePluginPhases(defaultsDir) {
|
|
2513
|
-
const lifecycleBoundaryPath = node_path.default.resolve(defaultsDir, "runtime/dev-css-handoff.client.ts");
|
|
2514
|
-
const registryUrl = (0, node_url.pathToFileURL)(node_path.default.resolve(defaultsDir, "runtime/dev-style-registry.client.ts")).href;
|
|
2515
|
-
const navigationLifecycleUrl = (0, node_url.pathToFileURL)(node_path.default.resolve(defaultsDir, "runtime/dev-style-navigation.client.ts")).href;
|
|
2516
|
-
const declarationsUrl = (0, node_url.pathToFileURL)(node_path.default.resolve(defaultsDir, "runtime/dev-style-declarations.server.ts")).href;
|
|
2517
|
-
const clientReferenceModuleIds = /* @__PURE__ */ new Set();
|
|
2518
|
-
let devServer;
|
|
2519
|
-
const plugins = [
|
|
2520
|
-
{
|
|
2521
|
-
name: "isr:dev-css-handoff",
|
|
2522
|
-
apply: applyDevCssLifecycle,
|
|
2523
|
-
enforce: "pre",
|
|
2524
|
-
configResolved() {
|
|
2525
|
-
assertPinnedViteVersion(vite.version);
|
|
2526
|
-
assertPinnedDevStyleResourceDispatcher();
|
|
2527
|
-
},
|
|
2528
|
-
configureServer(server) {
|
|
2529
|
-
devServer = server;
|
|
2530
|
-
},
|
|
2531
|
-
resolveId(id) {
|
|
2532
|
-
if (id === "virtual:vite-rsc/remove-duplicate-server-css") return DEV_CSS_HANDOFF_RESOLVED_ID;
|
|
2533
|
-
},
|
|
2534
|
-
load(id) {
|
|
2535
|
-
if (id !== "\0virtual:isr-engine/dev-css-handoff") return void 0;
|
|
2536
|
-
const boundary = (0, node_fs.readFileSync)(lifecycleBoundaryPath, "utf8");
|
|
2537
|
-
const directive = "'use client';";
|
|
2538
|
-
if (!boundary.startsWith(directive)) throw new Error("[isr-engine] Development CSS boundary lost its client directive.");
|
|
2539
|
-
if (this.environment.name !== "client") return boundary;
|
|
2540
|
-
return boundary.replace(directive, `${directive}\n\nimport ${JSON.stringify(DEV_STYLE_REGISTRY_ID)};`);
|
|
2541
|
-
},
|
|
2542
|
-
transform(code, id) {
|
|
2543
|
-
if (this?.environment.name === "rsc") {
|
|
2544
|
-
const moduleId = semanticModuleIdentity(id);
|
|
2545
|
-
if (hasUseClientDirective$1(code, id)) clientReferenceModuleIds.add(moduleId);
|
|
2546
|
-
else clientReferenceModuleIds.delete(moduleId);
|
|
2547
|
-
}
|
|
2548
|
-
const canonicalized = canonicalizeDevRscStylesheetModule(code, id);
|
|
2549
|
-
return instrumentDevRscStylesheetModule(canonicalized?.code ?? code, id, declarationsUrl) ?? canonicalized;
|
|
2550
|
-
}
|
|
2551
|
-
},
|
|
2552
|
-
{
|
|
2553
|
-
name: "isr:dev-client-reference-styles",
|
|
2554
|
-
apply: applyDevCssLifecycle,
|
|
2555
|
-
enforce: "post",
|
|
2556
|
-
async transform(code, id) {
|
|
2557
|
-
const moduleId = semanticModuleIdentity(id);
|
|
2558
|
-
if (this.environment.name !== "rsc" || !clientReferenceModuleIds.has(moduleId)) return;
|
|
2559
|
-
if (!devServer) throw new Error("[isr-engine] Development server is unavailable for CSS dependency mapping.");
|
|
2560
|
-
const referenceId = clientReferenceIdFromProxy(code, moduleId, devServer.config.root);
|
|
2561
|
-
const styleIds = await collectClientReferenceStyles(devServer, moduleId);
|
|
2562
|
-
return {
|
|
2563
|
-
code: `import { registerDevClientReferenceStyles as __isr_engine_register_client_styles } from ${JSON.stringify(declarationsUrl)};\n__isr_engine_register_client_styles(${JSON.stringify(referenceId)}, ${JSON.stringify(styleIds)});\n` + code,
|
|
2564
|
-
map: null
|
|
2565
|
-
};
|
|
2566
|
-
}
|
|
2567
|
-
},
|
|
2568
|
-
{
|
|
2569
|
-
name: "isr:dev-style-registry",
|
|
2570
|
-
apply: applyDevCssLifecycle,
|
|
2571
|
-
enforce: "post",
|
|
2572
|
-
resolveId(id) {
|
|
2573
|
-
return id === "virtual:isr-engine/dev-style-registry" ? DEV_STYLE_REGISTRY_RESOLVED_ID : void 0;
|
|
2574
|
-
},
|
|
2575
|
-
load(id) {
|
|
2576
|
-
if (id !== "\0virtual:isr-engine/dev-style-registry") return void 0;
|
|
2577
|
-
if (this.environment.name !== "client") return `
|
|
2578
|
-
export const devStyleRegistry = {
|
|
2579
|
-
publish() {},
|
|
2580
|
-
prune() {},
|
|
2581
|
-
};
|
|
2582
|
-
`;
|
|
2583
|
-
return `
|
|
2584
|
-
"use client";
|
|
2585
|
-
import { getOrCreateDevStyleRegistry } from ${JSON.stringify(registryUrl)};
|
|
2586
|
-
import {
|
|
2587
|
-
completeDevStyleNavigation,
|
|
2588
|
-
registerDevStyleRegistry,
|
|
2589
|
-
} from ${JSON.stringify(navigationLifecycleUrl)};
|
|
2590
|
-
|
|
2591
|
-
export const devStyleRegistry = getOrCreateDevStyleRegistry(document, {
|
|
2592
|
-
onRscCommit: completeDevStyleNavigation,
|
|
2593
|
-
});
|
|
2594
|
-
registerDevStyleRegistry(devStyleRegistry);
|
|
2595
|
-
import.meta.hot?.on('vite:beforeUpdate', () => devStyleRegistry.beginUpdate());
|
|
2596
|
-
import.meta.hot?.on('vite:afterUpdate', () => devStyleRegistry.commitUpdate());
|
|
2597
|
-
import.meta.hot?.on('vite:error', () => devStyleRegistry.abortUpdate());
|
|
2598
|
-
`;
|
|
2599
|
-
},
|
|
2600
|
-
transform(code, id) {
|
|
2601
|
-
return transformDevCssModule(code, id, DEV_STYLE_REGISTRY_ID, browserStyleIdForResolvedModule(devServer, id));
|
|
2602
|
-
}
|
|
2603
|
-
}
|
|
2604
|
-
];
|
|
2605
|
-
return {
|
|
2606
|
-
beforeRsc: [plugins[0]],
|
|
2607
|
-
afterRsc: [plugins[1], plugins[2]]
|
|
2608
|
-
};
|
|
2609
|
-
}
|
|
2610
|
-
//#endregion
|
|
2611
|
-
//#region src/plugin/createSsgPostBuildPlugin.ts
|
|
2612
|
-
/**
|
|
2613
|
-
* createSsgPostBuildPlugin —— vite 构建结束后自动跑 SSG 预渲染
|
|
2614
|
-
*
|
|
2615
|
-
* 让 `vite build` 成为唯一的构建入口(用户只需在 vite.config.ts 用 createIsrPlugin),
|
|
2616
|
-
* 不再需要 `isr-engine build` 这种 CLI 包一层。
|
|
2617
|
-
*
|
|
2618
|
-
* 实现要点:
|
|
2619
|
-
* - 在 plugin-rsc 的多 pass 构建里,client environment 是最后一轮
|
|
2620
|
-
* - 仅在 client 那一轮的 closeBundle 里跑 SSG(避免重复触发)
|
|
2621
|
-
* - 跑 SSG 需要 dist/rsc/index.js 已就绪 —— plugin-rsc 保证 client 是最后一环
|
|
2622
|
-
*/
|
|
2623
|
-
function createSsgPostBuildPlugin(explicitConfig) {
|
|
2624
|
-
let root = process.cwd();
|
|
2625
|
-
async function runSsg() {
|
|
2626
|
-
let userConfig = explicitConfig;
|
|
2627
|
-
if (!userConfig || Object.keys(userConfig).length === 0) userConfig = await require_createISRApp.loadConfig({ cwd: root });
|
|
2628
|
-
const ssgRoutes = await require_createISRApp.extractSsgRoutes(userConfig);
|
|
2629
|
-
require_createISRApp.assertDistinctHtmlRouteIdentities([...ssgRoutes, ...Object.keys(userConfig.routes ?? {})], { allowPatterns: true });
|
|
2630
|
-
if (ssgRoutes.length === 0) return [];
|
|
2631
|
-
const rscDistEntry = node_path.default.resolve(root, "dist/rsc/index.js");
|
|
2632
|
-
const clientDir = node_path.default.resolve(root, "dist/client");
|
|
2633
|
-
if (!(0, node_fs.existsSync)(rscDistEntry)) {
|
|
2634
|
-
require_createISRApp.logger.warn("[SSG] 未找到 dist/rsc/index.js,跳过 SSG 预生成");
|
|
2635
|
-
return [];
|
|
2636
|
-
}
|
|
2637
|
-
require_createISRApp.logger.info(`[SSG] 预生成 ${ssgRoutes.length} 个路由(${ssgRoutes.join(", ")})...`);
|
|
2638
|
-
const handler = require_createISRApp.resolveFetchHandler(await import(
|
|
2639
|
-
/* @vite-ignore */
|
|
2640
|
-
(0, node_url.pathToFileURL)(rscDistEntry).href
|
|
2641
|
-
));
|
|
2642
|
-
const ssgCfg = userConfig.ssg ?? {};
|
|
2643
|
-
const result = await require_createISRApp.spiderSsgRoutes({
|
|
2644
|
-
handler,
|
|
2645
|
-
routes: ssgRoutes,
|
|
2646
|
-
outDir: clientDir,
|
|
2647
|
-
options: {
|
|
2648
|
-
concurrency: ssgCfg.concurrent ?? 3,
|
|
2649
|
-
continueOnError: true,
|
|
2650
|
-
requestTimeoutMs: ssgCfg.requestTimeoutMs,
|
|
2651
|
-
maxRetries: ssgCfg.maxRetries,
|
|
2652
|
-
retryBaseDelayMs: ssgCfg.retryBaseDelayMs,
|
|
2653
|
-
failBuildThreshold: ssgCfg.failBuildThreshold
|
|
2654
|
-
}
|
|
2655
|
-
});
|
|
2656
|
-
require_createISRApp.logger.info(`[SSG] 预生成完成: ${result.successful} 成功, ${result.failed} 失败, 共 ${result.total} (失败率 ${(result.failureRate * 100).toFixed(1)}%)`);
|
|
2657
|
-
return ssgRoutes;
|
|
2658
|
-
}
|
|
2659
|
-
/**
|
|
2660
|
-
* 同 build 一并产 dist/spa/index.html ——
|
|
2661
|
-
* 复用 dist/client/ 已有的 client bundle + CSS chunks,触发 entry.tsx 的 SPA 路径
|
|
2662
|
-
* 部署:Nginx error_page 指向此文件,origin 5xx 时浏览器加载即启动 SPA fallback
|
|
2663
|
-
*/
|
|
2664
|
-
async function generateSpaShell() {
|
|
2665
|
-
const ssrManifest = node_path.default.resolve(root, "dist/ssr/__vite_rsc_assets_manifest.js");
|
|
2666
|
-
const spaDir = node_path.default.resolve(root, "dist/spa");
|
|
2667
|
-
if (!(0, node_fs.existsSync)(ssrManifest)) {
|
|
2668
|
-
require_createISRApp.logger.warn("[SPA] 未找到 dist/ssr/__vite_rsc_assets_manifest.js,跳过 SPA shell 生成");
|
|
2669
|
-
return;
|
|
2670
|
-
}
|
|
2671
|
-
const manifest = (await import(
|
|
2672
|
-
/* @vite-ignore */
|
|
2673
|
-
(0, node_url.pathToFileURL)(ssrManifest).href
|
|
2674
|
-
)).default;
|
|
2675
|
-
const bootstrap = manifest.bootstrapScriptContent ?? "";
|
|
2676
|
-
const cssSet = /* @__PURE__ */ new Set();
|
|
2677
|
-
for (const group of [manifest.clientReferenceDeps, manifest.serverResources]) {
|
|
2678
|
-
if (!group) continue;
|
|
2679
|
-
for (const id of Object.keys(group)) for (const href of group[id].css ?? []) cssSet.add(href);
|
|
2680
|
-
}
|
|
2681
|
-
const html = `<!DOCTYPE html>
|
|
2682
|
-
<html lang="zh-CN">
|
|
2683
|
-
<head>
|
|
2684
|
-
<meta charset="utf-8" />
|
|
2685
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2686
|
-
<title>正在加载…</title>
|
|
2687
|
-
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
|
2688
|
-
${Array.from(cssSet).map((h) => `<link rel="stylesheet" href="${h}" />`).join("\n ")}
|
|
2689
|
-
</head>
|
|
2690
|
-
<body>
|
|
2691
|
-
<script>self.__SPA_MODE__=1;${bootstrap}<\/script>
|
|
2692
|
-
</body>
|
|
2693
|
-
</html>
|
|
2694
|
-
`;
|
|
2695
|
-
await node_fs.promises.mkdir(spaDir, { recursive: true });
|
|
2696
|
-
await node_fs.promises.writeFile(node_path.default.join(spaDir, "index.html"), html, "utf-8");
|
|
2697
|
-
require_createISRApp.logger.info(`[SPA] dist/spa/index.html 已生成 (${cssSet.size} 个 CSS chunks 注入)`);
|
|
2698
|
-
}
|
|
2699
|
-
return {
|
|
2700
|
-
name: "isr-engine:ssg-post-build",
|
|
2701
|
-
apply: "build",
|
|
2702
|
-
configResolved(resolved) {
|
|
2703
|
-
root = resolved.root;
|
|
2704
|
-
},
|
|
2705
|
-
/**
|
|
2706
|
-
* vite 8 的 buildApp hook —— 在 builder.buildApp() 完成所有环境后调用一次。
|
|
2707
|
-
* 这是跑 SSG 的最佳时机:dist/{rsc,client,ssr}/* 全部就绪,manifest 也已生成。
|
|
2708
|
-
* 比挂在 closeBundle 里要稳定(closeBundle 在每个环境单独触发,且 manifest 不一定 ready)
|
|
2709
|
-
*/
|
|
2710
|
-
buildApp: {
|
|
2711
|
-
order: "post",
|
|
2712
|
-
async handler() {
|
|
2713
|
-
const ssgRoutes = await runSsg();
|
|
2714
|
-
await generateSpaShell();
|
|
2715
|
-
await require_createISRApp.generateStaticCspManifest(node_path.default.resolve(root, "dist"), { ssgRoutes });
|
|
2716
|
-
}
|
|
2717
|
-
}
|
|
2718
|
-
};
|
|
2719
|
-
}
|
|
2720
|
-
//#endregion
|
|
2721
|
-
//#region src/plugin/clientObservabilityConfig.ts
|
|
2722
|
-
var DEFAULT_ANALYTICS_PATH = "/api/observability/analytics";
|
|
2723
|
-
var DEFAULT_ERRORS_PATH = "/api/observability/errors";
|
|
2724
|
-
var ANALYTICS_BATCH_SIZE = 20;
|
|
2725
|
-
var ERRORS_BATCH_SIZE = 10;
|
|
2726
|
-
var FLUSH_INTERVAL_MS = 3e3;
|
|
2727
|
-
var ANALYTICS_MAX_QUEUE = 500;
|
|
2728
|
-
var ERRORS_MAX_QUEUE = 200;
|
|
2729
|
-
var RETRY_BASE_DELAY_MS = 1e3;
|
|
2730
|
-
var RETRY_MAX_DELAY_MS = 3e4;
|
|
2731
|
-
/**
|
|
2732
|
-
* Resolve the public browser telemetry config from ssr.config.ts runtime.
|
|
2733
|
-
*
|
|
2734
|
-
* Only this whitelisted shape may be serialized into the client bundle. Never
|
|
2735
|
-
* pass the whole runtime object to the browser because it can contain Redis,
|
|
2736
|
-
* Sentry DSN, private service URLs, and other server-only integration settings.
|
|
2737
|
-
*/
|
|
2738
|
-
function resolveClientObservabilityOptions({ runtime, root = process.cwd(), env = process.env }) {
|
|
2739
|
-
const config = runtime?.telemetry;
|
|
2740
|
-
if (config === false) return false;
|
|
2741
|
-
if (!config) return null;
|
|
2742
|
-
const serviceOrigin = runtime?.services?.telemetry ?? runtime?.services?.api ?? "";
|
|
2743
|
-
return {
|
|
2744
|
-
app: config.app ?? readPackageName(root) ?? "isr-engine-app",
|
|
2745
|
-
release: config.release ?? env.VITE_APP_VERSION ?? env.APP_VERSION ?? env.npm_package_version,
|
|
2746
|
-
environment: config.environment ?? env.NODE_ENV ?? env.MODE,
|
|
2747
|
-
includeQueryString: config.includeQueryString,
|
|
2748
|
-
analytics: resolveAnalyticsConfig(config, serviceOrigin),
|
|
2749
|
-
errorReporting: resolveErrorReportingConfig(config, serviceOrigin)
|
|
2750
|
-
};
|
|
2751
|
-
}
|
|
2752
|
-
function resolveAnalyticsConfig(config, serviceOrigin) {
|
|
2753
|
-
if (config.events === false) return false;
|
|
2754
|
-
const events = config.events;
|
|
2755
|
-
return {
|
|
2756
|
-
endpoint: resolveEndpoint(events, serviceOrigin, DEFAULT_ANALYTICS_PATH),
|
|
2757
|
-
sampleRate: events.sampleRate,
|
|
2758
|
-
batchSize: ANALYTICS_BATCH_SIZE,
|
|
2759
|
-
flushIntervalMs: FLUSH_INTERVAL_MS,
|
|
2760
|
-
maxQueueSize: ANALYTICS_MAX_QUEUE,
|
|
2761
|
-
retryBaseDelayMs: RETRY_BASE_DELAY_MS,
|
|
2762
|
-
retryMaxDelayMs: RETRY_MAX_DELAY_MS,
|
|
2763
|
-
webVitals: config.webVitals === false ? false : config.webVitals?.enabled ?? true,
|
|
2764
|
-
trackInitialPage: events.trackInitialPage
|
|
2765
|
-
};
|
|
2766
|
-
}
|
|
2767
|
-
function resolveErrorReportingConfig(config, serviceOrigin) {
|
|
2768
|
-
if (config.errors === false) return false;
|
|
2769
|
-
const errors = config.errors;
|
|
2770
|
-
return {
|
|
2771
|
-
endpoint: resolveEndpoint(errors, serviceOrigin, DEFAULT_ERRORS_PATH),
|
|
2772
|
-
sampleRate: errors.sampleRate,
|
|
2773
|
-
batchSize: ERRORS_BATCH_SIZE,
|
|
2774
|
-
flushIntervalMs: FLUSH_INTERVAL_MS,
|
|
2775
|
-
maxQueueSize: ERRORS_MAX_QUEUE,
|
|
2776
|
-
retryBaseDelayMs: RETRY_BASE_DELAY_MS,
|
|
2777
|
-
retryMaxDelayMs: RETRY_MAX_DELAY_MS,
|
|
2778
|
-
captureResourceErrors: errors.captureResourceErrors
|
|
2779
|
-
};
|
|
2780
|
-
}
|
|
2781
|
-
function resolveEndpoint(options, serviceOrigin, defaultPath) {
|
|
2782
|
-
return joinEndpoint(serviceOrigin, options.endpoint ?? defaultPath);
|
|
2783
|
-
}
|
|
2784
|
-
function joinEndpoint(origin, endpoint) {
|
|
2785
|
-
if (/^https?:\/\//i.test(endpoint)) return endpoint;
|
|
2786
|
-
if (!origin) return endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
|
|
2787
|
-
return `${require_i18n.trimTrailingSlashes(origin)}/${endpoint.replace(/^\/+/, "")}`;
|
|
2788
|
-
}
|
|
2789
|
-
function readPackageName(root) {
|
|
2790
|
-
try {
|
|
2791
|
-
const pkg = JSON.parse(node_fs.default.readFileSync(node_path.default.resolve(root, "package.json"), "utf8"));
|
|
2792
|
-
return typeof pkg.name === "string" && pkg.name.trim() ? pkg.name : void 0;
|
|
2793
|
-
} catch {
|
|
2794
|
-
return;
|
|
2795
|
-
}
|
|
2796
|
-
}
|
|
2797
|
-
//#endregion
|
|
2798
|
-
//#region src/plugin/createIsrPlugin.ts
|
|
2799
|
-
/**
|
|
2800
|
-
* ISR 插件工厂 —— 组合 @vitejs/plugin-rsc + ISR 缓存中间件
|
|
2801
|
-
*
|
|
2802
|
-
* 真·开箱即用:
|
|
2803
|
-
* import { createIsrPlugin } from './isr-engine';
|
|
2804
|
-
* export default defineConfig({ plugins: [...createIsrPlugin()] });
|
|
2805
|
-
*
|
|
2806
|
-
* 用户**唯一必需的应用代码**:`<root>/src/root.tsx`
|
|
2807
|
-
* - 必须 export `Root({ url: URL })` —— 即应用根 Server Component
|
|
2808
|
-
*
|
|
2809
|
-
* 三个 Vite environment 的入口(client / rsc / ssr)engine 全部内置默认实现:
|
|
2810
|
-
* - 用户不写任何入口文件即可跑起来
|
|
2811
|
-
* - 想覆盖任一个,把同名文件放到 `<root>/src/` 即可(约定优于配置)
|
|
2812
|
-
*
|
|
2813
|
-
* 入口约定(覆盖文件名):
|
|
2814
|
-
* src/entry.tsx —— 客户端水合入口(覆盖默认)
|
|
2815
|
-
* src/entry.server.tsx —— 服务端 RSC handler(覆盖默认)
|
|
2816
|
-
* src/entry.server.ssr.tsx —— SSR 转 HTML 入口(覆盖默认)
|
|
2817
|
-
*
|
|
2818
|
-
* 注:不要再额外注册 @vitejs/plugin-react —— @vitejs/plugin-rsc 已为客户端环境
|
|
2819
|
-
* 内置了 react-refresh 运行时注入与 JSX 处理;重复注册会触发
|
|
2820
|
-
* `Identifier 'RefreshRuntime' has already been declared` 错误。
|
|
2821
|
-
*/
|
|
2822
|
-
var logger = require_Logger.Logger.getInstance();
|
|
2823
|
-
var VIRTUAL_ENTRY_IDS = {
|
|
2824
|
-
client: "virtual:isr-engine/client-entry",
|
|
2825
|
-
rsc: "virtual:isr-engine/rsc-entry",
|
|
2826
|
-
runtime: "virtual:isr-engine/runtime-config",
|
|
2827
|
-
clientRuntime: "virtual:isr-engine/client-runtime-config"
|
|
2828
|
-
};
|
|
2829
|
-
var RESOLVED_VIRTUAL_PREFIX = "\0";
|
|
2830
|
-
/**
|
|
2831
|
-
* 三个 environment 的入口文件名约定 —— 用户在 src/ 下放同名文件即覆盖
|
|
2832
|
-
* engine 默认实现
|
|
2833
|
-
*/
|
|
2834
|
-
var ENTRY_CONVENTION = {
|
|
2835
|
-
client: "src/entry.tsx",
|
|
2836
|
-
rsc: "src/entry.server.tsx",
|
|
2837
|
-
ssr: "src/entry.server.ssr.tsx"
|
|
2838
|
-
};
|
|
2839
|
-
/** engine 内置默认入口文件名(位于 isr-engine/src/defaults/)*/
|
|
2840
|
-
var ENGINE_DEFAULTS = {
|
|
2841
|
-
client: "entry.tsx",
|
|
2842
|
-
rsc: "entry.server.tsx",
|
|
2843
|
-
ssr: "entry.server.ssr.tsx"
|
|
2844
|
-
};
|
|
2845
|
-
/** 解析 engine defaults 目录的绝对路径(兼容构建产物 dist/ 与源码) */
|
|
2846
|
-
function resolveEngineDefaultsDir() {
|
|
2847
|
-
const here = typeof __dirname === "string" ? __dirname : node_path.default.dirname((0, node_url.fileURLToPath)({}.url));
|
|
2848
|
-
const candidates = [
|
|
2849
|
-
node_path.default.resolve(here, "../src/defaults"),
|
|
2850
|
-
node_path.default.resolve(here, "../defaults"),
|
|
2851
|
-
node_path.default.resolve(here, "./defaults")
|
|
2852
|
-
];
|
|
2853
|
-
for (const c of candidates) if (node_fs.default.existsSync(c)) return c;
|
|
2854
|
-
throw new Error(`[isr-engine] 找不到 engine defaults 目录(候选:${candidates.join(" / ")})`);
|
|
2855
|
-
}
|
|
2856
|
-
/**
|
|
2857
|
-
* Entry 解析策略:
|
|
2858
|
-
* - client / rsc:永远指向 engine 内置 wrapper;
|
|
2859
|
-
* 用户的可选 src/entry.tsx / src/entry.server.tsx 通过 @app/_*-config 别名
|
|
2860
|
-
* 注入到 wrapper,wrapper 按形状分派(FaaS hooks 或完整 fetch handler)
|
|
2861
|
-
* - ssr:用户提供 src/entry.server.ssr.tsx 时直接用,否则 engine 默认(极少需要覆盖)
|
|
2862
|
-
*
|
|
2863
|
-
* 用户唯一必须提供的应用代码:`<root>/src/app.tsx`(导出 App({url}))
|
|
2864
|
-
*/
|
|
2865
|
-
function resolveEntries(root) {
|
|
2866
|
-
const defaultsDir = resolveEngineDefaultsDir();
|
|
2867
|
-
const wrapperPath = (file) => {
|
|
2868
|
-
const abs = node_path.default.resolve(defaultsDir, file);
|
|
2869
|
-
if (!node_fs.default.existsSync(abs)) throw new Error(`[isr-engine] engine 内置 wrapper 缺失:${abs}(请检查 engine 安装是否完整)`);
|
|
2870
|
-
return abs;
|
|
2871
|
-
};
|
|
2872
|
-
const appPath = node_path.default.resolve(root, "src/app.tsx");
|
|
2873
|
-
if (!node_fs.default.existsSync(appPath)) throw new Error(`[isr-engine] 找不到应用根组件 src/app.tsx,这是 engine 唯一要求的用户文件。\n请创建 ${appPath} 并 export function App({ url }: { url: URL }) {...}`);
|
|
2874
|
-
const hasUserConfig = (env) => node_fs.default.existsSync(node_path.default.resolve(root, ENTRY_CONVENTION[env]));
|
|
2875
|
-
const userSsr = node_path.default.resolve(root, ENTRY_CONVENTION.ssr);
|
|
2876
|
-
const ssrEntry = node_fs.default.existsSync(userSsr) ? userSsr : wrapperPath(ENGINE_DEFAULTS.ssr);
|
|
2877
|
-
return {
|
|
2878
|
-
client: wrapperPath(ENGINE_DEFAULTS.client),
|
|
2879
|
-
rsc: wrapperPath(ENGINE_DEFAULTS.rsc),
|
|
2880
|
-
ssr: ssrEntry,
|
|
2881
|
-
source: {
|
|
2882
|
-
client: hasUserConfig("client") ? "user" : "engine",
|
|
2883
|
-
rsc: hasUserConfig("rsc") ? "user" : "engine",
|
|
2884
|
-
ssr: hasUserConfig("ssr") ? "user" : "engine"
|
|
2885
|
-
}
|
|
2886
|
-
};
|
|
2887
|
-
}
|
|
2888
|
-
/**
|
|
2889
|
-
* 注入两件事:
|
|
2890
|
-
* 1. `@app/*` Vite alias
|
|
2891
|
-
* - `@app/_entry` 特殊指向用户的应用根组件文件(app.tsx 优先 / root.tsx 兼容)
|
|
2892
|
-
* - `@app/<x>` 通用指向 `<root>/src/<x>` —— 给用户自定义文件用
|
|
2893
|
-
*
|
|
2894
|
-
* 2. resolve.dedupe react / react-dom —— engine 默认入口被 plugin-rsc bundle 时,
|
|
2895
|
-
* 可能从 engine 的 node_modules 解析 react,导致用户项目里出现两份 React 实例,
|
|
2896
|
-
* 水合失败(Cannot read properties of null (reading 'useState'))。
|
|
2897
|
-
* 强制 dedupe 让 react 始终从用户项目根解析
|
|
2898
|
-
*/
|
|
2899
|
-
/**
|
|
2900
|
-
* 给 client environment 注入 process.* 兜底
|
|
2901
|
-
*
|
|
2902
|
-
* 原因:CJS 库(chalk / signal-exit / supports-color 等)一旦被打包进 client bundle
|
|
2903
|
-
* 会在浏览器报 ReferenceError: process is not defined。
|
|
2904
|
-
* 哪怕这些库是死代码(CSR fallback 路径不实际执行),rolldown 仍会保留它们的 top-level
|
|
2905
|
-
* statement,所以浏览器加载即崩。
|
|
2906
|
-
*
|
|
2907
|
-
* 兜底:仅对 client environment 注入 vite define,把 `process.platform` / `process.env`
|
|
2908
|
-
* 替换为浏览器友好的常量,避免 ReferenceError;不影响 server / rsc / ssr 环境的真实 Node 行为。
|
|
2909
|
-
*/
|
|
2910
|
-
/**
|
|
2911
|
-
* engine 拥有的 Vite build/define 默认值与硬约束 —— 消费侧 vite.config.ts 无权覆盖。
|
|
2912
|
-
*
|
|
2913
|
-
* 第一性原理:SSR/ISR 渲染正确性是 engine 的契约(开箱即用),消费侧不该有能力
|
|
2914
|
-
* 通过 vite 配置打破。两类职责合并:
|
|
2915
|
-
*
|
|
2916
|
-
* 1. `config()` 阶段注入 browser-friendly define
|
|
2917
|
-
* CJS 库(chalk / signal-exit / supports-color 等)一旦打进 client bundle
|
|
2918
|
-
* 会在浏览器报 ReferenceError: process is not defined。哪怕是死代码,
|
|
2919
|
-
* rolldown 也保留 top-level statement,浏览器加载即崩。把 process.*
|
|
2920
|
-
* 替换成浏览器友好的常量。
|
|
2921
|
-
*
|
|
2922
|
-
* 2. `configResolved()` 阶段静默 mutate 最终合并后的关键 build 项
|
|
2923
|
-
* configResolved 是 Vite 标准生命周期最后一步,跑在所有用户/插件 config
|
|
2924
|
-
* 合并之后。这里直接改 resolved config —— 消费侧任何 vite.config.ts 写法
|
|
2925
|
-
* 都被无视,构建不报错不警告,engine 静默接管。
|
|
2926
|
-
*
|
|
2927
|
-
* build.cssCodeSplit = true
|
|
2928
|
-
* plugin-rsc 依赖 chunk 级 CSS split 追踪每个 'use client' 组件的 CSS
|
|
2929
|
-
* chunk 依赖。关闭后 clientReferenceDeps[*].css 全空,plugin-rsc native
|
|
2930
|
-
* 自动注入失效,Header / Footer / Logo / Nav 等组件 .module.scss 样式
|
|
2931
|
-
* 丢失。消费侧无权决定此项。
|
|
2932
|
-
*/
|
|
2933
|
-
function createBrowserShimPlugin() {
|
|
2934
|
-
return {
|
|
2935
|
-
name: "isr:engine-build-overrides",
|
|
2936
|
-
config(_, { command }) {
|
|
2937
|
-
if (command !== "build") return;
|
|
2938
|
-
const stdMock = "({isTTY:false,write:()=>{},end:()=>{},on:()=>{},getColorDepth:()=>1})";
|
|
2939
|
-
return { define: {
|
|
2940
|
-
"process.platform": "\"browser\"",
|
|
2941
|
-
"process.arch": "\"unknown\"",
|
|
2942
|
-
"process.versions": "({})",
|
|
2943
|
-
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "production"),
|
|
2944
|
-
"process.stdout": stdMock,
|
|
2945
|
-
"process.stderr": stdMock,
|
|
2946
|
-
"process.argv": "[]"
|
|
2947
|
-
} };
|
|
2948
|
-
},
|
|
2949
|
-
configResolved(config) {
|
|
2950
|
-
const force = (b) => {
|
|
2951
|
-
if (b) b.cssCodeSplit = true;
|
|
2952
|
-
};
|
|
2953
|
-
force(config.build);
|
|
2954
|
-
const envs = config.environments;
|
|
2955
|
-
if (envs) for (const name of Object.keys(envs)) force(envs[name]?.build);
|
|
2956
|
-
}
|
|
2957
|
-
};
|
|
2958
|
-
}
|
|
2959
|
-
function readPackageDependencies(root) {
|
|
2960
|
-
const packageJsonPath = node_path.default.resolve(root, "package.json");
|
|
2961
|
-
if (!node_fs.default.existsSync(packageJsonPath)) return [];
|
|
2962
|
-
try {
|
|
2963
|
-
const pkg = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf8"));
|
|
2964
|
-
return Array.from(/* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]));
|
|
2965
|
-
} catch {
|
|
2966
|
-
return [];
|
|
2967
|
-
}
|
|
2968
|
-
}
|
|
2969
|
-
function hasUseClientDirective(filePath) {
|
|
2970
|
-
try {
|
|
2971
|
-
const source = node_fs.default.readFileSync(filePath, "utf8").slice(0, 2048);
|
|
2972
|
-
const scanner = typescript.default.createScanner(typescript.default.ScriptTarget.Latest, true, typescript.default.LanguageVariant.Standard, source);
|
|
2973
|
-
return scanner.scan() === typescript.default.SyntaxKind.StringLiteral && (scanner.getTokenText() === "'use client'" || scanner.getTokenText() === "\"use client\"");
|
|
2974
|
-
} catch {
|
|
2975
|
-
return false;
|
|
2976
|
-
}
|
|
2977
|
-
}
|
|
2978
|
-
function detectClientReferenceDependencies(root) {
|
|
2979
|
-
const requireFromRoot = (0, node_module.createRequire)(node_path.default.resolve(root, "package.json"));
|
|
2980
|
-
const result = [];
|
|
2981
|
-
for (const dep of readPackageDependencies(root)) try {
|
|
2982
|
-
if (hasUseClientDirective(requireFromRoot.resolve(dep))) result.push(dep);
|
|
2983
|
-
} catch {}
|
|
2984
|
-
return result;
|
|
2985
|
-
}
|
|
2986
|
-
function createEngineDefaultEntriesPlugin(root, inlineConfig) {
|
|
2987
|
-
const virtualEntryIds = new Set(Object.values(VIRTUAL_ENTRY_IDS));
|
|
2988
|
-
const resolvedVirtualEntryIds = new Set(Object.values(VIRTUAL_ENTRY_IDS).map((id) => `${RESOLVED_VIRTUAL_PREFIX}${id}`));
|
|
2989
|
-
const defaultsDir = resolveEngineDefaultsDir();
|
|
2990
|
-
const fileImport = (relativePath) => JSON.stringify((0, node_url.pathToFileURL)(node_path.default.resolve(defaultsDir, relativePath)).href);
|
|
2991
|
-
return {
|
|
2992
|
-
name: "isr:engine-default-entries",
|
|
2993
|
-
enforce: "pre",
|
|
2994
|
-
resolveId(id) {
|
|
2995
|
-
if (resolvedVirtualEntryIds.has(id)) return id;
|
|
2996
|
-
if (virtualEntryIds.has(id)) return `${RESOLVED_VIRTUAL_PREFIX}${id}`;
|
|
2997
|
-
return null;
|
|
2998
|
-
},
|
|
2999
|
-
load(id) {
|
|
3000
|
-
if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.client}`) return `
|
|
3001
|
-
import { defineClientEntry } from ${fileImport("runtime/defineClientEntry.tsx")};
|
|
3002
|
-
import userConfig from '@app/_client-config';
|
|
3003
|
-
import runtimeClientConfig from '${VIRTUAL_ENTRY_IDS.clientRuntime}';
|
|
3004
|
-
|
|
3005
|
-
defineClientEntry(mergeClientConfig(runtimeClientConfig ?? {}, userConfig ?? {}));
|
|
3006
|
-
|
|
3007
|
-
function mergeClientConfig(runtimeConfig, userConfig) {
|
|
3008
|
-
return {
|
|
3009
|
-
...runtimeConfig,
|
|
3010
|
-
...userConfig,
|
|
3011
|
-
telemetry:
|
|
3012
|
-
Object.prototype.hasOwnProperty.call(userConfig, 'telemetry')
|
|
3013
|
-
? userConfig.telemetry
|
|
3014
|
-
: runtimeConfig.telemetry,
|
|
3015
|
-
devInspector:
|
|
3016
|
-
Object.prototype.hasOwnProperty.call(userConfig, 'devInspector')
|
|
3017
|
-
? userConfig.devInspector
|
|
3018
|
-
: runtimeConfig.devInspector,
|
|
3019
|
-
};
|
|
3020
|
-
}
|
|
3021
|
-
`;
|
|
3022
|
-
if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.rsc}`) return `
|
|
3023
|
-
import { defineServerEntry } from ${fileImport("runtime/defineServerEntry.tsx")};
|
|
3024
|
-
import { applyRuntimeToServerHooks } from ${fileImport("runtime/defineSiteHooks.ts")};
|
|
3025
|
-
import { createAutoServerHooks } from 'isr-engine/auto-observability';
|
|
3026
|
-
import userConfig from '@app/_server-config';
|
|
3027
|
-
import runtimeConfig from '${VIRTUAL_ENTRY_IDS.runtime}';
|
|
3028
|
-
|
|
3029
|
-
function hasFetchHandler(x) {
|
|
3030
|
-
return !!x && typeof x.fetch === 'function';
|
|
3031
|
-
}
|
|
3032
|
-
|
|
3033
|
-
const autoHooksPromise = createAutoServerHooks();
|
|
3034
|
-
|
|
3035
|
-
const resolved = hasFetchHandler(userConfig)
|
|
3036
|
-
? userConfig
|
|
3037
|
-
: (() => {
|
|
3038
|
-
let realHandler = null;
|
|
3039
|
-
let initPromise = null;
|
|
3040
|
-
|
|
3041
|
-
return {
|
|
3042
|
-
async fetch(request) {
|
|
3043
|
-
if (!realHandler) {
|
|
3044
|
-
initPromise ??= (async () => {
|
|
3045
|
-
const auto = await autoHooksPromise;
|
|
3046
|
-
const user = applyRuntimeToServerHooks(userConfig ?? {}, runtimeConfig ?? {});
|
|
3047
|
-
const merged = {
|
|
3048
|
-
...auto,
|
|
3049
|
-
...user,
|
|
3050
|
-
beforeRequest: chainBefore(auto.beforeRequest, user.beforeRequest),
|
|
3051
|
-
onResponse: chainResponse(auto.onResponse, user.onResponse),
|
|
3052
|
-
onError: chainError(auto.onError, user.onError),
|
|
3053
|
-
};
|
|
3054
|
-
return defineServerEntry(merged);
|
|
3055
|
-
})();
|
|
3056
|
-
realHandler = await initPromise;
|
|
3057
|
-
}
|
|
3058
|
-
return realHandler.fetch(request);
|
|
3059
|
-
},
|
|
3060
|
-
};
|
|
3061
|
-
})();
|
|
3062
|
-
|
|
3063
|
-
function chainBefore(a, b) {
|
|
3064
|
-
if (!a) return b;
|
|
3065
|
-
if (!b) return a;
|
|
3066
|
-
return async (req, baseline) => {
|
|
3067
|
-
const ax = (await a(req, baseline)) ?? {};
|
|
3068
|
-
const bx = (await b(req, baseline)) ?? {};
|
|
3069
|
-
return { ...ax, ...bx };
|
|
3070
|
-
};
|
|
3071
|
-
}
|
|
3072
|
-
|
|
3073
|
-
function chainResponse(a, b) {
|
|
3074
|
-
if (!a) return b;
|
|
3075
|
-
if (!b) return a;
|
|
3076
|
-
return async (res, ctx) => {
|
|
3077
|
-
await a(res, ctx);
|
|
3078
|
-
await b(res, ctx);
|
|
3079
|
-
};
|
|
3080
|
-
}
|
|
3081
|
-
|
|
3082
|
-
function chainError(a, b) {
|
|
3083
|
-
if (!a) return b;
|
|
3084
|
-
if (!b) return a;
|
|
3085
|
-
return async (err, req, ctx) => {
|
|
3086
|
-
await a(err, req, ctx);
|
|
3087
|
-
await b(err, req, ctx);
|
|
3088
|
-
};
|
|
3089
|
-
}
|
|
3090
|
-
|
|
3091
|
-
export default resolved;
|
|
3092
|
-
|
|
3093
|
-
if (import.meta.hot) {
|
|
3094
|
-
import.meta.hot.accept();
|
|
3095
|
-
}
|
|
3096
|
-
`;
|
|
3097
|
-
if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.runtime}`) {
|
|
3098
|
-
const configPath = node_path.default.resolve(root, "ssr.config.ts");
|
|
3099
|
-
if (!node_fs.default.existsSync(configPath)) return `export default {};`;
|
|
3100
|
-
return `
|
|
3101
|
-
const configModule = await import(${JSON.stringify((0, node_url.pathToFileURL)(configPath).href)});
|
|
3102
|
-
const defaultConfig = configModule.default ?? {};
|
|
3103
|
-
const namedRuntime = configModule['runtime'];
|
|
3104
|
-
export default defaultConfig.runtime ?? namedRuntime ?? {};
|
|
3105
|
-
`;
|
|
3106
|
-
}
|
|
3107
|
-
if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.clientRuntime}`) return resolveClientRuntimeConfigModule(root, inlineConfig);
|
|
3108
|
-
return null;
|
|
3109
|
-
}
|
|
3110
|
-
};
|
|
3111
|
-
}
|
|
3112
|
-
async function resolveClientRuntimeConfigModule(root, inlineConfig) {
|
|
3113
|
-
const telemetry = resolveClientObservabilityOptions({
|
|
3114
|
-
runtime: (Object.keys(inlineConfig).length > 0 ? inlineConfig : await require_createISRApp.loadConfig({ cwd: root })).runtime,
|
|
3115
|
-
root
|
|
3116
|
-
});
|
|
3117
|
-
return `export default ${JSON.stringify({ ...telemetry === null ? {} : { telemetry } })};`;
|
|
3118
|
-
}
|
|
3119
|
-
function createAppAliasPlugin(root) {
|
|
3120
|
-
const userSrc = node_path.default.resolve(root, "src");
|
|
3121
|
-
const defaultsDir = resolveEngineDefaultsDir();
|
|
3122
|
-
const requireFromEngine = (0, node_module.createRequire)(node_path.default.resolve(defaultsDir, "../../package.json"));
|
|
3123
|
-
const transportAliases = ["client", "server"].map((entry) => {
|
|
3124
|
-
const find = `rsc-html-stream/${entry}`;
|
|
3125
|
-
return {
|
|
3126
|
-
find,
|
|
3127
|
-
replacement: requireFromEngine.resolve(find)
|
|
3128
|
-
};
|
|
3129
|
-
});
|
|
3130
|
-
for (const entry of [
|
|
3131
|
-
"client.browser",
|
|
3132
|
-
"client.edge",
|
|
3133
|
-
"server.edge",
|
|
3134
|
-
"static.edge"
|
|
3135
|
-
]) {
|
|
3136
|
-
const find = `@vitejs/plugin-rsc/vendor/react-server-dom/${entry}`;
|
|
3137
|
-
transportAliases.push({
|
|
3138
|
-
find,
|
|
3139
|
-
replacement: requireFromEngine.resolve(find)
|
|
3140
|
-
});
|
|
3141
|
-
}
|
|
3142
|
-
const emptyConfig = node_path.default.resolve(defaultsDir, "runtime/empty-config.ts");
|
|
3143
|
-
const emptyRoutes = node_path.default.resolve(defaultsDir, "runtime/empty-routes.ts");
|
|
3144
|
-
const appEntry = node_path.default.resolve(userSrc, "app.tsx");
|
|
3145
|
-
const appRoutes = node_path.default.resolve(userSrc, "routes.tsx");
|
|
3146
|
-
const userOrEmpty = (rel) => {
|
|
3147
|
-
const abs = node_path.default.resolve(root, rel);
|
|
3148
|
-
return node_fs.default.existsSync(abs) ? abs : emptyConfig;
|
|
3149
|
-
};
|
|
3150
|
-
return {
|
|
3151
|
-
name: "isr:app-alias",
|
|
3152
|
-
enforce: "pre",
|
|
3153
|
-
config() {
|
|
3154
|
-
const clientReferenceDeps = detectClientReferenceDependencies(root);
|
|
3155
|
-
return {
|
|
3156
|
-
resolve: {
|
|
3157
|
-
alias: [...[
|
|
3158
|
-
{
|
|
3159
|
-
find: "@app/_entry",
|
|
3160
|
-
replacement: appEntry
|
|
3161
|
-
},
|
|
3162
|
-
{
|
|
3163
|
-
find: "@app/_routes",
|
|
3164
|
-
replacement: node_fs.default.existsSync(appRoutes) ? appRoutes : emptyRoutes
|
|
3165
|
-
},
|
|
3166
|
-
{
|
|
3167
|
-
find: "@app/_client-config",
|
|
3168
|
-
replacement: userOrEmpty(ENTRY_CONVENTION.client)
|
|
3169
|
-
},
|
|
3170
|
-
{
|
|
3171
|
-
find: "@app/_server-config",
|
|
3172
|
-
replacement: userOrEmpty(ENTRY_CONVENTION.rsc)
|
|
3173
|
-
},
|
|
3174
|
-
{
|
|
3175
|
-
find: "@app/_ssr-config",
|
|
3176
|
-
replacement: userOrEmpty(ENTRY_CONVENTION.ssr)
|
|
3177
|
-
},
|
|
3178
|
-
{
|
|
3179
|
-
find: /^@app\/(.*)$/,
|
|
3180
|
-
replacement: `${userSrc}/$1`
|
|
3181
|
-
}
|
|
3182
|
-
], ...transportAliases],
|
|
3183
|
-
dedupe: ["react", "react-dom"]
|
|
3184
|
-
},
|
|
3185
|
-
optimizeDeps: {
|
|
3186
|
-
entries: ["src/**/*.{js,jsx,ts,tsx}"],
|
|
3187
|
-
include: [
|
|
3188
|
-
"react",
|
|
3189
|
-
"react/jsx-runtime",
|
|
3190
|
-
"react/jsx-dev-runtime",
|
|
3191
|
-
"react-dom",
|
|
3192
|
-
"react-dom/client",
|
|
3193
|
-
"rsc-html-stream/client"
|
|
3194
|
-
],
|
|
3195
|
-
exclude: [
|
|
3196
|
-
...clientReferenceDeps,
|
|
3197
|
-
"isr-engine",
|
|
3198
|
-
"isr-engine/runtime",
|
|
3199
|
-
"@app/_entry",
|
|
3200
|
-
"@app/_routes",
|
|
3201
|
-
"@app/_client-config",
|
|
3202
|
-
"@app/_server-config",
|
|
3203
|
-
"@app/_ssr-config"
|
|
3204
|
-
]
|
|
3205
|
-
}
|
|
3206
|
-
};
|
|
3207
|
-
}
|
|
3208
|
-
};
|
|
3209
|
-
}
|
|
3210
|
-
function createIsrPlugin(options = {}) {
|
|
3211
|
-
const { config: userConfig = {}, root = process.cwd(), rsc: rscOptions, isrCache: isrCacheOptions } = options;
|
|
3212
|
-
const entries = resolveEntries(root);
|
|
3213
|
-
const fmt = (env) => {
|
|
3214
|
-
if (env === "ssr") return entries.source.ssr === "user" ? `${node_path.default.relative(root, entries.ssr)}(用户覆盖)` : "<engine 默认>";
|
|
3215
|
-
return entries.source[env] === "user" ? `<engine wrapper> + ${ENTRY_CONVENTION[env]}(FaaS hooks 已挂载)` : "<engine 默认(无 hooks)>";
|
|
3216
|
-
};
|
|
3217
|
-
logger.info(`🧭 ISR entries:`);
|
|
3218
|
-
logger.info(` client = ${fmt("client")}`);
|
|
3219
|
-
logger.info(` server = ${fmt("rsc")}`);
|
|
3220
|
-
logger.info(` ssr = ${fmt("ssr")}`);
|
|
3221
|
-
const devCssLifecycle = createDevCssLifecyclePluginPhases(resolveEngineDefaultsDir());
|
|
3222
|
-
const plugins = [
|
|
3223
|
-
createEngineDefaultEntriesPlugin(root, userConfig),
|
|
3224
|
-
createAppAliasPlugin(root),
|
|
3225
|
-
createAutomaticImagePlugin(root, userConfig),
|
|
3226
|
-
require_createISRApp.createDevAssetRequestMiddleware(root),
|
|
3227
|
-
...devCssLifecycle.beforeRsc,
|
|
3228
|
-
createBrowserShimPlugin()
|
|
3229
|
-
];
|
|
3230
|
-
if (isrCacheOptions?.enabled !== false) plugins.push(require_createISRApp.createIsrCacheMiddleware(userConfig, {
|
|
3231
|
-
max: isrCacheOptions?.max,
|
|
3232
|
-
defaultTtlSeconds: isrCacheOptions?.defaultTtlSeconds
|
|
3233
|
-
}));
|
|
3234
|
-
plugins.push((0, _vitejs_plugin_rsc.default)({
|
|
3235
|
-
...rscOptions,
|
|
3236
|
-
entries: {
|
|
3237
|
-
client: VIRTUAL_ENTRY_IDS.client,
|
|
3238
|
-
rsc: VIRTUAL_ENTRY_IDS.rsc,
|
|
3239
|
-
ssr: entries.ssr
|
|
3240
|
-
}
|
|
3241
|
-
}));
|
|
3242
|
-
plugins.push(...devCssLifecycle.afterRsc);
|
|
3243
|
-
plugins.push(createSsgPostBuildPlugin(userConfig));
|
|
3244
|
-
return plugins;
|
|
3245
|
-
}
|
|
3246
|
-
//#endregion
|
|
3247
|
-
exports.CacheCleanup = require_createISRApp.CacheCleanup;
|
|
3248
|
-
exports.CacheManager = CacheManager;
|
|
3249
|
-
exports.DEFAULT_SCAN_CONFIG = require_createISRApp.DEFAULT_SCAN_CONFIG;
|
|
3250
|
-
exports.DEFAULT_SEO_CONFIG = require_createISRApp.DEFAULT_SEO_CONFIG;
|
|
3251
|
-
exports.FallbackChain = require_createISRApp.FallbackChain;
|
|
3252
|
-
exports.ISREngine = require_createISRApp.ISREngine;
|
|
3253
|
-
exports.InternalStrategies = require_createISRApp.InternalStrategies;
|
|
3254
|
-
exports.LEGACY_SERVER_ACTION_ENDPOINT = require_rsc.LEGACY_SERVER_ACTION_ENDPOINT;
|
|
3255
|
-
exports.Logger = require_Logger.Logger;
|
|
3256
|
-
exports.ManifestLoader = ManifestLoader;
|
|
3257
|
-
exports.MetricsCollector = MetricsCollector;
|
|
3258
|
-
exports.RedisCacheAdapter = require_createISRApp.RedisCacheAdapter;
|
|
3259
|
-
exports.RedisInvalidationBus = require_createISRApp.RedisInvalidationBus;
|
|
3260
|
-
exports.RenderModes = require_createISRApp.RenderModes;
|
|
3261
|
-
exports.RevalidationError = require_abVariantContext.RevalidationError;
|
|
3262
|
-
exports.RouteManager = RouteManager;
|
|
3263
|
-
exports.SEOEngine = require_createISRApp.SEOEngine;
|
|
3264
|
-
exports.SERVER_ACTION_ENDPOINT = require_rsc.SERVER_ACTION_ENDPOINT;
|
|
3265
|
-
exports.ServerActionUtils = require_rsc.ServerActionUtils;
|
|
3266
|
-
exports.applyRuntimeToServerHooks = require_defineSiteHooks.applyRuntimeToServerHooks;
|
|
3267
|
-
exports.cacheTag = require_abVariantContext.cacheTag;
|
|
3268
|
-
exports.collectTags = require_abVariantContext.collectTags;
|
|
3269
|
-
exports.createABVariantMiddleware = require_createISRApp.createABVariantMiddleware;
|
|
3270
|
-
exports.createAdminIntlLoader = require_defineSiteHooks.createAdminIntlLoader;
|
|
3271
|
-
exports.createAdminSeoLoader = require_defineSiteHooks.createAdminSeoLoader;
|
|
3272
|
-
exports.createCachedFetcher = require_defineSiteHooks.createCachedFetcher;
|
|
3273
|
-
exports.createCoherentCacheStore = require_createISRApp.createCoherentCacheStore;
|
|
3274
|
-
exports.createFontPlugin = createFontPlugin;
|
|
3275
|
-
exports.createHybridCacheStore = require_createISRApp.createHybridCacheStore;
|
|
3276
|
-
exports.createISRApp = require_createISRApp.createISRApp;
|
|
3277
|
-
exports.createImageMiddleware = require_createImagePlugin.createImageMiddleware;
|
|
3278
|
-
exports.createImagePlugin = require_createImagePlugin.createImagePlugin;
|
|
3279
|
-
exports.createIsrCacheHandler = require_createISRApp.createIsrCacheHandler;
|
|
3280
|
-
exports.createIsrCacheMiddleware = require_createISRApp.createIsrCacheMiddleware;
|
|
3281
|
-
exports.createIsrPlugin = createIsrPlugin;
|
|
3282
|
-
exports.createMemoryCacheStore = require_createISRApp.createMemoryCacheStore;
|
|
3283
|
-
exports.createPrometheusMetricsMiddleware = require_createISRApp.createPrometheusMetricsMiddleware;
|
|
3284
|
-
exports.createSEOEngine = require_createISRApp.createSEOEngine;
|
|
3285
|
-
exports.createServerAction = require_rsc.createServerAction;
|
|
3286
|
-
exports.defineAdminSiteHooks = require_defineSiteHooks.defineAdminSiteHooks;
|
|
3287
|
-
exports.defineIsrConfig = require_config_defineConfig.defineIsrConfig;
|
|
3288
|
-
exports.defineRuntimeConfig = require_config_defineConfig.defineRuntimeConfig;
|
|
3289
|
-
exports.defineSiteHooks = require_defineSiteHooks.defineSiteHooks;
|
|
3290
|
-
exports.getCookieHeader = require_i18n.getCookieHeader;
|
|
3291
|
-
exports.getEnv = require_createISRApp.getEnv;
|
|
3292
|
-
exports.getFallbackChain = require_createISRApp.getFallbackChain;
|
|
3293
|
-
exports.getI18n = require_rsc.getI18n;
|
|
3294
|
-
exports.getI18nLocale = require_rsc.getI18nLocale;
|
|
3295
|
-
exports.getRequestContext = require_abVariantContext.getRequestContext;
|
|
3296
|
-
exports.getRouteFallbackChain = require_createISRApp.getRouteFallbackChain;
|
|
3297
|
-
exports.getVariant = require_abVariantContext.getVariant;
|
|
3298
|
-
exports.injectSeoMeta = injectSeoMeta;
|
|
3299
|
-
exports.installBrowserObservability = installBrowserObservability;
|
|
3300
|
-
exports.invalidatorFailuresTotal = require_createISRApp.invalidatorFailuresTotal;
|
|
3301
|
-
exports.invalidatorRunsTotal = require_createISRApp.invalidatorRunsTotal;
|
|
3302
|
-
exports.isCodeFile = require_createISRApp.isCodeFile;
|
|
3303
|
-
exports.isDev = require_createISRApp.isDev;
|
|
3304
|
-
exports.isProd = require_createISRApp.isProd;
|
|
3305
|
-
exports.isTestFile = require_createISRApp.isTestFile;
|
|
3306
|
-
exports.loadConfig = require_createISRApp.loadConfig;
|
|
3307
|
-
exports.matchRoutePattern = require_createISRApp.matchRoutePattern;
|
|
3308
|
-
exports.mergeSEOConfig = require_createISRApp.mergeSEOConfig;
|
|
3309
|
-
exports.parseComponentFromFile = require_createISRApp.parseComponentFromFile;
|
|
3310
|
-
exports.parseComponents = require_createISRApp.parseComponents;
|
|
3311
|
-
exports.parseCookieHeader = require_i18n.parseCookieHeader;
|
|
3312
|
-
exports.parseRouteFromFile = require_createISRApp.parseRouteFromFile;
|
|
3313
|
-
exports.parseRoutes = require_createISRApp.parseRoutes;
|
|
3314
|
-
exports.promRegistry = require_createISRApp.promRegistry;
|
|
3315
|
-
exports.readCookie = require_i18n.readCookie;
|
|
3316
|
-
exports.readDirRecursive = require_createISRApp.readDirRecursive;
|
|
3317
|
-
exports.recordHttpRequest = require_createISRApp.recordHttpRequest;
|
|
3318
|
-
exports.registerInvalidator = require_abVariantContext.registerInvalidator;
|
|
3319
|
-
exports.renderPageSeoMeta = renderPageSeoMeta;
|
|
3320
|
-
exports.requestContext = require_abVariantContext.requestContext;
|
|
3321
|
-
exports.resolveRenderMode = require_createISRApp.resolveRenderMode;
|
|
3322
|
-
exports.revalidatePath = require_abVariantContext.revalidatePath;
|
|
3323
|
-
exports.revalidateTag = require_abVariantContext.revalidateTag;
|
|
3324
|
-
exports.runWithTagStore = require_abVariantContext.runWithTagStore;
|
|
3325
|
-
exports.scanComponents = require_createISRApp.scanComponents;
|
|
3326
|
-
exports.scanProject = require_createISRApp.scanProject;
|
|
3327
|
-
exports.scanRoutes = require_createISRApp.scanRoutes;
|
|
3328
|
-
exports.serverActionsRegistry = require_rsc.serverActionsRegistry;
|
|
3329
|
-
exports.shutdownServer = require_createISRApp.shutdownServer;
|
|
3330
|
-
exports.startAppServer = require_createISRApp.startAppServer;
|
|
3331
|
-
|
|
3332
|
-
//# sourceMappingURL=isr-engine.cjs.map
|