zcode-site.test.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. // zcode-site CLI 测试:用内存里的 Sites API 替身(按 api/openapi.yaml 的状态机)代替 zcode-server 和后面的控制面。
  2. import assert from "node:assert/strict";
  3. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { test } from "node:test";
  7. import { createServer } from "node:http";
  8. import { createEndpointFetch, main, normalizePrefix } from "../scripts/zcode-site.mjs";
  9. import { packStage } from "../scripts/stage.mjs";
  10. // CLI 只认 agent 注入的官方命令端点(技术方案 5.8);身份头和版本头由端点补,CLI 不带。
  11. const ENV = {
  12. ZCODE_OFFICIAL_ENDPOINT: "/tmp/zcode-official-test.sock",
  13. ZCODE_OFFICIAL_ENDPOINT_TOKEN: "session-token",
  14. };
  15. class FakeSites {
  16. constructor() {
  17. this.sites = [];
  18. this.deployments = [];
  19. this.nextId = 1000;
  20. // 发布结果:上传完成之后第几次轮询进入终态、终态是什么
  21. this.publishPolls = 1;
  22. this.publishOutcome = { status: "success" };
  23. this.uploads = 0;
  24. // 第一次上传:truncate 时服务端只收到一部分(3604);dropResponse 时服务端收完了但响应丢了(网络错误)
  25. this.firstUpload = undefined;
  26. this.unauthenticated = false;
  27. this.planExpired = false;
  28. this.endpointNetworkError = false;
  29. this.badgeRemovable = false;
  30. // 服务端机审:rejectNames 里的名称返回 3611,rejectPrefixes 里的(规范化后的)前缀换成 site。
  31. this.rejectNames = new Set();
  32. this.rejectPrefixes = new Set();
  33. }
  34. site({ prefix = "app", ...overrides } = {}) {
  35. const id = String(this.nextId++);
  36. const s = {
  37. id,
  38. name: overrides.name ?? "app",
  39. domainLabel: `${prefix}-${id}`,
  40. url: `https://${prefix}-${id}.zcode-cn.site`,
  41. status: "pending",
  42. region: "cn",
  43. badgeHidden: false,
  44. badgeVisible: true,
  45. currentDeployment: null,
  46. latestDeployment: null,
  47. ...overrides,
  48. };
  49. this.sites.push(s);
  50. return s;
  51. }
  52. deployment(siteId, overrides = {}) {
  53. const d = {
  54. id: String(this.nextId++),
  55. siteId,
  56. status: "preparing",
  57. artifactSize: 0,
  58. failure: null,
  59. logs: [],
  60. polls: 0,
  61. ...overrides,
  62. };
  63. this.deployments.push(d);
  64. return d;
  65. }
  66. view(d) {
  67. const { logs, polls, ...rest } = d;
  68. return rest;
  69. }
  70. fetch = async (url, init = {}) => {
  71. const method = init.method ?? "GET";
  72. if (this.unauthenticated) return new Response(null, { status: 401 });
  73. if (this.planExpired)
  74. return Response.json(
  75. { code: 3101, msg: "coding plan is required", logid: "l" },
  76. { status: 403 },
  77. );
  78. if (this.endpointNetworkError) {
  79. return Response.json(
  80. { code: 2007, msg: "x", data: null, logid: "" },
  81. { status: 502, headers: { "X-ZCode-Official-Endpoint-Error": "network" } },
  82. );
  83. }
  84. assert.equal(init.headers.Authorization, "Bearer session-token");
  85. assert.equal(init.headers["X-ZCode-App-Version"], undefined);
  86. assert.equal(init.headers["X-Bigmodel-Authorization"], undefined);
  87. const { pathname } = new URL(url);
  88. const body = typeof init.body === "string" ? JSON.parse(init.body) : init.body;
  89. const ok = (data) => Response.json({ code: 0, msg: "success", data, logid: "l" });
  90. const err = (status, code, data) =>
  91. Response.json({ code, msg: "x", data, logid: "l" }, { status });
  92. const parts = pathname.split("/").slice(4); // /api/v1/sites/...
  93. if (pathname === "/api/v1/sites/usage") return ok({ plan: "free", canDeploy: true });
  94. if (parts.length === 0 && method === "GET")
  95. return ok({ items: [...this.sites].reverse(), nextCursor: null });
  96. if (parts.length === 0 && method === "POST") {
  97. this.createBodies = [...(this.createBodies ?? []), body];
  98. if (this.rejectNames.has(body.name)) return err(400, 3611);
  99. const prefix = normalizePrefix(body.domainPrefix ?? body.name);
  100. return ok(
  101. this.site({ name: body.name, prefix: this.rejectPrefixes.has(prefix) ? "site" : prefix }),
  102. );
  103. }
  104. const site = this.sites.find((s) => s.id === parts[0]);
  105. if (!site) return err(404, 3601);
  106. if (parts.length === 1 && method === "GET") return ok(site);
  107. if (parts.length === 1 && method === "PATCH") {
  108. if (body.badgeHidden && !this.badgeRemovable) return err(403, 3608);
  109. if (this.rejectNames.has(body.name)) return err(400, 3611);
  110. // 服务端规则:当前线上版本被人审驳回时不能改回上线。
  111. if (body.status === "online" && site.offlineReason === "review_rejected")
  112. return err(403, 3612);
  113. if ("badgeHidden" in body) site.badgeVisible = !body.badgeHidden;
  114. Object.assign(site, body);
  115. // 服务端规则:没有线上版本的站点上线后还是 pending。
  116. if (site.status === "online" && !site.currentDeployment) site.status = "pending";
  117. return ok(site);
  118. }
  119. if (parts.length === 2 && method === "POST") {
  120. const busy = this.deployments.find((d) =>
  121. ["preparing", "uploading", "publishing", "verifying"].includes(d.status),
  122. );
  123. if (busy)
  124. return err(409, 3610, {
  125. inProgress: { siteId: busy.siteId, deploymentId: busy.id, status: busy.status },
  126. });
  127. const d = this.deployment(site.id, {
  128. artifactSize: body.artifactSize,
  129. logs: [{ stage: "preparing", level: "info", message: "created" }],
  130. });
  131. site.latestDeployment = this.view(d);
  132. return ok(this.view(d));
  133. }
  134. const d = this.deployments.find((x) => x.id === parts[2] && x.siteId === site.id);
  135. if (!d) return err(404, 3602);
  136. const action = parts[3];
  137. if (!action && method === "GET") {
  138. if (d.status === "publishing" && ++d.polls >= this.publishPolls) {
  139. Object.assign(d, this.publishOutcome);
  140. d.logs.push({
  141. stage: "verifying",
  142. level: d.status === "success" ? "info" : "error",
  143. message: d.status,
  144. });
  145. if (d.status === "success") {
  146. site.currentDeployment = this.view(d);
  147. site.status = "online";
  148. delete site.offlineReason;
  149. }
  150. }
  151. return ok(this.view(d));
  152. }
  153. if (action === "package" && method === "PUT") {
  154. this.uploads++;
  155. assert.equal(init.headers["Content-Type"], "application/gzip");
  156. if (!["preparing", "uploading"].includes(d.status)) return err(409, 3603);
  157. d.status = "uploading";
  158. const first = this.uploads === 1 ? this.firstUpload : undefined;
  159. if (first === "truncate" || body.length !== d.artifactSize) return err(409, 3604);
  160. d.status = "publishing";
  161. d.logs.push({ stage: "publishing", level: "info", message: "publishing" });
  162. if (first === "dropResponse") throw new TypeError("fetch failed");
  163. return ok(this.view(d));
  164. }
  165. if (action === "logs") {
  166. const offset = Number(new URL(url).searchParams.get("offset"));
  167. const entries = d.logs.slice(offset).map((e, i) => ({ ...e, offset: offset + i, ts: "t" }));
  168. return ok({
  169. entries,
  170. nextOffset: d.logs.length,
  171. done: !["preparing", "uploading", "publishing", "verifying"].includes(d.status),
  172. });
  173. }
  174. return err(404, 3601);
  175. };
  176. }
  177. async function project() {
  178. const dir = await mkdtemp(join(tmpdir(), "zcode-site-cli-"));
  179. await mkdir(join(dir, "stage"));
  180. await writeFile(join(dir, "stage", "start.sh"), "exec node static-server.mjs .\n");
  181. await writeFile(join(dir, "stage", "index.html"), "<h1>hi</h1>");
  182. return dir;
  183. }
  184. async function run(fake, cwd, ...argv) {
  185. let stdout = "";
  186. let stderr = "";
  187. const code = await main(argv, {
  188. env: ENV,
  189. cwd,
  190. fetchImpl: fake.fetch,
  191. stdout: { write: (s) => (stdout += s) },
  192. stderr: { write: (s) => (stderr += s) },
  193. sleep: async () => {},
  194. now: () => 0,
  195. });
  196. const lines = stdout
  197. .trim()
  198. .split("\n")
  199. .filter(Boolean)
  200. .map((l) => JSON.parse(l));
  201. return {
  202. code,
  203. lines,
  204. result: lines.at(-1),
  205. error: stderr ? JSON.parse(stderr).error : undefined,
  206. };
  207. }
  208. test("first deploy creates and binds a site, then later deploys reuse it", async () => {
  209. const fake = new FakeSites();
  210. const cwd = await project();
  211. const r = await run(fake, cwd, "deploy", "stage", "--name", "My App");
  212. assert.equal(r.code, 0, JSON.stringify(r.error));
  213. assert.equal(fake.sites.length, 1);
  214. assert.equal(fake.sites[0].name, "My App");
  215. assert.deepEqual(r.result, {
  216. siteId: fake.sites[0].id,
  217. deploymentId: fake.deployments[0].id,
  218. status: "success",
  219. url: fake.sites[0].url,
  220. failure: null,
  221. });
  222. assert.ok(r.lines.some((l) => l.event === "site_created"));
  223. assert.deepEqual(r.lines[0], {
  224. event: "packed",
  225. packageBytes: fake.deployments[0].artifactSize,
  226. unpackedBytes: 41,
  227. files: 2,
  228. linuxBinaries: 0,
  229. });
  230. assert.ok(r.lines.some((l) => l.event === "log" && l.message === "publishing"));
  231. const binding = JSON.parse(await readFile(join(cwd, ".zcode-site.json"), "utf8"));
  232. assert.deepEqual(binding, { siteId: fake.sites[0].id, domainLabel: fake.sites[0].domainLabel });
  233. const again = await run(fake, cwd, "deploy", "stage", "--quiet");
  234. assert.equal(again.code, 0);
  235. assert.equal(again.lines.length, 1, "--quiet prints only the result");
  236. assert.equal(fake.sites.length, 1);
  237. assert.equal(fake.deployments.length, 2);
  238. // skill 让首次部署统一带 --new;已绑定的项目误带时只提醒,仍部署到已绑定的站点。
  239. const withNew = await run(fake, cwd, "deploy", "stage", "--new");
  240. assert.equal(withNew.code, 0);
  241. assert.equal(fake.sites.length, 1);
  242. assert.ok(withNew.lines.some((l) => l.event === "warning" && /--new is ignored/.test(l.message)));
  243. });
  244. test("an unbound project does not guess among existing sites", async () => {
  245. const fake = new FakeSites();
  246. fake.site({ name: "a" });
  247. fake.site({ name: "b" });
  248. const r = await run(fake, await project(), "deploy", "stage");
  249. assert.equal(r.code, 1);
  250. assert.equal(r.error.code, "SITE_NOT_SELECTED");
  251. assert.deepEqual(
  252. r.error.data.candidates.map((c) => c.name),
  253. ["b", "a"],
  254. );
  255. assert.equal(fake.deployments.length, 0);
  256. const created = await run(fake, await project(), "deploy", "stage", "--new");
  257. assert.equal(created.code, 0);
  258. assert.equal(fake.sites.length, 3);
  259. });
  260. test("a 3610 for the same site that has not started publishing is resumed", async () => {
  261. const fake = new FakeSites();
  262. const site = fake.site();
  263. const cwd = await project();
  264. // 续传按包大小认同一次部署;同一个 stage 每次打出的包字节一致(tar 头用文件 mtime,gzip 头不写时间)。
  265. const { body } = await packStage(join(cwd, "stage"));
  266. const stuck = fake.deployment(site.id, { status: "uploading", artifactSize: body.length });
  267. const r = await run(fake, cwd, "deploy", "stage", "--site", site.id);
  268. assert.equal(r.code, 0, JSON.stringify(r.error));
  269. assert.equal(r.result.deploymentId, stuck.id);
  270. assert.ok(r.lines.some((l) => l.event === "deployment_started" && l.resumed === true));
  271. });
  272. test("a deployment in progress elsewhere is reported with exit code 3", async () => {
  273. const fake = new FakeSites();
  274. const other = fake.site();
  275. const mine = fake.site();
  276. fake.deployment(other.id, { status: "publishing" });
  277. const r = await run(fake, await project(), "deploy", "stage", "--site", mine.id);
  278. assert.equal(r.code, 3);
  279. assert.equal(r.error.code, 3610);
  280. assert.match(r.error.hint, new RegExp(other.id));
  281. });
  282. test("an upload the server rejects as incomplete is uploaded again", async () => {
  283. const fake = new FakeSites();
  284. fake.firstUpload = "truncate";
  285. const r = await run(fake, await project(), "deploy", "stage");
  286. assert.equal(r.code, 0, JSON.stringify(r.error));
  287. assert.equal(fake.uploads, 2);
  288. assert.equal(r.lines.filter((l) => l.event === "uploading").length, 2);
  289. });
  290. test("a lost upload response continues with the deployment the server already accepted", async () => {
  291. const fake = new FakeSites();
  292. fake.firstUpload = "dropResponse";
  293. const r = await run(fake, await project(), "deploy", "stage");
  294. assert.equal(r.code, 0, JSON.stringify(r.error));
  295. assert.equal(fake.uploads, 2); // 第二次收到 3603,CLI 查到部署已在发布,直接轮询
  296. assert.equal(r.result.status, "success");
  297. });
  298. test("a failed deployment exits 4 with the failure", async () => {
  299. const fake = new FakeSites();
  300. fake.publishPolls = 2;
  301. fake.publishOutcome = {
  302. status: "failed",
  303. failure: { stage: "verifying", code: "WARMUP_FAILED", message: "no 200 within 90s" },
  304. };
  305. const r = await run(fake, await project(), "deploy", "stage");
  306. assert.equal(r.code, 4);
  307. assert.equal(r.error.code, "WARMUP_FAILED");
  308. assert.match(r.error.hint, /start\.sh/);
  309. assert.equal(r.error.data.status, "failed");
  310. });
  311. test("a stage that fails the package contract creates nothing", async () => {
  312. const fake = new FakeSites();
  313. const cwd = await project();
  314. await writeFile(join(cwd, "stage", "start.sh"), "exec node server.js\r\n");
  315. await writeFile(join(cwd, "stage", ".env"), "SECRET=1");
  316. const r = await run(fake, cwd, "deploy", "stage", "--new");
  317. assert.equal(r.code, 1);
  318. assert.equal(r.error.code, "PACKAGE_CHECK_FAILED");
  319. assert.equal(r.error.data.problems.length, 2);
  320. assert.equal(fake.sites.length, 0);
  321. assert.equal(fake.deployments.length, 0);
  322. });
  323. test("local and auth errors", async () => {
  324. const fake = new FakeSites();
  325. const cwd = await project();
  326. assert.equal((await run(fake, cwd, "deploy", "missing")).error.code, "STAGE_NOT_FOUND");
  327. assert.equal((await run(fake, cwd, "deploy", "stage", "--site", "1", "--new")).code, 1);
  328. assert.equal((await run(fake, cwd, "nope")).error.code, "UNKNOWN_COMMAND");
  329. fake.unauthenticated = true;
  330. const r = await run(fake, cwd, "usage");
  331. assert.equal(r.code, 2);
  332. assert.equal(r.error.code, "UNAUTHENTICATED");
  333. fake.unauthenticated = false;
  334. fake.planExpired = true;
  335. const expired = await run(fake, cwd, "usage");
  336. assert.equal(expired.code, 2);
  337. assert.equal(expired.error.code, 3101);
  338. assert.match(expired.error.hint, /sign in to ZCode again/);
  339. const noEnv = await main(["usage"], {
  340. env: {},
  341. cwd,
  342. stdout: { write() {} },
  343. stderr: { write() {} },
  344. });
  345. assert.equal(noEnv, 2);
  346. fake.planExpired = false;
  347. fake.endpointNetworkError = true;
  348. const offline = await run(fake, cwd, "usage");
  349. assert.equal(offline.code, 4);
  350. assert.equal(offline.error.code, "NETWORK_ERROR");
  351. });
  352. test("createEndpointFetch talks HTTP over the endpoint socket", async () => {
  353. const dir = await mkdtemp(join(tmpdir(), "zcode-site-ep-"));
  354. const socketPath = join(dir, "endpoint.sock");
  355. const seen = [];
  356. const server = createServer((req, res) => {
  357. const chunks = [];
  358. req.on("data", (c) => chunks.push(c));
  359. req.on("end", () => {
  360. seen.push({
  361. method: req.method,
  362. url: req.url,
  363. headers: req.headers,
  364. body: Buffer.concat(chunks),
  365. });
  366. if (req.url === "/empty") return res.writeHead(204).end();
  367. res
  368. .writeHead(200, { "content-type": "application/json" })
  369. .end(JSON.stringify({ code: 0, data: { ok: true } }));
  370. });
  371. });
  372. await new Promise((resolve) => server.listen(socketPath, resolve));
  373. try {
  374. const fetchImpl = createEndpointFetch(socketPath);
  375. const res = await fetchImpl(
  376. "http://zcode-official-endpoint/api/v1/sites/1/deployments/2/package?x=1",
  377. {
  378. method: "PUT",
  379. headers: { Authorization: "Bearer t", "Content-Type": "application/gzip" },
  380. body: Buffer.from("tarball"),
  381. },
  382. );
  383. assert.equal(res.status, 200);
  384. assert.deepEqual(await res.json(), { code: 0, data: { ok: true } });
  385. assert.equal(seen[0].url, "/api/v1/sites/1/deployments/2/package?x=1");
  386. assert.equal(seen[0].headers["content-length"], "7");
  387. assert.equal(seen[0].headers["transfer-encoding"], undefined);
  388. assert.equal(seen[0].body.toString(), "tarball");
  389. assert.equal((await fetchImpl("http://zcode-official-endpoint/empty")).status, 204);
  390. } finally {
  391. await new Promise((resolve) => server.close(resolve));
  392. }
  393. });
  394. test("status, rename, offline and online use the bound site", async () => {
  395. const fake = new FakeSites();
  396. const site = fake.site();
  397. const cwd = await project();
  398. await writeFile(
  399. join(cwd, ".zcode-site.json"),
  400. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  401. );
  402. assert.equal((await run(fake, cwd, "status")).result.id, site.id);
  403. assert.equal((await run(fake, cwd, "rename", "New", "Name")).result.name, "New Name");
  404. assert.equal((await run(fake, cwd, "offline")).result.status, "offline");
  405. assert.equal((await run(fake, cwd, "online")).result.status, "pending");
  406. fake.sites[0].currentDeployment = { id: "1", status: "success" };
  407. assert.equal((await run(fake, cwd, "online")).result.status, "online");
  408. assert.equal((await run(fake, cwd, "list")).result.sites.length, 1);
  409. assert.equal((await run(fake, cwd, "status", "--site", "999")).code, 1);
  410. });
  411. test("badge hide needs a plan that can remove the badge", async () => {
  412. const fake = new FakeSites();
  413. const site = fake.site();
  414. const cwd = await project();
  415. await writeFile(
  416. join(cwd, ".zcode-site.json"),
  417. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  418. );
  419. const denied = await run(fake, cwd, "badge", "hide");
  420. assert.equal(denied.code, 3);
  421. assert.equal(denied.error.code, 3608);
  422. assert.match(denied.error.hint, /paid/);
  423. fake.badgeRemovable = true;
  424. const hidden = (await run(fake, cwd, "badge", "hide")).result;
  425. assert.equal(hidden.badgeHidden, true);
  426. assert.equal(hidden.badgeVisible, false);
  427. assert.equal((await run(fake, cwd, "badge", "show")).result.badgeVisible, true);
  428. assert.equal((await run(fake, cwd, "badge")).code, 1);
  429. });
  430. test("--prefix is sent as domainPrefix only when the site is created", async () => {
  431. const fake = new FakeSites();
  432. const cwd = await project();
  433. const r = await run(
  434. fake,
  435. cwd,
  436. "deploy",
  437. "stage",
  438. "--name",
  439. "生日网站",
  440. "--prefix",
  441. "happy-birthday",
  442. );
  443. assert.equal(r.code, 0, JSON.stringify(r.error));
  444. assert.deepEqual(fake.createBodies, [{ name: "生日网站", domainPrefix: "happy-birthday" }]);
  445. assert.ok(!r.lines.some((l) => l.event === "warning"));
  446. // 已绑定站点:--prefix 不生效,也不再创建,只提示一次。
  447. const again = await run(fake, cwd, "deploy", "stage", "--prefix", "other-name");
  448. assert.equal(again.code, 0);
  449. assert.equal(fake.createBodies.length, 1);
  450. assert.match(again.lines.find((l) => l.event === "warning").message, /ignored/);
  451. });
  452. test("without --prefix the server derives the prefix from the name", async () => {
  453. const fake = new FakeSites();
  454. const r = await run(fake, await project(), "deploy", "stage", "--name", "My App");
  455. assert.equal(r.code, 0);
  456. assert.deepEqual(fake.createBodies, [{ name: "My App" }]);
  457. });
  458. test("a non-conforming --prefix is still sent, with a warning about the normalized result", async () => {
  459. const fake = new FakeSites();
  460. const r = await run(fake, await project(), "deploy", "stage", "--prefix", "Happy Birthday!");
  461. assert.equal(r.code, 0);
  462. assert.equal(fake.createBodies[0].domainPrefix, "Happy Birthday!");
  463. assert.match(r.lines.find((l) => l.event === "warning").message, /"happy-birthday"/);
  464. const short = await run(fake, await project(), "deploy", "stage", "--new", "--prefix", "ab");
  465. assert.equal(short.code, 0);
  466. assert.match(short.lines.find((l) => l.event === "warning").message, /"site"/);
  467. });
  468. test("a name that fails content review gets 3611 and nothing is linked", async () => {
  469. const fake = new FakeSites();
  470. fake.rejectNames.add("bad name");
  471. const cwd = await project();
  472. const r = await run(
  473. fake,
  474. cwd,
  475. "deploy",
  476. "stage",
  477. "--name",
  478. "bad name",
  479. "--prefix",
  480. "fine-prefix",
  481. );
  482. assert.equal(r.code, 1);
  483. assert.equal(r.error.code, 3611);
  484. assert.match(r.error.hint, /--name/);
  485. assert.equal(fake.deployments.length, 0);
  486. await assert.rejects(readFile(join(cwd, ".zcode-site.json")));
  487. // 改名不通过时名称不变。
  488. assert.equal((await run(fake, cwd, "deploy", "stage", "--name", "good")).code, 0);
  489. const renamed = await run(fake, cwd, "rename", "bad", "name");
  490. assert.equal(renamed.code, 1);
  491. assert.equal(renamed.error.code, 3611);
  492. assert.equal(fake.sites[0].name, "good");
  493. });
  494. test("a site whose live version was rejected by content review gets 3612 until redeployed", async () => {
  495. const fake = new FakeSites();
  496. const cwd = await project();
  497. assert.equal((await run(fake, cwd, "deploy", "stage")).code, 0);
  498. const site = fake.sites[0];
  499. assert.equal((await run(fake, cwd, "status")).result.offlineReason, undefined);
  500. // 人审驳回:服务端把站点下线并带上 offlineReason。
  501. Object.assign(site, { status: "offline", offlineReason: "review_rejected" });
  502. const status = (await run(fake, cwd, "status")).result;
  503. assert.equal(status.status, "offline");
  504. assert.equal(status.offlineReason, "review_rejected");
  505. const denied = await run(fake, cwd, "online");
  506. assert.equal(denied.code, 3);
  507. assert.equal(denied.error.code, 3612);
  508. assert.match(denied.error.hint, /deploy again/);
  509. assert.equal(site.status, "offline");
  510. // 重新部署成功后站点恢复上线。
  511. assert.equal((await run(fake, cwd, "deploy", "stage")).code, 0);
  512. const redeployed = (await run(fake, cwd, "status")).result;
  513. assert.equal(redeployed.status, "online");
  514. assert.equal(redeployed.offlineReason, undefined);
  515. });
  516. test("a prefix replaced by site after content review gets a warning", async () => {
  517. const fake = new FakeSites();
  518. fake.rejectPrefixes.add("bad-prefix").add("bad-name");
  519. const r = await run(fake, await project(), "deploy", "stage", "--prefix", "Bad Prefix");
  520. assert.equal(r.code, 0);
  521. const warnings = r.lines.filter((l) => l.event === "warning").map((l) => l.message);
  522. assert.ok(
  523. warnings.some(
  524. (m) => /"bad-prefix" did not pass content review/.test(m) && m.includes(r.result.url),
  525. ),
  526. warnings,
  527. );
  528. assert.match(r.result.url, /^https:\/\/site-/);
  529. // 没有 --prefix 时前缀来自名称,同样提示。
  530. const byName = await run(fake, await project(), "deploy", "stage", "--new", "--name", "Bad Name");
  531. assert.ok(byName.lines.some((l) => l.event === "warning" && /"bad-name"/.test(l.message)));
  532. // 规范化后本来就是 site 的不算机审替换,只有规范化提示。
  533. const short = await run(fake, await project(), "deploy", "stage", "--new", "--prefix", "ab");
  534. assert.equal(short.code, 0);
  535. assert.ok(!short.lines.some((l) => /content review/.test(l.message ?? "")));
  536. });
  537. test("normalizePrefix matches the server rule", () => {
  538. const cases = [
  539. ["happy-birthday", "happy-birthday"],
  540. ["Happy Birthday!", "happy-birthday"],
  541. ["-a..b--cd-", "a-b-cd"],
  542. ["生日快乐", "site"],
  543. ["ab", "site"],
  544. ["abcd", "abcd"],
  545. ["", "site"],
  546. ["a".repeat(40), "a".repeat(30)],
  547. ["a".repeat(29) + "-b", "a".repeat(29)],
  548. ];
  549. for (const [input, want] of cases) assert.equal(normalizePrefix(input), want, input);
  550. });
  551. test("help documents every command and option, and needs no endpoint", async () => {
  552. let stdout = "";
  553. const code = await main(["help"], {
  554. env: {},
  555. cwd: tmpdir(),
  556. stdout: { write: (s) => (stdout += s) },
  557. stderr: { write() {} },
  558. });
  559. assert.equal(code, 0);
  560. const commands = [
  561. "check",
  562. "deploy",
  563. "status",
  564. "logs",
  565. "offline",
  566. "online",
  567. "rename",
  568. "badge",
  569. "list",
  570. "usage",
  571. "help",
  572. ];
  573. const options = [
  574. "--new",
  575. "--site",
  576. "--name",
  577. "--prefix",
  578. "--offset",
  579. "--quiet",
  580. "--port",
  581. "--allow-foreign-binaries",
  582. ];
  583. for (const word of commands) assert.match(stdout, new RegExp(`^ ${word}\\b`, "m"), word);
  584. for (const word of options) assert.ok(stdout.includes(word), word);
  585. for (const exit of ["0", "1", "2", "3", "4"])
  586. assert.match(stdout, new RegExp(`^ ${exit} `, "m"));
  587. });