child-source-bundled.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. /**
  2. * `renderChildEntry` 在 **esbuild 打包 / minify 之后**依然渲染出一份可运行的自包含入口文件。
  3. *
  4. * 为什么必须有这条测试:入口文件里的子进程逻辑是 `childMain.toString()` 拼出来的,而真实发布形态
  5. * 里这个函数先经 esbuild 打包(CLI 是单文件 bundle),desktop-agent 构建还会 minify。一旦
  6. * childMain 引用了模块作用域的任何绑定(常量、辅助函数、import),打包后那个标识符会被改名或
  7. * 提到别处,内嵌出来的文本就成了引用未定义标识符的非法程序——而且**只在发布产物里**坏,
  8. * 源码跑测试全绿。所以这里不测源码形态,专测打包形态,并且不止 `--check` 语法:真 spawn 一次
  9. * 跑到 complete,因为语法合法的坏程序(比如少了 bootstrap)照样能通过语法检查。
  10. *
  11. * esbuild 从 workspace 根解析而来(`apps/zcode-cli/package.json` 的依赖,CLI 的
  12. * `scripts/build.mjs` 用的是同一份)。
  13. */
  14. import { spawnSync } from "node:child_process";
  15. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  16. import { tmpdir } from "node:os";
  17. import { join } from "node:path";
  18. import { pathToFileURL } from "node:url";
  19. import { afterEach, describe, expect, it } from "vitest";
  20. import { build } from "esbuild";
  21. import type { renderChildEntry as renderChildEntryType } from "../src/child-source.js";
  22. const ENTRY = new URL("../src/child-source.ts", import.meta.url);
  23. const roots: string[] = [];
  24. afterEach(async () => {
  25. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  26. });
  27. async function tempRoot(prefix: string): Promise<string> {
  28. const root = await mkdtemp(join(tmpdir(), prefix));
  29. roots.push(root);
  30. return root;
  31. }
  32. /** 打包 child-source.ts 并取出打包产物里的 renderChildEntry(不是源码形态的那一份)。 */
  33. async function bundledRenderChildEntry(minify: boolean): Promise<typeof renderChildEntryType> {
  34. const root = await tempRoot("dwf-child-bundle-");
  35. const outfile = join(root, "child-source.mjs");
  36. await build({
  37. bundle: true,
  38. entryPoints: [new URL(ENTRY).pathname],
  39. format: "esm",
  40. // 与 CLI 发布构建同参:desktop-agent 是 minify + keepNames,普通/SEA 构建不压缩。
  41. keepNames: minify,
  42. minify,
  43. outfile,
  44. platform: "node",
  45. target: "node22",
  46. });
  47. const module = (await import(pathToFileURL(outfile).href)) as {
  48. renderChildEntry: typeof renderChildEntryType;
  49. };
  50. return module.renderChildEntry;
  51. }
  52. /** 按 harness 缺省策略写入口文件、真跑一次子进程,返回它写回的 NDJSON 行。 */
  53. async function runChild(
  54. render: typeof renderChildEntryType,
  55. payload: { lowered: string; args?: Record<string, unknown> },
  56. ): Promise<unknown[]> {
  57. const root = await tempRoot("dwf-child-entry-");
  58. const entryPath = join(root, "run.mjs");
  59. await writeFile(entryPath, render({ ...payload, maxOldSpaceSizeMb: 256 }, { runId: "run" }), "utf8");
  60. const result = spawnSync(process.execPath, ["--max-old-space-size=256", entryPath], {
  61. encoding: "utf8",
  62. input: "",
  63. timeout: 30_000,
  64. });
  65. // 子进程的 stderr 是这条测试唯一的归因材料——ReferenceError 之类会在这里现形。
  66. expect(result.stderr).toBe("");
  67. expect(result.status).toBe(0);
  68. return result.stdout
  69. .split("\n")
  70. .filter((line) => line.trim().length > 0)
  71. .map((line) => JSON.parse(line) as unknown);
  72. }
  73. describe.each([
  74. { label: "bundled", minify: false },
  75. { label: "bundled + minified", minify: true },
  76. ])("renderChildEntry ($label)", ({ minify }) => {
  77. it("runs the sandbox to completion", async () => {
  78. const render = await bundledRenderChildEntry(minify);
  79. const lines = await runChild(render, {
  80. lowered: '__host.log("from the sandbox");\nreturn { ok: 42 };',
  81. });
  82. expect(lines).toEqual([
  83. { kind: "event", type: "log", message: "from the sandbox" },
  84. { kind: "complete", ok: true, value: { ok: 42 } },
  85. ]);
  86. });
  87. it("keeps the sandbox bans and the curated realm intact", async () => {
  88. const render = await bundledRenderChildEntry(minify);
  89. // bootstrap 若被打包丢掉,脚本会拿到一个没有禁令的裸 context——那时这里会返回 ok:true。
  90. const lines = await runChild(render, {
  91. lowered: [
  92. "let bans = [];",
  93. 'try { Date.now(); } catch (e) { bans.push("Date.now"); }',
  94. 'try { Math.random(); } catch (e) { bans.push("Math.random"); }',
  95. 'return { bans, hasProcess: typeof process !== "undefined", hostKeys: Object.keys(__host).sort() };',
  96. ].join("\n"),
  97. });
  98. expect(lines).toEqual([
  99. {
  100. kind: "complete",
  101. ok: true,
  102. value: {
  103. bans: ["Date.now", "Math.random"],
  104. hasProcess: false,
  105. // Boundary A 的全部成员。产物的两族在这里就分得开:publishArtifact 是效应
  106. // (request/response),declareArtifact 是声明(事件通道)。
  107. hostKeys: [
  108. "args",
  109. "ask",
  110. "channel",
  111. "createActor",
  112. "declareArtifact",
  113. "enterPhase",
  114. "future",
  115. "hole",
  116. "log",
  117. "publishArtifact",
  118. "report",
  119. "worldRead",
  120. ],
  121. },
  122. },
  123. ]);
  124. });
  125. });