isr-engine 3.1.3 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{abVariantContext-Ud3aZ1yk.js → abVariantContext-CGBlCt0q.js} +9 -26
- package/dist/abVariantContext-CGBlCt0q.js.map +1 -0
- package/dist/adapters/observability/index.js +4 -8
- package/dist/adapters/observability/index.js.map +1 -1
- package/dist/adapters/runtime/index.js +4 -8
- package/dist/adapters/runtime/index.js.map +1 -1
- package/dist/cli/cli.js +12 -14
- package/dist/cli/cli.js.map +1 -1
- package/dist/config/defineConfig.js +1 -2
- package/dist/{createCacheInspectorMiddleware-GgzKVkq2.js → createCacheInspectorMiddleware-BjwSKfyf.js} +2 -3
- package/dist/{createCacheInspectorMiddleware-GgzKVkq2.js.map → createCacheInspectorMiddleware-BjwSKfyf.js.map} +1 -1
- package/dist/{createISRApp-DPD3Er4F.js → createISRApp-CbDPv6fY.js} +2276 -1798
- package/dist/createISRApp-CbDPv6fY.js.map +1 -0
- package/dist/defaults/auto-observability.js +1 -2
- package/dist/defaults/runtime/defineSiteHooks.js +2 -2
- package/dist/{defineSiteHooks-bHtGQftZ.js → defineSiteHooks-DUEds_hB.js} +4 -6
- package/dist/{defineSiteHooks-bHtGQftZ.js.map → defineSiteHooks-DUEds_hB.js.map} +1 -1
- package/dist/{error500-template-DhaZzLOB.js → error500-template-CFdKp8YG.js} +2 -3
- package/dist/{error500-template-DhaZzLOB.js.map → error500-template-CFdKp8YG.js.map} +1 -1
- package/dist/{i18n-CnXYAgQE.js → i18n-CJ0leKhc.js} +5 -14
- package/dist/{i18n-CnXYAgQE.js.map → i18n-CJ0leKhc.js.map} +1 -1
- package/dist/image/index.js +1 -2
- package/dist/image/index.js.map +1 -1
- package/dist/isr-engine.js +43 -55
- package/dist/isr-engine.js.map +1 -1
- package/dist/plugin/createDevCssHandoffPlugin.d.ts.map +1 -1
- package/dist/plugin/googleFontAssets.d.ts.map +1 -1
- package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
- package/dist/rsc/browser.js +1 -2
- package/dist/rsc/index.js +2 -2
- package/dist/{rsc-BJzB9s8U.js → rsc-DWwcqD4W.js} +6 -10
- package/dist/rsc-DWwcqD4W.js.map +1 -0
- package/dist/runtime/LocaleContext.d.ts +1 -1
- package/dist/runtime/LocaleContext.d.ts.map +1 -1
- package/dist/runtime/boundary.d.ts +2 -2
- package/dist/runtime/boundary.d.ts.map +1 -1
- package/dist/security/staticCspManifest.d.ts.map +1 -1
- package/dist/server/middleware.d.ts.map +1 -1
- package/dist/server/productionRuntime.d.ts.map +1 -1
- package/dist/server/requestLimits.d.ts.map +1 -1
- package/package.json +9 -9
- package/dist/Logger-bg-doGwZ.js +0 -174
- package/dist/Logger-bg-doGwZ.js.map +0 -1
- package/dist/abVariantContext-Ud3aZ1yk.js.map +0 -1
- package/dist/createISRApp-DPD3Er4F.js.map +0 -1
- package/dist/createImagePlugin-QNvY9vPB.js +0 -462
- package/dist/createImagePlugin-QNvY9vPB.js.map +0 -1
- package/dist/rolldown-runtime-D7D4PA-g.js +0 -13
- package/dist/rsc-BJzB9s8U.js.map +0 -1
|
@@ -1,20 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { c as readCookie, i as resolveI18nConfig, n as negotiateLocale, s as parseCookieHeader } from "./i18n-CnXYAgQE.js";
|
|
5
|
-
import fs, { createReadStream } from "node:fs";
|
|
1
|
+
import { C as getTraceId, S as getRequestId, T as requestContext, _ as escapeSupplementalLogControls, a as isUncacheable, f as setRevalidationMetricRecorder, g as encodeSpinnerMessage, h as encodeLogField, l as registerInvalidator, m as setOriginLogger, r as collectTags, s as runWithTagStore, v as snapshotLogArgument, x as getRequestContext } from "./abVariantContext-CGBlCt0q.js";
|
|
2
|
+
import { o as parseCookieHeader, r as resolveI18nConfig, s as readCookie, t as negotiateLocale } from "./i18n-CJ0leKhc.js";
|
|
3
|
+
import fs, { createReadStream, promises } from "node:fs";
|
|
6
4
|
import path from "node:path";
|
|
7
5
|
import express from "express";
|
|
8
6
|
import { ipKeyGenerator, rateLimit } from "express-rate-limit";
|
|
9
7
|
import ipaddr from "ipaddr.js";
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import * as
|
|
13
|
-
import
|
|
8
|
+
import chalk from "chalk";
|
|
9
|
+
import ora from "ora";
|
|
10
|
+
import path$1, * as path$2 from "path";
|
|
11
|
+
import pino from "pino";
|
|
12
|
+
import fs$1, * as fs$4 from "fs";
|
|
14
13
|
import fs$2 from "fs/promises";
|
|
15
14
|
import ts from "typescript";
|
|
16
|
-
import net from "node:net";
|
|
17
|
-
import { createServer, loadConfigFromFile, mergeConfig } from "vite";
|
|
15
|
+
import net, { isIP } from "node:net";
|
|
16
|
+
import { createServer, isFileLoadingAllowed, loadConfigFromFile, mergeConfig, normalizePath } from "vite";
|
|
18
17
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
19
18
|
import compression from "compression";
|
|
20
19
|
import helmet from "helmet";
|
|
@@ -22,17 +21,18 @@ import fs$3 from "node:fs/promises";
|
|
|
22
21
|
import { pathToFileURL } from "node:url";
|
|
23
22
|
import { Readable } from "node:stream";
|
|
24
23
|
import os from "node:os";
|
|
25
|
-
import http from "node:http";
|
|
24
|
+
import http, { request } from "node:http";
|
|
26
25
|
import { LRUCache } from "lru-cache";
|
|
27
26
|
import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from "prom-client";
|
|
28
27
|
import { pathToFileURL as pathToFileURL$1 } from "url";
|
|
29
28
|
import { createHash as createHash$1, randomUUID as randomUUID$1 } from "crypto";
|
|
30
29
|
import * as esbuild from "esbuild";
|
|
30
|
+
import { lookup } from "node:dns/promises";
|
|
31
|
+
import { request as request$1 } from "node:https";
|
|
32
|
+
import { SitemapStream, streamToPromise } from "sitemap";
|
|
31
33
|
import { parse } from "parse5";
|
|
32
34
|
import { createServer as createServer$1 } from "http";
|
|
33
|
-
|
|
34
|
-
//#region src/config/resolveImageOptions.ts
|
|
35
|
-
var resolveImageOptions_exports = /* @__PURE__ */ __exportAll({ resolveImageOptions: () => resolveImageOptions });
|
|
35
|
+
// src/config/resolveImageOptions.ts
|
|
36
36
|
/** Shared image policy for the automatic development and production endpoints. */
|
|
37
37
|
function resolveImageOptions(images) {
|
|
38
38
|
const invalid = () => /* @__PURE__ */ new Error("runtime.images must contain only remoteAllowlist: an array of exact host[:port] entries");
|
|
@@ -57,8 +57,7 @@ function resolveImageOptions(images) {
|
|
|
57
57
|
});
|
|
58
58
|
return { remoteAllowlist: [...new Set(hosts)] };
|
|
59
59
|
}
|
|
60
|
-
|
|
61
|
-
//#region src/utils/htmlPathname.ts
|
|
60
|
+
// src/utils/htmlPathname.ts
|
|
62
61
|
/** Shared logical identity for HTML dispatch, aliases and build-time route validation. */
|
|
63
62
|
function decodeHtmlPathname(raw) {
|
|
64
63
|
const pathname = decodeURIComponent(raw);
|
|
@@ -100,8 +99,7 @@ function assertDistinctHtmlRouteIdentities(routes, options = {}) {
|
|
|
100
99
|
owners.set(identity, route);
|
|
101
100
|
}
|
|
102
101
|
}
|
|
103
|
-
|
|
104
|
-
//#region src/utils/cacheDuration.ts
|
|
102
|
+
// src/utils/cacheDuration.ts
|
|
105
103
|
/** Cache deadlines must remain finite, positive (or explicitly zero for SWR) timestamps. */
|
|
106
104
|
function assertCacheDuration(seconds, label, allowZero = false) {
|
|
107
105
|
if (typeof seconds !== "number" || !Number.isFinite(seconds) || (allowZero ? seconds < 0 : seconds <= 0) || seconds * 1e3 > Number.MAX_SAFE_INTEGER) throw new RangeError(`${label} must be finite ${allowZero ? "non-negative" : "positive"} seconds within the safe cache window`);
|
|
@@ -119,8 +117,7 @@ function resolveCacheDurations(defaultTtl, overrides = {}, label = "route") {
|
|
|
119
117
|
swrSeconds: swr
|
|
120
118
|
};
|
|
121
119
|
}
|
|
122
|
-
|
|
123
|
-
//#region src/server/requestLimits.ts
|
|
120
|
+
// src/server/requestLimits.ts
|
|
124
121
|
/** Per-process admission budgets for engine-owned work, not page-cache hits or application APIs. */
|
|
125
122
|
var DEFAULT_REQUEST_LIMITS = {
|
|
126
123
|
ops: {
|
|
@@ -152,7 +149,8 @@ function resolveRequestLimitPolicy(category, input) {
|
|
|
152
149
|
"globalMaxRequests",
|
|
153
150
|
"maxClients"
|
|
154
151
|
]) {
|
|
155
|
-
const
|
|
152
|
+
const configured = input?.[field];
|
|
153
|
+
const value = configured === void 0 ? defaults[field] : configured;
|
|
156
154
|
if (!Number.isSafeInteger(value) || value <= 0 || value >= Number.MAX_SAFE_INTEGER) throw new TypeError(`server.requestLimits.${category}.${field} must be a positive safe integer`);
|
|
157
155
|
result[field] = value;
|
|
158
156
|
}
|
|
@@ -300,8 +298,7 @@ function admitRequest(limiter, req, res) {
|
|
|
300
298
|
}
|
|
301
299
|
});
|
|
302
300
|
}
|
|
303
|
-
|
|
304
|
-
//#region src/config/normalizeEngineConfig.ts
|
|
301
|
+
// src/config/normalizeEngineConfig.ts
|
|
305
302
|
/**
|
|
306
303
|
* Engine-owned config normalization.
|
|
307
304
|
*
|
|
@@ -374,8 +371,172 @@ function validateRoutes(routes, defaultTtl) {
|
|
|
374
371
|
function requireOwnProperties(value, keys, label) {
|
|
375
372
|
for (const key of keys) if (!Object.prototype.hasOwnProperty.call(value, key)) throw new Error(`ssr.config.ts 必须显式声明 ${label}.${key}`);
|
|
376
373
|
}
|
|
377
|
-
|
|
378
|
-
|
|
374
|
+
// src/logger/Logger.ts
|
|
375
|
+
var LogLevel = /* @__PURE__ */ function(LogLevel) {
|
|
376
|
+
LogLevel["VERBOSE"] = "verbose";
|
|
377
|
+
LogLevel["DEBUG"] = "debug";
|
|
378
|
+
LogLevel["INFO"] = "info";
|
|
379
|
+
LogLevel["WARN"] = "warn";
|
|
380
|
+
LogLevel["ERROR"] = "error";
|
|
381
|
+
LogLevel["SUCCESS"] = "success";
|
|
382
|
+
return LogLevel;
|
|
383
|
+
}({});
|
|
384
|
+
var Logger = class Logger {
|
|
385
|
+
static instance;
|
|
386
|
+
verboseMode = false;
|
|
387
|
+
logFile = null;
|
|
388
|
+
fileLogger = null;
|
|
389
|
+
fileDestination = null;
|
|
390
|
+
spinner = null;
|
|
391
|
+
static getInstance(options = {}) {
|
|
392
|
+
if (!Logger.instance) {
|
|
393
|
+
Logger.instance = new Logger();
|
|
394
|
+
setOriginLogger(Logger.instance);
|
|
395
|
+
}
|
|
396
|
+
if (options.verbose !== void 0) Logger.instance.verboseMode = options.verbose;
|
|
397
|
+
if (options.logFile !== void 0) Logger.instance.configureFile(options.logFile);
|
|
398
|
+
return Logger.instance;
|
|
399
|
+
}
|
|
400
|
+
/** File destinations are operator configuration; request data is only a record field. */
|
|
401
|
+
configureFile(logFile) {
|
|
402
|
+
if (typeof logFile !== "string" || /[\u0000-\u001f\u007f]/.test(logFile)) throw new TypeError("logFile must be a path without control characters");
|
|
403
|
+
const resolved = logFile ? path$1.resolve(logFile) : null;
|
|
404
|
+
if (resolved === this.logFile) return;
|
|
405
|
+
this.closeFileDestination();
|
|
406
|
+
if (!resolved) return;
|
|
407
|
+
try {
|
|
408
|
+
const destination = pino.destination({
|
|
409
|
+
dest: resolved,
|
|
410
|
+
mkdir: true,
|
|
411
|
+
sync: true
|
|
412
|
+
});
|
|
413
|
+
destination.on("error", (error) => {
|
|
414
|
+
if (this.fileDestination === destination) this.closeFileDestination();
|
|
415
|
+
this.reportFileError(error);
|
|
416
|
+
});
|
|
417
|
+
destination.once("close", () => {
|
|
418
|
+
if (this.fileDestination !== destination) return;
|
|
419
|
+
this.fileLogger = null;
|
|
420
|
+
this.fileDestination = null;
|
|
421
|
+
this.logFile = null;
|
|
422
|
+
});
|
|
423
|
+
this.fileDestination = destination;
|
|
424
|
+
this.fileLogger = pino({
|
|
425
|
+
base: null,
|
|
426
|
+
timestamp: false,
|
|
427
|
+
level: "trace",
|
|
428
|
+
hooks: { streamWrite: escapeSupplementalLogControls }
|
|
429
|
+
}, destination);
|
|
430
|
+
this.logFile = resolved;
|
|
431
|
+
} catch (error) {
|
|
432
|
+
this.closeFileDestination();
|
|
433
|
+
this.reportFileError(error);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
closeFileDestination() {
|
|
437
|
+
const destination = this.fileDestination;
|
|
438
|
+
this.fileLogger = null;
|
|
439
|
+
this.fileDestination = null;
|
|
440
|
+
this.logFile = null;
|
|
441
|
+
if (!destination) return;
|
|
442
|
+
try {
|
|
443
|
+
destination.flushSync();
|
|
444
|
+
destination.end();
|
|
445
|
+
} catch (error) {
|
|
446
|
+
destination.destroy();
|
|
447
|
+
this.reportFileError(error);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
reportFileError(error) {
|
|
451
|
+
try {
|
|
452
|
+
process.stderr.write(`Failed to write to log file: ${encodeLogField(snapshotLogArgument(error))}\n`);
|
|
453
|
+
} catch {}
|
|
454
|
+
}
|
|
455
|
+
getLevelColor(level) {
|
|
456
|
+
switch (level) {
|
|
457
|
+
case "error": return chalk.red.bold;
|
|
458
|
+
case "warn": return chalk.yellow.bold;
|
|
459
|
+
case "success": return chalk.green.bold;
|
|
460
|
+
case "info": return chalk.blue.bold;
|
|
461
|
+
case "debug": return chalk.magenta;
|
|
462
|
+
case "verbose": return chalk.gray;
|
|
463
|
+
default: return chalk.white;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
log(level, ...args) {
|
|
467
|
+
if (!Object.values(LogLevel).includes(level)) throw new TypeError("Unknown log level");
|
|
468
|
+
if (level === "verbose" && !this.verboseMode) return;
|
|
469
|
+
if (level === "debug" && !this.verboseMode) return;
|
|
470
|
+
if (this.spinner?.isSpinning) this.spinner.stop();
|
|
471
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
472
|
+
const traceId = snapshotLogArgument(getTraceId());
|
|
473
|
+
const requestId = snapshotLogArgument(getRequestId());
|
|
474
|
+
const values = args.map(snapshotLogArgument);
|
|
475
|
+
const errors = [];
|
|
476
|
+
const message = values.map((value, index) => {
|
|
477
|
+
if (args[index] instanceof Error) {
|
|
478
|
+
errors.push({
|
|
479
|
+
argument: index,
|
|
480
|
+
error: value
|
|
481
|
+
});
|
|
482
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value.stack || value.message || JSON.stringify(value, null, 2);
|
|
483
|
+
}
|
|
484
|
+
return typeof value === "string" ? value : JSON.stringify(value, null, 2);
|
|
485
|
+
}).join(" ");
|
|
486
|
+
const levelTag = this.getLevelColor(level)(`[${level.toUpperCase()}]`);
|
|
487
|
+
const traceTag = chalk.cyan(`traceId=${encodeLogField(traceId)}`);
|
|
488
|
+
const requestTag = requestId === "unknown" ? "" : chalk.blue(`requestId=${encodeLogField(requestId)}`);
|
|
489
|
+
console.log(`${chalk.gray(timestamp)} ${levelTag} ${traceTag} ${requestTag} message=${encodeLogField(message)}`);
|
|
490
|
+
if (this.fileLogger) {
|
|
491
|
+
const transportLevel = level === "verbose" ? "trace" : level === "success" ? "info" : level;
|
|
492
|
+
try {
|
|
493
|
+
this.fileLogger[transportLevel]({
|
|
494
|
+
timestamp,
|
|
495
|
+
severity: level,
|
|
496
|
+
traceId,
|
|
497
|
+
requestId,
|
|
498
|
+
args: values,
|
|
499
|
+
errors
|
|
500
|
+
});
|
|
501
|
+
} catch (error) {
|
|
502
|
+
this.closeFileDestination();
|
|
503
|
+
this.reportFileError(error);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (this.spinner && !this.spinner.isSpinning) this.spinner.start();
|
|
507
|
+
}
|
|
508
|
+
error(...args) {
|
|
509
|
+
this.log("error", ...args);
|
|
510
|
+
}
|
|
511
|
+
warn(...args) {
|
|
512
|
+
this.log("warn", ...args);
|
|
513
|
+
}
|
|
514
|
+
info(...args) {
|
|
515
|
+
this.log("info", ...args);
|
|
516
|
+
}
|
|
517
|
+
success(...args) {
|
|
518
|
+
this.log("success", ...args);
|
|
519
|
+
}
|
|
520
|
+
debug(...args) {
|
|
521
|
+
this.log("debug", ...args);
|
|
522
|
+
}
|
|
523
|
+
verbose(...args) {
|
|
524
|
+
this.log("verbose", ...args);
|
|
525
|
+
}
|
|
526
|
+
spin(message) {
|
|
527
|
+
if (this.spinner) this.spinner.succeed();
|
|
528
|
+
this.spinner = ora(encodeSpinnerMessage(message)).start();
|
|
529
|
+
return this.spinner;
|
|
530
|
+
}
|
|
531
|
+
stopSpinner(message, success = true) {
|
|
532
|
+
if (this.spinner) {
|
|
533
|
+
if (success) this.spinner.succeed(message === void 0 ? void 0 : encodeSpinnerMessage(message));
|
|
534
|
+
else this.spinner.fail(message === void 0 ? void 0 : encodeSpinnerMessage(message));
|
|
535
|
+
this.spinner = null;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
// src/utils/CacheCleanup.ts
|
|
379
540
|
var logger$9 = Logger.getInstance();
|
|
380
541
|
/**
|
|
381
542
|
* 缓存清理工具类
|
|
@@ -436,8 +597,7 @@ var CacheCleanup = class {
|
|
|
436
597
|
return path$2.resolve(process.cwd(), this.SSG_CACHE_DIR);
|
|
437
598
|
}
|
|
438
599
|
};
|
|
439
|
-
|
|
440
|
-
//#region src/config/getEnv.ts
|
|
600
|
+
// src/config/getEnv.ts
|
|
441
601
|
function getEnv(key, defaultValue) {
|
|
442
602
|
const value = process.env[key];
|
|
443
603
|
if (value === void 0) return defaultValue;
|
|
@@ -447,12 +607,10 @@ function getEnv(key, defaultValue) {
|
|
|
447
607
|
}
|
|
448
608
|
return value;
|
|
449
609
|
}
|
|
450
|
-
|
|
451
|
-
//#region src/config/getStatus.ts
|
|
610
|
+
// src/config/getStatus.ts
|
|
452
611
|
var isDev = () => getEnv("NODE_ENV") !== "production";
|
|
453
612
|
var isProd = () => getEnv("NODE_ENV") === "production";
|
|
454
|
-
|
|
455
|
-
//#region src/discovery/types.ts
|
|
613
|
+
// src/discovery/types.ts
|
|
456
614
|
/**
|
|
457
615
|
* 支持的文件扩展名
|
|
458
616
|
*/
|
|
@@ -462,8 +620,7 @@ var SUPPORTED_EXTENSIONS = [
|
|
|
462
620
|
".ts",
|
|
463
621
|
".js"
|
|
464
622
|
];
|
|
465
|
-
|
|
466
|
-
//#region src/discovery/fileSystem.ts
|
|
623
|
+
// src/discovery/fileSystem.ts
|
|
467
624
|
/**
|
|
468
625
|
* 文件系统工具函数
|
|
469
626
|
* 提供文件遍历、读取等基础能力
|
|
@@ -525,8 +682,7 @@ function isCodeFile(filePath) {
|
|
|
525
682
|
function isTestFile(filePath) {
|
|
526
683
|
return TEST_FILE_PATTERN.test(filePath);
|
|
527
684
|
}
|
|
528
|
-
|
|
529
|
-
//#region src/discovery/routeDiscovery.ts
|
|
685
|
+
// src/discovery/routeDiscovery.ts
|
|
530
686
|
/**
|
|
531
687
|
* 路由发现器
|
|
532
688
|
*
|
|
@@ -696,8 +852,7 @@ function parseRoutes(files, config) {
|
|
|
696
852
|
});
|
|
697
853
|
return routes;
|
|
698
854
|
}
|
|
699
|
-
|
|
700
|
-
//#region src/discovery/directiveParser.ts
|
|
855
|
+
// src/discovery/directiveParser.ts
|
|
701
856
|
/**
|
|
702
857
|
* AST 指令解析器
|
|
703
858
|
* 使用 TypeScript Compiler API 解析 'use client' 和 'use server' 指令
|
|
@@ -918,8 +1073,7 @@ function hasServerDirective(content) {
|
|
|
918
1073
|
const result = parseDirective(content);
|
|
919
1074
|
return result.directive === "use server" && result.isValidPosition;
|
|
920
1075
|
}
|
|
921
|
-
|
|
922
|
-
//#region src/discovery/exportParser.ts
|
|
1076
|
+
// src/discovery/exportParser.ts
|
|
923
1077
|
/**
|
|
924
1078
|
* AST 导出解析器
|
|
925
1079
|
* 使用 TypeScript Compiler API 解析模块导出
|
|
@@ -1038,8 +1192,7 @@ function getExportNames(content) {
|
|
|
1038
1192
|
for (const exp of result.exports) if (!exp.isType && exp.name !== "*") names.push(exp.name);
|
|
1039
1193
|
return [...new Set(names)];
|
|
1040
1194
|
}
|
|
1041
|
-
|
|
1042
|
-
//#region src/discovery/componentDiscovery.ts
|
|
1195
|
+
// src/discovery/componentDiscovery.ts
|
|
1043
1196
|
/**
|
|
1044
1197
|
* 组件发现器
|
|
1045
1198
|
*
|
|
@@ -1089,8 +1242,7 @@ function parseComponentFromFile(fileInfo) {
|
|
|
1089
1242
|
function parseComponents(files) {
|
|
1090
1243
|
return files.map(parseComponentFromFile);
|
|
1091
1244
|
}
|
|
1092
|
-
|
|
1093
|
-
//#region src/discovery/scan.ts
|
|
1245
|
+
// src/discovery/scan.ts
|
|
1094
1246
|
/**
|
|
1095
1247
|
* 目录扫描器 —— 轻量文件发现(用于 engine 启动日志 / sitemap 路由枚举)
|
|
1096
1248
|
*
|
|
@@ -1186,8 +1338,7 @@ async function scanRoutes(projectRoot, config = {}) {
|
|
|
1186
1338
|
async function scanComponents(projectRoot, componentDirs = ["src/components"]) {
|
|
1187
1339
|
return parseComponents(await collectComponentsWithContent(projectRoot, componentDirs, true, 50));
|
|
1188
1340
|
}
|
|
1189
|
-
|
|
1190
|
-
//#region src/server/viteDevServer.ts
|
|
1341
|
+
// src/server/viteDevServer.ts
|
|
1191
1342
|
/**
|
|
1192
1343
|
* Vite 开发服务器管理(plugin-rsc 模式)
|
|
1193
1344
|
*
|
|
@@ -1223,10 +1374,11 @@ async function resolveHmrPort(preferredPort, host) {
|
|
|
1223
1374
|
async function createViteDevServer() {
|
|
1224
1375
|
const logger = Logger.getInstance();
|
|
1225
1376
|
if (viteServer) return viteServer;
|
|
1377
|
+
const projectRoot = process.cwd();
|
|
1226
1378
|
const loadResult = await loadConfigFromFile({
|
|
1227
1379
|
command: "serve",
|
|
1228
1380
|
mode: "development"
|
|
1229
|
-
}, void 0,
|
|
1381
|
+
}, void 0, projectRoot);
|
|
1230
1382
|
const userHmr = loadResult?.config?.server?.hmr;
|
|
1231
1383
|
const hmrDisabled = userHmr === false;
|
|
1232
1384
|
const userHmrOptions = typeof userHmr === "object" ? userHmr : {};
|
|
@@ -1251,13 +1403,14 @@ async function createViteDevServer() {
|
|
|
1251
1403
|
const userSsrNoExternal = userConfig.ssr?.noExternal;
|
|
1252
1404
|
const ssrNoExternal = Array.isArray(userSsrNoExternal) ? [...userSsrNoExternal] : userSsrNoExternal ? [userSsrNoExternal] : [];
|
|
1253
1405
|
if (!ssrNoExternal.includes("isr-engine")) ssrNoExternal.push("isr-engine");
|
|
1254
|
-
|
|
1406
|
+
const finalConfig = mergeConfig(userConfig, {
|
|
1255
1407
|
...engineOverrides,
|
|
1256
1408
|
ssr: {
|
|
1257
1409
|
...userConfig.ssr,
|
|
1258
1410
|
noExternal: ssrNoExternal
|
|
1259
1411
|
}
|
|
1260
|
-
})
|
|
1412
|
+
});
|
|
1413
|
+
viteServer = await createServer(finalConfig);
|
|
1261
1414
|
} else {
|
|
1262
1415
|
logger.warn("未找到 vite.config.ts —— 消费者必须在项目根下提供配置,否则 RSC 不工作");
|
|
1263
1416
|
viteServer = await createServer({
|
|
@@ -1278,24 +1431,11 @@ async function closeViteDevServer() {
|
|
|
1278
1431
|
viteServer = null;
|
|
1279
1432
|
}
|
|
1280
1433
|
}
|
|
1281
|
-
|
|
1282
|
-
//#region src/server/middleware.ts
|
|
1434
|
+
// src/server/middleware.ts
|
|
1283
1435
|
/**
|
|
1284
1436
|
* 中间件配置
|
|
1285
1437
|
* 提供通用中间件和开发/生产环境特定中间件
|
|
1286
1438
|
*/
|
|
1287
|
-
var middleware_exports = /* @__PURE__ */ __exportAll({
|
|
1288
|
-
CSP_NONCE_HEADER: () => CSP_NONCE_HEADER,
|
|
1289
|
-
CSP_NONCE_LOCAL: () => CSP_NONCE_LOCAL,
|
|
1290
|
-
applyBaseMiddlewaresWithOptions: () => applyBaseMiddlewaresWithOptions,
|
|
1291
|
-
createCompressionMiddleware: () => createCompressionMiddleware,
|
|
1292
|
-
createCspNonceMiddleware: () => createCspNonceMiddleware,
|
|
1293
|
-
createJsonMiddleware: () => createJsonMiddleware,
|
|
1294
|
-
createSecurityMiddleware: () => createSecurityMiddleware,
|
|
1295
|
-
createStaticMiddleware: () => createStaticMiddleware,
|
|
1296
|
-
createUrlEncodedMiddleware: () => createUrlEncodedMiddleware,
|
|
1297
|
-
mountViteOrStatic: () => mountViteOrStatic
|
|
1298
|
-
});
|
|
1299
1439
|
/** 用于在 res.locals 上挂 CSP nonce 的 key (Lighthouse csp-xss 审计需要) */
|
|
1300
1440
|
var CSP_NONCE_LOCAL = "cspNonce";
|
|
1301
1441
|
/** 用于在 req.headers 上透传 nonce 到 RSC handler 的 header 名 */
|
|
@@ -1412,29 +1552,33 @@ var PROD_CSP_BASE = {
|
|
|
1412
1552
|
* 必须在前面挂 createCspNonceMiddleware 才能让 res.locals.cspNonce 存在。
|
|
1413
1553
|
*/
|
|
1414
1554
|
function createSecurityMiddleware(isDev, extraConnectSrc = []) {
|
|
1415
|
-
if (isDev)
|
|
1416
|
-
|
|
1555
|
+
if (isDev) {
|
|
1556
|
+
const directives = {
|
|
1417
1557
|
...DEV_CSP,
|
|
1418
1558
|
connectSrc: [...DEV_CSP.connectSrc, ...extraConnectSrc]
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
|
|
1559
|
+
};
|
|
1560
|
+
return helmet({
|
|
1561
|
+
contentSecurityPolicy: { directives },
|
|
1562
|
+
strictTransportSecurity: false
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1422
1565
|
const nonceFn = (_req, res) => {
|
|
1423
1566
|
const nonce = res.locals?.[CSP_NONCE_LOCAL];
|
|
1424
1567
|
return typeof nonce === "string" ? `'nonce-${nonce}'` : "'self'";
|
|
1425
1568
|
};
|
|
1569
|
+
const directives = {
|
|
1570
|
+
...PROD_CSP_BASE,
|
|
1571
|
+
connectSrc: [...PROD_CSP_BASE.connectSrc, ...extraConnectSrc],
|
|
1572
|
+
scriptSrc: [
|
|
1573
|
+
"'self'",
|
|
1574
|
+
nonceFn,
|
|
1575
|
+
"'strict-dynamic'",
|
|
1576
|
+
"'unsafe-inline'"
|
|
1577
|
+
]
|
|
1578
|
+
};
|
|
1426
1579
|
return helmet({
|
|
1427
|
-
contentSecurityPolicy: { directives
|
|
1428
|
-
|
|
1429
|
-
connectSrc: [...PROD_CSP_BASE.connectSrc, ...extraConnectSrc],
|
|
1430
|
-
scriptSrc: [
|
|
1431
|
-
"'self'",
|
|
1432
|
-
nonceFn,
|
|
1433
|
-
"'strict-dynamic'",
|
|
1434
|
-
"'unsafe-inline'"
|
|
1435
|
-
]
|
|
1436
|
-
} },
|
|
1437
|
-
strictTransportSecurity: void 0
|
|
1580
|
+
contentSecurityPolicy: { directives },
|
|
1581
|
+
strictTransportSecurity: { maxAge: 15552e3 }
|
|
1438
1582
|
});
|
|
1439
1583
|
}
|
|
1440
1584
|
/**
|
|
@@ -1497,8 +1641,7 @@ function mountViteOrStatic(ctx) {
|
|
|
1497
1641
|
if (isDev && viteDevMiddleware) requestHandler.use(viteDevMiddleware.middlewares);
|
|
1498
1642
|
else if (!isDev) requestHandler.use(createStaticMiddleware("./dist/client"));
|
|
1499
1643
|
}
|
|
1500
|
-
|
|
1501
|
-
//#region src/utils/resolveFetchHandler.ts
|
|
1644
|
+
// src/utils/resolveFetchHandler.ts
|
|
1502
1645
|
/** Resolve the built RSC module once, retaining the selected export's receiver. */
|
|
1503
1646
|
function resolveFetchHandler(module) {
|
|
1504
1647
|
const mod = module;
|
|
@@ -1511,7 +1654,7 @@ function resolveFetchHandler(module) {
|
|
|
1511
1654
|
}
|
|
1512
1655
|
var package_default = {
|
|
1513
1656
|
name: "isr-engine",
|
|
1514
|
-
version: "
|
|
1657
|
+
version: "4.0.0",
|
|
1515
1658
|
description: "ISR/SSG/Fallback rendering orchestration on Vite + React 19 RSC.",
|
|
1516
1659
|
license: "UNLICENSED",
|
|
1517
1660
|
repository: {
|
|
@@ -1618,14 +1761,14 @@ var package_default = {
|
|
|
1618
1761
|
"esbuild": "^0.28.2",
|
|
1619
1762
|
"express": "^5.3.0",
|
|
1620
1763
|
"express-rate-limit": "8.7.5",
|
|
1621
|
-
"helmet": "^
|
|
1764
|
+
"helmet": "^8.3.0",
|
|
1622
1765
|
"ipaddr.js": "^2.5.0",
|
|
1623
|
-
"lru-cache": "^
|
|
1766
|
+
"lru-cache": "^11.5.3",
|
|
1624
1767
|
"ora": "^10.0.0",
|
|
1625
1768
|
"parse5": "^8.0.1",
|
|
1626
1769
|
"pino": "10.4.0",
|
|
1627
1770
|
"prom-client": "^15.1.3",
|
|
1628
|
-
"rsc-html-stream": "0.0.
|
|
1771
|
+
"rsc-html-stream": "0.0.8",
|
|
1629
1772
|
"sharp": "^0.35.5",
|
|
1630
1773
|
"sitemap": "^10.0.0",
|
|
1631
1774
|
"typescript": "^6.0.3"
|
|
@@ -1633,7 +1776,7 @@ var package_default = {
|
|
|
1633
1776
|
peerDependencies: {
|
|
1634
1777
|
"react": "19.3.1",
|
|
1635
1778
|
"react-dom": "19.3.1",
|
|
1636
|
-
"vite": "8.
|
|
1779
|
+
"vite": "8.3.8"
|
|
1637
1780
|
},
|
|
1638
1781
|
optionalDependencies: { "ioredis": "^5.11.1" },
|
|
1639
1782
|
devDependencies: {
|
|
@@ -1650,15 +1793,15 @@ var package_default = {
|
|
|
1650
1793
|
"@types/node": "24.19.2",
|
|
1651
1794
|
"@types/react": "^19.2.15",
|
|
1652
1795
|
"@types/react-dom": "^19.0.0",
|
|
1653
|
-
"@typescript-eslint/eslint-plugin": "8.
|
|
1654
|
-
"@typescript-eslint/parser": "8.
|
|
1796
|
+
"@typescript-eslint/eslint-plugin": "8.73.0",
|
|
1797
|
+
"@typescript-eslint/parser": "8.73.0",
|
|
1655
1798
|
"@vitest/coverage-v8": "^4.1.12",
|
|
1656
1799
|
"eslint": "^9.15.0",
|
|
1657
1800
|
"eslint-config-prettier": "^10.1.8",
|
|
1658
1801
|
"eslint-plugin-prettier": "^5.5.7",
|
|
1659
1802
|
"eslint-plugin-react": "^7.37.2",
|
|
1660
1803
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
1661
|
-
"globals": "^
|
|
1804
|
+
"globals": "^17.14.0",
|
|
1662
1805
|
"happy-dom": "^21.0.4",
|
|
1663
1806
|
"husky": "^9.1.7",
|
|
1664
1807
|
"ioredis-mock": "^8.9.0",
|
|
@@ -1671,7 +1814,7 @@ var package_default = {
|
|
|
1671
1814
|
"semantic-release": "25.0.9",
|
|
1672
1815
|
"tsc-alias": "^1.9.10",
|
|
1673
1816
|
"undici": "8.12.4",
|
|
1674
|
-
"vite": "8.
|
|
1817
|
+
"vite": "8.3.8",
|
|
1675
1818
|
"vitest": "^4.1.12"
|
|
1676
1819
|
},
|
|
1677
1820
|
pnpm: { "overrides": {
|
|
@@ -1689,8 +1832,7 @@ var package_default = {
|
|
|
1689
1832
|
"@typescript-eslint/typescript-estree>minimatch": "11.0.5"
|
|
1690
1833
|
} }
|
|
1691
1834
|
};
|
|
1692
|
-
|
|
1693
|
-
//#region src/config/defaults.ts
|
|
1835
|
+
// src/config/defaults.ts
|
|
1694
1836
|
/**
|
|
1695
1837
|
* 框架级默认配置常量
|
|
1696
1838
|
*
|
|
@@ -1699,14 +1841,12 @@ var package_default = {
|
|
|
1699
1841
|
*/
|
|
1700
1842
|
/** 默认服务器端口 */
|
|
1701
1843
|
var DEFAULT_PORT = 3e3;
|
|
1702
|
-
|
|
1703
|
-
//#region src/logger/index.ts
|
|
1844
|
+
// src/logger/index.ts
|
|
1704
1845
|
var logger$8 = Logger.getInstance({
|
|
1705
1846
|
verbose: true,
|
|
1706
1847
|
logFile: "./logs/isr-engine.log"
|
|
1707
1848
|
});
|
|
1708
|
-
|
|
1709
|
-
//#region src/ssg/spider.ts
|
|
1849
|
+
// src/ssg/spider.ts
|
|
1710
1850
|
/**
|
|
1711
1851
|
* SSG 爬虫 —— 构建后爬取 RSC fetch handler,产出静态 HTML 到 dist/client
|
|
1712
1852
|
*
|
|
@@ -1829,7 +1969,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
|
|
|
1829
1969
|
signal: ctrl.signal
|
|
1830
1970
|
}));
|
|
1831
1971
|
if (ctrl.signal.aborted) {
|
|
1832
|
-
response.body?.cancel(ctrl.signal.reason).catch(() =>
|
|
1972
|
+
response.body?.cancel(ctrl.signal.reason).catch(() => void 0);
|
|
1833
1973
|
throw ctrl.signal.reason;
|
|
1834
1974
|
}
|
|
1835
1975
|
reader = response.body?.getReader();
|
|
@@ -1855,7 +1995,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
|
|
|
1855
1995
|
const abort = (reason) => {
|
|
1856
1996
|
rejectAbort(reason);
|
|
1857
1997
|
ctrl.abort(reason);
|
|
1858
|
-
reader?.cancel(reason).catch(() =>
|
|
1998
|
+
reader?.cancel(reason).catch(() => void 0);
|
|
1859
1999
|
};
|
|
1860
2000
|
const onBatchAbort = () => abort(batchSignal.reason);
|
|
1861
2001
|
batchSignal.addEventListener("abort", onBatchAbort, { once: true });
|
|
@@ -2078,8 +2218,7 @@ async function extractSsgRoutes(config) {
|
|
|
2078
2218
|
assertDistinctHtmlRouteIdentities(ssgRoutes);
|
|
2079
2219
|
return ssgRoutes;
|
|
2080
2220
|
}
|
|
2081
|
-
|
|
2082
|
-
//#region src/security/cspNonceTemplate.ts
|
|
2221
|
+
// src/security/cspNonceTemplate.ts
|
|
2083
2222
|
var NONCE_VALUE = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
2084
2223
|
var NONCE_SOURCE = /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/i;
|
|
2085
2224
|
/** Compile all verbatim nonce occurrences, including HTML attributes and serialized JS. */
|
|
@@ -2117,8 +2256,7 @@ function instantiateCspNonceTemplate(body, template, nonce) {
|
|
|
2117
2256
|
fragments.push(body.subarray(cursor));
|
|
2118
2257
|
return Buffer.concat(fragments);
|
|
2119
2258
|
}
|
|
2120
|
-
|
|
2121
|
-
//#region src/types/ISRConfig.ts
|
|
2259
|
+
// src/types/ISRConfig.ts
|
|
2122
2260
|
var RenderModes = {
|
|
2123
2261
|
SSG: "ssg",
|
|
2124
2262
|
ISR: "isr",
|
|
@@ -2156,8 +2294,7 @@ var FallbackChain = {
|
|
|
2156
2294
|
],
|
|
2157
2295
|
ssr: ["server", "csr-shell"]
|
|
2158
2296
|
};
|
|
2159
|
-
|
|
2160
|
-
//#region src/engine/RenderMode.ts
|
|
2297
|
+
// src/engine/RenderMode.ts
|
|
2161
2298
|
/**
|
|
2162
2299
|
* 渲染模式工具函数 —— 根据全局模式和路由覆盖配置,返回渲染模式 / 降级链
|
|
2163
2300
|
*
|
|
@@ -2285,8 +2422,7 @@ function selectRouteRule(url, routes) {
|
|
|
2285
2422
|
function getRouteFallbackChain(url, globalMode, overrides) {
|
|
2286
2423
|
return getFallbackChain(resolveRenderMode(url, globalMode, overrides));
|
|
2287
2424
|
}
|
|
2288
|
-
|
|
2289
|
-
//#region src/plugin/isrCacheStore.ts
|
|
2425
|
+
// src/plugin/isrCacheStore.ts
|
|
2290
2426
|
/**
|
|
2291
2427
|
* IsrCacheStore —— ISR HTTP 响应缓存的存储抽象(同步读 + 异步写穿)
|
|
2292
2428
|
*
|
|
@@ -2301,7 +2437,7 @@ function getRouteFallbackChain(url, globalMode, overrides) {
|
|
|
2301
2437
|
function createMemoryCacheStore(opts = {}) {
|
|
2302
2438
|
const lru = new LRUCache({
|
|
2303
2439
|
max: opts.max ?? 1e3,
|
|
2304
|
-
maxSize: opts.maxBytes ??
|
|
2440
|
+
maxSize: opts.maxBytes ?? 67108864,
|
|
2305
2441
|
sizeCalculation: (e) => e.body.byteLength + 1024
|
|
2306
2442
|
});
|
|
2307
2443
|
return {
|
|
@@ -2356,7 +2492,7 @@ function deserialize(value) {
|
|
|
2356
2492
|
function createHybridCacheStore(opts) {
|
|
2357
2493
|
const lru = new LRUCache({
|
|
2358
2494
|
max: opts.max ?? 1e3,
|
|
2359
|
-
maxSize: opts.maxBytes ??
|
|
2495
|
+
maxSize: opts.maxBytes ?? 67108864,
|
|
2360
2496
|
sizeCalculation: (e) => e.body.byteLength + 1024
|
|
2361
2497
|
});
|
|
2362
2498
|
const pendingReads = /* @__PURE__ */ new Map();
|
|
@@ -2492,8 +2628,7 @@ function createHybridCacheStore(opts) {
|
|
|
2492
2628
|
}
|
|
2493
2629
|
};
|
|
2494
2630
|
}
|
|
2495
|
-
|
|
2496
|
-
//#region src/metrics/PromMetrics.ts
|
|
2631
|
+
// src/metrics/PromMetrics.ts
|
|
2497
2632
|
/**
|
|
2498
2633
|
* PromMetrics —— prom-client 包装,导出 Prometheus 文本格式
|
|
2499
2634
|
*
|
|
@@ -2503,20 +2638,6 @@ function createHybridCacheStore(opts) {
|
|
|
2503
2638
|
* - 响应时间用 Histogram(带桶),不是平均值 —— 才能正确算 P95/P99
|
|
2504
2639
|
* - 默认采集 process_*(CPU / RSS / event-loop lag)—— 一行 collectDefaultMetrics
|
|
2505
2640
|
*/
|
|
2506
|
-
var PromMetrics_exports = /* @__PURE__ */ __exportAll({
|
|
2507
|
-
cacheEntriesGauge: () => cacheEntriesGauge,
|
|
2508
|
-
cacheHitsTotal: () => cacheHitsTotal,
|
|
2509
|
-
cacheRevalidatingGauge: () => cacheRevalidatingGauge,
|
|
2510
|
-
createPrometheusMetricsMiddleware: () => createPrometheusMetricsMiddleware,
|
|
2511
|
-
httpRequestDurationSeconds: () => httpRequestDurationSeconds,
|
|
2512
|
-
httpRequestsTotal: () => httpRequestsTotal,
|
|
2513
|
-
invalidatorFailuresTotal: () => invalidatorFailuresTotal,
|
|
2514
|
-
invalidatorRunsTotal: () => invalidatorRunsTotal,
|
|
2515
|
-
l2ReadTimeoutsTotal: () => l2ReadTimeoutsTotal,
|
|
2516
|
-
normalizeRoute: () => normalizeRoute,
|
|
2517
|
-
promRegistry: () => promRegistry,
|
|
2518
|
-
recordHttpRequest: () => recordHttpRequest
|
|
2519
|
-
});
|
|
2520
2641
|
var promRegistry = new Registry();
|
|
2521
2642
|
collectDefaultMetrics({
|
|
2522
2643
|
register: promRegistry,
|
|
@@ -2693,8 +2814,7 @@ function createPrometheusMetricsMiddleware(pathOrOptions = {}) {
|
|
|
2693
2814
|
}
|
|
2694
2815
|
};
|
|
2695
2816
|
}
|
|
2696
|
-
|
|
2697
|
-
//#region src/config/loadConfig.ts
|
|
2817
|
+
// src/config/loadConfig.ts
|
|
2698
2818
|
/**
|
|
2699
2819
|
* 配置加载工具
|
|
2700
2820
|
*/
|
|
@@ -2776,15 +2896,7 @@ async function resolveImportPath(filePath, options) {
|
|
|
2776
2896
|
}
|
|
2777
2897
|
return pathToFileURL$1(filePath).href + (forceReload ? `?t=${Date.now()}` : "");
|
|
2778
2898
|
}
|
|
2779
|
-
|
|
2780
|
-
//#region src/server/opsConfig.ts
|
|
2781
|
-
var opsConfig_exports = /* @__PURE__ */ __exportAll({
|
|
2782
|
-
bindRuntimeOpsConfig: () => bindRuntimeOpsConfig,
|
|
2783
|
-
createOpsAuthMiddleware: () => createOpsAuthMiddleware,
|
|
2784
|
-
getOpsRequestLimiter: () => getOpsRequestLimiter,
|
|
2785
|
-
getRuntimeOpsConfig: () => getRuntimeOpsConfig,
|
|
2786
|
-
resolveOpsConfig: () => resolveOpsConfig
|
|
2787
|
-
});
|
|
2899
|
+
// src/server/opsConfig.ts
|
|
2788
2900
|
var opsLimiters = /* @__PURE__ */ new WeakMap();
|
|
2789
2901
|
var runtimeOpsConfigs = /* @__PURE__ */ new WeakMap();
|
|
2790
2902
|
/** Carry one resolved policy from the Vite plugin into its owning Express runtime. */
|
|
@@ -2927,8 +3039,7 @@ function createOpsAuthMiddleware(endpoint, resolved) {
|
|
|
2927
3039
|
next();
|
|
2928
3040
|
};
|
|
2929
3041
|
}
|
|
2930
|
-
|
|
2931
|
-
//#region src/plugin/devAssetRequestMiddleware.ts
|
|
3042
|
+
// src/plugin/devAssetRequestMiddleware.ts
|
|
2932
3043
|
var CACHE_SUFFIX_MARKERS = ["$$cache=", "%24%24cache="];
|
|
2933
3044
|
var DEV_ASSET_EXT_RE = /\.(js|mjs|cjs|ts|tsx|jsx|json|map|css|scss|sass|less|stylus|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|eot|mp3|mp4|webm|ogg|wasm|zip|pdf)$/i;
|
|
2934
3045
|
var VITE_OPTIMIZED_DEPS_DIR_RE = /^deps(?:_(?:rsc|ssr))?(?:_temp_[0-9a-f]{8})?$/;
|
|
@@ -2999,8 +3110,7 @@ function assetExists(root, pathname) {
|
|
|
2999
3110
|
function resolveAssetPath(root, pathname) {
|
|
3000
3111
|
return pathname.startsWith("/@fs/") ? pathname.slice(4) : path.join(root, pathname);
|
|
3001
3112
|
}
|
|
3002
|
-
|
|
3003
|
-
//#region src/plugin/coherentCacheStore.ts
|
|
3113
|
+
// src/plugin/coherentCacheStore.ts
|
|
3004
3114
|
function decode(value) {
|
|
3005
3115
|
if (!value || typeof value !== "object") return void 0;
|
|
3006
3116
|
const entry = value;
|
|
@@ -3011,7 +3121,7 @@ function decode(value) {
|
|
|
3011
3121
|
};
|
|
3012
3122
|
}
|
|
3013
3123
|
/** Remote validation is mandatory; pub/sub is an eviction hint, never a read authority. */
|
|
3014
|
-
function createCoherentCacheStore({ backend, max = 1e3, maxBytes =
|
|
3124
|
+
function createCoherentCacheStore({ backend, max = 1e3, maxBytes = 67108864 }) {
|
|
3015
3125
|
const local = new LRUCache({
|
|
3016
3126
|
max,
|
|
3017
3127
|
maxSize: maxBytes,
|
|
@@ -3121,9 +3231,8 @@ function createCoherentCacheStore({ backend, max = 1e3, maxBytes = 64 * 1024 * 1
|
|
|
3121
3231
|
}
|
|
3122
3232
|
};
|
|
3123
3233
|
}
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
var MAX_RESPONSE_TTL_MS = 720 * 60 * 60 * 1e3;
|
|
3234
|
+
// src/cache/RedisResponseCacheBackend.ts
|
|
3235
|
+
var MAX_RESPONSE_TTL_MS = 2592e6;
|
|
3127
3236
|
var MAX_TAGS = 128;
|
|
3128
3237
|
var PRELUDE = `
|
|
3129
3238
|
local function kind(key)
|
|
@@ -3363,8 +3472,7 @@ var RedisResponseCacheBackend = class {
|
|
|
3363
3472
|
await this.close?.();
|
|
3364
3473
|
}
|
|
3365
3474
|
};
|
|
3366
|
-
|
|
3367
|
-
//#region src/cache/MemoryCacheAdapter.ts
|
|
3475
|
+
// src/cache/MemoryCacheAdapter.ts
|
|
3368
3476
|
var DEFAULT_CONFIG$1 = {
|
|
3369
3477
|
capacity: 1e4,
|
|
3370
3478
|
defaultTTL: 0,
|
|
@@ -3540,8 +3648,7 @@ var MemoryCacheAdapter = class {
|
|
|
3540
3648
|
}
|
|
3541
3649
|
}
|
|
3542
3650
|
};
|
|
3543
|
-
|
|
3544
|
-
//#region src/cache/RedisCacheAdapter.ts
|
|
3651
|
+
// src/cache/RedisCacheAdapter.ts
|
|
3545
3652
|
var DEFAULT_CONFIG = {
|
|
3546
3653
|
port: 6379,
|
|
3547
3654
|
db: 0,
|
|
@@ -4001,12 +4108,7 @@ var RedisCacheAdapter = class {
|
|
|
4001
4108
|
this.connected = false;
|
|
4002
4109
|
}
|
|
4003
4110
|
};
|
|
4004
|
-
|
|
4005
|
-
//#region src/config/resolveRuntimeRedis.ts
|
|
4006
|
-
var resolveRuntimeRedis_exports = /* @__PURE__ */ __exportAll({
|
|
4007
|
-
hasRuntimeRedisConnection: () => hasRuntimeRedisConnection,
|
|
4008
|
-
resolveRuntimeRedisConfig: () => resolveRuntimeRedisConfig
|
|
4009
|
-
});
|
|
4111
|
+
// src/config/resolveRuntimeRedis.ts
|
|
4010
4112
|
function nonEmpty(value) {
|
|
4011
4113
|
const trimmed = value?.trim();
|
|
4012
4114
|
return trimmed ? trimmed : void 0;
|
|
@@ -4049,8 +4151,7 @@ function hasRuntimeRedisConnection(redis) {
|
|
|
4049
4151
|
const resolved = resolveRuntimeRedisConfig(redis);
|
|
4050
4152
|
return Boolean(resolved?.url || resolved?.host);
|
|
4051
4153
|
}
|
|
4052
|
-
|
|
4053
|
-
//#region src/cache/createAutoCacheStore.ts
|
|
4154
|
+
// src/cache/createAutoCacheStore.ts
|
|
4054
4155
|
/**
|
|
4055
4156
|
* createAutoCacheStore —— 按显式 Redis 配置选择 cache backend
|
|
4056
4157
|
*
|
|
@@ -4058,7 +4159,6 @@ function hasRuntimeRedisConnection(redis) {
|
|
|
4058
4159
|
* - runtime.redis.url/host 已设 → revision-validated response cache(Redis 原子协议 + 本机字节缓存)
|
|
4059
4160
|
* - 未显式配置 Redis → MemoryCacheStore(单层 LRU,行为不变)
|
|
4060
4161
|
*/
|
|
4061
|
-
var createAutoCacheStore_exports = /* @__PURE__ */ __exportAll({ createAutoCacheStore: () => createAutoCacheStore });
|
|
4062
4162
|
var logger$6 = Logger.getInstance();
|
|
4063
4163
|
function createAutoCacheStore(opts = {}) {
|
|
4064
4164
|
const redisConfig = resolveRuntimeRedisConfig({
|
|
@@ -4090,9 +4190,7 @@ function createAutoCacheStore(opts = {}) {
|
|
|
4090
4190
|
max
|
|
4091
4191
|
});
|
|
4092
4192
|
}
|
|
4093
|
-
|
|
4094
|
-
//#region src/cache/RedisInvalidationBus.ts
|
|
4095
|
-
var RedisInvalidationBus_exports = /* @__PURE__ */ __exportAll({ RedisInvalidationBus: () => RedisInvalidationBus });
|
|
4193
|
+
// src/cache/RedisInvalidationBus.ts
|
|
4096
4194
|
function normalizeTarget(target) {
|
|
4097
4195
|
if (!target || typeof target !== "object") return null;
|
|
4098
4196
|
const candidate = target;
|
|
@@ -4133,12 +4231,12 @@ var RedisInvalidationBus = class {
|
|
|
4133
4231
|
channel: config.channel,
|
|
4134
4232
|
connectTimeout: config.connectTimeout ?? 5e3,
|
|
4135
4233
|
commandTimeout: config.commandTimeout ?? 3e3,
|
|
4136
|
-
replayWindowMs: config.replayWindowMs ??
|
|
4234
|
+
replayWindowMs: config.replayWindowMs ?? 3e5,
|
|
4137
4235
|
replayLogMaxEntries: config.replayLogMaxEntries ?? 5e3
|
|
4138
4236
|
};
|
|
4139
4237
|
this.channel = this.config.channel ?? `${this.config.keyPrefix}invalidate`;
|
|
4140
4238
|
this.logKey = `${this.channel}:log`;
|
|
4141
|
-
this.replayWindowMs = this.config.replayWindowMs ??
|
|
4239
|
+
this.replayWindowMs = this.config.replayWindowMs ?? 3e5;
|
|
4142
4240
|
this.replayLogMaxEntries = this.config.replayLogMaxEntries ?? 5e3;
|
|
4143
4241
|
this.lastSeenSentAt = Date.now();
|
|
4144
4242
|
this.initPromise = this.init();
|
|
@@ -4318,8 +4416,7 @@ var RedisInvalidationBus = class {
|
|
|
4318
4416
|
}
|
|
4319
4417
|
}
|
|
4320
4418
|
};
|
|
4321
|
-
|
|
4322
|
-
//#region src/context/createServerRequestContext.ts
|
|
4419
|
+
// src/context/createServerRequestContext.ts
|
|
4323
4420
|
/**
|
|
4324
4421
|
* createServerRequestContext —— engine 入口处构造 RequestContext 的统一工厂。
|
|
4325
4422
|
*
|
|
@@ -4333,16 +4430,10 @@ var RedisInvalidationBus = class {
|
|
|
4333
4430
|
* 必须在 cache lookup 之前 set,但 cache 层会把 anon 这一条从 captured.headers 里
|
|
4334
4431
|
* 剥掉再入缓存(见 plugin/isrCacheMiddleware.ts),保证缓存内容 user-agnostic。
|
|
4335
4432
|
*/
|
|
4336
|
-
var createServerRequestContext_exports = /* @__PURE__ */ __exportAll({
|
|
4337
|
-
ANON_COOKIE_MAX_AGE_SECONDS: () => ANON_COOKIE_MAX_AGE_SECONDS,
|
|
4338
|
-
ANON_COOKIE_NAME: () => ANON_COOKIE_NAME,
|
|
4339
|
-
applyAnonCookie: () => applyAnonCookie,
|
|
4340
|
-
createServerRequestContext: () => createServerRequestContext
|
|
4341
|
-
});
|
|
4342
4433
|
/** anonId cookie 名称 —— engine 全局常量,避免散落字符串。 */
|
|
4343
4434
|
var ANON_COOKIE_NAME = "anon";
|
|
4344
4435
|
/** anonId cookie 有效期(秒)。1 年;浏览器侧最大也只能撑到这个量级。 */
|
|
4345
|
-
var ANON_COOKIE_MAX_AGE_SECONDS =
|
|
4436
|
+
var ANON_COOKIE_MAX_AGE_SECONDS = 31536e3;
|
|
4346
4437
|
/**
|
|
4347
4438
|
* 从 IncomingMessage 构造 ISRContextData。
|
|
4348
4439
|
*
|
|
@@ -4355,7 +4446,8 @@ var ANON_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;
|
|
|
4355
4446
|
*/
|
|
4356
4447
|
function createServerRequestContext(req) {
|
|
4357
4448
|
const rawCookie = req.headers["cookie"];
|
|
4358
|
-
const
|
|
4449
|
+
const cookieHeader = Array.isArray(rawCookie) ? rawCookie.join("; ") : typeof rawCookie === "string" ? rawCookie : "";
|
|
4450
|
+
const cookies = parseCookieHeader(cookieHeader);
|
|
4359
4451
|
const headerReqId = req.headers["x-request-id"];
|
|
4360
4452
|
const headerTraceparent = req.headers["traceparent"];
|
|
4361
4453
|
const existingAnon = cookies[ANON_COOKIE_NAME];
|
|
@@ -4399,8 +4491,7 @@ function applyAnonCookie(res, anonId, cookieDomain) {
|
|
|
4399
4491
|
if (cookieDomain) parts.push(`Domain=${cookieDomain}`);
|
|
4400
4492
|
res.appendHeader("Set-Cookie", parts.join("; "));
|
|
4401
4493
|
}
|
|
4402
|
-
|
|
4403
|
-
//#region src/utils/hash.ts
|
|
4494
|
+
// src/utils/hash.ts
|
|
4404
4495
|
/**
|
|
4405
4496
|
* 通用 hash 工具 —— 非加密用途的快速字符串 hash。
|
|
4406
4497
|
*
|
|
@@ -4431,8 +4522,7 @@ function fnv1a32(input) {
|
|
|
4431
4522
|
function fnv1a32Base36(input) {
|
|
4432
4523
|
return fnv1a32(input).toString(36);
|
|
4433
4524
|
}
|
|
4434
|
-
|
|
4435
|
-
//#region src/plugin/isrCacheMiddleware.ts
|
|
4525
|
+
// src/plugin/isrCacheMiddleware.ts
|
|
4436
4526
|
/**
|
|
4437
4527
|
* ISR 缓存中间件插件 —— engine 的差异化核心能力
|
|
4438
4528
|
*
|
|
@@ -4576,7 +4666,7 @@ function createIsrCacheHandler(config, options = {}) {
|
|
|
4576
4666
|
const seeded = /* @__PURE__ */ new Map();
|
|
4577
4667
|
const internalToken = randomBytes(24).toString("hex");
|
|
4578
4668
|
const singleflightWaitMs = options.singleflightWaitMs ?? 5e3;
|
|
4579
|
-
const maxCachedBodyBytes = options.maxCachedBodyBytes ??
|
|
4669
|
+
const maxCachedBodyBytes = options.maxCachedBodyBytes ?? 5242880;
|
|
4580
4670
|
const prefetchOnHit = options.prefetchOnHit;
|
|
4581
4671
|
const prefetchCooldownMs = options.prefetchCooldownMs ?? 3e4;
|
|
4582
4672
|
/**
|
|
@@ -4803,7 +4893,6 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
|
|
|
4803
4893
|
logger$5.info(`📋 ISR cache: 自动加载 ssr.config.ts 成功(mode=${rules.globalMode}, overrides=${Object.keys(rules.routes).length})`);
|
|
4804
4894
|
}
|
|
4805
4895
|
const opsConfig = resolveOpsConfig(resolvedConfig, "development");
|
|
4806
|
-
const { bindRuntimeOpsConfig, getOpsRequestLimiter } = await Promise.resolve().then(() => opsConfig_exports);
|
|
4807
4896
|
const opsLimiter = getOpsRequestLimiter(opsConfig);
|
|
4808
4897
|
const metricsAuth = createOpsAuthMiddleware("metrics", opsConfig);
|
|
4809
4898
|
const nextHandler = createIsrCacheHandler(resolvedConfig, withRuntimeCacheOptions(resolvedConfig, {
|
|
@@ -4811,7 +4900,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
|
|
|
4811
4900
|
development: true
|
|
4812
4901
|
}));
|
|
4813
4902
|
try {
|
|
4814
|
-
const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-
|
|
4903
|
+
const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-BjwSKfyf.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
|
|
4815
4904
|
handler = nextHandler;
|
|
4816
4905
|
server.middlewares.use((req, res, next) => {
|
|
4817
4906
|
if (handler !== nextHandler) return next();
|
|
@@ -4819,8 +4908,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
|
|
|
4819
4908
|
opsLimiter(req, res, (error) => {
|
|
4820
4909
|
if (error) return next(error);
|
|
4821
4910
|
metricsAuth(req, res, () => {
|
|
4822
|
-
|
|
4823
|
-
const body = await promRegistry.metrics();
|
|
4911
|
+
promRegistry.metrics().then((body) => {
|
|
4824
4912
|
res.setHeader("content-type", promRegistry.contentType);
|
|
4825
4913
|
res.end(body);
|
|
4826
4914
|
}).catch((err) => {
|
|
@@ -4958,7 +5046,8 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4958
5046
|
logger$5.warn(`ISR cache L2 read 失败 ${cacheKey}: ${err.message}`);
|
|
4959
5047
|
}
|
|
4960
5048
|
if (!isActive()) return;
|
|
4961
|
-
|
|
5049
|
+
const staticSeed = ctx.staticSeed;
|
|
5050
|
+
if (!entry && ctx.state.invalidationGeneration === 0 && resolved.mode === "ssg" && staticSeed && (!ctx.staticSeedInfo || ctx.staticSeedInfo(logicalPath)) && !url.includes("?") && !url.endsWith(RSC_URL_POSTFIX) && !ctx.variantIsolation && !ctx.hostIsolation) {
|
|
4962
5051
|
let seedTask = ctx.seeded.get(cacheKey);
|
|
4963
5052
|
const leader = !seedTask;
|
|
4964
5053
|
if (!seedTask) {
|
|
@@ -4977,7 +5066,7 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4977
5066
|
if (!isActive()) return seedDenial(res);
|
|
4978
5067
|
const generation = ctx.state.invalidationGeneration;
|
|
4979
5068
|
if (generation !== 0) return true;
|
|
4980
|
-
const seed = await raceWithTimeout(
|
|
5069
|
+
const seed = await raceWithTimeout(staticSeed.call(ctx, logicalPath, String(res.getHeader("content-security-policy") || "default-src 'self'")), ctx.l2ReadTimeoutMs);
|
|
4981
5070
|
if (!seed) {
|
|
4982
5071
|
ctx.seeded.delete(cacheKey);
|
|
4983
5072
|
return true;
|
|
@@ -5635,964 +5724,932 @@ function refreshHeaders(req, ctx) {
|
|
|
5635
5724
|
}
|
|
5636
5725
|
return headers;
|
|
5637
5726
|
}
|
|
5638
|
-
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
for (const character of target) {
|
|
5645
|
-
const code = character.charCodeAt(0);
|
|
5646
|
-
if (code < 32 || code === 127) return false;
|
|
5727
|
+
// src/plugin/remoteImageSource.ts
|
|
5728
|
+
var ImageSourceError = class extends Error {
|
|
5729
|
+
status;
|
|
5730
|
+
constructor(status, message) {
|
|
5731
|
+
super(message);
|
|
5732
|
+
this.status = status;
|
|
5647
5733
|
}
|
|
5648
|
-
|
|
5649
|
-
|
|
5734
|
+
};
|
|
5735
|
+
var resolveAll = (hostname) => lookup(hostname, {
|
|
5736
|
+
all: true,
|
|
5737
|
+
verbatim: true
|
|
5738
|
+
});
|
|
5739
|
+
function isPublicImageAddress(address) {
|
|
5650
5740
|
try {
|
|
5651
|
-
return
|
|
5741
|
+
return ipaddr.parse(address).range() === "unicast";
|
|
5652
5742
|
} catch {
|
|
5653
5743
|
return false;
|
|
5654
5744
|
}
|
|
5655
5745
|
}
|
|
5656
|
-
function
|
|
5657
|
-
const
|
|
5658
|
-
|
|
5746
|
+
async function resolveImageAddress(hostname, resolve = resolveAll) {
|
|
5747
|
+
const name = hostname.replace(/^\[|\]$/g, "");
|
|
5748
|
+
const addresses = isIP(name) ? [{
|
|
5749
|
+
address: name,
|
|
5750
|
+
family: isIP(name)
|
|
5751
|
+
}] : await resolve(name);
|
|
5752
|
+
if (!addresses.length || addresses.some((a) => !isPublicImageAddress(a.address))) throw new ImageSourceError(400, "source address not allowed");
|
|
5753
|
+
return addresses[0];
|
|
5754
|
+
}
|
|
5755
|
+
/** Return the configured authority, rather than carrying the request's authority past a guard. */
|
|
5756
|
+
function selectImageOrigin(url, allow) {
|
|
5757
|
+
if (url.username || url.password || !["http:", "https:"].includes(url.protocol)) return;
|
|
5758
|
+
const protocol = url.protocol === "https:" ? "https:" : "http:";
|
|
5759
|
+
const defaultPort = protocol === "https:" ? 443 : 80;
|
|
5760
|
+
for (const entry of allow) {
|
|
5761
|
+
if (/[\s/@?#*\\]/.test(entry)) continue;
|
|
5762
|
+
const authority = /^(\[[^\]]+\]|[^:]+)(?::([0-9]+))?$/.exec(entry);
|
|
5763
|
+
if (!authority) continue;
|
|
5764
|
+
let configured;
|
|
5765
|
+
try {
|
|
5766
|
+
configured = new URL(`${protocol}//${entry}`);
|
|
5767
|
+
} catch {
|
|
5768
|
+
continue;
|
|
5769
|
+
}
|
|
5770
|
+
const port = authority[2] === void 0 ? defaultPort : Number(authority[2]);
|
|
5771
|
+
if (!configured.hostname || configured.pathname !== "/" || configured.username || configured.password || url.hostname !== configured.hostname || Number(url.port || defaultPort) !== port) continue;
|
|
5772
|
+
return {
|
|
5773
|
+
protocol,
|
|
5774
|
+
hostname: configured.hostname.replace(/^\[|\]$/g, ""),
|
|
5775
|
+
authority: configured.host,
|
|
5776
|
+
port
|
|
5777
|
+
};
|
|
5778
|
+
}
|
|
5659
5779
|
}
|
|
5660
|
-
function
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
return
|
|
5780
|
+
async function resolveBeforeAbort(hostname, signal) {
|
|
5781
|
+
signal.throwIfAborted();
|
|
5782
|
+
let abort;
|
|
5783
|
+
try {
|
|
5784
|
+
return await Promise.race([resolveImageAddress(hostname), new Promise((_resolve, reject) => {
|
|
5785
|
+
abort = () => reject(signal.reason);
|
|
5786
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
5787
|
+
})]);
|
|
5788
|
+
} finally {
|
|
5789
|
+
if (abort) signal.removeEventListener("abort", abort);
|
|
5665
5790
|
}
|
|
5666
|
-
res.redirect(status, target);
|
|
5667
5791
|
}
|
|
5668
|
-
|
|
5669
|
-
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
5675
|
-
|
|
5676
|
-
|
|
5677
|
-
|
|
5678
|
-
|
|
5679
|
-
|
|
5792
|
+
/** A fresh socket uses a validated public DNS answer and a configured origin at every hop. */
|
|
5793
|
+
async function fetchRemoteImage(src, allow, maxBytes) {
|
|
5794
|
+
const controller = new AbortController();
|
|
5795
|
+
const timer = setTimeout(() => controller.abort(), 1e4);
|
|
5796
|
+
try {
|
|
5797
|
+
let url = new URL(src);
|
|
5798
|
+
for (let hop = 0; hop <= 5; hop++) {
|
|
5799
|
+
const response = await requestPinnedImage(url, allow, controller.signal);
|
|
5800
|
+
if ([
|
|
5801
|
+
301,
|
|
5802
|
+
302,
|
|
5803
|
+
303,
|
|
5804
|
+
307,
|
|
5805
|
+
308
|
|
5806
|
+
].includes(response.statusCode ?? 0)) {
|
|
5807
|
+
response.destroy();
|
|
5808
|
+
if (!response.headers.location || hop === 5) throw new ImageSourceError(400, "invalid source redirect");
|
|
5809
|
+
url = new URL(response.headers.location, url);
|
|
5810
|
+
continue;
|
|
5811
|
+
}
|
|
5812
|
+
if ((response.statusCode ?? 0) < 200 || (response.statusCode ?? 0) >= 300) {
|
|
5813
|
+
response.destroy();
|
|
5814
|
+
throw new ImageSourceError(400, "source fetch failed");
|
|
5815
|
+
}
|
|
5816
|
+
if (Number(response.headers["content-length"]) > maxBytes) {
|
|
5817
|
+
response.destroy();
|
|
5818
|
+
throw new ImageSourceError(413, "source too large");
|
|
5819
|
+
}
|
|
5820
|
+
const chunks = [];
|
|
5821
|
+
let size = 0;
|
|
5822
|
+
try {
|
|
5823
|
+
for await (const chunk of response) {
|
|
5824
|
+
size += chunk.length;
|
|
5825
|
+
if (size > maxBytes) throw new ImageSourceError(413, "source too large");
|
|
5826
|
+
chunks.push(Buffer.from(chunk));
|
|
5827
|
+
}
|
|
5828
|
+
if (!response.complete) throw new ImageSourceError(400, "incomplete source response");
|
|
5829
|
+
return Buffer.concat(chunks, size);
|
|
5830
|
+
} finally {
|
|
5831
|
+
response.destroy();
|
|
5832
|
+
}
|
|
5680
5833
|
}
|
|
5681
|
-
|
|
5834
|
+
throw new ImageSourceError(400, "invalid source redirect");
|
|
5835
|
+
} catch (error) {
|
|
5836
|
+
if (error instanceof ImageSourceError) throw error;
|
|
5837
|
+
throw new ImageSourceError(controller.signal.aborted ? 504 : 400, "source fetch failed");
|
|
5838
|
+
} finally {
|
|
5839
|
+
clearTimeout(timer);
|
|
5682
5840
|
}
|
|
5683
|
-
visit(parse(html));
|
|
5684
|
-
return [...hashes].sort();
|
|
5685
|
-
}
|
|
5686
|
-
function applyStaticScriptPolicy(policy, hashes) {
|
|
5687
|
-
return [...policy.split(";").filter((directive) => {
|
|
5688
|
-
const name = directive.trim().split(/\s/, 1)[0].toLowerCase();
|
|
5689
|
-
return name !== "script-src" && name !== "script-src-elem";
|
|
5690
|
-
}), ["script-src 'self'", ...hashes].join(" ")].join(";");
|
|
5691
5841
|
}
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
5704
|
-
|
|
5705
|
-
|
|
5842
|
+
/** No transport entry point accepts a caller-supplied address or unvalidated authority. */
|
|
5843
|
+
async function requestPinnedImage(url, allow, signal, accept = "image/*", userAgent) {
|
|
5844
|
+
const origin = selectImageOrigin(url, allow);
|
|
5845
|
+
if (!origin) throw new ImageSourceError(400, "source origin not allowed");
|
|
5846
|
+
const requestPath = url.pathname + url.search;
|
|
5847
|
+
const resolved = await resolveBeforeAbort(origin.hostname, signal);
|
|
5848
|
+
const address = {
|
|
5849
|
+
address: resolved.address,
|
|
5850
|
+
family: resolved.family
|
|
5851
|
+
};
|
|
5852
|
+
signal.throwIfAborted();
|
|
5853
|
+
return new Promise((resolve, reject) => {
|
|
5854
|
+
const request$2 = (origin.protocol === "https:" ? request$1 : request)({
|
|
5855
|
+
protocol: origin.protocol,
|
|
5856
|
+
hostname: origin.hostname,
|
|
5857
|
+
port: origin.port,
|
|
5858
|
+
path: requestPath,
|
|
5859
|
+
agent: false,
|
|
5860
|
+
signal,
|
|
5861
|
+
maxHeaderSize: 16384,
|
|
5862
|
+
...origin.protocol === "https:" ? {
|
|
5863
|
+
servername: isIP(origin.hostname) ? void 0 : origin.hostname,
|
|
5864
|
+
rejectUnauthorized: true
|
|
5865
|
+
} : {},
|
|
5866
|
+
lookup: ((_host, options, callback) => {
|
|
5867
|
+
if (options.all) callback(null, [address]);
|
|
5868
|
+
else callback(null, address.address, address.family);
|
|
5869
|
+
}),
|
|
5870
|
+
headers: {
|
|
5871
|
+
host: origin.authority,
|
|
5872
|
+
accept,
|
|
5873
|
+
"accept-encoding": "identity",
|
|
5874
|
+
...userAgent ? { "user-agent": userAgent } : {}
|
|
5706
5875
|
}
|
|
5707
|
-
}
|
|
5876
|
+
}, resolve);
|
|
5877
|
+
request$2.once("error", reject);
|
|
5878
|
+
request$2.end();
|
|
5879
|
+
});
|
|
5880
|
+
}
|
|
5881
|
+
// src/plugin/createImagePlugin.ts
|
|
5882
|
+
/**
|
|
5883
|
+
* createImagePlugin —— 图片优化(dev + prod 通用 endpoint)
|
|
5884
|
+
*
|
|
5885
|
+
* 工业模式(对标 next/image / @vercel/og 的图片处理路径):
|
|
5886
|
+
* - 端点 `/_/img?src=&w=&q=&fmt=`:sharp 按需 resize/compress/格式转换
|
|
5887
|
+
* - LRU 缓存 transformed buffer + ETag —— 二次命中走 304/缓存
|
|
5888
|
+
* - sharp 是必需依赖:提供 resize / 格式转换;fmt=original 显式读取安全栅格原图
|
|
5889
|
+
* - <Image> 组件(src/runtime/Image.tsx)输出 srcset,浏览器选最佳分辨率
|
|
5890
|
+
*
|
|
5891
|
+
* 安全:
|
|
5892
|
+
* - allowlist origin:默认仅允许 same-origin + 用户配置白名单(防 SSRF)
|
|
5893
|
+
* - max 输出 8192px / 输入 25MB(防 zip-bomb / OOM)
|
|
5894
|
+
*/
|
|
5895
|
+
async function loadSharp() {
|
|
5896
|
+
try {
|
|
5897
|
+
return await import(
|
|
5898
|
+
/* @vite-ignore */
|
|
5899
|
+
"sharp"
|
|
5900
|
+
);
|
|
5901
|
+
} catch {
|
|
5902
|
+
return null;
|
|
5708
5903
|
}
|
|
5709
|
-
await walk(clientDir);
|
|
5710
|
-
return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
|
|
5711
5904
|
}
|
|
5712
|
-
var
|
|
5713
|
-
"
|
|
5714
|
-
"
|
|
5715
|
-
"
|
|
5716
|
-
"
|
|
5717
|
-
"
|
|
5718
|
-
".json",
|
|
5719
|
-
".html",
|
|
5720
|
-
".htm",
|
|
5721
|
-
".svg"
|
|
5905
|
+
var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
|
|
5906
|
+
"avif",
|
|
5907
|
+
"webp",
|
|
5908
|
+
"jpeg",
|
|
5909
|
+
"jpg",
|
|
5910
|
+
"png"
|
|
5722
5911
|
]);
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
return
|
|
5912
|
+
var MAX_INPUT_BYTES = 26214400;
|
|
5913
|
+
function createImagePlugin(options = {}, dependencies = {}) {
|
|
5914
|
+
return {
|
|
5915
|
+
name: "isr-engine:image-optimization",
|
|
5916
|
+
configureServer(server) {
|
|
5917
|
+
server.middlewares.use(createImageHandler(options, () => server.config.publicDir || void 0, dependencies, () => server));
|
|
5918
|
+
},
|
|
5919
|
+
configurePreviewServer(server) {
|
|
5920
|
+
const clientDir = path.resolve(server.config.root, server.config.environments?.client?.build.outDir ?? server.config.build.outDir);
|
|
5921
|
+
server.middlewares.use(createImageHandler(options, () => clientDir, dependencies));
|
|
5922
|
+
}
|
|
5923
|
+
};
|
|
5726
5924
|
}
|
|
5727
|
-
/**
|
|
5728
|
-
|
|
5729
|
-
|
|
5730
|
-
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
|
|
5925
|
+
/** Connect middleware shared by development, preview and production. */
|
|
5926
|
+
function createImageMiddleware(options = {}, dependencies = {}, publicDir = path.resolve(process.cwd(), "public")) {
|
|
5927
|
+
return createImageHandler(options, () => publicDir, dependencies);
|
|
5928
|
+
}
|
|
5929
|
+
var ImageError = ImageSourceError;
|
|
5930
|
+
function createImageHandler(opts, getPublicDir, dependencies, getDevServer) {
|
|
5931
|
+
let sharpCapability;
|
|
5932
|
+
const endpoint = opts.path ?? "/_/img";
|
|
5933
|
+
const allow = new Set(resolveImageOptions({ remoteAllowlist: opts.remoteAllowlist }).remoteAllowlist);
|
|
5934
|
+
const cache = new LRUCache({
|
|
5935
|
+
max: Math.max(1, opts.cacheMax ?? 500),
|
|
5936
|
+
maxSize: 67108864,
|
|
5937
|
+
sizeCalculation: (entry) => entry.body.byteLength,
|
|
5938
|
+
ttl: 6e4
|
|
5939
|
+
});
|
|
5940
|
+
const defaultQ = clamp(opts.defaultQuality ?? 75, 1, 100) || 75;
|
|
5941
|
+
const maxW = clamp(opts.maxWidth ?? 4096, 1, 8192) || 4096;
|
|
5942
|
+
let active = 0;
|
|
5943
|
+
return function imageMiddleware(req, res, next) {
|
|
5944
|
+
let u;
|
|
5945
|
+
try {
|
|
5946
|
+
u = new URL(req.url ?? "", "http://x");
|
|
5947
|
+
} catch {
|
|
5948
|
+
next();
|
|
5949
|
+
return;
|
|
5950
|
+
}
|
|
5951
|
+
if (u.pathname !== endpoint) {
|
|
5952
|
+
next();
|
|
5953
|
+
return;
|
|
5954
|
+
}
|
|
5955
|
+
handle(u).catch((error) => {
|
|
5956
|
+
if (res.destroyed || res.writableEnded) return;
|
|
5957
|
+
res.statusCode = error instanceof ImageError ? error.status : 500;
|
|
5958
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
5959
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
5960
|
+
res.setHeader("cache-control", "no-store");
|
|
5961
|
+
res.end(req.method === "HEAD" ? void 0 : error instanceof ImageError ? error.message : "image processing failed");
|
|
5962
|
+
});
|
|
5963
|
+
async function handle(url) {
|
|
5964
|
+
const src = url.searchParams.get("src");
|
|
5965
|
+
if (!src) throw new ImageError(400, "missing ?src=");
|
|
5966
|
+
if (req.method && req.method !== "GET" && req.method !== "HEAD") throw new ImageError(405, "method not allowed");
|
|
5967
|
+
const wParam = url.searchParams.get("w");
|
|
5968
|
+
const w = wParam === null ? void 0 : clamp(parseInt(wParam, 10), 1, maxW) || void 0;
|
|
5969
|
+
const q = clamp(parseInt(url.searchParams.get("q") ?? String(defaultQ), 10), 1, 100) || defaultQ;
|
|
5970
|
+
const fmt = (url.searchParams.get("fmt") ?? "").toLowerCase();
|
|
5971
|
+
if (fmt && fmt !== "original" && !SUPPORTED_FORMATS.has(fmt)) throw new ImageError(400, "unsupported format");
|
|
5972
|
+
if (fmt === "original" && (wParam !== null || url.searchParams.has("q"))) throw new ImageError(400, "original mode does not accept transformations");
|
|
5973
|
+
const format = fmt || pickAuto(req.headers.accept);
|
|
5974
|
+
const key = JSON.stringify([
|
|
5975
|
+
src,
|
|
5976
|
+
w,
|
|
5977
|
+
q,
|
|
5978
|
+
format
|
|
5979
|
+
]);
|
|
5980
|
+
const cached = cache.get(key);
|
|
5981
|
+
if (cached) {
|
|
5982
|
+
sendImage(req, res, cached);
|
|
5983
|
+
return;
|
|
5743
5984
|
}
|
|
5985
|
+
if (active >= 4) throw new ImageError(503, "image processing busy");
|
|
5986
|
+
active++;
|
|
5987
|
+
try {
|
|
5988
|
+
let out;
|
|
5989
|
+
let contentType;
|
|
5990
|
+
if (format === "original") {
|
|
5991
|
+
out = await loadSource(src, allow, getPublicDir(), getDevServer?.());
|
|
5992
|
+
contentType = originalContentType(out);
|
|
5993
|
+
} else {
|
|
5994
|
+
const sharp = await (sharpCapability ??= (dependencies.loadSharp ?? loadSharp)());
|
|
5995
|
+
if (!sharp) throw new ImageError(501, "image optimizer unavailable");
|
|
5996
|
+
const input = await loadSource(src, allow, getPublicDir(), getDevServer?.());
|
|
5997
|
+
let pipe = sharp.default(input, { limitInputPixels: 4e7 }).rotate();
|
|
5998
|
+
if (w) pipe = pipe.resize({
|
|
5999
|
+
width: w,
|
|
6000
|
+
withoutEnlargement: true
|
|
6001
|
+
});
|
|
6002
|
+
out = await pipe.toFormat(format === "jpg" ? "jpeg" : format, { quality: q }).toBuffer();
|
|
6003
|
+
contentType = `image/${format === "jpg" ? "jpeg" : format}`;
|
|
6004
|
+
}
|
|
6005
|
+
if (out.byteLength > MAX_INPUT_BYTES) throw new ImageError(413, "output too large");
|
|
6006
|
+
const entry = {
|
|
6007
|
+
body: out,
|
|
6008
|
+
contentType,
|
|
6009
|
+
etag: `"${createHash("sha1").update(out).digest("hex").slice(0, 16)}"`
|
|
6010
|
+
};
|
|
6011
|
+
cache.set(key, entry);
|
|
6012
|
+
sendImage(req, res, entry);
|
|
6013
|
+
} finally {
|
|
6014
|
+
active--;
|
|
6015
|
+
}
|
|
6016
|
+
}
|
|
6017
|
+
};
|
|
6018
|
+
}
|
|
6019
|
+
function clamp(n, lo, hi) {
|
|
6020
|
+
if (!Number.isFinite(n)) return 0;
|
|
6021
|
+
return Math.max(lo, Math.min(hi, n));
|
|
6022
|
+
}
|
|
6023
|
+
/** Media range specificity takes precedence over wildcard quality (RFC 9110). */
|
|
6024
|
+
function acceptQuality(contentType, accept) {
|
|
6025
|
+
if (accept === void 0) return 1;
|
|
6026
|
+
let specificity = -1;
|
|
6027
|
+
let quality = 0;
|
|
6028
|
+
for (const range of (Array.isArray(accept) ? accept.join(",") : accept).split(",")) {
|
|
6029
|
+
const [type, ...parameters] = range.trim().toLowerCase().split(";");
|
|
6030
|
+
const rank = type === contentType ? 2 : type === "image/*" ? 1 : type === "*/*" ? 0 : -1;
|
|
6031
|
+
if (rank < 0 || rank < specificity) continue;
|
|
6032
|
+
const qText = parameters.map((p) => p.trim()).find((p) => p.startsWith("q="))?.slice(2);
|
|
6033
|
+
const q = qText === void 0 ? 1 : /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(qText) ? Number(qText) : 0;
|
|
6034
|
+
if (rank > specificity) quality = q;
|
|
6035
|
+
else quality = Math.max(quality, q);
|
|
6036
|
+
specificity = rank;
|
|
6037
|
+
}
|
|
6038
|
+
return quality;
|
|
6039
|
+
}
|
|
6040
|
+
function pickAuto(accept) {
|
|
6041
|
+
const candidates = [
|
|
6042
|
+
"jpeg",
|
|
6043
|
+
"webp",
|
|
6044
|
+
"avif"
|
|
6045
|
+
];
|
|
6046
|
+
let selected = "";
|
|
6047
|
+
let best = 0;
|
|
6048
|
+
for (const format of candidates) {
|
|
6049
|
+
const quality = acceptQuality(`image/${format}`, accept);
|
|
6050
|
+
if (quality > best) {
|
|
6051
|
+
selected = format;
|
|
6052
|
+
best = quality;
|
|
5744
6053
|
}
|
|
5745
6054
|
}
|
|
5746
|
-
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
6055
|
+
if (!selected) throw new ImageError(406, "no acceptable image format");
|
|
6056
|
+
return selected;
|
|
6057
|
+
}
|
|
6058
|
+
function completePng(input) {
|
|
6059
|
+
let offset = 8;
|
|
6060
|
+
let hasPixels = false;
|
|
6061
|
+
while (offset + 12 <= input.length) {
|
|
6062
|
+
const size = input.readUInt32BE(offset);
|
|
6063
|
+
const type = input.toString("ascii", offset + 4, offset + 8);
|
|
6064
|
+
const end = offset + 12 + size;
|
|
6065
|
+
if (end > input.length) return false;
|
|
6066
|
+
if (type === "IDAT" && size > 0) hasPixels = true;
|
|
6067
|
+
if (type === "IEND") return size === 0 && end === input.length && hasPixels;
|
|
6068
|
+
offset = end;
|
|
5754
6069
|
}
|
|
5755
|
-
return
|
|
6070
|
+
return false;
|
|
5756
6071
|
}
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
|
|
5760
|
-
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
6072
|
+
/** Only inert raster containers are served directly; never trust extensions or upstream MIME. */
|
|
6073
|
+
function originalContentType(input) {
|
|
6074
|
+
if (input.length >= 33 && input.subarray(0, 8).equals(Buffer.from([
|
|
6075
|
+
137,
|
|
6076
|
+
80,
|
|
6077
|
+
78,
|
|
6078
|
+
71,
|
|
6079
|
+
13,
|
|
6080
|
+
10,
|
|
6081
|
+
26,
|
|
6082
|
+
10
|
|
6083
|
+
])) && input.readUInt32BE(8) === 13 && input.toString("ascii", 12, 16) === "IHDR" && input.readUInt32BE(16) > 0 && input.readUInt32BE(20) > 0 && completePng(input)) return "image/png";
|
|
6084
|
+
if (input.length >= 4 && input[0] === 255 && input[1] === 216 && input[2] === 255 && input[input.length - 2] === 255 && input[input.length - 1] === 217) return "image/jpeg";
|
|
6085
|
+
if (input.length >= 14 && ["GIF87a", "GIF89a"].includes(input.toString("ascii", 0, 6)) && input.readUInt16LE(6) > 0 && input.readUInt16LE(8) > 0 && input[input.length - 1] === 59) return "image/gif";
|
|
6086
|
+
if (input.length >= 20 && input.toString("ascii", 0, 4) === "RIFF" && input.readUInt32LE(4) === input.length - 8 && input.toString("ascii", 8, 12) === "WEBP" && [
|
|
6087
|
+
"VP8 ",
|
|
6088
|
+
"VP8L",
|
|
6089
|
+
"VP8X"
|
|
6090
|
+
].includes(input.toString("ascii", 12, 16))) return "image/webp";
|
|
6091
|
+
throw new ImageError(415, "unsupported original image type");
|
|
6092
|
+
}
|
|
6093
|
+
function sendImage(req, res, entry) {
|
|
6094
|
+
res.setHeader("vary", "Accept");
|
|
6095
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
6096
|
+
if (acceptQuality(entry.contentType, req.headers.accept) <= 0) throw new ImageError(406, "image type not acceptable");
|
|
6097
|
+
res.setHeader("cache-control", "public, max-age=60, must-revalidate");
|
|
6098
|
+
res.setHeader("etag", entry.etag);
|
|
6099
|
+
if (req.headers["if-none-match"] === entry.etag) {
|
|
6100
|
+
res.statusCode = 304;
|
|
6101
|
+
res.end();
|
|
6102
|
+
return;
|
|
6103
|
+
}
|
|
6104
|
+
res.statusCode = 200;
|
|
6105
|
+
res.setHeader("content-type", entry.contentType);
|
|
6106
|
+
res.setHeader("content-length", entry.body.byteLength);
|
|
6107
|
+
res.end(req.method === "HEAD" ? void 0 : entry.body);
|
|
5772
6108
|
}
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
const deploymentFiles = await readDeploymentFiles(distDir);
|
|
5777
|
-
const files = await readHtmlFiles(path.join(distDir, "client"), true);
|
|
5778
|
-
const payload = {
|
|
5779
|
-
schemaVersion: SCHEMA_VERSION,
|
|
5780
|
-
ssgRoutes: [...new Set(ssgRoutes)].sort(),
|
|
5781
|
-
deploymentFiles,
|
|
5782
|
-
files
|
|
5783
|
-
};
|
|
5784
|
-
return {
|
|
5785
|
-
...payload,
|
|
5786
|
-
buildId: sha256(manifestPayload(payload))
|
|
5787
|
-
};
|
|
6109
|
+
function inside(root, file) {
|
|
6110
|
+
const relative = path.relative(root, file);
|
|
6111
|
+
return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
5788
6112
|
}
|
|
5789
|
-
|
|
5790
|
-
|
|
5791
|
-
|
|
5792
|
-
|
|
5793
|
-
|
|
6113
|
+
async function loadSource(src, allow, publicDir, server) {
|
|
6114
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(src) || src.startsWith("//")) {
|
|
6115
|
+
let url;
|
|
6116
|
+
try {
|
|
6117
|
+
url = new URL(src);
|
|
6118
|
+
} catch {
|
|
6119
|
+
throw new ImageError(400, "invalid source URL");
|
|
6120
|
+
}
|
|
6121
|
+
return fetchRemoteImage(url.href, allow, MAX_INPUT_BYTES);
|
|
6122
|
+
}
|
|
6123
|
+
let pathname;
|
|
5794
6124
|
try {
|
|
5795
|
-
|
|
5796
|
-
|
|
5797
|
-
|
|
5798
|
-
await fs$3.rm(temporary, { force: true });
|
|
6125
|
+
pathname = decodeURIComponent(src.split(/[?#]/, 1)[0]);
|
|
6126
|
+
} catch {
|
|
6127
|
+
throw new ImageError(400, "invalid source URL");
|
|
5799
6128
|
}
|
|
5800
|
-
|
|
5801
|
-
}
|
|
5802
|
-
function validateManifest(value) {
|
|
5803
|
-
if (!value || typeof value !== "object") throw new Error("Invalid static CSP manifest");
|
|
5804
|
-
const manifest = value;
|
|
5805
|
-
if (manifest.schemaVersion !== SCHEMA_VERSION && manifest.schemaVersion !== 2) throw new Error("Unsupported static CSP manifest schema");
|
|
5806
|
-
if (manifest.schemaVersion >= 3 && (!Array.isArray(manifest.ssgRoutes) || manifest.ssgRoutes.some((route, index) => typeof route !== "string" || !route.startsWith("/") || route.includes("?") || route.includes("#") || index > 0 && route <= manifest.ssgRoutes[index - 1]))) throw new Error("Invalid static CSP manifest SSG routes");
|
|
5807
|
-
if (manifest.ssgRoutes) assertDistinctHtmlRouteIdentities(manifest.ssgRoutes);
|
|
5808
|
-
const digest = /^[a-f0-9]{64}$/;
|
|
5809
|
-
if (!Array.isArray(manifest.deploymentFiles) || typeof manifest.buildId !== "string" || !digest.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error("Invalid static CSP manifest fields");
|
|
5810
|
-
let previous = "";
|
|
5811
|
-
for (const file of manifest.deploymentFiles) {
|
|
5812
|
-
if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || !isDeploymentPath(file.path) || typeof file.sha256 !== "string" || !digest.test(file.sha256)) throw new Error("Invalid static CSP manifest deployment entry");
|
|
5813
|
-
previous = file.path;
|
|
5814
|
-
}
|
|
5815
|
-
if (!manifest.deploymentFiles.some((file) => file.path === "rsc/index.js")) throw new Error("Static CSP manifest is missing the RSC build");
|
|
5816
|
-
previous = "";
|
|
5817
|
-
for (const file of manifest.files) {
|
|
5818
|
-
if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || file.path.includes("\\") || file.path.startsWith("/") || file.path.split("/").some((segment) => !segment || segment === "." || segment === "..") || !file.path.toLowerCase().endsWith(".html") || typeof file.sha256 !== "string" || !digest.test(file.sha256) || manifest.schemaVersion === 3 && (!Number.isSafeInteger(file.generatedAt) || file.generatedAt < 0) || !Array.isArray(file.scriptHashes) || !file.scriptHashes.every((hash) => typeof hash === "string" && /^'sha256-[A-Za-z0-9+/]{43}='$/.test(hash))) throw new Error("Invalid static CSP manifest file entry");
|
|
5819
|
-
previous = file.path;
|
|
5820
|
-
}
|
|
5821
|
-
if (sha256(manifestPayload(manifest)) !== manifest.buildId) throw new Error("Static CSP manifest integrity mismatch");
|
|
5822
|
-
}
|
|
5823
|
-
/** Missing manifests are legacy builds; present but invalid manifests always stop startup. */
|
|
5824
|
-
async function loadStaticCspManifest(distDir, options = {}) {
|
|
5825
|
-
let serialized;
|
|
5826
|
-
try {
|
|
5827
|
-
serialized = await fs$3.readFile(path.join(distDir, STATIC_CSP_MANIFEST), "utf8");
|
|
5828
|
-
} catch (error) {
|
|
5829
|
-
if (error.code !== "ENOENT") throw error;
|
|
5830
|
-
const manifest = await createManifest(distDir);
|
|
5831
|
-
options.onLegacyBuild?.();
|
|
5832
|
-
return indexManifest(manifest, true);
|
|
5833
|
-
}
|
|
5834
|
-
let manifest;
|
|
6129
|
+
if (pathname.includes("\0") || pathname.includes("\\") || pathname.split("/").includes("..")) throw new ImageError(400, "path traversal blocked");
|
|
5835
6130
|
try {
|
|
5836
|
-
|
|
6131
|
+
const root = publicDir ? await promises.realpath(publicDir).catch(() => path.resolve(publicDir)) : void 0;
|
|
6132
|
+
const resolved = root ? path.resolve(root, pathname.replace(/^\//, "")) : void 0;
|
|
6133
|
+
if (root && resolved && !inside(root, resolved)) throw new ImageError(400, "path traversal blocked");
|
|
6134
|
+
let real;
|
|
6135
|
+
try {
|
|
6136
|
+
if (!root || !resolved) throw new Error("public directory disabled");
|
|
6137
|
+
real = await promises.realpath(resolved);
|
|
6138
|
+
if (!inside(root, real)) throw new ImageError(400, "path traversal blocked");
|
|
6139
|
+
} catch (error) {
|
|
6140
|
+
if (error instanceof ImageError || !server?.config) throw error;
|
|
6141
|
+
const candidate = pathname.startsWith("/@fs/") ? path.resolve(pathname.slice(4)) : path.resolve(server.config.root, pathname.replace(/^\//, ""));
|
|
6142
|
+
if (!isFileLoadingAllowed(server.config, normalizePath(candidate))) throw new ImageError(403, "source access denied");
|
|
6143
|
+
real = await promises.realpath(candidate);
|
|
6144
|
+
if (!isFileLoadingAllowed(server.config, normalizePath(real))) throw new ImageError(403, "source access denied");
|
|
6145
|
+
}
|
|
6146
|
+
const file = await promises.open(real, "r");
|
|
6147
|
+
try {
|
|
6148
|
+
const stat = await file.stat();
|
|
6149
|
+
if (!stat.isFile()) throw new ImageError(400, "invalid source file");
|
|
6150
|
+
if (stat.size > MAX_INPUT_BYTES) throw new ImageError(413, "source too large");
|
|
6151
|
+
const buffer = Buffer.alloc(Math.min(stat.size + 1, 26214401));
|
|
6152
|
+
let size = 0;
|
|
6153
|
+
while (size < buffer.length) {
|
|
6154
|
+
const { bytesRead } = await file.read(buffer, size, buffer.length - size, null);
|
|
6155
|
+
if (!bytesRead) break;
|
|
6156
|
+
size += bytesRead;
|
|
6157
|
+
}
|
|
6158
|
+
if (size > MAX_INPUT_BYTES || size > stat.size) throw new ImageError(413, "source changed during read");
|
|
6159
|
+
return buffer.subarray(0, size);
|
|
6160
|
+
} finally {
|
|
6161
|
+
await file.close();
|
|
6162
|
+
}
|
|
5837
6163
|
} catch (error) {
|
|
5838
|
-
|
|
6164
|
+
if (error instanceof ImageError) throw error;
|
|
6165
|
+
throw new ImageError(404, "source not found");
|
|
5839
6166
|
}
|
|
5840
|
-
validateManifest(manifest);
|
|
5841
|
-
const deployed = await readDeploymentFiles(distDir);
|
|
5842
|
-
if (JSON.stringify(deployed) !== JSON.stringify(manifest.deploymentFiles)) throw new Error("Static CSP manifest does not match the deployment build");
|
|
5843
|
-
const actual = await readHtmlFiles(path.join(distDir, "client"));
|
|
5844
|
-
if (actual.length !== manifest.files.length || actual.some((file, index) => file.path !== manifest.files[index].path || file.sha256 !== manifest.files[index].sha256)) throw new Error("Static CSP manifest does not match deployed HTML files");
|
|
5845
|
-
return indexManifest(manifest, false);
|
|
5846
6167
|
}
|
|
5847
|
-
|
|
6168
|
+
// src/engine/seo/config.ts
|
|
6169
|
+
/** 默认 SEO 配置 */
|
|
6170
|
+
var DEFAULT_SEO_CONFIG = {
|
|
6171
|
+
baseUrl: "",
|
|
6172
|
+
siteName: "My App",
|
|
6173
|
+
defaultLanguage: "zh",
|
|
6174
|
+
supportedLanguages: ["zh", "en"],
|
|
6175
|
+
defaultTitle: "My App",
|
|
6176
|
+
defaultDescription: "",
|
|
6177
|
+
titleTemplate: "%s | My App",
|
|
6178
|
+
keywords: [],
|
|
6179
|
+
author: "",
|
|
6180
|
+
robots: "index,follow",
|
|
6181
|
+
sitemap: {
|
|
6182
|
+
priority: {
|
|
6183
|
+
"/": 1,
|
|
6184
|
+
"/blog/*": .7,
|
|
6185
|
+
"*": .5
|
|
6186
|
+
},
|
|
6187
|
+
changeFreq: {
|
|
6188
|
+
"/": "daily",
|
|
6189
|
+
"/blog/*": "weekly",
|
|
6190
|
+
"*": "monthly"
|
|
6191
|
+
},
|
|
6192
|
+
excludePatterns: ["/admin/*", "/api/*"],
|
|
6193
|
+
cacheTimeout: 3600
|
|
6194
|
+
},
|
|
6195
|
+
openGraph: {
|
|
6196
|
+
enabled: true,
|
|
6197
|
+
locale: "zh_CN",
|
|
6198
|
+
defaultImage: "/images/og-default.jpg"
|
|
6199
|
+
},
|
|
6200
|
+
twitter: {
|
|
6201
|
+
enabled: true,
|
|
6202
|
+
card: "summary_large_image",
|
|
6203
|
+
site: ""
|
|
6204
|
+
},
|
|
6205
|
+
structuredData: {
|
|
6206
|
+
enabled: true,
|
|
6207
|
+
organizationLogo: ""
|
|
6208
|
+
}
|
|
6209
|
+
};
|
|
6210
|
+
/** 深度合并配置 */
|
|
6211
|
+
function mergeSEOConfig(base, override) {
|
|
5848
6212
|
return {
|
|
5849
|
-
|
|
5850
|
-
|
|
5851
|
-
|
|
5852
|
-
|
|
5853
|
-
|
|
6213
|
+
...base,
|
|
6214
|
+
...override,
|
|
6215
|
+
sitemap: {
|
|
6216
|
+
...base.sitemap,
|
|
6217
|
+
...override.sitemap
|
|
6218
|
+
},
|
|
6219
|
+
openGraph: {
|
|
6220
|
+
...base.openGraph,
|
|
6221
|
+
...override.openGraph
|
|
6222
|
+
},
|
|
6223
|
+
twitter: {
|
|
6224
|
+
...base.twitter,
|
|
6225
|
+
...override.twitter
|
|
6226
|
+
},
|
|
6227
|
+
structuredData: {
|
|
6228
|
+
...base.structuredData,
|
|
6229
|
+
...override.structuredData
|
|
6230
|
+
}
|
|
5854
6231
|
};
|
|
5855
6232
|
}
|
|
5856
|
-
|
|
5857
|
-
//#region src/server/productionRuntime.ts
|
|
5858
|
-
/** Shared production application assembly. Listening and process signals belong to callers. */
|
|
5859
|
-
function safeOrigin(url) {
|
|
5860
|
-
if (!url) return void 0;
|
|
5861
|
-
try {
|
|
5862
|
-
return new URL(url).origin;
|
|
5863
|
-
} catch {
|
|
5864
|
-
return;
|
|
5865
|
-
}
|
|
5866
|
-
}
|
|
5867
|
-
/**
|
|
5868
|
-
* 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
|
|
5869
|
-
* 导出以便单测覆盖(纯函数)
|
|
5870
|
-
*/
|
|
5871
|
-
function extractRoutesForSitemap(config) {
|
|
5872
|
-
const routes = config.routes ?? {};
|
|
5873
|
-
const out = [];
|
|
5874
|
-
for (const path of Object.keys(routes)) {
|
|
5875
|
-
if (path.includes("*") || path.includes(":")) continue;
|
|
5876
|
-
if (path.startsWith("/__") || path.startsWith("/api/")) continue;
|
|
5877
|
-
out.push(path);
|
|
5878
|
-
}
|
|
5879
|
-
return out;
|
|
5880
|
-
}
|
|
6233
|
+
// src/engine/seo/SEOEngine.ts
|
|
5881
6234
|
/**
|
|
5882
|
-
*
|
|
5883
|
-
*
|
|
5884
|
-
*
|
|
6235
|
+
* SEO 引擎 - 单例模式
|
|
6236
|
+
*
|
|
6237
|
+
* 核心功能:
|
|
6238
|
+
* - Meta 标签生成
|
|
6239
|
+
* - 结构化数据(JSON-LD)生成
|
|
6240
|
+
* - 站点地图生成
|
|
6241
|
+
* - Open Graph / Twitter Cards
|
|
5885
6242
|
*/
|
|
5886
|
-
|
|
5887
|
-
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
5891
|
-
|
|
5892
|
-
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
return;
|
|
6243
|
+
var SEOEngine = class SEOEngine {
|
|
6244
|
+
static instance = null;
|
|
6245
|
+
logger = Logger.getInstance();
|
|
6246
|
+
config;
|
|
6247
|
+
initialized = false;
|
|
6248
|
+
pageDataCache = /* @__PURE__ */ new Map();
|
|
6249
|
+
sitemapCache = null;
|
|
6250
|
+
sitemapLastGenerated = 0;
|
|
6251
|
+
constructor(config) {
|
|
6252
|
+
this.config = config ? mergeSEOConfig(DEFAULT_SEO_CONFIG, config) : { ...DEFAULT_SEO_CONFIG };
|
|
5897
6253
|
}
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5902
|
-
if (sentryIntegration.dsn) process.env.SENTRY_DSN = sentryIntegration.dsn;
|
|
5903
|
-
if (sentryIntegration.tracesSampleRate !== void 0) process.env.SENTRY_TRACES_SAMPLE_RATE = String(sentryIntegration.tracesSampleRate);
|
|
5904
|
-
if (sentryIntegration.environment) process.env.SENTRY_ENVIRONMENT = sentryIntegration.environment;
|
|
5905
|
-
} else {
|
|
5906
|
-
delete process.env.SENTRY_DSN;
|
|
5907
|
-
delete process.env.SENTRY_TRACES_SAMPLE_RATE;
|
|
5908
|
-
}
|
|
5909
|
-
} else {
|
|
5910
|
-
process.env.SENTRY_ENABLED = "false";
|
|
5911
|
-
delete process.env.SENTRY_DSN;
|
|
5912
|
-
delete process.env.SENTRY_TRACES_SAMPLE_RATE;
|
|
6254
|
+
/** 获取单例实例 */
|
|
6255
|
+
static getInstance(config) {
|
|
6256
|
+
if (!SEOEngine.instance) SEOEngine.instance = new SEOEngine(config);
|
|
6257
|
+
return SEOEngine.instance;
|
|
5913
6258
|
}
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
5918
|
-
delete process.env.OTEL_SERVICE_NAME;
|
|
5919
|
-
for (const exporter of telemetry.exporters) {
|
|
5920
|
-
if (exporter.type === "datadog") {
|
|
5921
|
-
if (exporter.service) process.env.DD_SERVICE = exporter.service;
|
|
5922
|
-
if (telemetry.environment) process.env.DD_ENV = telemetry.environment;
|
|
5923
|
-
if (telemetry.release) process.env.DD_VERSION = telemetry.release;
|
|
5924
|
-
continue;
|
|
5925
|
-
}
|
|
5926
|
-
if (exporter.type === "otel") {
|
|
5927
|
-
if (exporter.endpoint) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exporter.endpoint;
|
|
5928
|
-
if (exporter.serviceName) process.env.OTEL_SERVICE_NAME = exporter.serviceName;
|
|
5929
|
-
}
|
|
6259
|
+
/** 重置实例(仅用于测试) */
|
|
6260
|
+
static resetInstance() {
|
|
6261
|
+
SEOEngine.instance = null;
|
|
5930
6262
|
}
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
await fs$3.access(rscDistEntry);
|
|
5936
|
-
await fs$3.access(clientDir);
|
|
5937
|
-
return {
|
|
5938
|
-
rscDistEntry,
|
|
5939
|
-
clientDir,
|
|
5940
|
-
staticCspIndex: await loadStaticCspManifest(path.dirname(clientDir), { onLegacyBuild: () => logger$8.warn("[CSP] 构建缺少 static-csp-manifest.json;已在启动期生成兼容索引,请重新构建以生成清单") })
|
|
5941
|
-
};
|
|
5942
|
-
}
|
|
5943
|
-
async function createProductionRuntime(config, options = {}) {
|
|
5944
|
-
const { rscDistEntry, clientDir, staticCspIndex } = options.build ?? await prepareProductionBuild(options.root);
|
|
5945
|
-
const ssgRoutes = staticCspIndex.ssgRoutes ?? (Array.isArray(config.ssg?.routes) ? config.ssg.routes : []);
|
|
5946
|
-
const ssgFiles = new Map(ssgRoutes.map((route) => [route, routeToFilePath(route)]));
|
|
5947
|
-
const ssgAliases = /* @__PURE__ */ new Map();
|
|
5948
|
-
const configuredRoutes = Object.keys(config.routes ?? {});
|
|
5949
|
-
assertDistinctHtmlRouteIdentities(configuredRoutes, { allowPatterns: true });
|
|
5950
|
-
const routeNames = /* @__PURE__ */ new Set([...ssgFiles.keys(), ...configuredRoutes.filter((route) => !isHtmlRoutePattern(route))]);
|
|
5951
|
-
assertDistinctHtmlRouteIdentities(routeNames);
|
|
5952
|
-
const declaredIdentities = new Set([...routeNames].map((route) => decodeHtmlPathname(route)));
|
|
5953
|
-
const explicitRoutes = /* @__PURE__ */ new Map();
|
|
5954
|
-
for (const route of routeNames) {
|
|
5955
|
-
const target = new URL(route, "http://localhost").pathname;
|
|
5956
|
-
explicitRoutes.set(decodeHtmlPathname(route), target);
|
|
5957
|
-
if ((route === "/" || !route.endsWith("/")) && !declaredIdentities.has(decodeHtmlPathname(route + "_.rsc"))) explicitRoutes.set(decodeHtmlPathname(route + "_.rsc"), target + "_.rsc");
|
|
6263
|
+
/** 更新配置 */
|
|
6264
|
+
updateConfig(config) {
|
|
6265
|
+
this.config = mergeSEOConfig(this.config, config);
|
|
6266
|
+
this.clearCache();
|
|
5958
6267
|
}
|
|
5959
|
-
|
|
5960
|
-
|
|
5961
|
-
|
|
5962
|
-
const base = logical.replace(/\/$/, "") || "/";
|
|
5963
|
-
for (const alias of [
|
|
5964
|
-
logical,
|
|
5965
|
-
base,
|
|
5966
|
-
base === "/" ? "/" : base + "/",
|
|
5967
|
-
base === "/" ? "/index.html" : base + "/index.html",
|
|
5968
|
-
"/" + file
|
|
5969
|
-
]) {
|
|
5970
|
-
ssgAliases.set(alias, target);
|
|
5971
|
-
ssgAliases.set(alias + "_.rsc", target + "_.rsc");
|
|
5972
|
-
}
|
|
6268
|
+
/** 获取当前配置 */
|
|
6269
|
+
getConfig() {
|
|
6270
|
+
return this.config;
|
|
5973
6271
|
}
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
pathToFileURL(rscDistEntry).href
|
|
5995
|
-
));
|
|
5996
|
-
const extraConnectSrc = Array.from(new Set([runtime?.services?.api, runtime?.services?.telemetry].map(safeOrigin).filter((origin) => !!origin)));
|
|
5997
|
-
const app = express();
|
|
5998
|
-
app.disable("x-powered-by");
|
|
5999
|
-
app.set("trust proxy", config.server.trustProxy ?? false);
|
|
6000
|
-
app.use(createProductionJsonMiddleware());
|
|
6001
|
-
const opsConfig = resolveOpsConfig(config, "production");
|
|
6002
|
-
for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
|
|
6003
|
-
const { createSecurityMiddleware, createCompressionMiddleware, createCspNonceMiddleware } = await Promise.resolve().then(() => middleware_exports);
|
|
6004
|
-
app.use(createCspNonceMiddleware());
|
|
6005
|
-
app.use(createSecurityMiddleware(false, extraConnectSrc));
|
|
6006
|
-
app.use(createCompressionMiddleware());
|
|
6007
|
-
if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
|
|
6008
|
-
const { requestContext } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
|
|
6009
|
-
const { createServerRequestContext, applyAnonCookie } = await Promise.resolve().then(() => createServerRequestContext_exports);
|
|
6010
|
-
const cookieDomain = runtime?.cookieDomain;
|
|
6011
|
-
app.use((req, res, next) => {
|
|
6012
|
-
const { data, needsAnonCookie } = createServerRequestContext(req);
|
|
6013
|
-
if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
|
|
6014
|
-
requestContext.run(data, () => next());
|
|
6015
|
-
});
|
|
6016
|
-
if (runtime?.i18n?.prefixDefault) {
|
|
6017
|
-
const { createLocaleRedirectMiddleware } = await Promise.resolve().then(() => LocaleRedirect_exports);
|
|
6018
|
-
const { resolveI18nConfig } = await import("./i18n-CnXYAgQE.js").then((n) => n.t);
|
|
6019
|
-
const middleware = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(runtime.i18n) });
|
|
6020
|
-
if (middleware) {
|
|
6021
|
-
app.use(middleware);
|
|
6022
|
-
logger$8.info(`🌐 Locale redirect 已启用 (prefixDefault=true)`);
|
|
6023
|
-
}
|
|
6024
|
-
}
|
|
6025
|
-
const hasStaticExps = runtime?.experiments && Object.keys(runtime.experiments).length > 0;
|
|
6026
|
-
const hasManifest = !!runtime?.experimentManifest?.endpoint;
|
|
6027
|
-
let manifestLoader;
|
|
6028
|
-
let exposureQueue;
|
|
6029
|
-
if (hasStaticExps || hasManifest) {
|
|
6030
|
-
const baseOrigin = runtime?.services?.api;
|
|
6031
|
-
const { createABVariantMiddleware } = await Promise.resolve().then(() => ABVariantMiddleware_exports);
|
|
6032
|
-
const { resolveManifestLoader } = await Promise.resolve().then(() => ManifestLoader_exports);
|
|
6033
|
-
const { resolveExposureQueue } = await Promise.resolve().then(() => ExposureQueue_exports);
|
|
6034
|
-
manifestLoader = resolveManifestLoader(runtime?.experimentManifest, runtime?.experiments ?? {}, baseOrigin);
|
|
6035
|
-
if (manifestLoader) {
|
|
6036
|
-
cleanups.push(() => manifestLoader?.destroy());
|
|
6037
|
-
await manifestLoader.init();
|
|
6272
|
+
/** 初始化 */
|
|
6273
|
+
async initialize() {
|
|
6274
|
+
if (this.initialized) return;
|
|
6275
|
+
this.logger.info("🎯 初始化 SEO 引擎...");
|
|
6276
|
+
this.initialized = true;
|
|
6277
|
+
this.logger.info("✅ SEO 引擎初始化完成");
|
|
6278
|
+
}
|
|
6279
|
+
/** 优化页面 SEO */
|
|
6280
|
+
async optimizePage(url, context, result) {
|
|
6281
|
+
const pageData = this.getOrCreatePageData(url, context);
|
|
6282
|
+
const seoTags = this.generateAllTags(pageData);
|
|
6283
|
+
const structuredData = this.generateStructuredData(pageData);
|
|
6284
|
+
const html = this.insertSEOTags(result.html, seoTags, structuredData);
|
|
6285
|
+
return {
|
|
6286
|
+
...result,
|
|
6287
|
+
html,
|
|
6288
|
+
seoScore: this.calculateScore(pageData),
|
|
6289
|
+
meta: {
|
|
6290
|
+
...result.meta,
|
|
6291
|
+
seoOptimized: true
|
|
6038
6292
|
}
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
|
|
6047
|
-
|
|
6048
|
-
|
|
6049
|
-
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
|
|
6056
|
-
res.json({
|
|
6057
|
-
status: "healthy",
|
|
6058
|
-
version: package_default.version,
|
|
6059
|
-
mode: "plugin-rsc-production",
|
|
6060
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6293
|
+
};
|
|
6294
|
+
}
|
|
6295
|
+
/** 生成站点地图 */
|
|
6296
|
+
async generateSitemap(routes) {
|
|
6297
|
+
const now = Date.now();
|
|
6298
|
+
if (this.sitemapCache && now - this.sitemapLastGenerated < this.config.sitemap.cacheTimeout * 1e3) return this.sitemapCache;
|
|
6299
|
+
if (!this.config.baseUrl) throw new Error("SEO baseUrl 未配置,无法生成 sitemap。请设置 ssr.config.ts runtime.site。");
|
|
6300
|
+
const sitemap = new SitemapStream({ hostname: this.config.baseUrl });
|
|
6301
|
+
const urls = routes || Array.from(this.pageDataCache.keys());
|
|
6302
|
+
const finalUrls = urls.length > 0 ? urls : ["/"];
|
|
6303
|
+
for (const url of finalUrls) {
|
|
6304
|
+
if (this.shouldExcludeUrl(url)) continue;
|
|
6305
|
+
sitemap.write({
|
|
6306
|
+
url,
|
|
6307
|
+
priority: this.getUrlPriority(url),
|
|
6308
|
+
changefreq: this.getUrlChangeFreq(url),
|
|
6309
|
+
lastmod: (/* @__PURE__ */ new Date()).toISOString()
|
|
6061
6310
|
});
|
|
6062
|
-
});
|
|
6063
|
-
options.setupRoutes?.(app);
|
|
6064
|
-
const staticHtmlLimiter = createRequestLimiter("staticHtml", config.server.requestLimits?.staticHtml);
|
|
6065
|
-
const seoLimiter = createRequestLimiter("seo", config.server.requestLimits?.seo);
|
|
6066
|
-
app.use((req, res, next) => {
|
|
6067
|
-
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
6068
|
-
let pathname;
|
|
6069
|
-
try {
|
|
6070
|
-
pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
|
|
6071
|
-
} catch {
|
|
6072
|
-
res.status(400).end();
|
|
6073
|
-
return;
|
|
6074
|
-
}
|
|
6075
|
-
if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
|
|
6076
|
-
next();
|
|
6077
|
-
});
|
|
6078
|
-
app.use(createStaticAssetMiddleware(clientDir));
|
|
6079
|
-
app.use("/assets", (_req, res) => {
|
|
6080
|
-
res.status(404).set("Cache-Control", "no-store").end();
|
|
6081
|
-
});
|
|
6082
|
-
const { createImageMiddleware } = await import("./createImagePlugin-QNvY9vPB.js").then((n) => n.r);
|
|
6083
|
-
const { resolveImageOptions } = await Promise.resolve().then(() => resolveImageOptions_exports);
|
|
6084
|
-
app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
|
|
6085
|
-
const { createAutoCacheStore } = await Promise.resolve().then(() => createAutoCacheStore_exports);
|
|
6086
|
-
const { RedisInvalidationBus } = await Promise.resolve().then(() => RedisInvalidationBus_exports);
|
|
6087
|
-
const { hasRuntimeRedisConnection, resolveRuntimeRedisConfig } = await Promise.resolve().then(() => resolveRuntimeRedis_exports);
|
|
6088
|
-
const redisCfg = resolveRuntimeRedisConfig(runtime?.redis);
|
|
6089
|
-
const hasRedisConfig = hasRuntimeRedisConnection(runtime?.redis);
|
|
6090
|
-
const cacheRoutes = { ...config.routes };
|
|
6091
|
-
for (const route of ssgRoutes) {
|
|
6092
|
-
const rule = cacheRoutes[route];
|
|
6093
|
-
cacheRoutes[route] = typeof rule === "object" ? {
|
|
6094
|
-
...rule,
|
|
6095
|
-
mode: "ssg"
|
|
6096
|
-
} : "ssg";
|
|
6097
|
-
}
|
|
6098
|
-
const cache = createIsrCacheHandler({
|
|
6099
|
-
...config,
|
|
6100
|
-
routes: cacheRoutes
|
|
6101
|
-
}, {
|
|
6102
|
-
buildId: process.env.APP_VERSION ?? staticCspIndex.buildId,
|
|
6103
|
-
resolveInvalidationPath: resolveSsgIdentity,
|
|
6104
|
-
staticSeedAdmission: (req, res) => admitRequest(staticHtmlLimiter, req, res),
|
|
6105
|
-
staticSeedInfo: (pathname) => {
|
|
6106
|
-
const htmlPath = ssgFiles.get(pathname);
|
|
6107
|
-
if (!htmlPath) return;
|
|
6108
|
-
const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
|
|
6109
|
-
return generatedAt === void 0 || generatedAt > Date.now() ? void 0 : { generatedAt };
|
|
6110
|
-
},
|
|
6111
|
-
staticSeed: async (pathname, policy) => {
|
|
6112
|
-
const htmlPath = ssgFiles.get(pathname);
|
|
6113
|
-
if (!htmlPath) return;
|
|
6114
|
-
const hashes = staticCspIndex.scriptHashes.get(htmlPath);
|
|
6115
|
-
if (!hashes) return;
|
|
6116
|
-
const absolute = path.join(clientDir, htmlPath);
|
|
6117
|
-
const body = await fs$3.readFile(absolute);
|
|
6118
|
-
const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
|
|
6119
|
-
if (generatedAt === void 0) return;
|
|
6120
|
-
return {
|
|
6121
|
-
body,
|
|
6122
|
-
statusCode: 200,
|
|
6123
|
-
contentType: "text/html; charset=utf-8",
|
|
6124
|
-
headers: {
|
|
6125
|
-
"content-type": "text/html; charset=utf-8",
|
|
6126
|
-
"content-security-policy": applyStaticScriptPolicy(policy, hashes),
|
|
6127
|
-
"cache-control": "no-cache",
|
|
6128
|
-
"x-served-by": "ssg-static"
|
|
6129
|
-
},
|
|
6130
|
-
storedAt: generatedAt,
|
|
6131
|
-
expiresAt: 0,
|
|
6132
|
-
hardExpiresAt: 0,
|
|
6133
|
-
tags: []
|
|
6134
|
-
};
|
|
6135
|
-
},
|
|
6136
|
-
store: createAutoCacheStore({
|
|
6137
|
-
responseNamespace: `production:${process.env.ISR_CACHE_NAMESPACE ?? "default"}`,
|
|
6138
|
-
redisUrl: redisCfg?.url,
|
|
6139
|
-
redisHost: redisCfg?.host,
|
|
6140
|
-
redisPort: redisCfg?.port,
|
|
6141
|
-
redisPassword: redisCfg?.password,
|
|
6142
|
-
redisKeyPrefix: redisCfg?.keyPrefix
|
|
6143
|
-
}),
|
|
6144
|
-
invalidationBus: hasRedisConfig ? new RedisInvalidationBus({
|
|
6145
|
-
url: redisCfg?.url,
|
|
6146
|
-
host: redisCfg?.host,
|
|
6147
|
-
port: redisCfg?.port,
|
|
6148
|
-
password: redisCfg?.password,
|
|
6149
|
-
keyPrefix: redisCfg?.keyPrefix,
|
|
6150
|
-
channel: redisCfg?.invalidationChannel
|
|
6151
|
-
}) : void 0
|
|
6152
|
-
});
|
|
6153
|
-
cleanups.push(() => cache.destroy());
|
|
6154
|
-
if (opsConfig.inventory.enabled) {
|
|
6155
|
-
const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-GgzKVkq2.js");
|
|
6156
|
-
app.use(createCacheInspectorMiddleware(cache, opsConfig));
|
|
6157
|
-
logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
|
|
6158
6311
|
}
|
|
6159
|
-
|
|
6160
|
-
|
|
6161
|
-
|
|
6162
|
-
|
|
6163
|
-
|
|
6164
|
-
|
|
6165
|
-
|
|
6166
|
-
|
|
6167
|
-
|
|
6168
|
-
|
|
6169
|
-
|
|
6170
|
-
|
|
6171
|
-
|
|
6172
|
-
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6176
|
-
|
|
6177
|
-
|
|
6178
|
-
|
|
6179
|
-
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
|
|
6185
|
-
|
|
6186
|
-
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
const
|
|
6190
|
-
|
|
6191
|
-
const
|
|
6192
|
-
const
|
|
6193
|
-
|
|
6194
|
-
|
|
6195
|
-
|
|
6196
|
-
|
|
6197
|
-
|
|
6198
|
-
|
|
6199
|
-
|
|
6200
|
-
|
|
6201
|
-
} catch (err) {
|
|
6202
|
-
res.status(500).type("text/plain").end(`sitemap error: ${String(err)}`);
|
|
6203
|
-
}
|
|
6204
|
-
});
|
|
6205
|
-
app.get("/robots.txt", (_req, res) => {
|
|
6206
|
-
res.set("content-type", "text/plain; charset=utf-8");
|
|
6207
|
-
res.set("cache-control", "public, max-age=3600");
|
|
6208
|
-
res.end(seo.generateRobotsTxt());
|
|
6209
|
-
});
|
|
6210
|
-
const { renderError500Html } = await import("./error500-template-DhaZzLOB.js");
|
|
6211
|
-
const { getTraceId } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
|
|
6212
|
-
app.all(/.*/, createProductionRequestHandler(rscHandler, (err, _req, res) => {
|
|
6213
|
-
logger$8.error("[Server]", "请求处理异常", err);
|
|
6214
|
-
if (!res.headersSent) {
|
|
6215
|
-
const traceId = getTraceId();
|
|
6216
|
-
res.status(500).type("text/html; charset=utf-8").send(renderError500Html(traceId));
|
|
6217
|
-
} else res.destroy();
|
|
6218
|
-
}));
|
|
6219
|
-
return {
|
|
6220
|
-
app,
|
|
6221
|
-
close
|
|
6312
|
+
sitemap.end();
|
|
6313
|
+
this.sitemapCache = (await streamToPromise(sitemap)).toString();
|
|
6314
|
+
this.sitemapLastGenerated = now;
|
|
6315
|
+
this.logger.info(`✅ 站点地图已生成: ${urls.length} 个页面`);
|
|
6316
|
+
return this.sitemapCache;
|
|
6317
|
+
}
|
|
6318
|
+
/** 生成 Robots.txt */
|
|
6319
|
+
generateRobotsTxt() {
|
|
6320
|
+
return [
|
|
6321
|
+
"User-agent: *",
|
|
6322
|
+
"Allow: /",
|
|
6323
|
+
"",
|
|
6324
|
+
...this.config.sitemap.excludePatterns.map((p) => `Disallow: ${p}`),
|
|
6325
|
+
"",
|
|
6326
|
+
`Sitemap: ${this.config.baseUrl}/sitemap.xml`
|
|
6327
|
+
].join("\n");
|
|
6328
|
+
}
|
|
6329
|
+
/** 清理缓存 */
|
|
6330
|
+
clearCache() {
|
|
6331
|
+
this.pageDataCache.clear();
|
|
6332
|
+
this.sitemapCache = null;
|
|
6333
|
+
this.sitemapLastGenerated = 0;
|
|
6334
|
+
}
|
|
6335
|
+
/** 关闭引擎 */
|
|
6336
|
+
async shutdown() {
|
|
6337
|
+
this.clearCache();
|
|
6338
|
+
this.initialized = false;
|
|
6339
|
+
this.logger.debug("✅ SEO 引擎已关闭");
|
|
6340
|
+
}
|
|
6341
|
+
getOrCreatePageData(url, context) {
|
|
6342
|
+
const cached = this.pageDataCache.get(url);
|
|
6343
|
+
if (cached) return cached;
|
|
6344
|
+
const pageType = this.detectPageType(url);
|
|
6345
|
+
const pageData = {
|
|
6346
|
+
url: `${this.config.baseUrl}${url}`,
|
|
6347
|
+
title: this.generateTitle(url),
|
|
6348
|
+
description: this.generateDescription(url, pageType),
|
|
6349
|
+
keywords: [...this.config.keywords, ...this.extractKeywordsFromUrl(url)],
|
|
6350
|
+
image: this.config.openGraph.defaultImage,
|
|
6351
|
+
type: pageType,
|
|
6352
|
+
language: this.detectLanguage(url, context),
|
|
6353
|
+
modifiedTime: (/* @__PURE__ */ new Date()).toISOString()
|
|
6222
6354
|
};
|
|
6223
|
-
|
|
6224
|
-
|
|
6225
|
-
throw error;
|
|
6355
|
+
this.pageDataCache.set(url, pageData);
|
|
6356
|
+
return pageData;
|
|
6226
6357
|
}
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
|
|
6232
|
-
|
|
6233
|
-
|
|
6358
|
+
generateAllTags(pageData) {
|
|
6359
|
+
const tags = [];
|
|
6360
|
+
tags.push(`<title>${pageData.title}</title>`);
|
|
6361
|
+
tags.push(`<meta name="description" content="${pageData.description}">`);
|
|
6362
|
+
if (pageData.keywords?.length) tags.push(`<meta name="keywords" content="${pageData.keywords.join(", ")}">`);
|
|
6363
|
+
tags.push(`<meta name="author" content="${this.config.author}">`);
|
|
6364
|
+
tags.push(`<meta name="robots" content="${this.config.robots}">`);
|
|
6365
|
+
tags.push(`<link rel="canonical" href="${pageData.url}">`);
|
|
6366
|
+
if (this.config.openGraph.enabled) {
|
|
6367
|
+
tags.push(`<meta property="og:title" content="${pageData.title}">`);
|
|
6368
|
+
tags.push(`<meta property="og:description" content="${pageData.description}">`);
|
|
6369
|
+
tags.push(`<meta property="og:type" content="${pageData.type}">`);
|
|
6370
|
+
tags.push(`<meta property="og:url" content="${pageData.url}">`);
|
|
6371
|
+
tags.push(`<meta property="og:site_name" content="${this.config.siteName}">`);
|
|
6372
|
+
tags.push(`<meta property="og:locale" content="${this.config.openGraph.locale}">`);
|
|
6373
|
+
if (pageData.image) tags.push(`<meta property="og:image" content="${pageData.image}">`);
|
|
6234
6374
|
}
|
|
6235
|
-
|
|
6236
|
-
}
|
|
6237
|
-
|
|
6238
|
-
|
|
6239
|
-
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
|
|
6243
|
-
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
const
|
|
6247
|
-
|
|
6248
|
-
|
|
6249
|
-
|
|
6250
|
-
|
|
6251
|
-
|
|
6252
|
-
|
|
6253
|
-
|
|
6254
|
-
|
|
6255
|
-
|
|
6256
|
-
|
|
6257
|
-
|
|
6258
|
-
|
|
6259
|
-
|
|
6260
|
-
|
|
6261
|
-
|
|
6262
|
-
|
|
6263
|
-
|
|
6375
|
+
if (this.config.twitter.enabled) {
|
|
6376
|
+
tags.push(`<meta name="twitter:card" content="${this.config.twitter.card}">`);
|
|
6377
|
+
tags.push(`<meta name="twitter:site" content="${this.config.twitter.site}">`);
|
|
6378
|
+
tags.push(`<meta name="twitter:title" content="${pageData.title}">`);
|
|
6379
|
+
tags.push(`<meta name="twitter:description" content="${pageData.description}">`);
|
|
6380
|
+
if (pageData.image) tags.push(`<meta name="twitter:image" content="${pageData.image}">`);
|
|
6381
|
+
}
|
|
6382
|
+
return tags.join("\n ");
|
|
6383
|
+
}
|
|
6384
|
+
generateStructuredData(pageData) {
|
|
6385
|
+
if (!this.config.structuredData.enabled) return "";
|
|
6386
|
+
const data = [{
|
|
6387
|
+
"@context": "https://schema.org",
|
|
6388
|
+
"@type": "WebSite",
|
|
6389
|
+
name: this.config.siteName,
|
|
6390
|
+
url: this.config.baseUrl
|
|
6391
|
+
}, {
|
|
6392
|
+
"@context": "https://schema.org",
|
|
6393
|
+
"@type": "Organization",
|
|
6394
|
+
name: this.config.siteName,
|
|
6395
|
+
url: this.config.baseUrl,
|
|
6396
|
+
logo: this.config.structuredData.organizationLogo
|
|
6397
|
+
}];
|
|
6398
|
+
if (pageData.type === "article") data.push({
|
|
6399
|
+
"@context": "https://schema.org",
|
|
6400
|
+
"@type": "Article",
|
|
6401
|
+
headline: pageData.title,
|
|
6402
|
+
description: pageData.description,
|
|
6403
|
+
url: pageData.url,
|
|
6404
|
+
dateModified: pageData.modifiedTime,
|
|
6405
|
+
author: {
|
|
6406
|
+
"@type": "Person",
|
|
6407
|
+
name: pageData.author || this.config.author
|
|
6264
6408
|
}
|
|
6265
|
-
|
|
6266
|
-
|
|
6267
|
-
if (!controller.signal.aborted) onError(error, req, res);
|
|
6268
|
-
} finally {
|
|
6269
|
-
if (controller.signal.aborted || res.writableFinished) cleanup();
|
|
6270
|
-
}
|
|
6271
|
-
};
|
|
6272
|
-
}
|
|
6273
|
-
function nodeToWebRequest(req, signal) {
|
|
6274
|
-
const host = String(req.headers.host || "localhost");
|
|
6275
|
-
const transport = req.socket?.encrypted ? "https" : "http";
|
|
6276
|
-
const selected = req.protocol?.toLowerCase();
|
|
6277
|
-
const url = `${selected === "https" || selected === "http" ? selected : transport}://${host}${req.url}`;
|
|
6278
|
-
const headers = new Headers();
|
|
6279
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
6280
|
-
if (v == null) continue;
|
|
6281
|
-
if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
|
|
6282
|
-
else headers.set(k, String(v));
|
|
6409
|
+
});
|
|
6410
|
+
return `<script type="application/ld+json">${JSON.stringify(data)}<\/script>`;
|
|
6283
6411
|
}
|
|
6284
|
-
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
signal
|
|
6289
|
-
};
|
|
6290
|
-
if (method !== "GET" && method !== "HEAD") {
|
|
6291
|
-
init.body = rawRequestBodies.get(req) ?? Readable.toWeb(req);
|
|
6292
|
-
init.duplex = "half";
|
|
6412
|
+
insertSEOTags(html, seoTags, structuredData) {
|
|
6413
|
+
const headEndIndex = html.indexOf("</head>");
|
|
6414
|
+
if (headEndIndex === -1) return html;
|
|
6415
|
+
return html.slice(0, headEndIndex) + " " + seoTags + "\n " + structuredData + "\n" + html.slice(headEndIndex);
|
|
6293
6416
|
}
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
if (
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
const existing = res.getHeader?.("set-cookie");
|
|
6305
|
-
res.setHeader("set-cookie", [...existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)], ...cookies]);
|
|
6417
|
+
calculateScore(pageData) {
|
|
6418
|
+
let score = 0;
|
|
6419
|
+
if (pageData.title && pageData.title.length >= 30 && pageData.title.length <= 60) score += 25;
|
|
6420
|
+
else if (pageData.title) score += 15;
|
|
6421
|
+
if (pageData.description && pageData.description.length >= 100) score += 25;
|
|
6422
|
+
else if (pageData.description) score += 15;
|
|
6423
|
+
if (pageData.keywords && pageData.keywords.length >= 3) score += 20;
|
|
6424
|
+
if (pageData.image) score += 15;
|
|
6425
|
+
if (this.config.structuredData.enabled) score += 15;
|
|
6426
|
+
return Math.min(score, 100);
|
|
6306
6427
|
}
|
|
6307
|
-
|
|
6308
|
-
|
|
6309
|
-
return;
|
|
6428
|
+
detectPageType(url) {
|
|
6429
|
+
if (url.includes("/blog/") || url.includes("/article/")) return "article";
|
|
6430
|
+
if (url.includes("/product/") || url.includes("/shop/")) return "product";
|
|
6431
|
+
return "website";
|
|
6310
6432
|
}
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
const
|
|
6314
|
-
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
}
|
|
6322
|
-
|
|
6323
|
-
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6328
|
-
|
|
6329
|
-
|
|
6330
|
-
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6335
|
-
|
|
6336
|
-
|
|
6337
|
-
|
|
6338
|
-
|
|
6339
|
-
|
|
6340
|
-
|
|
6341
|
-
}
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
|
|
6346
|
-
guarded.use((req, res, next) => {
|
|
6347
|
-
const target = targets.get(req);
|
|
6348
|
-
targets.delete(req);
|
|
6349
|
-
if (!target) return next();
|
|
6350
|
-
res.setHeader("Content-Security-Policy", applyStaticScriptPolicy(String(res.getHeader("Content-Security-Policy") ?? "default-src 'self'"), target.hashes));
|
|
6351
|
-
res.setHeader("Cache-Control", "public, max-age=3600");
|
|
6352
|
-
res.setHeader("X-Served-By", "ssg-static");
|
|
6353
|
-
res.sendFile(target.htmlPath, {
|
|
6354
|
-
root: clientDir,
|
|
6355
|
-
maxAge: "1h",
|
|
6356
|
-
dotfiles: "ignore"
|
|
6357
|
-
}, (error) => {
|
|
6358
|
-
if (error) next(error);
|
|
6359
|
-
});
|
|
6360
|
-
});
|
|
6361
|
-
return (req, res, next) => {
|
|
6362
|
-
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
6363
|
-
let pathname;
|
|
6364
|
-
try {
|
|
6365
|
-
pathname = decodeHtmlPathname(req.path);
|
|
6366
|
-
} catch {
|
|
6367
|
-
res.status(400).end();
|
|
6368
|
-
return;
|
|
6369
|
-
}
|
|
6370
|
-
const relative = pathname.slice(1);
|
|
6371
|
-
const htmlPath = relative.endsWith("/") || !relative ? relative + "index.html" : relative.toLowerCase().endsWith(".html") ? relative : relative + "/index.html";
|
|
6372
|
-
const hashes = index.scriptHashes.get(htmlPath);
|
|
6373
|
-
if (!hashes) return next();
|
|
6374
|
-
targets.set(req, {
|
|
6375
|
-
htmlPath,
|
|
6376
|
-
hashes
|
|
6377
|
-
});
|
|
6378
|
-
guarded(req, res, next);
|
|
6379
|
-
};
|
|
6380
|
-
}
|
|
6381
|
-
/** Asset serving must never discover HTML outside the validated build manifest. */
|
|
6382
|
-
function normalizeStaticAssetPathname(pathname) {
|
|
6383
|
-
return path.posix.normalize(decodeURIComponent(new URL(`http://localhost${pathname}`).pathname).replaceAll("\\", "/"));
|
|
6384
|
-
}
|
|
6385
|
-
function createStaticAssetMiddleware(clientDir) {
|
|
6386
|
-
const assets = express.static(clientDir, {
|
|
6387
|
-
index: false,
|
|
6388
|
-
redirect: false,
|
|
6389
|
-
maxAge: "1h",
|
|
6390
|
-
fallthrough: true,
|
|
6391
|
-
setHeaders: (res, filePath) => {
|
|
6392
|
-
if (filePath.includes(`${path.sep}assets${path.sep}`)) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
6393
|
-
else if (/\.(jpe?g|png|webp|avif|gif|svg|ico|woff2?)$/i.test(filePath)) res.setHeader("Cache-Control", "public, max-age=604800, stale-while-revalidate=86400");
|
|
6394
|
-
}
|
|
6395
|
-
});
|
|
6396
|
-
return (req, res, next) => {
|
|
6397
|
-
let pathname;
|
|
6398
|
-
try {
|
|
6399
|
-
pathname = normalizeStaticAssetPathname(req.path);
|
|
6400
|
-
} catch {
|
|
6401
|
-
res.status(400).end();
|
|
6402
|
-
return;
|
|
6403
|
-
}
|
|
6404
|
-
if ([".html", ".htm"].includes(path.posix.extname(pathname).toLowerCase())) return next();
|
|
6405
|
-
assets(req, res, next);
|
|
6406
|
-
};
|
|
6433
|
+
generateTitle(url) {
|
|
6434
|
+
if (url === "/") return this.config.defaultTitle;
|
|
6435
|
+
const title = url.split("/").filter(Boolean).map((s) => s.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())).join(" - ");
|
|
6436
|
+
return this.config.titleTemplate.replace("%s", title);
|
|
6437
|
+
}
|
|
6438
|
+
generateDescription(url, pageType) {
|
|
6439
|
+
if (url === "/") return this.config.defaultDescription;
|
|
6440
|
+
const topic = url.split("/").pop()?.replace(/-/g, " ") || "";
|
|
6441
|
+
if (pageType === "article") return `阅读关于 ${topic} 的最新文章。`;
|
|
6442
|
+
if (pageType === "product") return `探索 ${topic} 的详细信息。`;
|
|
6443
|
+
return `了解更多关于 ${topic} 的内容。`;
|
|
6444
|
+
}
|
|
6445
|
+
extractKeywordsFromUrl(url) {
|
|
6446
|
+
return url.split("/").filter(Boolean).flatMap((s) => s.split("-"));
|
|
6447
|
+
}
|
|
6448
|
+
detectLanguage(url, _context) {
|
|
6449
|
+
const pathLang = url.split("/")[1];
|
|
6450
|
+
if (this.config.supportedLanguages.includes(pathLang)) return pathLang;
|
|
6451
|
+
return this.config.defaultLanguage;
|
|
6452
|
+
}
|
|
6453
|
+
shouldExcludeUrl(url) {
|
|
6454
|
+
return this.config.sitemap.excludePatterns.some((pattern) => new RegExp(pattern.replace(/\*/g, ".*")).test(url));
|
|
6455
|
+
}
|
|
6456
|
+
getUrlPriority(url) {
|
|
6457
|
+
for (const [pattern, priority] of Object.entries(this.config.sitemap.priority)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return priority;
|
|
6458
|
+
return .5;
|
|
6459
|
+
}
|
|
6460
|
+
getUrlChangeFreq(url) {
|
|
6461
|
+
for (const [pattern, freq] of Object.entries(this.config.sitemap.changeFreq)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return freq;
|
|
6462
|
+
return "monthly";
|
|
6463
|
+
}
|
|
6464
|
+
};
|
|
6465
|
+
/** 创建 SEO 引擎实例(获取单例) */
|
|
6466
|
+
function createSEOEngine(config) {
|
|
6467
|
+
return SEOEngine.getInstance(config);
|
|
6407
6468
|
}
|
|
6408
|
-
|
|
6409
|
-
//#region src/server/httpServer.ts
|
|
6469
|
+
// src/engine/seo/resolveSeoConfig.ts
|
|
6410
6470
|
/**
|
|
6411
|
-
*
|
|
6412
|
-
*
|
|
6413
|
-
* Node origin 只启动 HTTP/1.1。
|
|
6471
|
+
* SEO 配置解析器 —— 唯一的 baseUrl 解析入口
|
|
6414
6472
|
*
|
|
6415
|
-
*
|
|
6416
|
-
*
|
|
6473
|
+
* 设计目标:
|
|
6474
|
+
* - SEO 是 SSR/ISR 基础能力,始终启用,不暴露 enabled/sitemap/robots 开关
|
|
6475
|
+
* - 用户在 ssr.config.ts 里只关心 prod 域名是什么
|
|
6476
|
+
* - prod 只读 runtime.site,避免 SEO baseUrl 变成隐藏环境变量
|
|
6477
|
+
* - dev 自动用 localhost,降低本地启动成本
|
|
6417
6478
|
*/
|
|
6418
6479
|
var logger$4 = Logger.getInstance();
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
|
|
6425
|
-
|
|
6426
|
-
|
|
6427
|
-
|
|
6428
|
-
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
6432
|
-
|
|
6433
|
-
|
|
6434
|
-
|
|
6435
|
-
server.__shutdownTimeoutMs = DEFAULT_TIMEOUTS.shutdownTimeoutMs;
|
|
6436
|
-
}
|
|
6437
|
-
function getServerAddress(server) {
|
|
6438
|
-
const addr = server.address();
|
|
6439
|
-
if (addr && typeof addr === "object") {
|
|
6440
|
-
const info = addr;
|
|
6441
|
-
return {
|
|
6442
|
-
address: info.address,
|
|
6443
|
-
port: info.port
|
|
6444
|
-
};
|
|
6480
|
+
/**
|
|
6481
|
+
* 按以下顺序解析 baseUrl:
|
|
6482
|
+
* 1. runtime.site
|
|
6483
|
+
* 2. dev 模式:`http://localhost:${server.port||3000}`
|
|
6484
|
+
* 3. prod 且未配置:返回空串(SEOEngine 在调用 generateSitemap 时报错给出修复提示)
|
|
6485
|
+
*/
|
|
6486
|
+
function resolveSeoConfig(config) {
|
|
6487
|
+
let baseUrl = "";
|
|
6488
|
+
let source = "unset";
|
|
6489
|
+
if (config.runtime?.site) {
|
|
6490
|
+
baseUrl = config.runtime.site;
|
|
6491
|
+
source = "runtime.site";
|
|
6492
|
+
} else if (isDev()) {
|
|
6493
|
+
const envPort = process.env.PORT ? Number(process.env.PORT) : NaN;
|
|
6494
|
+
baseUrl = `http://localhost:${config.server?.port ?? (Number.isFinite(envPort) ? envPort : 3e3)}`;
|
|
6495
|
+
source = "dev-default";
|
|
6445
6496
|
}
|
|
6497
|
+
if (!baseUrl) logger$4.warn("⚠️ SEO baseUrl 未配置:sitemap 端点将报错。请在 ssr.config.ts 设置 runtime.site。");
|
|
6498
|
+
else logger$4.info(`🎯 SEO baseUrl=${baseUrl}(来源:${source})`);
|
|
6446
6499
|
return {
|
|
6447
|
-
|
|
6448
|
-
|
|
6500
|
+
baseUrl,
|
|
6501
|
+
baseUrlSource: source
|
|
6449
6502
|
};
|
|
6450
6503
|
}
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
|
|
6454
|
-
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
|
|
6461
|
-
|
|
6462
|
-
|
|
6463
|
-
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
|
|
6471
|
-
|
|
6472
|
-
|
|
6473
|
-
|
|
6474
|
-
|
|
6504
|
+
// src/experiments/ExposureQueue.ts
|
|
6505
|
+
/**
|
|
6506
|
+
* ExposureQueue —— 曝光事件批量上报队列
|
|
6507
|
+
*
|
|
6508
|
+
* 设计取舍:
|
|
6509
|
+
* - **fire-and-forget**:业务渲染路径 push() 完立刻返回,不等任何 IO
|
|
6510
|
+
* - **批量 flush**:减小 admin-server QPS(默认 100 条 / 1s 攒一批)
|
|
6511
|
+
* - **不去重**:写入全量;分析期 COUNT(DISTINCT anon_id) 解(业界惯例,
|
|
6512
|
+
* GrowthBook / Statsig / LinkedIn LiX 同款)
|
|
6513
|
+
* - **不阻塞退出**:进程收到 SIGTERM 时同步 flush 一次最后批次再退出
|
|
6514
|
+
* - **失败丢弃 + 警告日志**:业务不应该感知 exposure 失败
|
|
6515
|
+
* - **采样**:sampleRate < 1 时随机丢弃,高 QPS 场景控制 admin-server 负载
|
|
6516
|
+
*
|
|
6517
|
+
* 不在本模块的事:
|
|
6518
|
+
* - HTTP retry / backoff 走 fetch + 短暂 retry,admin-server 全挂时丢这一批
|
|
6519
|
+
* - dedupe(写期不做)
|
|
6520
|
+
* - schema 校验(admin-server 那边做)
|
|
6521
|
+
*/
|
|
6522
|
+
var logger$3 = Logger.getInstance();
|
|
6523
|
+
/**
|
|
6524
|
+
* 创建上报队列。同一进程整个 lifecycle 只创建一个;engine 入口保管 instance。
|
|
6525
|
+
* 返回 push() / flush() / destroy() 三个方法。
|
|
6526
|
+
*/
|
|
6527
|
+
function createExposureQueue(options) {
|
|
6528
|
+
const batchSize = options.batchSize ?? 100;
|
|
6529
|
+
const flushIntervalMs = options.flushIntervalMs ?? 1e3;
|
|
6530
|
+
const sampleRate = options.sampleRate ?? 1;
|
|
6531
|
+
const maxQueueSize = options.maxQueueSize ?? batchSize * 2;
|
|
6532
|
+
const fetcher = options.fetcher ?? globalThis.fetch;
|
|
6533
|
+
const endpoint = options.endpoint;
|
|
6534
|
+
const state = {
|
|
6535
|
+
events: [],
|
|
6536
|
+
flushTimer: null,
|
|
6537
|
+
destroyed: false
|
|
6538
|
+
};
|
|
6539
|
+
const shutdownHook = () => {
|
|
6540
|
+
if (state.events.length > 0) flushNow().catch(() => {});
|
|
6541
|
+
};
|
|
6542
|
+
if (typeof process !== "undefined" && typeof process.on === "function") {
|
|
6543
|
+
process.on("SIGTERM", shutdownHook);
|
|
6544
|
+
process.on("SIGINT", shutdownHook);
|
|
6545
|
+
process.on("beforeExit", shutdownHook);
|
|
6546
|
+
}
|
|
6547
|
+
function scheduleFlush() {
|
|
6548
|
+
if (state.flushTimer || state.destroyed) return;
|
|
6549
|
+
state.flushTimer = setTimeout(() => {
|
|
6550
|
+
state.flushTimer = null;
|
|
6551
|
+
flushNow().catch((err) => {
|
|
6552
|
+
logger$3.warn("[ExposureQueue] flush 异常(已吞):", err);
|
|
6475
6553
|
});
|
|
6476
|
-
};
|
|
6477
|
-
|
|
6478
|
-
|
|
6479
|
-
|
|
6480
|
-
|
|
6481
|
-
|
|
6482
|
-
|
|
6483
|
-
|
|
6554
|
+
}, flushIntervalMs);
|
|
6555
|
+
state.flushTimer.unref?.();
|
|
6556
|
+
}
|
|
6557
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
6558
|
+
function flushNow() {
|
|
6559
|
+
const delivery = sendBatch();
|
|
6560
|
+
inFlight.add(delivery);
|
|
6561
|
+
delivery.finally(() => inFlight.delete(delivery));
|
|
6562
|
+
return delivery;
|
|
6563
|
+
}
|
|
6564
|
+
async function sendBatch() {
|
|
6565
|
+
if (state.events.length === 0) return;
|
|
6566
|
+
const batch = state.events.splice(0, batchSize);
|
|
6567
|
+
try {
|
|
6568
|
+
const res = await fetcher(endpoint, {
|
|
6569
|
+
method: "POST",
|
|
6570
|
+
headers: { "content-type": "application/json" },
|
|
6571
|
+
body: JSON.stringify({ events: batch }),
|
|
6572
|
+
signal: AbortSignal.timeout(3e3)
|
|
6484
6573
|
});
|
|
6485
|
-
|
|
6486
|
-
|
|
6487
|
-
|
|
6488
|
-
|
|
6489
|
-
|
|
6490
|
-
|
|
6491
|
-
|
|
6492
|
-
|
|
6574
|
+
if (!res.ok) logger$3.warn(`[ExposureQueue] admin-server 返回 ${res.status},丢弃 ${batch.length} 条曝光(不重试,业务无影响)`);
|
|
6575
|
+
} catch (err) {
|
|
6576
|
+
logger$3.warn(`[ExposureQueue] 上报失败,丢弃 ${batch.length} 条曝光(${err instanceof Error ? err.message : String(err)})`);
|
|
6577
|
+
}
|
|
6578
|
+
if (state.events.length > 0) scheduleFlush();
|
|
6579
|
+
}
|
|
6580
|
+
return {
|
|
6581
|
+
/**
|
|
6582
|
+
* 入队一个曝光事件。完全同步、永远不抛错。
|
|
6583
|
+
* - 队列满(maxQueueSize)→ 丢最早事件(FIFO)+ critical log
|
|
6584
|
+
* - 采样未命中 → 直接丢弃
|
|
6585
|
+
*/
|
|
6586
|
+
push(event) {
|
|
6587
|
+
if (state.destroyed) return;
|
|
6588
|
+
if (sampleRate < 1 && Math.random() >= sampleRate) return;
|
|
6589
|
+
if (state.events.length >= maxQueueSize) {
|
|
6590
|
+
const dropped = state.events.shift();
|
|
6591
|
+
logger$3.warn(`[ExposureQueue] 队列满(${maxQueueSize})丢弃最早事件,admin-server 可能下线`);
|
|
6592
|
+
if (!dropped) return;
|
|
6493
6593
|
}
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6501
|
-
|
|
6502
|
-
}
|
|
6503
|
-
|
|
6504
|
-
|
|
6505
|
-
|
|
6506
|
-
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
|
|
6513
|
-
|
|
6514
|
-
|
|
6515
|
-
|
|
6594
|
+
state.events.push(event);
|
|
6595
|
+
if (state.events.length >= batchSize) {
|
|
6596
|
+
if (state.flushTimer) {
|
|
6597
|
+
clearTimeout(state.flushTimer);
|
|
6598
|
+
state.flushTimer = null;
|
|
6599
|
+
}
|
|
6600
|
+
flushNow().catch((err) => {
|
|
6601
|
+
logger$3.warn("[ExposureQueue] flush 异常(已吞):", err);
|
|
6602
|
+
});
|
|
6603
|
+
} else scheduleFlush();
|
|
6604
|
+
},
|
|
6605
|
+
/** 立即 flush 当前批次(测试 / 优雅退出用) */
|
|
6606
|
+
async flush() {
|
|
6607
|
+
do {
|
|
6608
|
+
await flushNow();
|
|
6609
|
+
await Promise.all([...inFlight]);
|
|
6610
|
+
} while (state.events.length > 0 || inFlight.size > 0);
|
|
6611
|
+
},
|
|
6612
|
+
/** 销毁队列(清定时器、丢残留);engine 关闭时调 */
|
|
6613
|
+
destroy() {
|
|
6614
|
+
state.destroyed = true;
|
|
6615
|
+
process.removeListener("SIGTERM", shutdownHook);
|
|
6616
|
+
process.removeListener("SIGINT", shutdownHook);
|
|
6617
|
+
process.removeListener("beforeExit", shutdownHook);
|
|
6618
|
+
if (state.flushTimer) {
|
|
6619
|
+
clearTimeout(state.flushTimer);
|
|
6620
|
+
state.flushTimer = null;
|
|
6516
6621
|
}
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6520
|
-
|
|
6521
|
-
|
|
6522
|
-
else resolve();
|
|
6523
|
-
});
|
|
6524
|
-
server.closeIdleConnections();
|
|
6525
|
-
} catch (error) {
|
|
6526
|
-
clearTimeout(timeout);
|
|
6527
|
-
reject(error);
|
|
6622
|
+
state.events.length = 0;
|
|
6623
|
+
},
|
|
6624
|
+
/** 测试用:当前队列长度 */
|
|
6625
|
+
get size() {
|
|
6626
|
+
return state.events.length;
|
|
6528
6627
|
}
|
|
6529
|
-
}
|
|
6530
|
-
closingServers.set(server, closing);
|
|
6531
|
-
return closing;
|
|
6628
|
+
};
|
|
6532
6629
|
}
|
|
6533
|
-
//#endregion
|
|
6534
|
-
//#region src/middlewares/ABVariantMiddleware.ts
|
|
6535
|
-
var ABVariantMiddleware_exports = /* @__PURE__ */ __exportAll({ createABVariantMiddleware: () => createABVariantMiddleware });
|
|
6536
|
-
/** 总桶数;10000 给到 0.01% 权重精度,业界通行做法 */
|
|
6537
|
-
var BUCKET_SPACE = 1e4;
|
|
6538
6630
|
/**
|
|
6539
|
-
*
|
|
6540
|
-
*
|
|
6541
|
-
* 同一 (variants, weights, bucket) → 永远同一结果(确定性)。
|
|
6631
|
+
* 解析配置,决定是否创建 queue 实例。配置缺失 / disabled / 无 endpoint 返回 null。
|
|
6632
|
+
* services.api 或 services.telemetry origin 用于把相对路径补全为绝对 URL。
|
|
6542
6633
|
*/
|
|
6543
|
-
function
|
|
6544
|
-
|
|
6545
|
-
|
|
6546
|
-
let
|
|
6547
|
-
|
|
6548
|
-
|
|
6549
|
-
|
|
6550
|
-
|
|
6551
|
-
|
|
6552
|
-
|
|
6553
|
-
|
|
6554
|
-
|
|
6555
|
-
|
|
6556
|
-
|
|
6557
|
-
|
|
6558
|
-
|
|
6559
|
-
|
|
6560
|
-
return i === -1 ? url : url.slice(0, i);
|
|
6561
|
-
}
|
|
6562
|
-
function createABVariantMiddleware(options) {
|
|
6563
|
-
const { experiments: staticExperiments, assigner = defaultAssigner } = options;
|
|
6564
|
-
const { manifestLoader, exposureQueue } = options;
|
|
6565
|
-
return function abMiddleware(req, _res, next) {
|
|
6566
|
-
const ctx = getRequestContext();
|
|
6567
|
-
if (!ctx) {
|
|
6568
|
-
next();
|
|
6569
|
-
return;
|
|
6570
|
-
}
|
|
6571
|
-
const effectiveExperiments = manifestLoader ? manifestLoader.getCurrent() : staticExperiments;
|
|
6572
|
-
const anonId = ctx.anonId;
|
|
6573
|
-
const assignments = {};
|
|
6574
|
-
for (const [name, exp] of Object.entries(effectiveExperiments)) assignments[name] = assigner(anonId, name, exp);
|
|
6575
|
-
ctx.experiments = {
|
|
6576
|
-
...ctx.experiments ?? {},
|
|
6577
|
-
...assignments
|
|
6578
|
-
};
|
|
6579
|
-
ctx.flags = {
|
|
6580
|
-
...ctx.flags ?? {},
|
|
6581
|
-
...assignments
|
|
6582
|
-
};
|
|
6583
|
-
if (exposureQueue && Object.keys(assignments).length > 0) exposureQueue.push({
|
|
6584
|
-
anonId,
|
|
6585
|
-
userId: ctx.userId ?? null,
|
|
6586
|
-
requestId: ctx.requestId,
|
|
6587
|
-
experiments: assignments,
|
|
6588
|
-
path: stripQuery(req.url ?? "/"),
|
|
6589
|
-
ts: Date.now()
|
|
6590
|
-
});
|
|
6591
|
-
next();
|
|
6592
|
-
};
|
|
6634
|
+
function resolveExposureQueue(config, baseOrigin) {
|
|
6635
|
+
if (!config?.endpoint) return null;
|
|
6636
|
+
if (config.enabled === false) return null;
|
|
6637
|
+
let endpoint = config.endpoint;
|
|
6638
|
+
if (endpoint.startsWith("/")) {
|
|
6639
|
+
if (!baseOrigin) {
|
|
6640
|
+
logger$3.warn("[ExposureQueue] endpoint 是相对路径但没有 baseOrigin,跳过 exposure 上报");
|
|
6641
|
+
return null;
|
|
6642
|
+
}
|
|
6643
|
+
endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
|
|
6644
|
+
}
|
|
6645
|
+
return createExposureQueue({
|
|
6646
|
+
endpoint,
|
|
6647
|
+
batchSize: config.batchSize,
|
|
6648
|
+
flushIntervalMs: config.flushIntervalMs,
|
|
6649
|
+
sampleRate: config.sampleRate
|
|
6650
|
+
});
|
|
6593
6651
|
}
|
|
6594
|
-
|
|
6595
|
-
//#region src/experiments/ManifestLoader.ts
|
|
6652
|
+
// src/experiments/ManifestLoader.ts
|
|
6596
6653
|
/**
|
|
6597
6654
|
* ManifestLoader —— 实验定义动态拉取
|
|
6598
6655
|
*
|
|
@@ -6609,12 +6666,7 @@ function createABVariantMiddleware(options) {
|
|
|
6609
6666
|
* - 'paused' / 'killed' → 强制回第一个 variant(control)
|
|
6610
6667
|
* - 'concluded' → 同上 + admin-platform 高亮
|
|
6611
6668
|
*/
|
|
6612
|
-
var
|
|
6613
|
-
createManifestLoader: () => createManifestLoader,
|
|
6614
|
-
normalizeManifestExperiments: () => normalizeManifestExperiments,
|
|
6615
|
-
resolveManifestLoader: () => resolveManifestLoader
|
|
6616
|
-
});
|
|
6617
|
-
var logger$3 = Logger.getInstance();
|
|
6669
|
+
var logger$2 = Logger.getInstance();
|
|
6618
6670
|
/**
|
|
6619
6671
|
* 把 manifest 里的实验定义归一化为 engine 内部用的 RuntimeExperimentConfig。
|
|
6620
6672
|
* killed / paused / concluded 状态的实验:**weights 强制变成 [100, 0, 0, ...]**,
|
|
@@ -6673,7 +6725,7 @@ function createManifestLoader(options) {
|
|
|
6673
6725
|
return;
|
|
6674
6726
|
}
|
|
6675
6727
|
state.current = normalizeManifestExperiments(json.experiments);
|
|
6676
|
-
logger$
|
|
6728
|
+
logger$2.debug(`[ManifestLoader] 拉取成功 version=${json.version} 实验数=${Object.keys(state.current).length}`);
|
|
6677
6729
|
} catch (err) {
|
|
6678
6730
|
applyFallback(err instanceof Error ? err.message : String(err));
|
|
6679
6731
|
}
|
|
@@ -6681,16 +6733,15 @@ function createManifestLoader(options) {
|
|
|
6681
6733
|
function applyFallback(reason) {
|
|
6682
6734
|
switch (fallbackOnError) {
|
|
6683
6735
|
case "cache":
|
|
6684
|
-
logger$
|
|
6736
|
+
logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),沿用 cache 快照`);
|
|
6685
6737
|
break;
|
|
6686
6738
|
case "static":
|
|
6687
6739
|
state.current = { ...options.staticExperiments ?? {} };
|
|
6688
|
-
logger$
|
|
6740
|
+
logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),回退到 static 配置`);
|
|
6689
6741
|
break;
|
|
6690
6742
|
case "empty":
|
|
6691
6743
|
state.current = {};
|
|
6692
|
-
logger$
|
|
6693
|
-
break;
|
|
6744
|
+
logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),关闭所有实验`);
|
|
6694
6745
|
}
|
|
6695
6746
|
}
|
|
6696
6747
|
function schedulePoll() {
|
|
@@ -6732,7 +6783,7 @@ function resolveManifestLoader(config, staticExperiments, baseOrigin) {
|
|
|
6732
6783
|
let endpoint = config.endpoint;
|
|
6733
6784
|
if (endpoint.startsWith("/")) {
|
|
6734
6785
|
if (!baseOrigin) {
|
|
6735
|
-
logger$
|
|
6786
|
+
logger$2.warn("[ManifestLoader] endpoint 是相对路径但没有 baseOrigin,跳过 manifest 拉取");
|
|
6736
6787
|
return null;
|
|
6737
6788
|
}
|
|
6738
6789
|
endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
|
|
@@ -6745,162 +6796,95 @@ function resolveManifestLoader(config, staticExperiments, baseOrigin) {
|
|
|
6745
6796
|
staticExperiments
|
|
6746
6797
|
});
|
|
6747
6798
|
}
|
|
6748
|
-
|
|
6749
|
-
|
|
6750
|
-
|
|
6751
|
-
* ExposureQueue —— 曝光事件批量上报队列
|
|
6752
|
-
*
|
|
6753
|
-
* 设计取舍:
|
|
6754
|
-
* - **fire-and-forget**:业务渲染路径 push() 完立刻返回,不等任何 IO
|
|
6755
|
-
* - **批量 flush**:减小 admin-server QPS(默认 100 条 / 1s 攒一批)
|
|
6756
|
-
* - **不去重**:写入全量;分析期 COUNT(DISTINCT anon_id) 解(业界惯例,
|
|
6757
|
-
* GrowthBook / Statsig / LinkedIn LiX 同款)
|
|
6758
|
-
* - **不阻塞退出**:进程收到 SIGTERM 时同步 flush 一次最后批次再退出
|
|
6759
|
-
* - **失败丢弃 + 警告日志**:业务不应该感知 exposure 失败
|
|
6760
|
-
* - **采样**:sampleRate < 1 时随机丢弃,高 QPS 场景控制 admin-server 负载
|
|
6761
|
-
*
|
|
6762
|
-
* 不在本模块的事:
|
|
6763
|
-
* - HTTP retry / backoff 走 fetch + 短暂 retry,admin-server 全挂时丢这一批
|
|
6764
|
-
* - dedupe(写期不做)
|
|
6765
|
-
* - schema 校验(admin-server 那边做)
|
|
6766
|
-
*/
|
|
6767
|
-
var ExposureQueue_exports = /* @__PURE__ */ __exportAll({
|
|
6768
|
-
createExposureQueue: () => createExposureQueue,
|
|
6769
|
-
resolveExposureQueue: () => resolveExposureQueue
|
|
6770
|
-
});
|
|
6771
|
-
var logger$2 = Logger.getInstance();
|
|
6799
|
+
// src/middlewares/ABVariantMiddleware.ts
|
|
6800
|
+
/** 总桶数;10000 给到 0.01% 权重精度,业界通行做法 */
|
|
6801
|
+
var BUCKET_SPACE = 1e4;
|
|
6772
6802
|
/**
|
|
6773
|
-
*
|
|
6774
|
-
*
|
|
6803
|
+
* 按权重 + bucket 索引选 variant。
|
|
6804
|
+
* 把 weights 累加得到分段边界,bucket 落在哪段就选哪个 variant。
|
|
6805
|
+
* 同一 (variants, weights, bucket) → 永远同一结果(确定性)。
|
|
6775
6806
|
*/
|
|
6776
|
-
function
|
|
6777
|
-
const
|
|
6778
|
-
const
|
|
6779
|
-
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
|
|
6783
|
-
const state = {
|
|
6784
|
-
events: [],
|
|
6785
|
-
flushTimer: null,
|
|
6786
|
-
destroyed: false
|
|
6787
|
-
};
|
|
6788
|
-
const shutdownHook = () => {
|
|
6789
|
-
if (state.events.length > 0) flushNow().catch(() => {});
|
|
6790
|
-
};
|
|
6791
|
-
if (typeof process !== "undefined" && typeof process.on === "function") {
|
|
6792
|
-
process.on("SIGTERM", shutdownHook);
|
|
6793
|
-
process.on("SIGINT", shutdownHook);
|
|
6794
|
-
process.on("beforeExit", shutdownHook);
|
|
6795
|
-
}
|
|
6796
|
-
function scheduleFlush() {
|
|
6797
|
-
if (state.flushTimer || state.destroyed) return;
|
|
6798
|
-
state.flushTimer = setTimeout(() => {
|
|
6799
|
-
state.flushTimer = null;
|
|
6800
|
-
flushNow().catch((err) => {
|
|
6801
|
-
logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
|
|
6802
|
-
});
|
|
6803
|
-
}, flushIntervalMs);
|
|
6804
|
-
state.flushTimer.unref?.();
|
|
6805
|
-
}
|
|
6806
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
6807
|
-
function flushNow() {
|
|
6808
|
-
const delivery = sendBatch();
|
|
6809
|
-
inFlight.add(delivery);
|
|
6810
|
-
delivery.finally(() => inFlight.delete(delivery));
|
|
6811
|
-
return delivery;
|
|
6812
|
-
}
|
|
6813
|
-
async function sendBatch() {
|
|
6814
|
-
if (state.events.length === 0) return;
|
|
6815
|
-
const batch = state.events.splice(0, batchSize);
|
|
6816
|
-
try {
|
|
6817
|
-
const res = await fetcher(endpoint, {
|
|
6818
|
-
method: "POST",
|
|
6819
|
-
headers: { "content-type": "application/json" },
|
|
6820
|
-
body: JSON.stringify({ events: batch }),
|
|
6821
|
-
signal: AbortSignal.timeout(3e3)
|
|
6822
|
-
});
|
|
6823
|
-
if (!res.ok) logger$2.warn(`[ExposureQueue] admin-server 返回 ${res.status},丢弃 ${batch.length} 条曝光(不重试,业务无影响)`);
|
|
6824
|
-
} catch (err) {
|
|
6825
|
-
logger$2.warn(`[ExposureQueue] 上报失败,丢弃 ${batch.length} 条曝光(${err instanceof Error ? err.message : String(err)})`);
|
|
6826
|
-
}
|
|
6827
|
-
if (state.events.length > 0) scheduleFlush();
|
|
6807
|
+
function pickByBucket(variants, weights, bucket) {
|
|
6808
|
+
const w = weights && weights.length === variants.length ? weights : variants.map(() => 1);
|
|
6809
|
+
const total = w.reduce((a, b) => a + b, 0);
|
|
6810
|
+
let cursor = 0;
|
|
6811
|
+
for (let i = 0; i < variants.length; i++) {
|
|
6812
|
+
cursor += w[i] / total * BUCKET_SPACE;
|
|
6813
|
+
if (bucket < cursor) return variants[i];
|
|
6828
6814
|
}
|
|
6829
|
-
return
|
|
6830
|
-
|
|
6831
|
-
|
|
6832
|
-
|
|
6833
|
-
|
|
6834
|
-
|
|
6835
|
-
|
|
6836
|
-
|
|
6837
|
-
|
|
6838
|
-
|
|
6839
|
-
|
|
6840
|
-
|
|
6841
|
-
|
|
6842
|
-
|
|
6843
|
-
|
|
6844
|
-
|
|
6845
|
-
|
|
6846
|
-
|
|
6847
|
-
|
|
6848
|
-
}
|
|
6849
|
-
flushNow().catch((err) => {
|
|
6850
|
-
logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
|
|
6851
|
-
});
|
|
6852
|
-
} else scheduleFlush();
|
|
6853
|
-
},
|
|
6854
|
-
/** 立即 flush 当前批次(测试 / 优雅退出用) */
|
|
6855
|
-
async flush() {
|
|
6856
|
-
do {
|
|
6857
|
-
await flushNow();
|
|
6858
|
-
await Promise.all([...inFlight]);
|
|
6859
|
-
} while (state.events.length > 0 || inFlight.size > 0);
|
|
6860
|
-
},
|
|
6861
|
-
/** 销毁队列(清定时器、丢残留);engine 关闭时调 */
|
|
6862
|
-
destroy() {
|
|
6863
|
-
state.destroyed = true;
|
|
6864
|
-
process.removeListener("SIGTERM", shutdownHook);
|
|
6865
|
-
process.removeListener("SIGINT", shutdownHook);
|
|
6866
|
-
process.removeListener("beforeExit", shutdownHook);
|
|
6867
|
-
if (state.flushTimer) {
|
|
6868
|
-
clearTimeout(state.flushTimer);
|
|
6869
|
-
state.flushTimer = null;
|
|
6870
|
-
}
|
|
6871
|
-
state.events.length = 0;
|
|
6872
|
-
},
|
|
6873
|
-
/** 测试用:当前队列长度 */
|
|
6874
|
-
get size() {
|
|
6875
|
-
return state.events.length;
|
|
6815
|
+
return variants[variants.length - 1];
|
|
6816
|
+
}
|
|
6817
|
+
/** 默认分桶:fnv1a(anonId + ':' + experimentKey) % BUCKET_SPACE。稳定、无外部依赖 */
|
|
6818
|
+
function defaultAssigner(anonId, name, exp) {
|
|
6819
|
+
const bucket = fnv1a32(`${anonId}:${name}`) % BUCKET_SPACE;
|
|
6820
|
+
return pickByBucket(exp.variants, exp.weights, bucket);
|
|
6821
|
+
}
|
|
6822
|
+
function stripQuery(url) {
|
|
6823
|
+
const i = url.indexOf("?");
|
|
6824
|
+
return i === -1 ? url : url.slice(0, i);
|
|
6825
|
+
}
|
|
6826
|
+
function createABVariantMiddleware(options) {
|
|
6827
|
+
const { experiments: staticExperiments, assigner = defaultAssigner } = options;
|
|
6828
|
+
const { manifestLoader, exposureQueue } = options;
|
|
6829
|
+
return function abMiddleware(req, _res, next) {
|
|
6830
|
+
const ctx = getRequestContext();
|
|
6831
|
+
if (!ctx) {
|
|
6832
|
+
next();
|
|
6833
|
+
return;
|
|
6876
6834
|
}
|
|
6835
|
+
const effectiveExperiments = manifestLoader ? manifestLoader.getCurrent() : staticExperiments;
|
|
6836
|
+
const anonId = ctx.anonId;
|
|
6837
|
+
const assignments = {};
|
|
6838
|
+
for (const [name, exp] of Object.entries(effectiveExperiments)) assignments[name] = assigner(anonId, name, exp);
|
|
6839
|
+
ctx.experiments = {
|
|
6840
|
+
...ctx.experiments ?? {},
|
|
6841
|
+
...assignments
|
|
6842
|
+
};
|
|
6843
|
+
ctx.flags = {
|
|
6844
|
+
...ctx.flags ?? {},
|
|
6845
|
+
...assignments
|
|
6846
|
+
};
|
|
6847
|
+
if (exposureQueue && Object.keys(assignments).length > 0) exposureQueue.push({
|
|
6848
|
+
anonId,
|
|
6849
|
+
userId: ctx.userId ?? null,
|
|
6850
|
+
requestId: ctx.requestId,
|
|
6851
|
+
experiments: assignments,
|
|
6852
|
+
path: stripQuery(req.url ?? "/"),
|
|
6853
|
+
ts: Date.now()
|
|
6854
|
+
});
|
|
6855
|
+
next();
|
|
6877
6856
|
};
|
|
6878
6857
|
}
|
|
6879
|
-
|
|
6880
|
-
|
|
6881
|
-
|
|
6882
|
-
|
|
6883
|
-
|
|
6884
|
-
|
|
6885
|
-
|
|
6886
|
-
|
|
6887
|
-
if (endpoint.startsWith("/")) {
|
|
6888
|
-
if (!baseOrigin) {
|
|
6889
|
-
logger$2.warn("[ExposureQueue] endpoint 是相对路径但没有 baseOrigin,跳过 exposure 上报");
|
|
6890
|
-
return null;
|
|
6891
|
-
}
|
|
6892
|
-
endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
|
|
6858
|
+
// src/server/safeRedirect.ts
|
|
6859
|
+
var REDIRECT_ORIGIN = "https://isr.invalid";
|
|
6860
|
+
/** Validate the final Location value against a fixed origin, never an untrusted Host header. */
|
|
6861
|
+
function isSafeLocalRedirect(target) {
|
|
6862
|
+
if (!target.startsWith("/") || target.startsWith("//")) return false;
|
|
6863
|
+
for (const character of target) {
|
|
6864
|
+
const code = character.charCodeAt(0);
|
|
6865
|
+
if (code < 32 || code === 127) return false;
|
|
6893
6866
|
}
|
|
6894
|
-
|
|
6895
|
-
|
|
6896
|
-
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
|
|
6867
|
+
const pathEnd = target.search(/[?#]/);
|
|
6868
|
+
if (target.slice(0, pathEnd < 0 ? void 0 : pathEnd).includes("\\")) return false;
|
|
6869
|
+
try {
|
|
6870
|
+
return new URL(target, REDIRECT_ORIGIN).origin === REDIRECT_ORIGIN;
|
|
6871
|
+
} catch {
|
|
6872
|
+
return false;
|
|
6873
|
+
}
|
|
6874
|
+
}
|
|
6875
|
+
function readRedirectQuery(url) {
|
|
6876
|
+
const delimiter = url.indexOf("?");
|
|
6877
|
+
return delimiter < 0 ? void 0 : url.slice(delimiter + 1);
|
|
6878
|
+
}
|
|
6879
|
+
function redirectLocal(res, status, pathname, query) {
|
|
6880
|
+
const target = query === void 0 ? pathname : `${pathname}?${query}`;
|
|
6881
|
+
if (!isSafeLocalRedirect(target)) {
|
|
6882
|
+
res.status(400).end();
|
|
6883
|
+
return;
|
|
6884
|
+
}
|
|
6885
|
+
res.redirect(status, target);
|
|
6900
6886
|
}
|
|
6901
|
-
|
|
6902
|
-
//#region src/middlewares/LocaleRedirect.ts
|
|
6903
|
-
var LocaleRedirect_exports = /* @__PURE__ */ __exportAll({ createLocaleRedirectMiddleware: () => createLocaleRedirectMiddleware });
|
|
6887
|
+
// src/middlewares/LocaleRedirect.ts
|
|
6904
6888
|
var FRAMEWORK_SKIP_PREFIXES = [
|
|
6905
6889
|
"/api/",
|
|
6906
6890
|
"/_rsc",
|
|
@@ -6972,614 +6956,1113 @@ function readCookieLocale(header) {
|
|
|
6972
6956
|
return trimmed.slice(eq + 1).trim();
|
|
6973
6957
|
}
|
|
6974
6958
|
}
|
|
6975
|
-
return null;
|
|
6959
|
+
return null;
|
|
6960
|
+
}
|
|
6961
|
+
// src/security/staticCspManifest.ts
|
|
6962
|
+
var STATIC_CSP_MANIFEST = "static-csp-manifest.json";
|
|
6963
|
+
var SCHEMA_VERSION = 3;
|
|
6964
|
+
var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
6965
|
+
/** parse5 follows browser tokenization, including raw script text and inert templates. */
|
|
6966
|
+
function collectInlineScriptHashes(html) {
|
|
6967
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
6968
|
+
function visit(node) {
|
|
6969
|
+
if ("tagName" in node && node.tagName === "script" && !node.attrs.some((attr) => attr.name === "src")) {
|
|
6970
|
+
const text = node.childNodes.map((child) => "value" in child ? child.value : "").join("");
|
|
6971
|
+
hashes.add(`'sha256-${createHash("sha256").update(text).digest("base64")}'`);
|
|
6972
|
+
}
|
|
6973
|
+
if ("childNodes" in node) node.childNodes.forEach(visit);
|
|
6974
|
+
}
|
|
6975
|
+
visit(parse(html));
|
|
6976
|
+
return [...hashes].sort();
|
|
6977
|
+
}
|
|
6978
|
+
function applyStaticScriptPolicy(policy, hashes) {
|
|
6979
|
+
return [...policy.split(";").filter((directive) => {
|
|
6980
|
+
const name = directive.trim().split(/\s/, 1)[0].toLowerCase();
|
|
6981
|
+
return name !== "script-src" && name !== "script-src-elem";
|
|
6982
|
+
}), ["script-src 'self'", ...hashes].join(" ")].join(";");
|
|
6983
|
+
}
|
|
6984
|
+
async function readHtmlFiles(clientDir, parseScripts = false) {
|
|
6985
|
+
const files = [];
|
|
6986
|
+
async function walk(dir) {
|
|
6987
|
+
for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
|
|
6988
|
+
const absolute = path.join(dir, entry.name);
|
|
6989
|
+
if (entry.isDirectory()) await walk(absolute);
|
|
6990
|
+
else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
|
|
6991
|
+
const bytes = await fs$3.readFile(absolute);
|
|
6992
|
+
files.push({
|
|
6993
|
+
path: path.relative(clientDir, absolute).split(path.sep).join("/"),
|
|
6994
|
+
sha256: sha256(bytes),
|
|
6995
|
+
scriptHashes: parseScripts ? collectInlineScriptHashes(bytes.toString("utf8")) : [],
|
|
6996
|
+
...parseScripts ? { generatedAt: Math.floor((await fs$3.stat(absolute)).mtimeMs) } : {}
|
|
6997
|
+
});
|
|
6998
|
+
}
|
|
6999
|
+
}
|
|
7000
|
+
}
|
|
7001
|
+
await walk(clientDir);
|
|
7002
|
+
return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
|
|
6976
7003
|
}
|
|
6977
|
-
|
|
6978
|
-
|
|
6979
|
-
|
|
6980
|
-
|
|
6981
|
-
|
|
6982
|
-
|
|
6983
|
-
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
|
|
6987
|
-
|
|
6988
|
-
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
async function closeDevelopmentResources() {
|
|
6992
|
-
const owned = developmentCleanups.splice(0).reverse();
|
|
6993
|
-
const failures = (await Promise.allSettled(owned.map((close) => Promise.resolve().then(close)))).filter((result) => result.status === "rejected");
|
|
6994
|
-
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Development cleanup failed");
|
|
7004
|
+
var CLIENT_BUILD_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
7005
|
+
".js",
|
|
7006
|
+
".mjs",
|
|
7007
|
+
".cjs",
|
|
7008
|
+
".css",
|
|
7009
|
+
".wasm",
|
|
7010
|
+
".json",
|
|
7011
|
+
".html",
|
|
7012
|
+
".htm",
|
|
7013
|
+
".svg"
|
|
7014
|
+
]);
|
|
7015
|
+
function isDeploymentPath(relative) {
|
|
7016
|
+
if (relative.includes("\\") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) return false;
|
|
7017
|
+
return relative.startsWith("rsc/") || relative.startsWith("ssr/") || relative.startsWith("client/") && CLIENT_BUILD_EXTENSIONS.has(path.posix.extname(relative).toLowerCase());
|
|
6995
7018
|
}
|
|
6996
|
-
/**
|
|
6997
|
-
function
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
7005
|
-
|
|
7006
|
-
|
|
7007
|
-
|
|
7008
|
-
|
|
7019
|
+
/** Hash executable build artifacts incrementally; do not load media or source maps from client/. */
|
|
7020
|
+
async function readDeploymentFiles(distDir) {
|
|
7021
|
+
const files = [];
|
|
7022
|
+
async function walk(dir) {
|
|
7023
|
+
for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
|
|
7024
|
+
const absolute = path.join(dir, entry.name);
|
|
7025
|
+
if (entry.isDirectory()) await walk(absolute);
|
|
7026
|
+
else if (entry.isFile()) {
|
|
7027
|
+
const relative = path.relative(distDir, absolute).split(path.sep).join("/");
|
|
7028
|
+
if (!isDeploymentPath(relative)) continue;
|
|
7029
|
+
const digest = createHash("sha256");
|
|
7030
|
+
for await (const chunk of createReadStream(absolute)) digest.update(chunk);
|
|
7031
|
+
files.push({
|
|
7032
|
+
path: relative,
|
|
7033
|
+
sha256: digest.digest("hex")
|
|
7034
|
+
});
|
|
7035
|
+
}
|
|
7009
7036
|
}
|
|
7010
7037
|
}
|
|
7011
|
-
|
|
7038
|
+
for (const directory of [
|
|
7039
|
+
"rsc",
|
|
7040
|
+
"ssr",
|
|
7041
|
+
"client"
|
|
7042
|
+
]) try {
|
|
7043
|
+
await walk(path.join(distDir, directory));
|
|
7044
|
+
} catch (error) {
|
|
7045
|
+
if (directory !== "ssr" || error.code !== "ENOENT") throw error;
|
|
7046
|
+
}
|
|
7047
|
+
return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
|
|
7012
7048
|
}
|
|
7013
|
-
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
|
|
7019
|
-
|
|
7049
|
+
function manifestPayload(manifest) {
|
|
7050
|
+
return JSON.stringify({
|
|
7051
|
+
schemaVersion: manifest.schemaVersion,
|
|
7052
|
+
...manifest.schemaVersion >= 3 ? { ssgRoutes: manifest.ssgRoutes } : {},
|
|
7053
|
+
deploymentFiles: manifest.deploymentFiles.map((file) => ({
|
|
7054
|
+
path: file.path,
|
|
7055
|
+
sha256: file.sha256
|
|
7056
|
+
})),
|
|
7057
|
+
files: manifest.files.map((file) => ({
|
|
7058
|
+
path: file.path,
|
|
7059
|
+
sha256: file.sha256,
|
|
7060
|
+
scriptHashes: file.scriptHashes,
|
|
7061
|
+
...manifest.schemaVersion < 3 || file.generatedAt === void 0 ? {} : { generatedAt: file.generatedAt }
|
|
7062
|
+
}))
|
|
7063
|
+
});
|
|
7064
|
+
}
|
|
7065
|
+
async function createManifest(distDir, ssgRoutes = []) {
|
|
7066
|
+
assertDistinctHtmlRouteIdentities(ssgRoutes);
|
|
7067
|
+
await fs$3.access(path.join(distDir, "rsc/index.js"));
|
|
7068
|
+
const deploymentFiles = await readDeploymentFiles(distDir);
|
|
7069
|
+
const files = await readHtmlFiles(path.join(distDir, "client"), true);
|
|
7070
|
+
const payload = {
|
|
7071
|
+
schemaVersion: SCHEMA_VERSION,
|
|
7072
|
+
ssgRoutes: [...new Set(ssgRoutes)].sort(),
|
|
7073
|
+
deploymentFiles,
|
|
7074
|
+
files
|
|
7075
|
+
};
|
|
7020
7076
|
return {
|
|
7021
|
-
|
|
7022
|
-
|
|
7023
|
-
isDev: true,
|
|
7024
|
-
manifest: null,
|
|
7025
|
-
httpServer: null
|
|
7077
|
+
...payload,
|
|
7078
|
+
buildId: sha256(manifestPayload(payload))
|
|
7026
7079
|
};
|
|
7027
7080
|
}
|
|
7028
|
-
/**
|
|
7029
|
-
|
|
7030
|
-
|
|
7031
|
-
|
|
7032
|
-
|
|
7033
|
-
|
|
7034
|
-
|
|
7035
|
-
|
|
7036
|
-
|
|
7037
|
-
|
|
7038
|
-
const { data, needsAnonCookie } = createServerRequestContext(req);
|
|
7039
|
-
if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
|
|
7040
|
-
requestContext.run(data, () => next());
|
|
7041
|
-
});
|
|
7042
|
-
if (config?.runtime?.i18n?.prefixDefault) {
|
|
7043
|
-
const localeRedirect = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(config.runtime.i18n) });
|
|
7044
|
-
if (localeRedirect) serverContext.requestHandler.use(localeRedirect);
|
|
7045
|
-
}
|
|
7046
|
-
const hasStaticExps = config?.runtime?.experiments && Object.keys(config.runtime.experiments).length > 0;
|
|
7047
|
-
const hasManifest = !!config?.runtime?.experimentManifest?.endpoint;
|
|
7048
|
-
if (hasStaticExps || hasManifest) {
|
|
7049
|
-
const baseOrigin = config?.runtime?.services?.api;
|
|
7050
|
-
const manifestLoader = resolveManifestLoader(config?.runtime?.experimentManifest, config?.runtime?.experiments ?? {}, baseOrigin);
|
|
7051
|
-
if (manifestLoader) {
|
|
7052
|
-
developmentCleanups.push(() => manifestLoader.destroy());
|
|
7053
|
-
await manifestLoader.init();
|
|
7054
|
-
}
|
|
7055
|
-
const exposureQueue = resolveExposureQueue(config?.runtime?.experimentTracking, baseOrigin);
|
|
7056
|
-
if (exposureQueue) developmentCleanups.push(async () => {
|
|
7057
|
-
try {
|
|
7058
|
-
await exposureQueue.flush();
|
|
7059
|
-
} finally {
|
|
7060
|
-
exposureQueue.destroy();
|
|
7061
|
-
}
|
|
7062
|
-
});
|
|
7063
|
-
serverContext.requestHandler.use(createABVariantMiddleware({
|
|
7064
|
-
experiments: config?.runtime?.experiments ?? {},
|
|
7065
|
-
manifestLoader,
|
|
7066
|
-
exposureQueue
|
|
7067
|
-
}));
|
|
7068
|
-
const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(config?.runtime?.experiments ?? {});
|
|
7069
|
-
logger$1.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
|
|
7081
|
+
/** Called only after every build environment, SSG output and SPA shell are complete. */
|
|
7082
|
+
async function generateStaticCspManifest(distDir, options = {}) {
|
|
7083
|
+
const manifest = await createManifest(distDir, options.ssgRoutes);
|
|
7084
|
+
const destination = path.join(distDir, STATIC_CSP_MANIFEST);
|
|
7085
|
+
const temporary = `${destination}.${process.pid}.tmp`;
|
|
7086
|
+
try {
|
|
7087
|
+
await fs$3.writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n");
|
|
7088
|
+
await fs$3.rename(temporary, destination);
|
|
7089
|
+
} finally {
|
|
7090
|
+
await fs$3.rm(temporary, { force: true });
|
|
7070
7091
|
}
|
|
7071
|
-
|
|
7072
|
-
return serverContext;
|
|
7092
|
+
return manifest;
|
|
7073
7093
|
}
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7077
|
-
|
|
7078
|
-
|
|
7079
|
-
if (
|
|
7080
|
-
if (
|
|
7081
|
-
|
|
7082
|
-
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
7094
|
+
function validateManifest(value) {
|
|
7095
|
+
if (!value || typeof value !== "object") throw new Error("Invalid static CSP manifest");
|
|
7096
|
+
const manifest = value;
|
|
7097
|
+
if (manifest.schemaVersion !== SCHEMA_VERSION && manifest.schemaVersion !== 2) throw new Error("Unsupported static CSP manifest schema");
|
|
7098
|
+
const { ssgRoutes } = manifest;
|
|
7099
|
+
if (manifest.schemaVersion >= 3 && (!Array.isArray(ssgRoutes) || ssgRoutes.some((route, index) => typeof route !== "string" || !route.startsWith("/") || route.includes("?") || route.includes("#") || index > 0 && route <= ssgRoutes[index - 1]))) throw new Error("Invalid static CSP manifest SSG routes");
|
|
7100
|
+
if (ssgRoutes) assertDistinctHtmlRouteIdentities(ssgRoutes);
|
|
7101
|
+
const digest = /^[a-f0-9]{64}$/;
|
|
7102
|
+
if (!Array.isArray(manifest.deploymentFiles) || typeof manifest.buildId !== "string" || !digest.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error("Invalid static CSP manifest fields");
|
|
7103
|
+
let previous = "";
|
|
7104
|
+
for (const file of manifest.deploymentFiles) {
|
|
7105
|
+
if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || !isDeploymentPath(file.path) || typeof file.sha256 !== "string" || !digest.test(file.sha256)) throw new Error("Invalid static CSP manifest deployment entry");
|
|
7106
|
+
previous = file.path;
|
|
7107
|
+
}
|
|
7108
|
+
if (!manifest.deploymentFiles.some((file) => file.path === "rsc/index.js")) throw new Error("Static CSP manifest is missing the RSC build");
|
|
7109
|
+
previous = "";
|
|
7110
|
+
for (const file of manifest.files) {
|
|
7111
|
+
if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || file.path.includes("\\") || file.path.startsWith("/") || file.path.split("/").some((segment) => !segment || segment === "." || segment === "..") || !file.path.toLowerCase().endsWith(".html") || typeof file.sha256 !== "string" || !digest.test(file.sha256) || manifest.schemaVersion === 3 && (typeof file.generatedAt !== "number" || !Number.isSafeInteger(file.generatedAt) || file.generatedAt < 0) || !Array.isArray(file.scriptHashes) || !file.scriptHashes.every((hash) => typeof hash === "string" && /^'sha256-[A-Za-z0-9+/]{43}='$/.test(hash))) throw new Error("Invalid static CSP manifest file entry");
|
|
7112
|
+
previous = file.path;
|
|
7113
|
+
}
|
|
7114
|
+
if (sha256(manifestPayload(manifest)) !== manifest.buildId) throw new Error("Static CSP manifest integrity mismatch");
|
|
7086
7115
|
}
|
|
7087
|
-
|
|
7116
|
+
/** Missing manifests are legacy builds; present but invalid manifests always stop startup. */
|
|
7117
|
+
async function loadStaticCspManifest(distDir, options = {}) {
|
|
7118
|
+
let serialized;
|
|
7088
7119
|
try {
|
|
7089
|
-
|
|
7120
|
+
serialized = await fs$3.readFile(path.join(distDir, STATIC_CSP_MANIFEST), "utf8");
|
|
7090
7121
|
} catch (error) {
|
|
7091
|
-
if (
|
|
7092
|
-
|
|
7093
|
-
|
|
7094
|
-
|
|
7095
|
-
|
|
7096
|
-
|
|
7097
|
-
|
|
7098
|
-
|
|
7122
|
+
if (error.code !== "ENOENT") throw error;
|
|
7123
|
+
const manifest = await createManifest(distDir);
|
|
7124
|
+
options.onLegacyBuild?.();
|
|
7125
|
+
return indexManifest(manifest, true);
|
|
7126
|
+
}
|
|
7127
|
+
let manifest;
|
|
7128
|
+
try {
|
|
7129
|
+
manifest = JSON.parse(serialized);
|
|
7130
|
+
} catch (error) {
|
|
7131
|
+
throw new Error("Invalid static CSP manifest JSON", { cause: error });
|
|
7132
|
+
}
|
|
7133
|
+
validateManifest(manifest);
|
|
7134
|
+
const deployed = await readDeploymentFiles(distDir);
|
|
7135
|
+
if (JSON.stringify(deployed) !== JSON.stringify(manifest.deploymentFiles)) throw new Error("Static CSP manifest does not match the deployment build");
|
|
7136
|
+
const actual = await readHtmlFiles(path.join(distDir, "client"));
|
|
7137
|
+
if (actual.length !== manifest.files.length || actual.some((file, index) => file.path !== manifest.files[index].path || file.sha256 !== manifest.files[index].sha256)) throw new Error("Static CSP manifest does not match deployed HTML files");
|
|
7138
|
+
return indexManifest(manifest, false);
|
|
7139
|
+
}
|
|
7140
|
+
function indexManifest(manifest, legacy) {
|
|
7141
|
+
return {
|
|
7142
|
+
legacy,
|
|
7143
|
+
ssgRoutes: legacy || manifest.schemaVersion < 3 ? void 0 : Object.freeze([...manifest.ssgRoutes ?? []]),
|
|
7144
|
+
buildId: manifest.buildId,
|
|
7145
|
+
generatedAt: new Map(legacy || manifest.schemaVersion < 3 ? [] : manifest.files.flatMap((file) => file.generatedAt === void 0 ? [] : [[file.path, file.generatedAt]])),
|
|
7146
|
+
scriptHashes: new Map(manifest.files.map((file) => [file.path, Object.freeze([...file.scriptHashes])]))
|
|
7147
|
+
};
|
|
7148
|
+
}
|
|
7149
|
+
// src/server/productionRuntime.ts
|
|
7150
|
+
/** Shared production application assembly. Listening and process signals belong to callers. */
|
|
7151
|
+
function safeOrigin(url) {
|
|
7152
|
+
if (!url) return void 0;
|
|
7153
|
+
try {
|
|
7154
|
+
return new URL(url).origin;
|
|
7155
|
+
} catch {
|
|
7156
|
+
return;
|
|
7099
7157
|
}
|
|
7100
7158
|
}
|
|
7101
|
-
|
|
7102
|
-
|
|
7103
|
-
|
|
7104
|
-
|
|
7105
|
-
|
|
7106
|
-
|
|
7107
|
-
|
|
7108
|
-
|
|
7109
|
-
|
|
7110
|
-
|
|
7111
|
-
|
|
7112
|
-
url: result.url,
|
|
7113
|
-
isDev: false,
|
|
7114
|
-
manifest: loadProdManifest()
|
|
7115
|
-
};
|
|
7116
|
-
return serverContext;
|
|
7117
|
-
} catch (error) {
|
|
7118
|
-
try {
|
|
7119
|
-
await runtime.close();
|
|
7120
|
-
} catch (cleanupError) {
|
|
7121
|
-
logger$1.warn("Production startup cleanup failed", cleanupError);
|
|
7122
|
-
}
|
|
7123
|
-
throw error;
|
|
7124
|
-
}
|
|
7159
|
+
/**
|
|
7160
|
+
* 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
|
|
7161
|
+
* 导出以便单测覆盖(纯函数)
|
|
7162
|
+
*/
|
|
7163
|
+
function extractRoutesForSitemap(config) {
|
|
7164
|
+
const routes = config.routes ?? {};
|
|
7165
|
+
const out = [];
|
|
7166
|
+
for (const path of Object.keys(routes)) {
|
|
7167
|
+
if (path.includes("*") || path.includes(":")) continue;
|
|
7168
|
+
if (path.startsWith("/__") || path.startsWith("/api/")) continue;
|
|
7169
|
+
out.push(path);
|
|
7125
7170
|
}
|
|
7126
|
-
|
|
7127
|
-
if (!serverContext) throw new Error("服务器上下文初始化失败");
|
|
7128
|
-
setupRoutes(serverContext.requestHandler);
|
|
7129
|
-
mountViteOrStatic(serverContext);
|
|
7130
|
-
const serverConfig = {
|
|
7131
|
-
port: config.server.port,
|
|
7132
|
-
host: config.server.host,
|
|
7133
|
-
strictPort: config.server.strictPort
|
|
7134
|
-
};
|
|
7135
|
-
const result = await startServer(serverContext.requestHandler, serverConfig);
|
|
7136
|
-
serverContext.httpServer = result.server;
|
|
7137
|
-
serverContext.url = result.url;
|
|
7138
|
-
logger$1.success(`🚀 ${isDev() ? "开发" : "生产"}服务器已启动: ${result.url}`);
|
|
7139
|
-
return serverContext;
|
|
7171
|
+
return out;
|
|
7140
7172
|
}
|
|
7141
7173
|
/**
|
|
7142
|
-
*
|
|
7174
|
+
* 把 ssr.config.ts 的 telemetry 第三方配置映射到可选 adapter 使用的 env。
|
|
7175
|
+
* 这一步必须发生在 import dist/rsc/index.js 之前,因为内置 entry.server 会在模块加载时
|
|
7176
|
+
* 初始化 auto hooks。engine 仍不静态 import vendor SDK;这里仅做启动期配置桥接。
|
|
7143
7177
|
*/
|
|
7144
|
-
function
|
|
7145
|
-
|
|
7146
|
-
|
|
7147
|
-
|
|
7148
|
-
|
|
7149
|
-
|
|
7178
|
+
function applyTelemetryIntegrationEnv(runtime) {
|
|
7179
|
+
const telemetry = runtime?.telemetry;
|
|
7180
|
+
delete process.env.SENTRY_ENVIRONMENT;
|
|
7181
|
+
if (!telemetry) {
|
|
7182
|
+
process.env.SENTRY_ENABLED = "false";
|
|
7183
|
+
delete process.env.DD_SERVICE;
|
|
7184
|
+
delete process.env.DD_ENV;
|
|
7185
|
+
delete process.env.DD_VERSION;
|
|
7186
|
+
delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
7187
|
+
delete process.env.OTEL_SERVICE_NAME;
|
|
7188
|
+
return;
|
|
7189
|
+
}
|
|
7190
|
+
const sentryIntegration = telemetry.integrations?.sentry;
|
|
7191
|
+
if (sentryIntegration) {
|
|
7192
|
+
process.env.SENTRY_ENABLED = sentryIntegration.enabled ? "true" : "false";
|
|
7193
|
+
if (sentryIntegration.enabled) {
|
|
7194
|
+
if (sentryIntegration.dsn) process.env.SENTRY_DSN = sentryIntegration.dsn;
|
|
7195
|
+
if (sentryIntegration.tracesSampleRate !== void 0) process.env.SENTRY_TRACES_SAMPLE_RATE = String(sentryIntegration.tracesSampleRate);
|
|
7196
|
+
if (sentryIntegration.environment) process.env.SENTRY_ENVIRONMENT = sentryIntegration.environment;
|
|
7197
|
+
} else {
|
|
7198
|
+
delete process.env.SENTRY_DSN;
|
|
7199
|
+
delete process.env.SENTRY_TRACES_SAMPLE_RATE;
|
|
7200
|
+
}
|
|
7201
|
+
} else {
|
|
7202
|
+
process.env.SENTRY_ENABLED = "false";
|
|
7203
|
+
delete process.env.SENTRY_DSN;
|
|
7204
|
+
delete process.env.SENTRY_TRACES_SAMPLE_RATE;
|
|
7205
|
+
}
|
|
7206
|
+
delete process.env.DD_SERVICE;
|
|
7207
|
+
delete process.env.DD_ENV;
|
|
7208
|
+
delete process.env.DD_VERSION;
|
|
7209
|
+
delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
7210
|
+
delete process.env.OTEL_SERVICE_NAME;
|
|
7211
|
+
for (const exporter of telemetry.exporters) {
|
|
7212
|
+
if (exporter.type === "datadog") {
|
|
7213
|
+
if (exporter.service) process.env.DD_SERVICE = exporter.service;
|
|
7214
|
+
if (telemetry.environment) process.env.DD_ENV = telemetry.environment;
|
|
7215
|
+
if (telemetry.release) process.env.DD_VERSION = telemetry.release;
|
|
7216
|
+
continue;
|
|
7217
|
+
}
|
|
7218
|
+
if (exporter.type === "otel") {
|
|
7219
|
+
if (exporter.endpoint) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exporter.endpoint;
|
|
7220
|
+
if (exporter.serviceName) process.env.OTEL_SERVICE_NAME = exporter.serviceName;
|
|
7221
|
+
}
|
|
7222
|
+
}
|
|
7150
7223
|
}
|
|
7151
|
-
async function
|
|
7152
|
-
|
|
7153
|
-
|
|
7154
|
-
|
|
7155
|
-
|
|
7156
|
-
|
|
7157
|
-
|
|
7158
|
-
|
|
7159
|
-
|
|
7160
|
-
|
|
7224
|
+
async function prepareProductionBuild(root = process.cwd()) {
|
|
7225
|
+
const rscDistEntry = path.resolve(root, "dist/rsc/index.js");
|
|
7226
|
+
const clientDir = path.resolve(root, "dist/client");
|
|
7227
|
+
await fs$3.access(rscDistEntry);
|
|
7228
|
+
await fs$3.access(clientDir);
|
|
7229
|
+
return {
|
|
7230
|
+
rscDistEntry,
|
|
7231
|
+
clientDir,
|
|
7232
|
+
staticCspIndex: await loadStaticCspManifest(path.dirname(clientDir), { onLegacyBuild: () => logger$8.warn("[CSP] 构建缺少 static-csp-manifest.json;已在启动期生成兼容索引,请重新构建以生成清单") })
|
|
7233
|
+
};
|
|
7161
7234
|
}
|
|
7162
|
-
|
|
7163
|
-
|
|
7164
|
-
|
|
7165
|
-
|
|
7166
|
-
|
|
7167
|
-
|
|
7168
|
-
|
|
7169
|
-
|
|
7170
|
-
|
|
7171
|
-
|
|
7172
|
-
|
|
7173
|
-
|
|
7174
|
-
|
|
7175
|
-
|
|
7235
|
+
async function createProductionRuntime(config, options = {}) {
|
|
7236
|
+
const { rscDistEntry, clientDir, staticCspIndex } = options.build ?? await prepareProductionBuild(options.root);
|
|
7237
|
+
const ssgRoutes = staticCspIndex.ssgRoutes ?? (Array.isArray(config.ssg?.routes) ? config.ssg.routes : []);
|
|
7238
|
+
const ssgFiles = new Map(ssgRoutes.map((route) => [route, routeToFilePath(route)]));
|
|
7239
|
+
const ssgAliases = /* @__PURE__ */ new Map();
|
|
7240
|
+
const configuredRoutes = Object.keys(config.routes ?? {});
|
|
7241
|
+
assertDistinctHtmlRouteIdentities(configuredRoutes, { allowPatterns: true });
|
|
7242
|
+
const routeNames = /* @__PURE__ */ new Set([...ssgFiles.keys(), ...configuredRoutes.filter((route) => !isHtmlRoutePattern(route))]);
|
|
7243
|
+
assertDistinctHtmlRouteIdentities(routeNames);
|
|
7244
|
+
const declaredIdentities = new Set([...routeNames].map((route) => decodeHtmlPathname(route)));
|
|
7245
|
+
const explicitRoutes = /* @__PURE__ */ new Map();
|
|
7246
|
+
for (const route of routeNames) {
|
|
7247
|
+
const target = new URL(route, "http://localhost").pathname;
|
|
7248
|
+
explicitRoutes.set(decodeHtmlPathname(route), target);
|
|
7249
|
+
if ((route === "/" || !route.endsWith("/")) && !declaredIdentities.has(decodeHtmlPathname(route + "_.rsc"))) explicitRoutes.set(decodeHtmlPathname(route + "_.rsc"), target + "_.rsc");
|
|
7176
7250
|
}
|
|
7177
|
-
|
|
7178
|
-
const
|
|
7179
|
-
const
|
|
7180
|
-
|
|
7181
|
-
|
|
7182
|
-
|
|
7183
|
-
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
|
|
7187
|
-
|
|
7188
|
-
|
|
7251
|
+
for (const [canonical, file] of ssgFiles) {
|
|
7252
|
+
const logical = decodeHtmlPathname(canonical);
|
|
7253
|
+
const target = new URL(canonical, "http://localhost").pathname;
|
|
7254
|
+
const base = logical.replace(/\/$/, "") || "/";
|
|
7255
|
+
for (const alias of [
|
|
7256
|
+
logical,
|
|
7257
|
+
base,
|
|
7258
|
+
base === "/" ? "/" : base + "/",
|
|
7259
|
+
base === "/" ? "/index.html" : base + "/index.html",
|
|
7260
|
+
"/" + file
|
|
7261
|
+
]) {
|
|
7262
|
+
ssgAliases.set(alias, target);
|
|
7263
|
+
ssgAliases.set(alias + "_.rsc", target + "_.rsc");
|
|
7264
|
+
}
|
|
7265
|
+
}
|
|
7266
|
+
const resolveSsgIdentity = (pathname) => {
|
|
7267
|
+
const logical = decodeHtmlPathname(pathname);
|
|
7268
|
+
const known = ssgAliases.get(logical);
|
|
7269
|
+
return known ? explicitRoutes.get(logical) ?? known : pathname;
|
|
7270
|
+
};
|
|
7271
|
+
const cleanups = [];
|
|
7272
|
+
let closed;
|
|
7273
|
+
const close = () => closed ??= (async () => {
|
|
7274
|
+
const errors = (await Promise.allSettled(cleanups.reverse().map((cleanup) => Promise.resolve().then(cleanup)))).filter((result) => result.status === "rejected");
|
|
7275
|
+
if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Production runtime cleanup failed");
|
|
7276
|
+
})();
|
|
7277
|
+
try {
|
|
7278
|
+
validateRequestLimits(config.server.requestLimits);
|
|
7279
|
+
const runtime = config.runtime;
|
|
7280
|
+
applyTelemetryIntegrationEnv(runtime);
|
|
7281
|
+
const sentryIntegration = runtime?.telemetry ? runtime.telemetry.integrations?.sentry : void 0;
|
|
7282
|
+
if (sentryIntegration?.enabled && process.env.SENTRY_DSN) logger$8.info(`🛰️ Sentry integration 来自 ssr.config.ts runtime.telemetry.integrations`);
|
|
7283
|
+
else if (sentryIntegration?.enabled) logger$8.warn(`🛰️ Sentry integration 已启用但缺少 SENTRY_DSN,跳过 Sentry adapter`);
|
|
7284
|
+
const { fetch: rscHandler } = resolveFetchHandler(await import(
|
|
7285
|
+
/* @vite-ignore */
|
|
7286
|
+
pathToFileURL(rscDistEntry).href
|
|
7287
|
+
));
|
|
7288
|
+
const extraConnectSrc = Array.from(new Set([runtime?.services?.api, runtime?.services?.telemetry].map(safeOrigin).filter((origin) => !!origin)));
|
|
7289
|
+
const app = express();
|
|
7290
|
+
app.disable("x-powered-by");
|
|
7291
|
+
app.set("trust proxy", config.server.trustProxy ?? false);
|
|
7292
|
+
app.use(createProductionJsonMiddleware());
|
|
7293
|
+
const opsConfig = resolveOpsConfig(config, "production");
|
|
7294
|
+
for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
|
|
7295
|
+
app.use(createCspNonceMiddleware());
|
|
7296
|
+
app.use(createSecurityMiddleware(false, extraConnectSrc));
|
|
7297
|
+
app.use(createCompressionMiddleware());
|
|
7298
|
+
if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
|
|
7299
|
+
const cookieDomain = runtime?.cookieDomain;
|
|
7300
|
+
app.use((req, res, next) => {
|
|
7301
|
+
const { data, needsAnonCookie } = createServerRequestContext(req);
|
|
7302
|
+
if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
|
|
7303
|
+
requestContext.run(data, () => next());
|
|
7189
7304
|
});
|
|
7190
|
-
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
|
|
7194
|
-
|
|
7195
|
-
|
|
7196
|
-
|
|
7197
|
-
|
|
7198
|
-
|
|
7199
|
-
|
|
7200
|
-
|
|
7201
|
-
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
7207
|
-
}
|
|
7208
|
-
res.setHeader("Content-Type", "application/xml; charset=utf-8");
|
|
7209
|
-
res.send(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>`);
|
|
7210
|
-
} catch (error) {
|
|
7211
|
-
this.logger.error("生成 sitemap 失败:", error);
|
|
7212
|
-
res.status(500).send("Internal Server Error");
|
|
7305
|
+
if (runtime?.i18n?.prefixDefault) {
|
|
7306
|
+
const middleware = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(runtime.i18n) });
|
|
7307
|
+
if (middleware) {
|
|
7308
|
+
app.use(middleware);
|
|
7309
|
+
logger$8.info(`🌐 Locale redirect 已启用 (prefixDefault=true)`);
|
|
7310
|
+
}
|
|
7311
|
+
}
|
|
7312
|
+
const hasStaticExps = runtime?.experiments && Object.keys(runtime.experiments).length > 0;
|
|
7313
|
+
const hasManifest = !!runtime?.experimentManifest?.endpoint;
|
|
7314
|
+
let manifestLoader;
|
|
7315
|
+
let exposureQueue;
|
|
7316
|
+
if (hasStaticExps || hasManifest) {
|
|
7317
|
+
const baseOrigin = runtime?.services?.api;
|
|
7318
|
+
manifestLoader = resolveManifestLoader(runtime?.experimentManifest, runtime?.experiments ?? {}, baseOrigin);
|
|
7319
|
+
if (manifestLoader) {
|
|
7320
|
+
cleanups.push(() => manifestLoader?.destroy());
|
|
7321
|
+
await manifestLoader.init();
|
|
7213
7322
|
}
|
|
7323
|
+
exposureQueue = resolveExposureQueue(runtime?.experimentTracking, baseOrigin);
|
|
7324
|
+
cleanups.push(async () => {
|
|
7325
|
+
try {
|
|
7326
|
+
await exposureQueue?.flush();
|
|
7327
|
+
} finally {
|
|
7328
|
+
exposureQueue?.destroy();
|
|
7329
|
+
}
|
|
7330
|
+
});
|
|
7331
|
+
app.use(createABVariantMiddleware({
|
|
7332
|
+
experiments: runtime?.experiments ?? {},
|
|
7333
|
+
manifestLoader,
|
|
7334
|
+
exposureQueue
|
|
7335
|
+
}));
|
|
7336
|
+
const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(runtime?.experiments ?? {});
|
|
7337
|
+
logger$8.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
|
|
7338
|
+
}
|
|
7339
|
+
if (opsConfig.health.enabled) app.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
|
|
7340
|
+
res.json({
|
|
7341
|
+
status: "healthy",
|
|
7342
|
+
version: package_default.version,
|
|
7343
|
+
mode: "plugin-rsc-production",
|
|
7344
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
7345
|
+
});
|
|
7214
7346
|
});
|
|
7215
|
-
|
|
7347
|
+
options.setupRoutes?.(app);
|
|
7348
|
+
const staticHtmlLimiter = createRequestLimiter("staticHtml", config.server.requestLimits?.staticHtml);
|
|
7349
|
+
const seoLimiter = createRequestLimiter("seo", config.server.requestLimits?.seo);
|
|
7350
|
+
app.use((req, res, next) => {
|
|
7351
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
7352
|
+
let pathname;
|
|
7216
7353
|
try {
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
|
|
7221
|
-
];
|
|
7222
|
-
for (const p of candidates) if (fs.existsSync(p)) {
|
|
7223
|
-
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
7224
|
-
res.send(await fs.promises.readFile(p, "utf-8"));
|
|
7225
|
-
return;
|
|
7226
|
-
}
|
|
7227
|
-
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
7228
|
-
res.send("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n");
|
|
7229
|
-
} catch (error) {
|
|
7230
|
-
this.logger.error("生成 robots.txt 失败:", error);
|
|
7231
|
-
res.status(500).send("Internal Server Error");
|
|
7354
|
+
pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
|
|
7355
|
+
} catch {
|
|
7356
|
+
res.status(400).end();
|
|
7357
|
+
return;
|
|
7232
7358
|
}
|
|
7359
|
+
if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
|
|
7360
|
+
next();
|
|
7233
7361
|
});
|
|
7234
|
-
|
|
7235
|
-
|
|
7236
|
-
|
|
7237
|
-
|
|
7238
|
-
|
|
7239
|
-
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
|
|
7243
|
-
|
|
7244
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
keywords: [],
|
|
7249
|
-
author: "",
|
|
7250
|
-
robots: "index,follow",
|
|
7251
|
-
sitemap: {
|
|
7252
|
-
priority: {
|
|
7253
|
-
"/": 1,
|
|
7254
|
-
"/blog/*": .7,
|
|
7255
|
-
"*": .5
|
|
7256
|
-
},
|
|
7257
|
-
changeFreq: {
|
|
7258
|
-
"/": "daily",
|
|
7259
|
-
"/blog/*": "weekly",
|
|
7260
|
-
"*": "monthly"
|
|
7261
|
-
},
|
|
7262
|
-
excludePatterns: ["/admin/*", "/api/*"],
|
|
7263
|
-
cacheTimeout: 3600
|
|
7264
|
-
},
|
|
7265
|
-
openGraph: {
|
|
7266
|
-
enabled: true,
|
|
7267
|
-
locale: "zh_CN",
|
|
7268
|
-
defaultImage: "/images/og-default.jpg"
|
|
7269
|
-
},
|
|
7270
|
-
twitter: {
|
|
7271
|
-
enabled: true,
|
|
7272
|
-
card: "summary_large_image",
|
|
7273
|
-
site: ""
|
|
7274
|
-
},
|
|
7275
|
-
structuredData: {
|
|
7276
|
-
enabled: true,
|
|
7277
|
-
organizationLogo: ""
|
|
7278
|
-
}
|
|
7279
|
-
};
|
|
7280
|
-
/** 深度合并配置 */
|
|
7281
|
-
function mergeSEOConfig(base, override) {
|
|
7282
|
-
return {
|
|
7283
|
-
...base,
|
|
7284
|
-
...override,
|
|
7285
|
-
sitemap: {
|
|
7286
|
-
...base.sitemap,
|
|
7287
|
-
...override.sitemap
|
|
7288
|
-
},
|
|
7289
|
-
openGraph: {
|
|
7290
|
-
...base.openGraph,
|
|
7291
|
-
...override.openGraph
|
|
7292
|
-
},
|
|
7293
|
-
twitter: {
|
|
7294
|
-
...base.twitter,
|
|
7295
|
-
...override.twitter
|
|
7296
|
-
},
|
|
7297
|
-
structuredData: {
|
|
7298
|
-
...base.structuredData,
|
|
7299
|
-
...override.structuredData
|
|
7362
|
+
app.use(createStaticAssetMiddleware(clientDir));
|
|
7363
|
+
app.use("/assets", (_req, res) => {
|
|
7364
|
+
res.status(404).set("Cache-Control", "no-store").end();
|
|
7365
|
+
});
|
|
7366
|
+
app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
|
|
7367
|
+
const redisCfg = resolveRuntimeRedisConfig(runtime?.redis);
|
|
7368
|
+
const hasRedisConfig = hasRuntimeRedisConnection(runtime?.redis);
|
|
7369
|
+
const cacheRoutes = { ...config.routes };
|
|
7370
|
+
for (const route of ssgRoutes) {
|
|
7371
|
+
const rule = cacheRoutes[route];
|
|
7372
|
+
cacheRoutes[route] = typeof rule === "object" ? {
|
|
7373
|
+
...rule,
|
|
7374
|
+
mode: "ssg"
|
|
7375
|
+
} : "ssg";
|
|
7300
7376
|
}
|
|
7301
|
-
|
|
7302
|
-
|
|
7303
|
-
|
|
7304
|
-
|
|
7305
|
-
|
|
7306
|
-
|
|
7307
|
-
|
|
7308
|
-
|
|
7309
|
-
|
|
7310
|
-
|
|
7311
|
-
|
|
7312
|
-
|
|
7313
|
-
|
|
7314
|
-
|
|
7315
|
-
|
|
7316
|
-
|
|
7317
|
-
|
|
7318
|
-
|
|
7319
|
-
|
|
7320
|
-
|
|
7321
|
-
|
|
7322
|
-
|
|
7323
|
-
|
|
7324
|
-
|
|
7325
|
-
|
|
7326
|
-
|
|
7327
|
-
|
|
7328
|
-
|
|
7329
|
-
|
|
7330
|
-
|
|
7331
|
-
|
|
7332
|
-
|
|
7333
|
-
|
|
7334
|
-
|
|
7335
|
-
|
|
7336
|
-
|
|
7337
|
-
|
|
7338
|
-
|
|
7339
|
-
|
|
7340
|
-
|
|
7341
|
-
|
|
7342
|
-
|
|
7343
|
-
|
|
7344
|
-
|
|
7345
|
-
|
|
7346
|
-
|
|
7347
|
-
|
|
7348
|
-
|
|
7349
|
-
|
|
7350
|
-
|
|
7351
|
-
|
|
7352
|
-
|
|
7353
|
-
|
|
7354
|
-
|
|
7355
|
-
|
|
7356
|
-
|
|
7357
|
-
|
|
7358
|
-
|
|
7359
|
-
|
|
7360
|
-
|
|
7361
|
-
|
|
7362
|
-
|
|
7363
|
-
|
|
7364
|
-
|
|
7365
|
-
|
|
7366
|
-
|
|
7377
|
+
const cache = createIsrCacheHandler({
|
|
7378
|
+
...config,
|
|
7379
|
+
routes: cacheRoutes
|
|
7380
|
+
}, {
|
|
7381
|
+
buildId: process.env.APP_VERSION ?? staticCspIndex.buildId,
|
|
7382
|
+
resolveInvalidationPath: resolveSsgIdentity,
|
|
7383
|
+
staticSeedAdmission: (req, res) => admitRequest(staticHtmlLimiter, req, res),
|
|
7384
|
+
staticSeedInfo: (pathname) => {
|
|
7385
|
+
const htmlPath = ssgFiles.get(pathname);
|
|
7386
|
+
if (!htmlPath) return;
|
|
7387
|
+
const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
|
|
7388
|
+
return generatedAt === void 0 || generatedAt > Date.now() ? void 0 : { generatedAt };
|
|
7389
|
+
},
|
|
7390
|
+
staticSeed: async (pathname, policy) => {
|
|
7391
|
+
const htmlPath = ssgFiles.get(pathname);
|
|
7392
|
+
if (!htmlPath) return;
|
|
7393
|
+
const hashes = staticCspIndex.scriptHashes.get(htmlPath);
|
|
7394
|
+
if (!hashes) return;
|
|
7395
|
+
const absolute = path.join(clientDir, htmlPath);
|
|
7396
|
+
const body = await fs$3.readFile(absolute);
|
|
7397
|
+
const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
|
|
7398
|
+
if (generatedAt === void 0) return;
|
|
7399
|
+
return {
|
|
7400
|
+
body,
|
|
7401
|
+
statusCode: 200,
|
|
7402
|
+
contentType: "text/html; charset=utf-8",
|
|
7403
|
+
headers: {
|
|
7404
|
+
"content-type": "text/html; charset=utf-8",
|
|
7405
|
+
"content-security-policy": applyStaticScriptPolicy(policy, hashes),
|
|
7406
|
+
"cache-control": "no-cache",
|
|
7407
|
+
"x-served-by": "ssg-static"
|
|
7408
|
+
},
|
|
7409
|
+
storedAt: generatedAt,
|
|
7410
|
+
expiresAt: 0,
|
|
7411
|
+
hardExpiresAt: 0,
|
|
7412
|
+
tags: []
|
|
7413
|
+
};
|
|
7414
|
+
},
|
|
7415
|
+
store: createAutoCacheStore({
|
|
7416
|
+
responseNamespace: `production:${process.env.ISR_CACHE_NAMESPACE ?? "default"}`,
|
|
7417
|
+
redisUrl: redisCfg?.url,
|
|
7418
|
+
redisHost: redisCfg?.host,
|
|
7419
|
+
redisPort: redisCfg?.port,
|
|
7420
|
+
redisPassword: redisCfg?.password,
|
|
7421
|
+
redisKeyPrefix: redisCfg?.keyPrefix
|
|
7422
|
+
}),
|
|
7423
|
+
invalidationBus: hasRedisConfig ? new RedisInvalidationBus({
|
|
7424
|
+
url: redisCfg?.url,
|
|
7425
|
+
host: redisCfg?.host,
|
|
7426
|
+
port: redisCfg?.port,
|
|
7427
|
+
password: redisCfg?.password,
|
|
7428
|
+
keyPrefix: redisCfg?.keyPrefix,
|
|
7429
|
+
channel: redisCfg?.invalidationChannel
|
|
7430
|
+
}) : void 0
|
|
7431
|
+
});
|
|
7432
|
+
cleanups.push(() => cache.destroy());
|
|
7433
|
+
if (opsConfig.inventory.enabled) {
|
|
7434
|
+
const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-BjwSKfyf.js");
|
|
7435
|
+
app.use(createCacheInspectorMiddleware(cache, opsConfig));
|
|
7436
|
+
logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
|
|
7437
|
+
}
|
|
7438
|
+
app.use((req, res, next) => {
|
|
7439
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
7440
|
+
let logical;
|
|
7441
|
+
try {
|
|
7442
|
+
logical = decodeHtmlPathname(req.path);
|
|
7443
|
+
} catch {
|
|
7444
|
+
res.status(400).end();
|
|
7445
|
+
return;
|
|
7367
7446
|
}
|
|
7447
|
+
const known = ssgAliases.get(logical);
|
|
7448
|
+
if (!known) return next();
|
|
7449
|
+
const canonical = explicitRoutes.get(logical) ?? known;
|
|
7450
|
+
if (req.path === canonical) return next();
|
|
7451
|
+
redirectLocal(res, 308, canonical, readRedirectQuery(req.url));
|
|
7452
|
+
});
|
|
7453
|
+
app.use(cache);
|
|
7454
|
+
const staticHtml = createStaticHtmlMiddlewareWithLimiter(clientDir, staticCspIndex, staticHtmlLimiter);
|
|
7455
|
+
app.use((req, res, next) => {
|
|
7456
|
+
if (res.getHeader("X-Resolved-Mode") === "ssg" || ssgAliases.has(decodeHtmlPathname(req.path)) && explicitRoutes.has(decodeHtmlPathname(req.path))) return next();
|
|
7457
|
+
staticHtml(req, res, next);
|
|
7458
|
+
});
|
|
7459
|
+
if (opsConfig.metrics.enabled) app.get("/metrics", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("metrics", opsConfig), async (_req, res) => {
|
|
7460
|
+
try {
|
|
7461
|
+
res.set("content-type", promRegistry.contentType);
|
|
7462
|
+
res.end(await promRegistry.metrics());
|
|
7463
|
+
} catch (err) {
|
|
7464
|
+
res.status(500).type("text/plain").end(`metrics error: ${String(err)}`);
|
|
7465
|
+
}
|
|
7466
|
+
});
|
|
7467
|
+
const seoCfg = resolveSeoConfig(config);
|
|
7468
|
+
const seo = SEOEngine.getInstance({ baseUrl: seoCfg.baseUrl });
|
|
7469
|
+
cleanups.push(() => seo.shutdown());
|
|
7470
|
+
await seo.initialize();
|
|
7471
|
+
app.get("/sitemap.xml", async (_req, res) => {
|
|
7472
|
+
try {
|
|
7473
|
+
const xml = await seo.generateSitemap(extractRoutesForSitemap(config));
|
|
7474
|
+
res.set("content-type", "application/xml; charset=utf-8");
|
|
7475
|
+
res.set("cache-control", "public, max-age=3600");
|
|
7476
|
+
res.end(xml);
|
|
7477
|
+
} catch (err) {
|
|
7478
|
+
res.status(500).type("text/plain").end(`sitemap error: ${String(err)}`);
|
|
7479
|
+
}
|
|
7480
|
+
});
|
|
7481
|
+
app.get("/robots.txt", (_req, res) => {
|
|
7482
|
+
res.set("content-type", "text/plain; charset=utf-8");
|
|
7483
|
+
res.set("cache-control", "public, max-age=3600");
|
|
7484
|
+
res.end(seo.generateRobotsTxt());
|
|
7485
|
+
});
|
|
7486
|
+
const { renderError500Html } = await import("./error500-template-CFdKp8YG.js");
|
|
7487
|
+
app.all(/.*/, createProductionRequestHandler(rscHandler, (err, _req, res) => {
|
|
7488
|
+
logger$8.error("[Server]", "请求处理异常", err);
|
|
7489
|
+
if (!res.headersSent) {
|
|
7490
|
+
const traceId = getTraceId();
|
|
7491
|
+
res.status(500).type("text/html; charset=utf-8").send(renderError500Html(traceId));
|
|
7492
|
+
} else res.destroy();
|
|
7493
|
+
}));
|
|
7494
|
+
return {
|
|
7495
|
+
app,
|
|
7496
|
+
close
|
|
7368
7497
|
};
|
|
7498
|
+
} catch (error) {
|
|
7499
|
+
await close().catch((cleanupError) => logger$8.error("[Server]", "Production initialization cleanup failed", cleanupError));
|
|
7500
|
+
throw error;
|
|
7369
7501
|
}
|
|
7370
|
-
|
|
7371
|
-
|
|
7372
|
-
|
|
7373
|
-
|
|
7374
|
-
|
|
7375
|
-
|
|
7376
|
-
|
|
7377
|
-
const finalUrls = urls.length > 0 ? urls : ["/"];
|
|
7378
|
-
for (const url of finalUrls) {
|
|
7379
|
-
if (this.shouldExcludeUrl(url)) continue;
|
|
7380
|
-
sitemap.write({
|
|
7381
|
-
url,
|
|
7382
|
-
priority: this.getUrlPriority(url),
|
|
7383
|
-
changefreq: this.getUrlChangeFreq(url),
|
|
7384
|
-
lastmod: (/* @__PURE__ */ new Date()).toISOString()
|
|
7385
|
-
});
|
|
7502
|
+
}
|
|
7503
|
+
var rawRequestBodies = /* @__PURE__ */ new WeakMap();
|
|
7504
|
+
function createProductionJsonMiddleware() {
|
|
7505
|
+
return express.json({
|
|
7506
|
+
limit: "1mb",
|
|
7507
|
+
verify: (req, _res, body) => {
|
|
7508
|
+
rawRequestBodies.set(req, Buffer.from(body));
|
|
7386
7509
|
}
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7391
|
-
|
|
7510
|
+
});
|
|
7511
|
+
}
|
|
7512
|
+
/** Own cancellation until the outgoing response finishes, not IncomingMessage.close. */
|
|
7513
|
+
function createProductionRequestHandler(handler, onError) {
|
|
7514
|
+
return async (req, res) => {
|
|
7515
|
+
const controller = new AbortController();
|
|
7516
|
+
const cleanup = () => {
|
|
7517
|
+
req.removeListener("aborted", onAborted);
|
|
7518
|
+
res.removeListener("close", onClose);
|
|
7519
|
+
res.removeListener("finish", cleanup);
|
|
7520
|
+
};
|
|
7521
|
+
const onAborted = () => {
|
|
7522
|
+
controller.abort(new DOMException("Client disconnected", "AbortError"));
|
|
7523
|
+
cleanup();
|
|
7524
|
+
};
|
|
7525
|
+
const onClose = () => {
|
|
7526
|
+
if (!res.writableFinished) onAborted();
|
|
7527
|
+
else cleanup();
|
|
7528
|
+
};
|
|
7529
|
+
req.once("aborted", onAborted);
|
|
7530
|
+
res.once("close", onClose);
|
|
7531
|
+
res.once("finish", cleanup);
|
|
7532
|
+
if (req.aborted || res.destroyed) onAborted();
|
|
7533
|
+
try {
|
|
7534
|
+
if (controller.signal.aborted) return;
|
|
7535
|
+
const response = await handler(nodeToWebRequest(req, controller.signal));
|
|
7536
|
+
if (controller.signal.aborted) {
|
|
7537
|
+
response.body?.cancel(controller.signal.reason).catch(() => {});
|
|
7538
|
+
return;
|
|
7539
|
+
}
|
|
7540
|
+
await pipeWebResponse(response, res);
|
|
7541
|
+
} catch (error) {
|
|
7542
|
+
if (!controller.signal.aborted) onError(error, req, res);
|
|
7543
|
+
} finally {
|
|
7544
|
+
if (controller.signal.aborted || res.writableFinished) cleanup();
|
|
7545
|
+
}
|
|
7546
|
+
};
|
|
7547
|
+
}
|
|
7548
|
+
function nodeToWebRequest(req, signal) {
|
|
7549
|
+
const host = String(req.headers.host || "localhost");
|
|
7550
|
+
const transport = req.socket?.encrypted ? "https" : "http";
|
|
7551
|
+
const selected = req.protocol?.toLowerCase();
|
|
7552
|
+
const url = `${selected === "https" || selected === "http" ? selected : transport}://${host}${req.url}`;
|
|
7553
|
+
const headers = new Headers();
|
|
7554
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
7555
|
+
if (v == null) continue;
|
|
7556
|
+
if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
|
|
7557
|
+
else headers.set(k, String(v));
|
|
7392
7558
|
}
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
|
|
7398
|
-
|
|
7399
|
-
|
|
7400
|
-
|
|
7401
|
-
|
|
7402
|
-
].join("\n");
|
|
7559
|
+
const method = req.method || "GET";
|
|
7560
|
+
const init = {
|
|
7561
|
+
method,
|
|
7562
|
+
headers,
|
|
7563
|
+
signal
|
|
7564
|
+
};
|
|
7565
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
7566
|
+
init.body = rawRequestBodies.get(req) ?? Readable.toWeb(req);
|
|
7567
|
+
init.duplex = "half";
|
|
7403
7568
|
}
|
|
7404
|
-
|
|
7405
|
-
|
|
7406
|
-
|
|
7407
|
-
|
|
7408
|
-
|
|
7569
|
+
return new Request(url, init);
|
|
7570
|
+
}
|
|
7571
|
+
async function pipeWebResponse(response, res) {
|
|
7572
|
+
res.status(response.status);
|
|
7573
|
+
response.headers.forEach((v, k) => {
|
|
7574
|
+
if (k.toLowerCase() === "content-length" || k.toLowerCase() === "set-cookie") return;
|
|
7575
|
+
res.setHeader(k, v);
|
|
7576
|
+
});
|
|
7577
|
+
const cookies = response.headers.getSetCookie();
|
|
7578
|
+
if (cookies.length) {
|
|
7579
|
+
const existing = res.getHeader?.("set-cookie");
|
|
7580
|
+
res.setHeader("set-cookie", [...existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)], ...cookies]);
|
|
7409
7581
|
}
|
|
7410
|
-
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
this.initialized = false;
|
|
7414
|
-
this.logger.debug("✅ SEO 引擎已关闭");
|
|
7582
|
+
if (!response.body) {
|
|
7583
|
+
res.end();
|
|
7584
|
+
return;
|
|
7415
7585
|
}
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
url: `${this.config.baseUrl}${url}`,
|
|
7422
|
-
title: this.generateTitle(url),
|
|
7423
|
-
description: this.generateDescription(url, pageType),
|
|
7424
|
-
keywords: [...this.config.keywords, ...this.extractKeywordsFromUrl(url)],
|
|
7425
|
-
image: this.config.openGraph.defaultImage,
|
|
7426
|
-
type: pageType,
|
|
7427
|
-
language: this.detectLanguage(url, context),
|
|
7428
|
-
modifiedTime: (/* @__PURE__ */ new Date()).toISOString()
|
|
7586
|
+
const nodeReadable = Readable.fromWeb(response.body);
|
|
7587
|
+
await new Promise((resolve, reject) => {
|
|
7588
|
+
const cleanup = () => {
|
|
7589
|
+
res.removeListener?.("close", onClose);
|
|
7590
|
+
res.removeListener?.("error", onError);
|
|
7429
7591
|
};
|
|
7430
|
-
|
|
7431
|
-
|
|
7432
|
-
|
|
7433
|
-
|
|
7434
|
-
|
|
7435
|
-
|
|
7436
|
-
|
|
7437
|
-
|
|
7438
|
-
|
|
7439
|
-
|
|
7440
|
-
|
|
7441
|
-
|
|
7442
|
-
|
|
7443
|
-
|
|
7444
|
-
|
|
7445
|
-
|
|
7446
|
-
|
|
7447
|
-
|
|
7448
|
-
if (
|
|
7592
|
+
const onClose = () => {
|
|
7593
|
+
nodeReadable.destroy();
|
|
7594
|
+
cleanup();
|
|
7595
|
+
resolve();
|
|
7596
|
+
};
|
|
7597
|
+
const onError = (error) => {
|
|
7598
|
+
nodeReadable.destroy();
|
|
7599
|
+
cleanup();
|
|
7600
|
+
reject(error);
|
|
7601
|
+
};
|
|
7602
|
+
res.once("close", onClose);
|
|
7603
|
+
res.once("error", onError);
|
|
7604
|
+
nodeReadable.once("end", () => {
|
|
7605
|
+
cleanup();
|
|
7606
|
+
resolve();
|
|
7607
|
+
});
|
|
7608
|
+
nodeReadable.once("error", (error) => {
|
|
7609
|
+
cleanup();
|
|
7610
|
+
if (res.headersSent) res.destroy?.(error);
|
|
7611
|
+
reject(error);
|
|
7612
|
+
});
|
|
7613
|
+
if (res.destroyed) onClose();
|
|
7614
|
+
else nodeReadable.pipe(res);
|
|
7615
|
+
});
|
|
7616
|
+
}
|
|
7617
|
+
function createStaticHtmlMiddlewareWithLimiter(clientDir, index, limiter) {
|
|
7618
|
+
const targets = /* @__PURE__ */ new WeakMap();
|
|
7619
|
+
const guarded = express.Router();
|
|
7620
|
+
guarded.use(limiter);
|
|
7621
|
+
guarded.use((req, res, next) => {
|
|
7622
|
+
const target = targets.get(req);
|
|
7623
|
+
targets.delete(req);
|
|
7624
|
+
if (!target) return next();
|
|
7625
|
+
res.setHeader("Content-Security-Policy", applyStaticScriptPolicy(String(res.getHeader("Content-Security-Policy") ?? "default-src 'self'"), target.hashes));
|
|
7626
|
+
res.setHeader("Cache-Control", "public, max-age=3600");
|
|
7627
|
+
res.setHeader("X-Served-By", "ssg-static");
|
|
7628
|
+
res.sendFile(target.htmlPath, {
|
|
7629
|
+
root: clientDir,
|
|
7630
|
+
maxAge: "1h",
|
|
7631
|
+
dotfiles: "ignore"
|
|
7632
|
+
}, (error) => {
|
|
7633
|
+
if (error) next(error);
|
|
7634
|
+
});
|
|
7635
|
+
});
|
|
7636
|
+
return (req, res, next) => {
|
|
7637
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
7638
|
+
let pathname;
|
|
7639
|
+
try {
|
|
7640
|
+
pathname = decodeHtmlPathname(req.path);
|
|
7641
|
+
} catch {
|
|
7642
|
+
res.status(400).end();
|
|
7643
|
+
return;
|
|
7449
7644
|
}
|
|
7450
|
-
|
|
7451
|
-
|
|
7452
|
-
|
|
7453
|
-
|
|
7454
|
-
|
|
7455
|
-
|
|
7645
|
+
const relative = pathname.slice(1);
|
|
7646
|
+
const htmlPath = relative.endsWith("/") || !relative ? relative + "index.html" : relative.toLowerCase().endsWith(".html") ? relative : relative + "/index.html";
|
|
7647
|
+
const hashes = index.scriptHashes.get(htmlPath);
|
|
7648
|
+
if (!hashes) return next();
|
|
7649
|
+
targets.set(req, {
|
|
7650
|
+
htmlPath,
|
|
7651
|
+
hashes
|
|
7652
|
+
});
|
|
7653
|
+
guarded(req, res, next);
|
|
7654
|
+
};
|
|
7655
|
+
}
|
|
7656
|
+
/** Asset serving must never discover HTML outside the validated build manifest. */
|
|
7657
|
+
function normalizeStaticAssetPathname(pathname) {
|
|
7658
|
+
return path.posix.normalize(decodeURIComponent(new URL(`http://localhost${pathname}`).pathname).replaceAll("\\", "/"));
|
|
7659
|
+
}
|
|
7660
|
+
function createStaticAssetMiddleware(clientDir) {
|
|
7661
|
+
const assets = express.static(clientDir, {
|
|
7662
|
+
index: false,
|
|
7663
|
+
redirect: false,
|
|
7664
|
+
maxAge: "1h",
|
|
7665
|
+
fallthrough: true,
|
|
7666
|
+
setHeaders: (res, filePath) => {
|
|
7667
|
+
if (filePath.includes(`${path.sep}assets${path.sep}`)) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
7668
|
+
else if (/\.(jpe?g|png|webp|avif|gif|svg|ico|woff2?)$/i.test(filePath)) res.setHeader("Cache-Control", "public, max-age=604800, stale-while-revalidate=86400");
|
|
7456
7669
|
}
|
|
7457
|
-
|
|
7670
|
+
});
|
|
7671
|
+
return (req, res, next) => {
|
|
7672
|
+
let pathname;
|
|
7673
|
+
try {
|
|
7674
|
+
pathname = normalizeStaticAssetPathname(req.path);
|
|
7675
|
+
} catch {
|
|
7676
|
+
res.status(400).end();
|
|
7677
|
+
return;
|
|
7678
|
+
}
|
|
7679
|
+
if ([".html", ".htm"].includes(path.posix.extname(pathname).toLowerCase())) return next();
|
|
7680
|
+
assets(req, res, next);
|
|
7681
|
+
};
|
|
7682
|
+
}
|
|
7683
|
+
// src/server/httpServer.ts
|
|
7684
|
+
/**
|
|
7685
|
+
* HTTP 服务器启动器
|
|
7686
|
+
*
|
|
7687
|
+
* Node origin 只启动 HTTP/1.1。
|
|
7688
|
+
*
|
|
7689
|
+
* TLS / HTTP/2 / HTTP/3 / Brotli 属于 CDN / Ingress / Nginx / Envoy / ALB 边界。
|
|
7690
|
+
* isr-engine 负责 SSR/ISR/RSC/cache/revalidate,不把网关层协议暴露为业务配置。
|
|
7691
|
+
*/
|
|
7692
|
+
var logger$1 = Logger.getInstance();
|
|
7693
|
+
var DEFAULT_TIMEOUTS = {
|
|
7694
|
+
requestTimeoutMs: 6e4,
|
|
7695
|
+
headersTimeoutMs: 15e3,
|
|
7696
|
+
keepAliveTimeoutMs: 5e3,
|
|
7697
|
+
idleTimeoutMs: 3e4,
|
|
7698
|
+
shutdownTimeoutMs: 5e3,
|
|
7699
|
+
maxRequestsPerSocket: 0
|
|
7700
|
+
};
|
|
7701
|
+
var LISTEN_BACKLOG = 8192;
|
|
7702
|
+
var serverSockets = /* @__PURE__ */ new WeakMap();
|
|
7703
|
+
function applyHttpTimeouts(server) {
|
|
7704
|
+
server.requestTimeout = DEFAULT_TIMEOUTS.requestTimeoutMs;
|
|
7705
|
+
server.headersTimeout = DEFAULT_TIMEOUTS.headersTimeoutMs;
|
|
7706
|
+
server.keepAliveTimeout = DEFAULT_TIMEOUTS.keepAliveTimeoutMs;
|
|
7707
|
+
server.maxRequestsPerSocket = DEFAULT_TIMEOUTS.maxRequestsPerSocket;
|
|
7708
|
+
server.setTimeout(DEFAULT_TIMEOUTS.idleTimeoutMs);
|
|
7709
|
+
server.__shutdownTimeoutMs = DEFAULT_TIMEOUTS.shutdownTimeoutMs;
|
|
7710
|
+
}
|
|
7711
|
+
function getServerAddress(server) {
|
|
7712
|
+
const addr = server.address();
|
|
7713
|
+
if (addr && typeof addr === "object") {
|
|
7714
|
+
const info = addr;
|
|
7715
|
+
return {
|
|
7716
|
+
address: info.address,
|
|
7717
|
+
port: info.port
|
|
7718
|
+
};
|
|
7458
7719
|
}
|
|
7459
|
-
|
|
7460
|
-
|
|
7461
|
-
|
|
7462
|
-
|
|
7463
|
-
|
|
7464
|
-
|
|
7465
|
-
|
|
7466
|
-
|
|
7467
|
-
|
|
7468
|
-
|
|
7469
|
-
|
|
7470
|
-
|
|
7471
|
-
|
|
7472
|
-
|
|
7473
|
-
|
|
7474
|
-
|
|
7475
|
-
|
|
7476
|
-
|
|
7477
|
-
|
|
7478
|
-
|
|
7479
|
-
|
|
7480
|
-
|
|
7481
|
-
|
|
7482
|
-
|
|
7720
|
+
return {
|
|
7721
|
+
address: "<unknown>",
|
|
7722
|
+
port: 0
|
|
7723
|
+
};
|
|
7724
|
+
}
|
|
7725
|
+
function formatHostForUrl(address) {
|
|
7726
|
+
if (address === "::" || address === "0.0.0.0" || address === "") return "localhost";
|
|
7727
|
+
if (address.includes(":") && !address.startsWith("[")) return `[${address}]`;
|
|
7728
|
+
return address;
|
|
7729
|
+
}
|
|
7730
|
+
/** 启动 HTTP/1.1 服务器 */
|
|
7731
|
+
function startHttp1Server(app, config) {
|
|
7732
|
+
const maxAttempts = config.strictPort === false ? 20 : 1;
|
|
7733
|
+
const startPort = config.port;
|
|
7734
|
+
return new Promise((resolve, reject) => {
|
|
7735
|
+
const server = createServer$1(app);
|
|
7736
|
+
applyHttpTimeouts(server);
|
|
7737
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
7738
|
+
serverSockets.set(server, sockets);
|
|
7739
|
+
server.on("connection", (socket) => {
|
|
7740
|
+
sockets.add(socket);
|
|
7741
|
+
socket.once("close", () => sockets.delete(socket));
|
|
7742
|
+
});
|
|
7743
|
+
let attempt = 0;
|
|
7744
|
+
const listen = (port) => {
|
|
7745
|
+
server.listen({
|
|
7746
|
+
port,
|
|
7747
|
+
host: config.host,
|
|
7748
|
+
backlog: LISTEN_BACKLOG
|
|
7749
|
+
});
|
|
7750
|
+
};
|
|
7751
|
+
server.on("listening", () => {
|
|
7752
|
+
const { address, port } = getServerAddress(server);
|
|
7753
|
+
const url = `http://${formatHostForUrl(address)}:${port || config.port}`;
|
|
7754
|
+
logger$1.info(`HTTP/1.1 服务器已启动: ${url}`);
|
|
7755
|
+
resolve({
|
|
7756
|
+
server,
|
|
7757
|
+
url
|
|
7758
|
+
});
|
|
7759
|
+
});
|
|
7760
|
+
server.on("error", (error) => {
|
|
7761
|
+
if (error.code === "EADDRINUSE" && attempt + 1 < maxAttempts) {
|
|
7762
|
+
attempt += 1;
|
|
7763
|
+
const nextPort = startPort + attempt;
|
|
7764
|
+
logger$1.warn(`端口 ${startPort + attempt - 1} 已占用,尝试 ${nextPort}`);
|
|
7765
|
+
listen(nextPort);
|
|
7766
|
+
return;
|
|
7483
7767
|
}
|
|
7768
|
+
reject(error);
|
|
7484
7769
|
});
|
|
7485
|
-
|
|
7486
|
-
}
|
|
7487
|
-
|
|
7488
|
-
|
|
7489
|
-
|
|
7490
|
-
|
|
7491
|
-
|
|
7492
|
-
|
|
7493
|
-
|
|
7494
|
-
|
|
7495
|
-
|
|
7496
|
-
|
|
7497
|
-
|
|
7498
|
-
|
|
7499
|
-
|
|
7500
|
-
|
|
7501
|
-
|
|
7502
|
-
|
|
7503
|
-
|
|
7504
|
-
|
|
7505
|
-
|
|
7506
|
-
|
|
7507
|
-
|
|
7508
|
-
|
|
7509
|
-
|
|
7510
|
-
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
|
|
7514
|
-
|
|
7515
|
-
|
|
7516
|
-
|
|
7517
|
-
|
|
7518
|
-
|
|
7519
|
-
|
|
7520
|
-
|
|
7521
|
-
|
|
7522
|
-
|
|
7523
|
-
|
|
7524
|
-
|
|
7525
|
-
|
|
7526
|
-
|
|
7527
|
-
|
|
7528
|
-
|
|
7529
|
-
|
|
7530
|
-
|
|
7531
|
-
|
|
7532
|
-
|
|
7533
|
-
|
|
7534
|
-
|
|
7535
|
-
|
|
7536
|
-
|
|
7537
|
-
|
|
7770
|
+
listen(startPort);
|
|
7771
|
+
});
|
|
7772
|
+
}
|
|
7773
|
+
/** 启动 Node origin 服务器 */
|
|
7774
|
+
function startServer(app, config) {
|
|
7775
|
+
return startHttp1Server(app, config);
|
|
7776
|
+
}
|
|
7777
|
+
var closingServers = /* @__PURE__ */ new WeakMap();
|
|
7778
|
+
/** Stop accepting requests, drain active responses, then force overdue connections closed. */
|
|
7779
|
+
function closeServer(server) {
|
|
7780
|
+
const existing = closingServers.get(server);
|
|
7781
|
+
if (existing) return existing;
|
|
7782
|
+
const closing = new Promise((resolve, reject) => {
|
|
7783
|
+
const shutdownTimeoutMs = server.__shutdownTimeoutMs ?? DEFAULT_TIMEOUTS.shutdownTimeoutMs;
|
|
7784
|
+
const timeout = setTimeout(() => {
|
|
7785
|
+
try {
|
|
7786
|
+
server.closeAllConnections();
|
|
7787
|
+
for (const socket of serverSockets.get(server) ?? []) socket.destroy();
|
|
7788
|
+
} catch (error) {
|
|
7789
|
+
reject(error);
|
|
7790
|
+
}
|
|
7791
|
+
}, shutdownTimeoutMs);
|
|
7792
|
+
try {
|
|
7793
|
+
server.close((error) => {
|
|
7794
|
+
clearTimeout(timeout);
|
|
7795
|
+
if (error) reject(error);
|
|
7796
|
+
else resolve();
|
|
7797
|
+
});
|
|
7798
|
+
server.closeIdleConnections();
|
|
7799
|
+
} catch (error) {
|
|
7800
|
+
clearTimeout(timeout);
|
|
7801
|
+
reject(error);
|
|
7802
|
+
}
|
|
7803
|
+
});
|
|
7804
|
+
closingServers.set(server, closing);
|
|
7805
|
+
return closing;
|
|
7806
|
+
}
|
|
7807
|
+
// src/server/manager.ts
|
|
7808
|
+
/**
|
|
7809
|
+
* 服务器管理器
|
|
7810
|
+
* 整合 Vite 开发服务器、HTTP 服务器和中间件
|
|
7811
|
+
* ISREngine 唯一需要关心的服务器入口
|
|
7812
|
+
*/
|
|
7813
|
+
var logger = Logger.getInstance();
|
|
7814
|
+
/** 服务器上下文 */
|
|
7815
|
+
var serverContext = null;
|
|
7816
|
+
var productionRuntime;
|
|
7817
|
+
var starting;
|
|
7818
|
+
var stopping;
|
|
7819
|
+
var developmentCleanups = [];
|
|
7820
|
+
async function closeDevelopmentResources() {
|
|
7821
|
+
const owned = developmentCleanups.splice(0).reverse();
|
|
7822
|
+
const failures = (await Promise.allSettled(owned.map((close) => Promise.resolve().then(close)))).filter((result) => result.status === "rejected");
|
|
7823
|
+
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Development cleanup failed");
|
|
7824
|
+
}
|
|
7825
|
+
/** Retain the optional public ServerContext manifest for programmatic consumers. */
|
|
7826
|
+
function loadProdManifest() {
|
|
7827
|
+
for (const relativePath of [
|
|
7828
|
+
"dist/.vite/manifest.json",
|
|
7829
|
+
"dist/client/.vite/manifest.json",
|
|
7830
|
+
"dist/manifest.json"
|
|
7831
|
+
]) {
|
|
7832
|
+
const absolutePath = path.resolve(process.cwd(), relativePath);
|
|
7833
|
+
if (!fs.existsSync(absolutePath)) continue;
|
|
7834
|
+
try {
|
|
7835
|
+
return JSON.parse(fs.readFileSync(absolutePath, "utf8"));
|
|
7836
|
+
} catch {
|
|
7837
|
+
logger.warn(`Manifest 解析失败: ${relativePath}`);
|
|
7838
|
+
}
|
|
7538
7839
|
}
|
|
7539
|
-
|
|
7540
|
-
/** 创建 SEO 引擎实例(获取单例) */
|
|
7541
|
-
function createSEOEngine(config) {
|
|
7542
|
-
return SEOEngine.getInstance(config);
|
|
7840
|
+
return null;
|
|
7543
7841
|
}
|
|
7544
|
-
//#endregion
|
|
7545
|
-
//#region src/engine/seo/resolveSeoConfig.ts
|
|
7546
7842
|
/**
|
|
7547
|
-
*
|
|
7548
|
-
*
|
|
7549
|
-
* 设计目标:
|
|
7550
|
-
* - SEO 是 SSR/ISR 基础能力,始终启用,不暴露 enabled/sitemap/robots 开关
|
|
7551
|
-
* - 用户在 ssr.config.ts 里只关心 prod 域名是什么
|
|
7552
|
-
* - prod 只读 runtime.site,避免 SEO baseUrl 变成隐藏环境变量
|
|
7553
|
-
* - dev 自动用 localhost,降低本地启动成本
|
|
7843
|
+
* 初始化开发模式服务器上下文
|
|
7554
7844
|
*/
|
|
7555
|
-
|
|
7556
|
-
|
|
7845
|
+
async function initDevContext(requestHandler, config) {
|
|
7846
|
+
logger.info("🔧 初始化开发模式服务器...");
|
|
7847
|
+
const viteDevMiddleware = await createViteDevServer();
|
|
7848
|
+
bindRuntimeOpsConfig(requestHandler, getRuntimeOpsConfig(viteDevMiddleware) ?? resolveOpsConfig(config, "development"));
|
|
7849
|
+
return {
|
|
7850
|
+
requestHandler,
|
|
7851
|
+
viteDevMiddleware,
|
|
7852
|
+
isDev: true,
|
|
7853
|
+
manifest: null,
|
|
7854
|
+
httpServer: null
|
|
7855
|
+
};
|
|
7856
|
+
}
|
|
7557
7857
|
/**
|
|
7558
|
-
*
|
|
7559
|
-
* 1. runtime.site
|
|
7560
|
-
* 2. dev 模式:`http://localhost:${server.port||3000}`
|
|
7561
|
-
* 3. prod 且未配置:返回空串(SEOEngine 在调用 generateSitemap 时报错给出修复提示)
|
|
7858
|
+
* 初始化服务器上下文(内部使用)
|
|
7562
7859
|
*/
|
|
7563
|
-
function
|
|
7564
|
-
|
|
7565
|
-
|
|
7566
|
-
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7570
|
-
const
|
|
7571
|
-
|
|
7572
|
-
|
|
7860
|
+
async function initServerContext(config) {
|
|
7861
|
+
if (serverContext) return serverContext;
|
|
7862
|
+
serverContext = await initDevContext(express(), config);
|
|
7863
|
+
developmentCleanups.push(closeViteDevServer);
|
|
7864
|
+
applyBaseMiddlewaresWithOptions(serverContext);
|
|
7865
|
+
const cookieDomain = config?.runtime?.cookieDomain;
|
|
7866
|
+
serverContext.requestHandler.use((req, res, next) => {
|
|
7867
|
+
const { data, needsAnonCookie } = createServerRequestContext(req);
|
|
7868
|
+
if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
|
|
7869
|
+
requestContext.run(data, () => next());
|
|
7870
|
+
});
|
|
7871
|
+
if (config?.runtime?.i18n?.prefixDefault) {
|
|
7872
|
+
const localeRedirect = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(config.runtime.i18n) });
|
|
7873
|
+
if (localeRedirect) serverContext.requestHandler.use(localeRedirect);
|
|
7573
7874
|
}
|
|
7574
|
-
|
|
7575
|
-
|
|
7576
|
-
|
|
7577
|
-
|
|
7578
|
-
|
|
7875
|
+
const hasStaticExps = config?.runtime?.experiments && Object.keys(config.runtime.experiments).length > 0;
|
|
7876
|
+
const hasManifest = !!config?.runtime?.experimentManifest?.endpoint;
|
|
7877
|
+
if (hasStaticExps || hasManifest) {
|
|
7878
|
+
const baseOrigin = config?.runtime?.services?.api;
|
|
7879
|
+
const manifestLoader = resolveManifestLoader(config?.runtime?.experimentManifest, config?.runtime?.experiments ?? {}, baseOrigin);
|
|
7880
|
+
if (manifestLoader) {
|
|
7881
|
+
developmentCleanups.push(() => manifestLoader.destroy());
|
|
7882
|
+
await manifestLoader.init();
|
|
7883
|
+
}
|
|
7884
|
+
const exposureQueue = resolveExposureQueue(config?.runtime?.experimentTracking, baseOrigin);
|
|
7885
|
+
if (exposureQueue) developmentCleanups.push(async () => {
|
|
7886
|
+
try {
|
|
7887
|
+
await exposureQueue.flush();
|
|
7888
|
+
} finally {
|
|
7889
|
+
exposureQueue.destroy();
|
|
7890
|
+
}
|
|
7891
|
+
});
|
|
7892
|
+
serverContext.requestHandler.use(createABVariantMiddleware({
|
|
7893
|
+
experiments: config?.runtime?.experiments ?? {},
|
|
7894
|
+
manifestLoader,
|
|
7895
|
+
exposureQueue
|
|
7896
|
+
}));
|
|
7897
|
+
const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(config?.runtime?.experiments ?? {});
|
|
7898
|
+
logger.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
|
|
7899
|
+
}
|
|
7900
|
+
logger.info(`✅ 服务器上下文已初始化 (${isDev() ? "开发" : "生产"}模式)`);
|
|
7901
|
+
return serverContext;
|
|
7902
|
+
}
|
|
7903
|
+
/**
|
|
7904
|
+
* 启动服务器
|
|
7905
|
+
* @returns 服务器上下文,包含 loadRenderFunction 等方法
|
|
7906
|
+
*/
|
|
7907
|
+
function startAppServer(config, setupRoutes) {
|
|
7908
|
+
if (stopping) return stopping.then(() => startAppServer(config, setupRoutes));
|
|
7909
|
+
if (starting) return starting;
|
|
7910
|
+
if (serverContext?.httpServer) return Promise.resolve(serverContext);
|
|
7911
|
+
starting = startAppServerInternal(config, setupRoutes).finally(() => {
|
|
7912
|
+
starting = void 0;
|
|
7913
|
+
});
|
|
7914
|
+
return starting;
|
|
7915
|
+
}
|
|
7916
|
+
async function startAppServerInternal(config, setupRoutes) {
|
|
7917
|
+
try {
|
|
7918
|
+
return await createAndListenAppServer(config, setupRoutes);
|
|
7919
|
+
} catch (error) {
|
|
7920
|
+
if (serverContext?.isDev || developmentCleanups.length) {
|
|
7921
|
+
const context = serverContext;
|
|
7922
|
+
serverContext = null;
|
|
7923
|
+
const rollback = await Promise.allSettled([context?.httpServer ? closeServer(context.httpServer) : Promise.resolve()]);
|
|
7924
|
+
rollback.push(...await Promise.allSettled([closeDevelopmentResources()]));
|
|
7925
|
+
for (const result of rollback) if (result.status === "rejected") logger.warn("Development startup cleanup failed", result.reason);
|
|
7926
|
+
}
|
|
7927
|
+
throw error;
|
|
7928
|
+
}
|
|
7929
|
+
}
|
|
7930
|
+
async function createAndListenAppServer(config, setupRoutes) {
|
|
7931
|
+
if (!isDev()) {
|
|
7932
|
+
if (serverContext) return serverContext;
|
|
7933
|
+
const runtime = await createProductionRuntime(config, { setupRoutes });
|
|
7934
|
+
try {
|
|
7935
|
+
const result = await startServer(runtime.app, config.server);
|
|
7936
|
+
productionRuntime = runtime;
|
|
7937
|
+
serverContext = {
|
|
7938
|
+
requestHandler: runtime.app,
|
|
7939
|
+
viteDevMiddleware: null,
|
|
7940
|
+
httpServer: result.server,
|
|
7941
|
+
url: result.url,
|
|
7942
|
+
isDev: false,
|
|
7943
|
+
manifest: loadProdManifest()
|
|
7944
|
+
};
|
|
7945
|
+
return serverContext;
|
|
7946
|
+
} catch (error) {
|
|
7947
|
+
try {
|
|
7948
|
+
await runtime.close();
|
|
7949
|
+
} catch (cleanupError) {
|
|
7950
|
+
logger.warn("Production startup cleanup failed", cleanupError);
|
|
7951
|
+
}
|
|
7952
|
+
throw error;
|
|
7953
|
+
}
|
|
7954
|
+
}
|
|
7955
|
+
if (!serverContext) await initServerContext(config);
|
|
7956
|
+
if (!serverContext) throw new Error("服务器上下文初始化失败");
|
|
7957
|
+
setupRoutes(serverContext.requestHandler);
|
|
7958
|
+
mountViteOrStatic(serverContext);
|
|
7959
|
+
const serverConfig = {
|
|
7960
|
+
port: config.server.port,
|
|
7961
|
+
host: config.server.host,
|
|
7962
|
+
strictPort: config.server.strictPort
|
|
7579
7963
|
};
|
|
7964
|
+
const result = await startServer(serverContext.requestHandler, serverConfig);
|
|
7965
|
+
serverContext.httpServer = result.server;
|
|
7966
|
+
serverContext.url = result.url;
|
|
7967
|
+
logger.success(`🚀 ${isDev() ? "开发" : "生产"}服务器已启动: ${result.url}`);
|
|
7968
|
+
return serverContext;
|
|
7969
|
+
}
|
|
7970
|
+
/**
|
|
7971
|
+
* 关闭服务器
|
|
7972
|
+
*/
|
|
7973
|
+
function shutdownServer() {
|
|
7974
|
+
if (stopping) return stopping;
|
|
7975
|
+
stopping = stopAppServer().finally(() => {
|
|
7976
|
+
stopping = void 0;
|
|
7977
|
+
});
|
|
7978
|
+
return stopping;
|
|
7979
|
+
}
|
|
7980
|
+
async function stopAppServer() {
|
|
7981
|
+
await starting?.catch(() => void 0);
|
|
7982
|
+
if (!serverContext) return;
|
|
7983
|
+
const context = serverContext;
|
|
7984
|
+
const runtime = productionRuntime;
|
|
7985
|
+
serverContext = null;
|
|
7986
|
+
productionRuntime = void 0;
|
|
7987
|
+
const errors = (await Promise.allSettled([context.httpServer ? closeServer(context.httpServer) : Promise.resolve()])).concat(await Promise.allSettled([Promise.resolve().then(() => context.isDev ? closeDevelopmentResources() : void 0), Promise.resolve().then(() => runtime?.close())])).filter((result) => result.status === "rejected");
|
|
7988
|
+
if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Server shutdown failed");
|
|
7989
|
+
logger.success("✅ 服务器已完全关闭");
|
|
7580
7990
|
}
|
|
7581
|
-
|
|
7582
|
-
|
|
7991
|
+
// src/isr/ISRRoutes.ts
|
|
7992
|
+
var ISRRoutes = class {
|
|
7993
|
+
engine;
|
|
7994
|
+
logger;
|
|
7995
|
+
defaultMode;
|
|
7996
|
+
routes;
|
|
7997
|
+
requestLimits;
|
|
7998
|
+
constructor(engine, logger, config) {
|
|
7999
|
+
this.engine = engine;
|
|
8000
|
+
this.logger = logger;
|
|
8001
|
+
this.defaultMode = config.renderMode;
|
|
8002
|
+
this.routes = config.routes || {};
|
|
8003
|
+
this.requestLimits = config.requestLimits;
|
|
8004
|
+
}
|
|
8005
|
+
setup(requestHandler) {
|
|
8006
|
+
const seoLimiter = createRequestLimiter("seo", this.requestLimits?.seo);
|
|
8007
|
+
const opsConfig = getRuntimeOpsConfig(requestHandler) ?? resolveOpsConfig({ server: { requestLimits: this.requestLimits } }, "development");
|
|
8008
|
+
if (opsConfig.health.enabled) requestHandler.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
|
|
8009
|
+
res.json({
|
|
8010
|
+
status: "healthy",
|
|
8011
|
+
version: package_default.version,
|
|
8012
|
+
mode: "plugin-rsc",
|
|
8013
|
+
defaultRenderMode: this.defaultMode,
|
|
8014
|
+
routes: Object.keys(this.routes).length,
|
|
8015
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
8016
|
+
});
|
|
8017
|
+
});
|
|
8018
|
+
requestHandler.get("/sitemap.xml", seoLimiter, async (_req, res) => {
|
|
8019
|
+
try {
|
|
8020
|
+
const candidates = [
|
|
8021
|
+
path.resolve(process.cwd(), "dist/client/sitemap.xml"),
|
|
8022
|
+
path.resolve(process.cwd(), ".isr-hyou/ssg/sitemap.xml"),
|
|
8023
|
+
path.resolve(process.cwd(), "public/sitemap.xml")
|
|
8024
|
+
];
|
|
8025
|
+
for (const p of candidates) if (fs.existsSync(p)) {
|
|
8026
|
+
res.setHeader("Content-Type", "application/xml; charset=utf-8");
|
|
8027
|
+
res.send(await fs.promises.readFile(p, "utf-8"));
|
|
8028
|
+
return;
|
|
8029
|
+
}
|
|
8030
|
+
await this.engine.generateSeo();
|
|
8031
|
+
for (const p of candidates) if (fs.existsSync(p)) {
|
|
8032
|
+
res.setHeader("Content-Type", "application/xml; charset=utf-8");
|
|
8033
|
+
res.send(await fs.promises.readFile(p, "utf-8"));
|
|
8034
|
+
return;
|
|
8035
|
+
}
|
|
8036
|
+
res.setHeader("Content-Type", "application/xml; charset=utf-8");
|
|
8037
|
+
res.send(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>`);
|
|
8038
|
+
} catch (error) {
|
|
8039
|
+
this.logger.error("生成 sitemap 失败:", error);
|
|
8040
|
+
res.status(500).send("Internal Server Error");
|
|
8041
|
+
}
|
|
8042
|
+
});
|
|
8043
|
+
requestHandler.get("/robots.txt", seoLimiter, async (_req, res) => {
|
|
8044
|
+
try {
|
|
8045
|
+
const candidates = [
|
|
8046
|
+
path.resolve(process.cwd(), "dist/client/robots.txt"),
|
|
8047
|
+
path.resolve(process.cwd(), ".isr-hyou/ssg/robots.txt"),
|
|
8048
|
+
path.resolve(process.cwd(), "public/robots.txt")
|
|
8049
|
+
];
|
|
8050
|
+
for (const p of candidates) if (fs.existsSync(p)) {
|
|
8051
|
+
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
8052
|
+
res.send(await fs.promises.readFile(p, "utf-8"));
|
|
8053
|
+
return;
|
|
8054
|
+
}
|
|
8055
|
+
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
8056
|
+
res.send("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n");
|
|
8057
|
+
} catch (error) {
|
|
8058
|
+
this.logger.error("生成 robots.txt 失败:", error);
|
|
8059
|
+
res.status(500).send("Internal Server Error");
|
|
8060
|
+
}
|
|
8061
|
+
});
|
|
8062
|
+
this.logger.debug("ISRRoutes: 已注册 ops 端点 (/health, /sitemap.xml, /robots.txt)");
|
|
8063
|
+
}
|
|
8064
|
+
};
|
|
8065
|
+
// src/middlewares/MiddlewareComposer.ts
|
|
7583
8066
|
var MiddlewareComposer = class MiddlewareComposer {
|
|
7584
8067
|
static instance;
|
|
7585
8068
|
middlewares = [];
|
|
@@ -7620,8 +8103,7 @@ var MiddlewareComposer = class MiddlewareComposer {
|
|
|
7620
8103
|
return dispatch(0);
|
|
7621
8104
|
}
|
|
7622
8105
|
};
|
|
7623
|
-
|
|
7624
|
-
//#region src/middlewares/TraceMiddleware.ts
|
|
8106
|
+
// src/middlewares/TraceMiddleware.ts
|
|
7625
8107
|
/**
|
|
7626
8108
|
* W3C trace-context (traceparent) 解析
|
|
7627
8109
|
*
|
|
@@ -7675,8 +8157,7 @@ var traceMiddleware = async (context, next) => {
|
|
|
7675
8157
|
await next();
|
|
7676
8158
|
});
|
|
7677
8159
|
};
|
|
7678
|
-
|
|
7679
|
-
//#region src/middlewares/PerformanceMiddleware.ts
|
|
8160
|
+
// src/middlewares/PerformanceMiddleware.ts
|
|
7680
8161
|
/**
|
|
7681
8162
|
* 性能观测中间件 —— 记录中间件链的总耗时。
|
|
7682
8163
|
*
|
|
@@ -7703,8 +8184,7 @@ var performanceMiddleware = async (context, next) => {
|
|
|
7703
8184
|
}
|
|
7704
8185
|
}
|
|
7705
8186
|
};
|
|
7706
|
-
|
|
7707
|
-
//#region src/engine/ISREngine.ts
|
|
8187
|
+
// src/engine/ISREngine.ts
|
|
7708
8188
|
/**
|
|
7709
8189
|
* ISR 引擎 —— ISR/SSG/Fallback 编排层(plugin-rsc 模式)
|
|
7710
8190
|
*
|
|
@@ -7803,8 +8283,7 @@ var ISREngine = class {
|
|
|
7803
8283
|
this.logger.success("ISR 引擎关闭完成");
|
|
7804
8284
|
}
|
|
7805
8285
|
};
|
|
7806
|
-
|
|
7807
|
-
//#region src/app/createISRApp.ts
|
|
8286
|
+
// src/app/createISRApp.ts
|
|
7808
8287
|
function normalizeAppConfig(raw) {
|
|
7809
8288
|
return normalizeEngineConfig(raw);
|
|
7810
8289
|
}
|
|
@@ -7840,7 +8319,6 @@ async function createISRApp(appOption) {
|
|
|
7840
8319
|
shutdown: async () => engine.shutdown()
|
|
7841
8320
|
};
|
|
7842
8321
|
}
|
|
7843
|
-
|
|
7844
|
-
export { isCodeFile as $, createHybridCacheStore as A, spiderSsgRoutes as B, getOpsRequestLimiter as C, invalidatorRunsTotal as D, invalidatorFailuresTotal as E, resolveRenderMode as F, DEFAULT_SCAN_CONFIG as G, DEFAULT_PORT as H, FallbackChain as I, scanRoutes as J, scanComponents as K, InternalStrategies as L, getFallbackChain as M, getRouteFallbackChain as N, promRegistry as O, matchRoutePattern as P, parseRoutes as Q, RenderModes as R, createOpsAuthMiddleware as S, createPrometheusMetricsMiddleware as T, package_default as U, logger$8 as V, resolveFetchHandler as W, parseComponents as X, parseComponentFromFile as Y, parseRouteFromFile as Z, RedisInvalidationBus as _, DEFAULT_SEO_CONFIG as a, CacheCleanup as at, createCoherentCacheStore as b, startAppServer as c, startServer as d, isTestFile as et, createProductionRuntime as f, createIsrCacheMiddleware as g, createIsrCacheHandler as h, createSEOEngine as i, getEnv as it, createMemoryCacheStore as j, recordHttpRequest as k, createABVariantMiddleware as l, generateStaticCspManifest as m, ISREngine as n, isDev as nt, mergeSEOConfig as o, assertDistinctHtmlRouteIdentities as ot, prepareProductionBuild as p, scanProject as q, SEOEngine as r, isProd as rt, shutdownServer as s, resolveImageOptions as st, createISRApp as t, readDirRecursive as tt, closeServer as u, RedisCacheAdapter as v, loadConfig as w, createDevAssetRequestMiddleware as x, MemoryCacheAdapter as y, extractSsgRoutes as z };
|
|
8322
|
+
export { parseComponents as $, invalidatorRunsTotal as A, InternalStrategies as B, createCoherentCacheStore as C, loadConfig as D, getOpsRequestLimiter as E, getFallbackChain as F, DEFAULT_PORT as G, extractSsgRoutes as H, getRouteFallbackChain as I, DEFAULT_SCAN_CONFIG as J, package_default as K, matchRoutePattern as L, recordHttpRequest as M, createHybridCacheStore as N, createPrometheusMetricsMiddleware as O, createMemoryCacheStore as P, parseComponentFromFile as Q, resolveRenderMode as R, MemoryCacheAdapter as S, createOpsAuthMiddleware as T, spiderSsgRoutes as U, RenderModes as V, logger$8 as W, scanProject as X, scanComponents as Y, scanRoutes as Z, requestPinnedImage as _, closeServer as a, isDev as at, RedisInvalidationBus as b, prepareProductionBuild as c, CacheCleanup as ct, SEOEngine as d, resolveImageOptions as dt, parseRouteFromFile as et, createSEOEngine as f, createImagePlugin as g, createImageMiddleware as h, startAppServer as i, readDirRecursive as it, promRegistry as j, invalidatorFailuresTotal as k, generateStaticCspManifest as l, Logger as lt, mergeSEOConfig as m, ISREngine as n, isCodeFile as nt, startServer as o, isProd as ot, DEFAULT_SEO_CONFIG as p, resolveFetchHandler as q, shutdownServer as r, isTestFile as rt, createProductionRuntime as s, getEnv as st, createISRApp as t, parseRoutes as tt, createABVariantMiddleware as u, assertDistinctHtmlRouteIdentities as ut, createIsrCacheHandler as v, createDevAssetRequestMiddleware as w, RedisCacheAdapter as x, createIsrCacheMiddleware as y, FallbackChain as z };
|
|
7845
8323
|
|
|
7846
|
-
//# sourceMappingURL=createISRApp-
|
|
8324
|
+
//# sourceMappingURL=createISRApp-CbDPv6fY.js.map
|