help-client-config-fixture.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { createServer } from "node:http";
  2. import { once } from "node:events";
  3. import { readFile } from "node:fs/promises";
  4. import { resolve } from "node:path";
  5. import { build } from "esbuild";
  6. export const HELP_FIXTURE_PATH = resolve(
  7. import.meta.dirname,
  8. "../fixtures/fs/settings/help-client-config/config.json",
  9. );
  10. export interface HelpFixtureConfig {
  11. community_urls?: Partial<Record<"zh-CN" | "en-US", string>>;
  12. feedback_url?: string;
  13. feedback_use_external_form?: boolean;
  14. }
  15. export async function readHelpFixture(): Promise<{
  16. remote: HelpFixtureConfig;
  17. local: HelpFixtureConfig;
  18. }> {
  19. return JSON.parse(await readFile(HELP_FIXTURE_PATH, "utf8"));
  20. }
  21. export async function startHelpConfigFixture(config: HelpFixtureConfig, browserBundle?: string) {
  22. let payload: unknown = { code: 0, data: { configs: { feedbackUrl: config } } };
  23. let status = 200;
  24. let raw: string | undefined;
  25. let responseGate: ReturnType<typeof Promise.withResolvers<void>> | undefined;
  26. const requests: Array<{ url: string; headers: Record<string, string | string[] | undefined> }> =
  27. [];
  28. const server = createServer((req, res) => {
  29. if (req.url === "/web-helper.js") {
  30. res.writeHead(200, { "Content-Type": "application/javascript", "Cache-Control": "no-store" });
  31. res.end(browserBundle ?? "");
  32. return;
  33. }
  34. if (req.url === "/") {
  35. res.writeHead(200, { "Content-Type": "text/html", "Cache-Control": "no-store" });
  36. res.end(
  37. '<!doctype html><meta name="viewport" content="width=device-width"><title>E2E_HELP_WEB</title><script src="/web-helper.js"></script>',
  38. );
  39. return;
  40. }
  41. if (!req.url?.startsWith("/api/v1/client/configs?")) {
  42. res.writeHead(404);
  43. res.end();
  44. return;
  45. }
  46. requests.push({ url: req.url, headers: req.headers });
  47. // 服务端刻意允许缓存;客户端 no-store 应保证新页面仍拿到新响应。
  48. res.writeHead(status, {
  49. "Content-Type": "application/json",
  50. "Cache-Control": "public, max-age=3600",
  51. "Access-Control-Allow-Origin": "*",
  52. });
  53. const body = raw ?? JSON.stringify(payload);
  54. if (responseGate) void responseGate.promise.then(() => res.end(body));
  55. else res.end(body);
  56. });
  57. server.listen(0, "127.0.0.1");
  58. await once(server, "listening");
  59. const address = server.address();
  60. if (!address || typeof address === "string") throw new Error("No fixture listener");
  61. return {
  62. origin: `http://127.0.0.1:${address.port}`,
  63. requests,
  64. holdResponses() {
  65. if (responseGate) throw new Error("Help config responses are already held");
  66. const gate = Promise.withResolvers<void>();
  67. responseGate = gate;
  68. return () => {
  69. responseGate = undefined;
  70. gate.resolve();
  71. };
  72. },
  73. setClientConfigs(configs: Record<string, unknown>) {
  74. payload = { code: 0, data: { configs } };
  75. status = 200;
  76. raw = undefined;
  77. },
  78. setConfig(value: HelpFixtureConfig) {
  79. payload = { code: 0, data: { configs: { feedbackUrl: value } } };
  80. status = 200;
  81. raw = undefined;
  82. },
  83. setFailure(kind: "http" | "business" | "json") {
  84. status = kind === "http" ? 503 : 200;
  85. payload = { code: 1, data: { configs: { feedbackUrl: config } } };
  86. raw = kind === "json" ? "invalid json" : undefined;
  87. },
  88. async close() {
  89. responseGate?.resolve();
  90. server.closeAllConnections();
  91. await new Promise<void>((resolveClose, reject) =>
  92. server.close((error) => (error ? reject(error) : resolveClose())),
  93. );
  94. },
  95. };
  96. }
  97. export async function buildHelpBrowserFixture(): Promise<string> {
  98. const result = await build({
  99. stdin: {
  100. contents:
  101. 'import * as help from "./packages/web/src/communityUrl.ts"; window.helpFixture = help;',
  102. resolveDir: resolve(import.meta.dirname, "../../../../.."),
  103. },
  104. bundle: true,
  105. write: false,
  106. platform: "browser",
  107. format: "iife",
  108. define: { "import.meta.env": "{}" },
  109. });
  110. return result.outputFiles[0]!.text;
  111. }