official-marketplace.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { createServer } from "node:http";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { setTimeout as delay } from "node:timers/promises";
  6. import * as asyncFs from "node:fs/promises";
  7. import * as pluginFiles from "../src/plugins/helpers.js";
  8. import { afterEach, describe, expect, it, vi } from "vitest";
  9. import {
  10. writeBundledOfficialMarketplacePartition,
  11. writeCdnOfficialMarketplacePartition,
  12. updateMarketplace,
  13. } from "../src/plugins/index.js";
  14. vi.mock("node:fs/promises", async (importOriginal) => {
  15. const actual = await importOriginal<typeof import("node:fs/promises")>();
  16. return {
  17. ...actual,
  18. mkdir: vi.fn(actual.mkdir),
  19. realpath: vi.fn(actual.realpath),
  20. rename: vi.fn(actual.rename),
  21. };
  22. });
  23. vi.mock("../src/plugins/helpers.js", async (importOriginal) => {
  24. const actual = await importOriginal<typeof import("../src/plugins/helpers.js")>();
  25. return { ...actual, writePluginTextIfChanged: vi.fn(actual.writePluginTextIfChanged) };
  26. });
  27. describe("ZCode official marketplace partitions", () => {
  28. const cleanups: string[] = [];
  29. afterEach(async () => {
  30. vi.resetAllMocks();
  31. vi.restoreAllMocks();
  32. await Promise.all(cleanups.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
  33. });
  34. it("serializes bundled and CDN publication across asynchronous writes", async () => {
  35. const storageRoot = await makeStorageRoot();
  36. const actualFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  37. const actualFiles = await vi.importActual<typeof import("../src/plugins/helpers.js")>(
  38. "../src/plugins/helpers.js",
  39. );
  40. // 根已存在;让 admission 前的元数据步骤立即完成,以受控 Promise 决定 writer 顺序。
  41. vi.spyOn(asyncFs, "mkdir").mockImplementation(async (...args) =>
  42. args[0] === storageRoot ? undefined : actualFs.mkdir(...args),
  43. );
  44. vi.spyOn(asyncFs, "realpath").mockImplementation(async (...args) =>
  45. args[0] === storageRoot ? storageRoot : actualFs.realpath(...args),
  46. );
  47. const entered = Promise.withResolvers<void>();
  48. const release = Promise.withResolvers<void>();
  49. let cdnStarted = false;
  50. vi.spyOn(pluginFiles, "writePluginTextIfChanged").mockImplementation(async (path, contents) => {
  51. if (path.endsWith("bundled-marketplace.json")) {
  52. entered.resolve();
  53. await release.promise;
  54. }
  55. if (path.endsWith("cdn-marketplace.json")) cdnStarted = true;
  56. await actualFiles.writePluginTextIfChanged(path, contents);
  57. });
  58. const bundled = writeBundledOfficialMarketplacePartition({
  59. storageRoot,
  60. manifest: {
  61. name: "zcode-plugins-official",
  62. plugins: [{ name: "bundled", version: "1" }],
  63. },
  64. });
  65. await entered.promise;
  66. const cdn = writeCdnOfficialMarketplacePartition({
  67. storageRoot,
  68. manifest: {
  69. name: "zcode-plugins-official",
  70. plugins: [{ name: "cdn", version: "2" }],
  71. },
  72. });
  73. try {
  74. await new Promise<void>((resolve) => setImmediate(resolve));
  75. expect(cdnStarted).toBe(false);
  76. } finally {
  77. release.resolve();
  78. await Promise.all([bundled, cdn]);
  79. }
  80. const manifest = JSON.parse(
  81. await readFile(
  82. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  83. "utf8",
  84. ),
  85. );
  86. expect(manifest.plugins.map((plugin: { name: string }) => plugin.name)).toEqual([
  87. "cdn",
  88. "bundled",
  89. ]);
  90. });
  91. it("retries transient rename contention and preserves the previous file on persistent failure", async () => {
  92. const root = await makeStorageRoot();
  93. const path = join(root, "manifest.json");
  94. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  95. await writeFile(path, "old");
  96. const rename = vi
  97. .spyOn(asyncFs, "rename")
  98. .mockClear()
  99. .mockRejectedValueOnce(Object.assign(new Error("busy"), { code: "EPERM" }));
  100. rename.mockImplementationOnce(actual.rename);
  101. await pluginFiles.writePluginTextIfChanged(path, "new");
  102. expect(rename).toHaveBeenCalledTimes(2);
  103. expect(await readFile(path, "utf8")).toBe("new");
  104. rename.mockRejectedValue(Object.assign(new Error("busy"), { code: "EACCES" }));
  105. await expect(pluginFiles.writePluginTextIfChanged(path, "incomplete")).rejects.toMatchObject({
  106. code: "EACCES",
  107. });
  108. expect(await readFile(path, "utf8")).toBe("new");
  109. expect(await actual.readdir(root)).toEqual(["manifest.json"]);
  110. });
  111. async function makeStorageRoot(): Promise<string> {
  112. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-official-marketplace-"));
  113. cleanups.push(storageRoot);
  114. return storageRoot;
  115. }
  116. it("merges bundled and CDN entries under one marketplace with CDN entries taking precedence", async () => {
  117. const storageRoot = await makeStorageRoot();
  118. await writeBundledOfficialMarketplacePartition({
  119. manifest: {
  120. name: "zcode-plugins-official",
  121. plugins: [
  122. { name: "shared", source: "filesystem", version: "1.0.0" },
  123. { name: "bundled-only", source: "filesystem", version: "1.0.0" },
  124. ],
  125. version: 1,
  126. },
  127. storageRoot,
  128. });
  129. await writeCdnOfficialMarketplacePartition({
  130. manifest: {
  131. name: "zcode-plugins-official",
  132. featured: ["remote"],
  133. plugins: [
  134. { name: "shared", source: { source: "url", type: "zip" }, version: "9.0.0" },
  135. { name: "remote", source: { source: "url", type: "zip" }, version: "2.0.0" },
  136. ],
  137. },
  138. storageRoot,
  139. });
  140. const merged = JSON.parse(
  141. await readFile(
  142. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  143. "utf8",
  144. ),
  145. ) as { featured?: string[]; name: string; plugins: Array<Record<string, unknown>> };
  146. expect(merged.name).toBe("zcode-plugins-official");
  147. expect(merged.featured).toEqual(["remote"]);
  148. expect(merged.plugins.map((plugin) => plugin.name)).toEqual([
  149. "shared",
  150. "remote",
  151. "bundled-only",
  152. ]);
  153. expect(merged.plugins[0]).toMatchObject({
  154. source: { source: "url", type: "zip" },
  155. version: "9.0.0",
  156. });
  157. });
  158. it("preserves the CDN partition when the application reseeds bundled plugins", async () => {
  159. const storageRoot = await makeStorageRoot();
  160. await writeCdnOfficialMarketplacePartition({
  161. manifest: {
  162. name: "zcode-plugins-official",
  163. plugins: [{ name: "remote", source: { source: "url", type: "zip" } }],
  164. },
  165. storageRoot,
  166. });
  167. await writeBundledOfficialMarketplacePartition({
  168. manifest: {
  169. name: "zcode-plugins-official",
  170. plugins: [{ name: "bundled-v2", source: "sea", version: "2.0.0" }],
  171. version: 1,
  172. },
  173. storageRoot,
  174. });
  175. const merged = JSON.parse(
  176. await readFile(
  177. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  178. "utf8",
  179. ),
  180. ) as { plugins: Array<{ name: string }> };
  181. expect(merged.plugins.map((plugin) => plugin.name)).toEqual(["remote", "bundled-v2"]);
  182. });
  183. it("does not rewrite unchanged official marketplace files", async () => {
  184. const storageRoot = await makeStorageRoot();
  185. const bundledManifest = {
  186. name: "zcode-plugins-official",
  187. plugins: [{ name: "bundled", source: "filesystem", version: "1.0.0" }],
  188. };
  189. const cdnManifest = {
  190. name: "zcode-plugins-official",
  191. plugins: [{ name: "remote", source: { source: "url", type: "zip" } }],
  192. };
  193. const marketplaceRoot = join(storageRoot, "marketplaces", "zcode-plugins-official");
  194. await writeBundledOfficialMarketplacePartition({
  195. manifest: bundledManifest,
  196. storageRoot,
  197. });
  198. await writeCdnOfficialMarketplacePartition({
  199. manifest: cdnManifest,
  200. storageRoot,
  201. });
  202. const paths = [
  203. join(marketplaceRoot, "bundled-marketplace.json"),
  204. join(marketplaceRoot, "cdn-marketplace.json"),
  205. join(marketplaceRoot, "marketplace.json"),
  206. ];
  207. const firstMtimes = await Promise.all(paths.map(async (path) => (await stat(path)).mtimeMs));
  208. await delay(30);
  209. await writeBundledOfficialMarketplacePartition({
  210. manifest: bundledManifest,
  211. storageRoot,
  212. });
  213. await writeCdnOfficialMarketplacePartition({
  214. manifest: cdnManifest,
  215. storageRoot,
  216. });
  217. expect(await Promise.all(paths.map(async (path) => (await stat(path)).mtimeMs))).toEqual(
  218. firstMtimes,
  219. );
  220. });
  221. it("rejects the retired CDN marketplace id instead of creating a compatibility alias", async () => {
  222. const storageRoot = await makeStorageRoot();
  223. await expect(
  224. (async () =>
  225. await writeCdnOfficialMarketplacePartition({
  226. manifest: { name: "zcode-plugins", plugins: [] },
  227. storageRoot,
  228. }))(),
  229. ).rejects.toThrow("Official marketplace manifest must be named zcode-plugins-official");
  230. });
  231. it("refreshes the registered official source and returns the merged plugin count", async () => {
  232. const storageRoot = await makeStorageRoot();
  233. await writeBundledOfficialMarketplacePartition({
  234. manifest: {
  235. name: "zcode-plugins-official",
  236. plugins: [{ name: "bundled", source: "filesystem" }],
  237. },
  238. storageRoot,
  239. });
  240. const server = createServer((_request, response) => {
  241. response.writeHead(200, { "content-type": "application/json" });
  242. response.end(
  243. JSON.stringify({
  244. name: "zcode-plugins-official",
  245. plugins: [{ name: "remote", source: { source: "url", type: "zip" } }],
  246. }),
  247. );
  248. });
  249. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  250. try {
  251. const address = server.address();
  252. if (!address || typeof address === "string") throw new Error("test server address missing");
  253. await writeFile(
  254. join(storageRoot, "known_marketplaces.json"),
  255. JSON.stringify({
  256. version: 1,
  257. marketplaces: [
  258. {
  259. id: "zcode-plugins-official",
  260. source: { source: "url", url: `http://127.0.0.1:${address.port}/marketplace.json` },
  261. name: "zcode-plugins-official",
  262. addedAt: "2026-01-01T00:00:00.000Z",
  263. pluginCount: 1,
  264. },
  265. ],
  266. }),
  267. );
  268. const [updated] = await updateMarketplace({
  269. marketplace: "zcode-plugins-official",
  270. storageRoot,
  271. });
  272. expect(updated).toMatchObject({
  273. id: "zcode-plugins-official",
  274. pluginCount: 2,
  275. });
  276. const merged = JSON.parse(
  277. await readFile(
  278. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  279. "utf8",
  280. ),
  281. ) as { plugins: Array<{ name: string }> };
  282. expect(merged.plugins.map((plugin) => plugin.name)).toEqual(["remote", "bundled"]);
  283. } finally {
  284. await new Promise<void>((resolve, reject) => {
  285. server.close((error) => (error ? reject(error) : resolve()));
  286. });
  287. }
  288. });
  289. });