build.test.mjs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import test from "node:test";
  6. import { fileURLToPath } from "node:url";
  7. import { runInNewContext } from "node:vm";
  8. import { build } from "esbuild";
  9. import {
  10. assertZodBundleIdentity,
  11. createZodDedupePlugin,
  12. readRootPackageVersion,
  13. resolveBuildAliases,
  14. resolveBuildOptions,
  15. resolveBuildExternal,
  16. } from "../scripts/build.mjs";
  17. async function withZodFixture(run) {
  18. const directory = await mkdtemp(join(tmpdir(), "zcode-zod-bundle-"));
  19. try {
  20. for (const [consumer, version] of [
  21. ["first", "4.6.5"],
  22. ["second", "4.6.5"],
  23. ["legacy", "3.25.76"],
  24. ]) {
  25. const packageRoot = join(directory, consumer, "node_modules", "zod");
  26. await mkdir(packageRoot, { recursive: true });
  27. await writeFile(
  28. join(packageRoot, "package.json"),
  29. JSON.stringify({
  30. name: "zod",
  31. version,
  32. type: "module",
  33. exports: {
  34. ".": { import: "./index.js", require: "./index.cjs" },
  35. "./v3": "./v3.js",
  36. },
  37. }),
  38. );
  39. await writeFile(
  40. join(packageRoot, "index.js"),
  41. `export const schema = {version: ${JSON.stringify(version)}, format: "esm"};`,
  42. );
  43. await writeFile(
  44. join(packageRoot, "index.cjs"),
  45. `exports.schema = {version: ${JSON.stringify(version)}, format: "cjs"};`,
  46. );
  47. await writeFile(join(packageRoot, "v3.js"), 'export const schema = {format: "compat-v3"};');
  48. await writeFile(
  49. join(directory, consumer, "entry.mjs"),
  50. 'export {schema} from "zod"; export {schema as compat} from "zod/v3";',
  51. );
  52. await writeFile(join(directory, consumer, "entry.cjs"), 'module.exports = require("zod");');
  53. }
  54. const entry = join(directory, "entry.mjs");
  55. await writeFile(
  56. entry,
  57. `
  58. import {schema as first, compat as firstCompat} from "./first/entry.mjs";
  59. import {schema as second, compat as secondCompat} from "./second/entry.mjs";
  60. import {schema as legacy} from "./legacy/entry.mjs";
  61. import cjsFirst from "./first/entry.cjs";
  62. import cjsSecond from "./second/entry.cjs";
  63. export {first, second, legacy, firstCompat, secondCompat, cjsFirst, cjsSecond};
  64. `,
  65. );
  66. const options = {
  67. absWorkingDir: directory,
  68. entryPoints: [entry],
  69. bundle: true,
  70. write: false,
  71. metafile: true,
  72. platform: "node",
  73. format: "cjs",
  74. logLevel: "silent",
  75. };
  76. await run({ directory, options });
  77. } finally {
  78. await rm(directory, { recursive: true, force: true });
  79. }
  80. }
  81. test("Zod dedupe shares equal versions while preserving majors, subpaths and export conditions", async () => {
  82. await withZodFixture(async ({ options }) => {
  83. const result = await build({
  84. ...options,
  85. plugins: [createZodDedupePlugin({ expectedV4Version: "4.6.5" })],
  86. });
  87. const context = { module: { exports: {} } };
  88. runInNewContext(result.outputFiles[0].text, context);
  89. const { first, second, legacy, firstCompat, secondCompat, cjsFirst, cjsSecond } =
  90. context.module.exports;
  91. assert.equal(first, second);
  92. assert.equal(firstCompat, secondCompat);
  93. assert.equal(firstCompat.format, "compat-v3");
  94. assert.notEqual(first, firstCompat);
  95. assert.notEqual(first, legacy);
  96. assert.equal(legacy.version, "3.25.76");
  97. assert.equal(cjsFirst.schema, cjsSecond.schema);
  98. assert.notEqual(first, cjsFirst.schema);
  99. assert.equal(first.format, "esm");
  100. assert.equal(cjsFirst.schema.format, "cjs");
  101. });
  102. });
  103. test("Zod metafile gate rejects duplicate physical packages even when versions match", async () => {
  104. await withZodFixture(async ({ directory, options }) => {
  105. const result = await build(options);
  106. await assert.rejects(
  107. assertZodBundleIdentity(result.metafile, {
  108. workingDirectory: directory,
  109. expectedV4Version: "4.6.5",
  110. }),
  111. /Duplicate Zod 4\.6\.5/,
  112. );
  113. });
  114. });
  115. test("Zod bundle rejects an unexpected v4 version without rewriting it across versions", async () => {
  116. await withZodFixture(async ({ options }) => {
  117. await assert.rejects(
  118. build({ ...options, plugins: [createZodDedupePlugin({ expectedV4Version: "4.4.3" })] }),
  119. /Expected Zod v4 4\.4\.3/,
  120. );
  121. });
  122. });
  123. test("Zod resolver preserves missing-export failures", async () => {
  124. await withZodFixture(async ({ directory, options }) => {
  125. await writeFile(join(directory, "first", "entry.mjs"), 'export * from "zod/not-exported";');
  126. await assert.rejects(
  127. build({ ...options, plugins: [createZodDedupePlugin({ expectedV4Version: "4.6.5" })] }),
  128. /zod\/not-exported/,
  129. );
  130. });
  131. });
  132. test("reads CLI build version from the repository root package", async () => {
  133. const directory = await mkdtemp(join(tmpdir(), "zcode-root-version-"));
  134. try {
  135. await mkdir(join(directory, "packages", "cli"), {
  136. recursive: true,
  137. });
  138. await writeFile(join(directory, "package.json"), JSON.stringify({ version: "9.8.7" }));
  139. await writeFile(
  140. join(directory, "packages", "cli", "package.json"),
  141. JSON.stringify({ version: "1.2.3" }),
  142. );
  143. assert.equal(
  144. await readRootPackageVersion({
  145. root: directory,
  146. }),
  147. "9.8.7",
  148. );
  149. } finally {
  150. await rm(directory, {
  151. force: true,
  152. recursive: true,
  153. });
  154. }
  155. });
  156. test("rejects missing root package versions during CLI builds", async () => {
  157. const directory = await mkdtemp(join(tmpdir(), "zcode-root-version-"));
  158. try {
  159. await writeFile(join(directory, "package.json"), JSON.stringify({ name: "zcode-cli" }));
  160. await assert.rejects(
  161. readRootPackageVersion({
  162. root: directory,
  163. }),
  164. /Root package\.json must define a non-empty string version/,
  165. );
  166. } finally {
  167. await rm(directory, {
  168. force: true,
  169. recursive: true,
  170. });
  171. }
  172. });
  173. test("desktop agent builds minify the app-facing JS bundle", () => {
  174. assert.deepEqual(resolveBuildOptions([]), {
  175. minify: false,
  176. sourcemap: true,
  177. });
  178. assert.deepEqual(resolveBuildOptions(["--desktop-agent"]), {
  179. minify: true,
  180. sourcemap: false,
  181. });
  182. assert.deepEqual(resolveBuildOptions(["--desktop-agent"], { ZCODE_E2E_COVERAGE: "1" }), {
  183. minify: false,
  184. sourcemap: true,
  185. });
  186. });
  187. test("CLI bundle externalizes native koffi so esbuild does not parse platform .node files", () => {
  188. assert.ok(resolveBuildExternal().includes("koffi"));
  189. });
  190. test("every shared package export has an exact build alias, including SQLite migrations", async () => {
  191. const shared = JSON.parse(
  192. await readFile(new URL("../../../../../packages/shared/package.json", import.meta.url), "utf8"),
  193. );
  194. const rootDirectory = resolve("/repo/apps/zcode-cli");
  195. const aliases = resolveBuildAliases({ rootDirectory });
  196. for (const [subpath, target] of Object.entries(shared.exports)) {
  197. const name = subpath === "." ? "@zcode/shared" : `@zcode/shared/${subpath.slice(2)}`;
  198. assert.equal(aliases[name], resolve(rootDirectory, "../../packages/shared", target));
  199. if (subpath !== ".")
  200. assert.ok(Object.keys(aliases).indexOf(name) < Object.keys(aliases).indexOf("@zcode/shared"));
  201. }
  202. });
  203. test("CLI bundles session migrations through the shared sqlite subpath", async () => {
  204. const result = await build({
  205. entryPoints: [
  206. fileURLToPath(
  207. new URL("../../adapters/src/storage/session-store/migration-runner.ts", import.meta.url),
  208. ),
  209. ],
  210. alias: resolveBuildAliases(),
  211. bundle: true,
  212. platform: "node",
  213. format: "cjs",
  214. write: false,
  215. metafile: true,
  216. logLevel: "silent",
  217. });
  218. assert.equal(
  219. Object.keys(result.metafile.inputs).filter((path) =>
  220. path.endsWith("/shared/src/sqlite-migrations/index.ts"),
  221. ).length,
  222. 1,
  223. );
  224. assert.ok(
  225. Object.values(result.metafile.outputs).every((output) =>
  226. output.imports.every((entry) => entry.path !== "@zcode/shared/sqlite-migrations"),
  227. ),
  228. );
  229. });
  230. test("built CLI embeds the compact registry without a runtime Fig dependency", async (t) => {
  231. let bundle;
  232. try {
  233. bundle = await readFile(new URL("../dist/zcode.cjs", import.meta.url), "utf8");
  234. } catch {
  235. t.skip("build the CLI before running the bundle content gate");
  236. return;
  237. }
  238. assert.match(bundle, /"@commercelayer\/cli"\s*:/);
  239. assert.match(bundle, /(?:"git"|git)\s*:\s*\[\["git"\]/);
  240. assert.doesNotMatch(bundle, /node_modules\/@withfig\/autocomplete/);
  241. assert.doesNotMatch(bundle, /@withfig\/autocomplete\/build/);
  242. });
  243. test("request security subpath bundles through its edition entry", async () => {
  244. const result = await build({
  245. stdin: {
  246. contents: 'import * as security from "@zcode/shared/request-security"; export { security };',
  247. resolveDir: resolve(import.meta.dirname, ".."),
  248. },
  249. alias: resolveBuildAliases(),
  250. bundle: true,
  251. platform: "node",
  252. format: "esm",
  253. write: false,
  254. metafile: true,
  255. });
  256. assert.ok(
  257. Object.keys(result.metafile.inputs).some((path) =>
  258. path.endsWith("shared/src/request-security-edition/index.ts"),
  259. ),
  260. );
  261. });