cloud-content-mock.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { createHash } from "node:crypto";
  2. import { readFile } from "node:fs/promises";
  3. import { createServer } from "node:http";
  4. import { pathToFileURL } from "node:url";
  5. import yazl from "yazl";
  6. /** 显式启动的开发 fixture 服务,不由生产 App 自动开启。 */
  7. export async function createCloudContentMockServer({ port = 0 } = {}) {
  8. const video = Buffer.from(
  9. await readFile(
  10. new URL("../../ui/src/assets/cloud-content/preview.webm.base64", import.meta.url),
  11. "utf8",
  12. ),
  13. "base64",
  14. );
  15. const lottie = {
  16. v: "5.13.0",
  17. fr: 30,
  18. ip: 0,
  19. op: 60,
  20. w: 400,
  21. h: 300,
  22. nm: "Cloud content demo",
  23. ddd: 0,
  24. assets: [],
  25. layers: [
  26. {
  27. ddd: 0,
  28. ind: 1,
  29. ty: 4,
  30. nm: "Rotating square",
  31. sr: 1,
  32. ks: {
  33. o: { a: 0, k: 100 },
  34. r: {
  35. a: 1,
  36. k: [
  37. { t: 0, s: [0], e: [360], i: { x: [0.67], y: [1] }, o: { x: [0.33], y: [0] } },
  38. { t: 60, s: [360] },
  39. ],
  40. },
  41. p: { a: 0, k: [200, 150, 0] },
  42. a: { a: 0, k: [0, 0, 0] },
  43. s: { a: 0, k: [100, 100, 100] },
  44. },
  45. ao: 0,
  46. shapes: [
  47. {
  48. ty: "rc",
  49. d: 1,
  50. s: { a: 0, k: [110, 110] },
  51. p: { a: 0, k: [0, 0] },
  52. r: { a: 0, k: 14 },
  53. },
  54. { ty: "fl", c: { a: 0, k: [0.2, 0.6, 1, 1] }, o: { a: 0, k: 100 }, r: 1 },
  55. ],
  56. ip: 0,
  57. op: 60,
  58. st: 0,
  59. bm: 0,
  60. },
  61. ],
  62. };
  63. const hero = await readFile(
  64. new URL("../../ui/src/assets/cloud-content/weekend-plan-hero.html", import.meta.url),
  65. );
  66. const fixture = JSON.parse(
  67. await readFile(
  68. new URL(
  69. "../../ui/src/components/cloud-content-dialog/mocks/weekendPlanResultDialog.zh-CN.json",
  70. import.meta.url,
  71. ),
  72. "utf8",
  73. ),
  74. );
  75. const zip = new yazl.ZipFile();
  76. zip.addBuffer(hero, "index.html", { mtime: new Date("2026-01-01T00:00:00Z") });
  77. zip.end();
  78. const chunks = [];
  79. for await (const chunk of zip.outputStream) chunks.push(chunk);
  80. const bytes = Buffer.concat(chunks);
  81. const sha256 = createHash("sha256").update(bytes).digest("hex");
  82. const requests = [];
  83. let baseUrl;
  84. const server = createServer((req, res) => {
  85. requests.push(req.url ?? "/");
  86. res.setHeader("Access-Control-Allow-Origin", "*");
  87. res.setHeader("Cache-Control", "no-store");
  88. res.setHeader("X-Content-Type-Options", "nosniff");
  89. if (req.method !== "GET") {
  90. res.writeHead(405).end();
  91. return;
  92. }
  93. const url = new URL(req.url ?? "/", baseUrl);
  94. if (url.pathname === "/preview.webm") {
  95. const range = req.headers.range?.match(/^bytes=(\d+)-(\d*)$/u);
  96. if (range) {
  97. const start = Number(range[1]);
  98. const end = Math.min(video.length - 1, range[2] ? Number(range[2]) : video.length - 1);
  99. if (start > end || start >= video.length) {
  100. res.writeHead(416).end();
  101. return;
  102. }
  103. res
  104. .writeHead(206, {
  105. "Content-Type": "video/webm",
  106. "Accept-Ranges": "bytes",
  107. "Content-Range": `bytes ${start}-${end}/${video.length}`,
  108. "Content-Length": end - start + 1,
  109. })
  110. .end(video.subarray(start, end + 1));
  111. } else
  112. res
  113. .writeHead(200, {
  114. "Content-Type": "video/webm",
  115. "Content-Length": video.length,
  116. "Accept-Ranges": "bytes",
  117. })
  118. .end(video);
  119. return;
  120. }
  121. if (url.pathname === "/preview.json") {
  122. res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(lottie));
  123. return;
  124. }
  125. if (["/preview-light.svg", "/preview-dark.svg"].includes(url.pathname)) {
  126. const dark = url.pathname.includes("dark");
  127. res
  128. .writeHead(200, {
  129. "Content-Type": "image/svg+xml",
  130. "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
  131. })
  132. .end(
  133. `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300"><rect width="400" height="300" fill="${dark ? "#14243c" : "#e8f1ff"}"/><rect x="140" y="65" width="120" height="120" rx="20" fill="#398deb"/><text x="200" y="240" text-anchor="middle" font-family="sans-serif" font-size="22" fill="${dark ? "#ffffff" : "#14243c"}">Cloud content preview</text></svg>`,
  134. );
  135. return;
  136. }
  137. if (url.pathname === `/bundles/${sha256}.zip`) {
  138. res
  139. .writeHead(200, { "Content-Type": "application/zip", "Content-Length": bytes.length })
  140. .end(bytes);
  141. return;
  142. }
  143. if (url.pathname === "/dialog") {
  144. const payload = structuredClone(fixture);
  145. payload.dialog.hero.bundle = {
  146. format: "zip",
  147. url: `${baseUrl}/bundles/${sha256}.zip`,
  148. entry: "index.html",
  149. sha256,
  150. sizeBytes: bytes.length,
  151. };
  152. payload.dialog.description = {
  153. format: "html",
  154. text: "<p><b>GLM-5.3-Flash</b> 已可使用。</p><p>这是本地 HTTP mock,不会领取真实套餐。</p>",
  155. };
  156. if (url.searchParams.get("locale") === "en-US") {
  157. payload.locale = "en-US";
  158. payload.dialog.title = "Your Weekend Plan is ready";
  159. payload.dialog.description.text =
  160. "<p><b>GLM-5.3-Flash</b> is ready to use.</p><p>This local HTTP mock does not claim a real plan.</p>";
  161. payload.dialog.buttons[0].label = "Model settings";
  162. payload.dialog.buttons[1].label = "Copy & share";
  163. payload.dialog.hero.data.endsAtPrefix = "Valid until";
  164. payload.dialog.hero.data.replayLabel = "Replay";
  165. payload.dialog.hero.data.benefits = ["GLM-5.3-Flash daily quota"];
  166. payload.actions["copy-share"].text = "Try the new ZCode experience.";
  167. }
  168. const english = payload.locale === "en-US";
  169. const scenario = url.searchParams.get("scenario");
  170. if (scenario === "feature") {
  171. payload.id = "new-feature-dialog";
  172. payload.kind = "feature";
  173. payload.dialog.title = english ? "Meet the new feature" : "认识新功能";
  174. payload.dialog.description.text = english
  175. ? "<p>A <b>new feature</b> is ready.</p><ul><li>Cloud-driven content</li><li>Interactive previews</li></ul>"
  176. : "<p><b>新功能</b>已准备就绪。</p><ul><li>云端内容</li><li>交互预览</li></ul>";
  177. }
  178. if (scenario === "bad_hash") payload.dialog.hero.bundle.sha256 = "0".repeat(64);
  179. const image = {
  180. type: "image",
  181. src: `${baseUrl}/preview-light.svg`,
  182. darkSrc: `${baseUrl}/preview-dark.svg`,
  183. alt: english ? "Feature preview" : "功能预览",
  184. fit: "contain",
  185. };
  186. switch (url.searchParams.get("type")) {
  187. case "image":
  188. payload.dialog.hero = image;
  189. break;
  190. case "video":
  191. payload.dialog.hero = {
  192. type: "video",
  193. src: `${baseUrl}/preview.webm`,
  194. poster: image.src,
  195. muted: true,
  196. autoplay: true,
  197. loop: true,
  198. fit: "contain",
  199. };
  200. break;
  201. case "lottie":
  202. payload.dialog.hero = {
  203. type: "lottie",
  204. src: `${baseUrl}/preview.json`,
  205. autoplay: true,
  206. loop: true,
  207. speed: 1,
  208. fallback: image,
  209. };
  210. break;
  211. }
  212. payload.dialog.buttons.push({
  213. id: "close-preview",
  214. label: english ? "Close preview" : "关闭预览",
  215. variant: "link",
  216. actionId: "close-preview",
  217. });
  218. payload.actions["close-preview"] = { type: "close" };
  219. res
  220. .writeHead(200, { "Content-Type": "application/json; charset=utf-8" })
  221. .end(JSON.stringify(payload));
  222. return;
  223. }
  224. res.writeHead(404).end();
  225. });
  226. await new Promise((resolve, reject) => {
  227. server.once("error", reject);
  228. server.listen(port, "127.0.0.1", resolve);
  229. });
  230. const address = server.address();
  231. baseUrl = `http://127.0.0.1:${address.port}`;
  232. return {
  233. url: baseUrl,
  234. requests,
  235. close: () =>
  236. new Promise((resolve, reject) => {
  237. server.close((error) => (error ? reject(error) : resolve()));
  238. server.closeIdleConnections();
  239. }),
  240. };
  241. }
  242. if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  243. const mock = await createCloudContentMockServer({
  244. port: Number(process.env.CLOUD_CONTENT_MOCK_PORT ?? 4319),
  245. });
  246. console.log(`Cloud content mock: ${mock.url}/dialog`);
  247. for (const signal of ["SIGINT", "SIGTERM"])
  248. process.once(signal, () => {
  249. void mock.close();
  250. });
  251. }