zcode-site.mjs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. #!/usr/bin/env node
  2. // zcode-site:ZCode Sites 的命令行客户端(技术方案 4.2、4.3、5.3)。
  3. // deploy 的输入是 Agent 准备好的 stage 目录,打包与契约检查、以及本地命令 check 在 stage.mjs;其余只和云端交互,不探测项目。
  4. // 命令、参数、输出和错误码的完整说明只写在 HELP 里(`zcode-site help`),site-deploy skill 引用它,不再重复。
  5. //
  6. // 输出契约:成功时 stdout 输出 JSON,退出码 0;deploy 过程中每个阶段和每条日志各输出一行 JSON(--quiet 只输出终态)。
  7. // 失败时 stderr 输出一行 {"error":{code,message,hint}},退出码 1=参数或本地文件错误、2=未登录、3=超出额度或限额、4=部署失败或服务端错误。
  8. //
  9. // 鉴权(技术方案 5.8):CLI 不持有任何登录凭证。请求发给 ZCode agent 侧的官方命令端点,端点按
  10. // session token 认出会话,补上 ZCode 身份头和 X-ZCode-App-Version 后转发给 zcode-server。
  11. // 端点地址和 token 由 ZCode 注入当前会话的 Bash,在普通终端里运行会按未登录退出:
  12. // ZCODE_OFFICIAL_ENDPOINT 端点地址(macOS / Linux 是 UDS 路径,Windows 是命名管道;
  13. // 以 http:// 或 https:// 开头时是 HTTP(S) 基地址,直接用 fetch 请求,供 Z.ai 沙箱等环境使用)
  14. // ZCODE_OFFICIAL_ENDPOINT_TOKEN 本会话的 token
  15. import { realpathSync } from "node:fs";
  16. import { request as httpRequest } from "node:http";
  17. import { readFile, rm, writeFile } from "node:fs/promises";
  18. import { basename, join } from "node:path";
  19. import { pathToFileURL } from "node:url";
  20. import { parseArgs } from "node:util";
  21. import { apiError, CliError, localError } from "./errors.mjs";
  22. import { checkStage, packStage } from "./stage.mjs";
  23. const BINDING_FILE = ".zcode-site.json";
  24. const POLL_INTERVAL_MS = 2000;
  25. // 服务端兜底清理会把 publishing / verifying 超 10 分钟的部署置为 failed,这里多等一点再放弃。
  26. const POLL_TIMEOUT_MS = 15 * 60 * 1000;
  27. const UPLOAD_ATTEMPTS = 3;
  28. const IN_FLIGHT = new Set(["preparing", "uploading", "publishing", "verifying"]);
  29. const RESUMABLE = new Set(["preparing", "uploading"]);
  30. // 统计在服务端 5 秒内没算完时返回 computing,后台继续算;按契约每 3 秒再读,最多约 1 分钟。
  31. const ANALYTICS_RANGES = ["24h", "7d", "30d"];
  32. const ANALYTICS_RETRY_MS = 3000;
  33. const ANALYTICS_ATTEMPTS = 20;
  34. // ---------- 鉴权与 API ----------
  35. const ENDPOINT_ORIGIN = "http://zcode-official-endpoint";
  36. // 端点自己产生的错误经这个响应头说明类型;network 表示端点连不上 zcode-server。
  37. const ENDPOINT_ERROR_HEADER = "x-zcode-official-endpoint-error";
  38. function loadEndpoint(env) {
  39. const address = env.ZCODE_OFFICIAL_ENDPOINT?.trim();
  40. const token = env.ZCODE_OFFICIAL_ENDPOINT_TOKEN?.trim();
  41. if (!address || !token) {
  42. throw new CliError(
  43. "UNAUTHENTICATED",
  44. "Sites credentials are not available",
  45. "Run zcode-site from a session that provides Sites credentials (in ZCode, the Sites plugin must be enabled); ask the user to sign in again or start a new session, then retry.",
  46. 2,
  47. );
  48. }
  49. return { address, token };
  50. }
  51. // 经 UDS / 命名管道发 HTTP 请求,返回标准 Response,和 fetch 同形状(测试注入 fetchImpl 替换它)。
  52. // 端点是 http(s) 地址时改用全局 fetch,把 url 里的路径和 query 接到端点基地址后面;
  53. // Buffer 请求体由 fetch 按长度带 Content-Length,不会变成 chunked(服务端要求它等于 artifactSize)。
  54. export function createEndpointFetch(address) {
  55. if (/^https?:\/\//i.test(address)) {
  56. const base = address.replace(/\/+$/, "");
  57. return (url, init = {}) => {
  58. const { pathname, search } = new URL(url);
  59. return fetch(base + pathname + search, init);
  60. };
  61. }
  62. return (url, init = {}) =>
  63. new Promise((resolve, reject) => {
  64. const { pathname, search } = new URL(url);
  65. const headers = { ...init.headers };
  66. if (init.body !== undefined) headers["Content-Length"] = String(Buffer.byteLength(init.body));
  67. const req = httpRequest(
  68. { socketPath: address, path: pathname + search, method: init.method ?? "GET", headers },
  69. (res) => {
  70. const chunks = [];
  71. res.on("data", (chunk) => chunks.push(chunk));
  72. res.on("error", reject);
  73. res.on("aborted", () =>
  74. reject(new Error("the connection was closed before the response ended")),
  75. );
  76. res.on("end", () => {
  77. if (!res.complete)
  78. return reject(new Error("the connection was closed before the response ended"));
  79. const responseHeaders = new Headers();
  80. for (const [name, value] of Object.entries(res.headers)) {
  81. if (value !== undefined)
  82. responseHeaders.set(name, Array.isArray(value) ? value.join(", ") : value);
  83. }
  84. const status = res.statusCode ?? 502;
  85. const nullBody = status === 204 || status === 205 || status === 304;
  86. resolve(
  87. new Response(nullBody ? null : Buffer.concat(chunks), {
  88. status,
  89. headers: responseHeaders,
  90. }),
  91. );
  92. });
  93. },
  94. );
  95. req.on("error", reject);
  96. req.end(init.body);
  97. });
  98. }
  99. function createClient(endpoint, fetchImpl) {
  100. // body 是 JSON 对象;Buffer 原样作为请求体发送(产物包),按长度带上 Content-Length。
  101. async function call(method, path, body) {
  102. const headers = { Authorization: `Bearer ${endpoint.token}` };
  103. const raw = Buffer.isBuffer(body);
  104. if (body !== undefined) headers["Content-Type"] = raw ? "application/gzip" : "application/json";
  105. let res;
  106. try {
  107. res = await fetchImpl(ENDPOINT_ORIGIN + path, {
  108. method,
  109. headers,
  110. body: body === undefined || raw ? body : JSON.stringify(body),
  111. });
  112. } catch (err) {
  113. throw new CliError(
  114. "NETWORK_ERROR",
  115. `Cannot reach the Sites API: ${err.message}`,
  116. "Check the network connection to ZCode and retry.",
  117. 4,
  118. );
  119. }
  120. if (res.headers.get(ENDPOINT_ERROR_HEADER) === "network") {
  121. throw new CliError(
  122. "NETWORK_ERROR",
  123. "ZCode cannot reach the Sites API",
  124. "Check the network connection and retry.",
  125. 4,
  126. );
  127. }
  128. const text = await res.text();
  129. let parsed;
  130. try {
  131. parsed = text ? JSON.parse(text) : undefined;
  132. } catch {
  133. parsed = undefined;
  134. }
  135. if (!res.ok || parsed?.code !== 0) throw apiError(res.status, parsed);
  136. return parsed.data;
  137. }
  138. return {
  139. listSites: (cursor) =>
  140. call(
  141. "GET",
  142. `/api/v1/sites?limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`,
  143. ),
  144. // domainPrefix 不传时服务端按 name 规范化(openapi createSite)。
  145. createSite: (name, domainPrefix) =>
  146. call("POST", "/api/v1/sites", domainPrefix === undefined ? { name } : { name, domainPrefix }),
  147. getSite: (id) => call("GET", `/api/v1/sites/${id}`),
  148. updateSite: (id, patch) => call("PATCH", `/api/v1/sites/${id}`, patch),
  149. createDeployment: (siteId, artifactSize) =>
  150. call("POST", `/api/v1/sites/${siteId}/deployments`, { artifactSize }),
  151. getDeployment: (siteId, id) => call("GET", `/api/v1/sites/${siteId}/deployments/${id}`),
  152. uploadPackage: (siteId, id, body) =>
  153. call("PUT", `/api/v1/sites/${siteId}/deployments/${id}/package`, body),
  154. logs: (siteId, id, offset) =>
  155. call("GET", `/api/v1/sites/${siteId}/deployments/${id}/logs?offset=${offset}`),
  156. usage: () => call("GET", "/api/v1/sites/usage"),
  157. analytics: (siteId, range) =>
  158. call("GET", `/api/v1/sites/${siteId}/analytics?range=${encodeURIComponent(range)}`),
  159. deleteSite: (id) => call("DELETE", `/api/v1/sites/${id}`),
  160. };
  161. }
  162. // ---------- 站点绑定(技术方案 4.3) ----------
  163. async function readBinding(cwd) {
  164. let text;
  165. try {
  166. text = await readFile(join(cwd, BINDING_FILE), "utf8");
  167. } catch (err) {
  168. if (err.code === "ENOENT") return undefined;
  169. throw err;
  170. }
  171. try {
  172. const b = JSON.parse(text);
  173. if (typeof b.siteId === "string" && b.siteId) return b;
  174. } catch {
  175. // 落到下面统一报错
  176. }
  177. throw localError(
  178. "INVALID_BINDING",
  179. `${BINDING_FILE} is not valid`,
  180. `Fix or delete ${BINDING_FILE}, or pass --site <id>.`,
  181. );
  182. }
  183. async function writeBinding(cwd, site) {
  184. await writeFile(
  185. join(cwd, BINDING_FILE),
  186. `${JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }, null, 2)}\n`,
  187. );
  188. }
  189. async function allSites(client) {
  190. const items = [];
  191. let cursor;
  192. do {
  193. const page = await client.listSites(cursor);
  194. items.push(...page.items);
  195. cursor = page.nextCursor;
  196. } while (cursor);
  197. return items;
  198. }
  199. function candidates(sites) {
  200. return sites.map((s) => ({ id: s.id, name: s.name, url: s.url, status: s.status }));
  201. }
  202. // resolveSite 的规则:--site > 绑定文件 > 账户下没有站点时(只限 deploy)新建;已有站点时报错并给出候选,不按名字匹配,也不自动新建。
  203. async function resolveSite(ctx, { allowCreate }) {
  204. const { client, cwd, opts } = ctx;
  205. if (opts.site) return { site: await client.getSite(opts.site), bound: false };
  206. const binding = await readBinding(cwd);
  207. if (binding) return { site: await client.getSite(binding.siteId), bound: true };
  208. if (allowCreate && opts.new)
  209. return {
  210. site: await client.createSite(siteName(ctx), opts.prefix),
  211. bound: false,
  212. created: true,
  213. };
  214. const sites = await allSites(client);
  215. if (allowCreate && sites.length === 0)
  216. return {
  217. site: await client.createSite(siteName(ctx), opts.prefix),
  218. bound: false,
  219. created: true,
  220. };
  221. throw new CliError(
  222. "SITE_NOT_SELECTED",
  223. sites.length ? "This project is not linked to a site" : "You have no sites yet",
  224. allowCreate
  225. ? "Ask the user which site to update, then retry with --site <id>, or with --new to create a new site."
  226. : "Pass --site <id>, or deploy first.",
  227. 1,
  228. { candidates: candidates(sites) },
  229. );
  230. }
  231. function siteName(ctx) {
  232. return (ctx.opts.name ?? basename(ctx.cwd)).trim() || "site";
  233. }
  234. // normalizePrefix 与服务端 site.NormalizePrefix 同一规则(技术方案 5.4),只用来提前告诉 Agent 实际会得到的前缀;
  235. // 发给服务端的仍是原值,以服务端规范化的结果为准。
  236. export function normalizePrefix(prefix) {
  237. let s = prefix
  238. .toLowerCase()
  239. .replace(/[^a-z0-9]+/g, "-")
  240. .replace(/^-+|-+$/g, "");
  241. if (s.length > 30) s = s.slice(0, 30).replace(/-+$/, "");
  242. return s.length < 4 ? "site" : s;
  243. }
  244. // --prefix 只在本次新建站点时生效;不合规时提示规范化结果,但不拦截,交给服务端兜底。
  245. // 前缀(没有 --prefix 时是名称)没有通过服务端机审时,服务端换成 site,按返回的 domainLabel 提示(契约 0.15.0)。
  246. function prefixNotice(opts, created, site) {
  247. if (!created)
  248. return opts.prefix === undefined
  249. ? undefined
  250. : "--prefix is ignored: the site already exists. Change its domain with `zcode-site prefix <prefix>`.";
  251. const expected = normalizePrefix(opts.prefix ?? site.name);
  252. if (expected !== "site" && !site.domainLabel.startsWith(`${expected}-`))
  253. return `The domain prefix ${JSON.stringify(expected)} did not pass content review, so the server used "site": the domain is ${site.url}. Change it with \`zcode-site prefix <prefix>\`.`;
  254. if (opts.prefix === undefined) return undefined;
  255. const normalized = expected;
  256. if (normalized === opts.prefix) return undefined;
  257. return normalized === "site"
  258. ? `--prefix ${JSON.stringify(opts.prefix)} has fewer than 4 usable [a-z0-9-] characters; the server falls back to "site".`
  259. : `--prefix ${JSON.stringify(opts.prefix)} is normalized to ${JSON.stringify(normalized)}.`;
  260. }
  261. // ---------- deploy ----------
  262. async function deploy(ctx, stageDir) {
  263. const { client, out, opts } = ctx;
  264. if (!stageDir)
  265. throw localError(
  266. "MISSING_STAGE",
  267. "Missing stage directory",
  268. "Usage: zcode-site deploy <stage-dir> [--new | --site <id>]",
  269. );
  270. if (opts.site && opts.new)
  271. throw localError(
  272. "INVALID_ARGS",
  273. "--site and --new cannot be used together",
  274. "Pass only one of them.",
  275. );
  276. // 先打包再选站点:契约检查不过时不建站、不建部署。
  277. const packed = await packStage(stageDir, {
  278. cwd: ctx.cwd,
  279. allowForeignBinaries: opts["allow-foreign-binaries"],
  280. });
  281. if (packed.error)
  282. throw localError(packed.error, packed.message, "Pass the stage directory that holds start.sh.");
  283. if (packed.problems)
  284. throw new CliError(
  285. "PACKAGE_CHECK_FAILED",
  286. `The stage does not meet the package contract:\n${packed.problems.map((p) => ` - ${p}`).join("\n")}`,
  287. "Fix every listed problem in the stage (see the site-deploy skill references), then deploy again.",
  288. 1,
  289. { problems: packed.problems },
  290. );
  291. out.event({ event: "packed", ...packed.result });
  292. for (const message of packed.warnings) out.event({ event: "warning", message });
  293. const { site, bound, created } = await resolveSite(ctx, { allowCreate: true });
  294. if (!bound) await writeBinding(ctx.cwd, site);
  295. if (created) out.event({ event: "site_created", siteId: site.id, url: site.url });
  296. // 已绑定时 --new 不生效:首次部署统一带 --new,后续部署即使误带也只会更新已绑定的站点,不会重复建站。
  297. if (bound && opts.new)
  298. out.event({
  299. event: "warning",
  300. message: `--new is ignored: this project is linked to site ${site.id} (${BINDING_FILE}).`,
  301. });
  302. const notice = prefixNotice(opts, created, site);
  303. if (notice) out.event({ event: "warning", message: notice });
  304. const deployment = await startDeployment(client, site.id, packed.body.length);
  305. out.event({
  306. event: "deployment_started",
  307. siteId: site.id,
  308. deploymentId: deployment.id,
  309. resumed: deployment.resumed,
  310. });
  311. await uploadPackage(ctx, site.id, deployment.id, packed.body);
  312. const final = await watch(ctx, site.id, deployment.id);
  313. const result = {
  314. siteId: site.id,
  315. deploymentId: final.id,
  316. status: final.status,
  317. url: site.url,
  318. failure: final.failure,
  319. };
  320. if (final.status !== "success") {
  321. throw new CliError(
  322. final.failure?.code ?? "DEPLOYMENT_FAILED",
  323. `Deployment failed at ${final.failure?.stage ?? "unknown"}: ${final.failure?.message ?? final.status}`,
  324. deployHint(final.failure?.code),
  325. 4,
  326. result,
  327. );
  328. }
  329. return result;
  330. }
  331. // 同一用户同时只能有一个进行中的部署。3610 指向本站点、且还没开始发布时,多半是上一次请求成功了但响应丢了,直接续传(技术方案 5.3)。
  332. async function startDeployment(client, siteId, size) {
  333. try {
  334. return { ...(await client.createDeployment(siteId, size)), resumed: false };
  335. } catch (err) {
  336. const p = err.data?.inProgress;
  337. if (err.code === 3610 && p && p.siteId === siteId && RESUMABLE.has(p.status)) {
  338. const d = await client.getDeployment(siteId, p.deploymentId);
  339. if (d.artifactSize === size) return { ...d, resumed: true };
  340. }
  341. if (err.code === 3610 && p)
  342. err.hint = `Deployment ${p.deploymentId} of site ${p.siteId} is ${p.status}. Wait for it to finish, then retry.`;
  343. throw err;
  344. }
  345. }
  346. // 包经 zcode-server 转发给控制面,由控制面写 OSS 并进入 publishing(openapi uploadPackage),CLI 不直接访问 OSS。
  347. // 断网或 3604(传输中断、长度不符)时用同一个请求整包重传;3603 说明上一次其实已经传完、只是响应丢了,直接进入轮询。
  348. async function uploadPackage(ctx, siteId, deploymentId, body) {
  349. const { client, out } = ctx;
  350. for (let attempt = 1; ; attempt++) {
  351. out.event({ event: "uploading", attempt, bytes: body.length });
  352. try {
  353. return await client.uploadPackage(siteId, deploymentId, body);
  354. } catch (err) {
  355. if (err.code === 3603) {
  356. const d = await client.getDeployment(siteId, deploymentId);
  357. if (!RESUMABLE.has(d.status)) return d;
  358. throw err;
  359. }
  360. const retryable = err.code === 3604 || err.code === "NETWORK_ERROR";
  361. if (!retryable || attempt >= UPLOAD_ATTEMPTS) throw err;
  362. }
  363. }
  364. }
  365. async function watch(ctx, siteId, deploymentId) {
  366. const { client, out, sleep, now } = ctx;
  367. const deadline = now() + POLL_TIMEOUT_MS;
  368. let offset = 0;
  369. let lastStatus;
  370. const drainLogs = async () => {
  371. const logs = await client.logs(siteId, deploymentId, offset);
  372. for (const e of logs.entries)
  373. out.event({ event: "log", stage: e.stage, level: e.level, message: e.message, ts: e.ts });
  374. offset = logs.nextOffset;
  375. };
  376. for (;;) {
  377. const d = await client.getDeployment(siteId, deploymentId);
  378. // 先读状态再读日志:状态已到终态时,这一轮读到的日志一定是全部。
  379. await drainLogs();
  380. if (d.status !== lastStatus) {
  381. out.event({ event: "status", status: d.status });
  382. lastStatus = d.status;
  383. }
  384. if (!IN_FLIGHT.has(d.status)) return d;
  385. if (now() > deadline) {
  386. throw new CliError(
  387. "WATCH_TIMEOUT",
  388. "Timed out waiting for the deployment to finish",
  389. `It is still ${d.status}; check later with \`zcode-site status --site ${siteId}\`.`,
  390. 4,
  391. { siteId, deploymentId },
  392. );
  393. }
  394. await sleep(POLL_INTERVAL_MS);
  395. }
  396. }
  397. function deployHint(code) {
  398. switch (code) {
  399. case "PACKAGE_INVALID":
  400. return "Fix the stage as described in the message (see the site-deploy skill's packaging reference) and deploy again.";
  401. case "WARMUP_FAILED":
  402. return "start.sh did not answer GET / on 0.0.0.0:3000 with a status below 500 in time. Read `zcode-site logs <deploymentId>`, run `zcode-site check <stage-dir>`, fix it and deploy again.";
  403. case "UPLOAD_TIMEOUT":
  404. return "The upload did not finish in time. Run `zcode-site deploy` again.";
  405. default:
  406. return "Run `zcode-site logs <deploymentId>` for details, then retry. The previous live version keeps serving.";
  407. }
  408. }
  409. // ---------- 其他命令 ----------
  410. function summarize(site) {
  411. return {
  412. id: site.id,
  413. name: site.name,
  414. url: site.url,
  415. status: site.status,
  416. ...(site.offlineReason && { offlineReason: site.offlineReason }),
  417. region: site.region,
  418. badgeHidden: site.badgeHidden,
  419. badgeVisible: site.badgeVisible,
  420. multiInstance: site.multiInstance,
  421. currentDeployment: site.currentDeployment && pickDeployment(site.currentDeployment),
  422. latestDeployment: site.latestDeployment && pickDeployment(site.latestDeployment),
  423. };
  424. }
  425. function pickDeployment(d) {
  426. return {
  427. id: d.id,
  428. status: d.status,
  429. createdAt: d.createdAt,
  430. finishedAt: d.finishedAt,
  431. failure: d.failure,
  432. };
  433. }
  434. async function logsCommand(ctx, deploymentId) {
  435. if (!deploymentId)
  436. throw localError(
  437. "MISSING_DEPLOYMENT",
  438. "Missing deployment id",
  439. "Usage: zcode-site logs <deploymentId> [--site <id>] [--offset <n>]",
  440. );
  441. const { site } = await resolveSite(ctx, { allowCreate: false });
  442. const offset = ctx.opts.offset === undefined ? 0 : Number(ctx.opts.offset);
  443. if (!Number.isInteger(offset) || offset < 0)
  444. throw localError(
  445. "INVALID_ARGS",
  446. "--offset must be a non-negative integer",
  447. "Pass the nextOffset from the previous call.",
  448. );
  449. return ctx.client.logs(site.id, deploymentId, offset);
  450. }
  451. async function setStatus(ctx, status) {
  452. const { site } = await resolveSite(ctx, { allowCreate: false });
  453. return summarize(await ctx.client.updateSite(site.id, { status }));
  454. }
  455. async function setBadge(ctx, action) {
  456. if (action !== "hide" && action !== "show")
  457. throw localError(
  458. "INVALID_ARGS",
  459. "Expected hide or show",
  460. "Usage: zcode-site badge hide|show [--site <id>]",
  461. );
  462. const { site } = await resolveSite(ctx, { allowCreate: false });
  463. return summarize(await ctx.client.updateSite(site.id, { badgeHidden: action === "hide" }));
  464. }
  465. // 实例模式(契约 Site.multiInstance):single 是默认,所有请求进同一个实例;multi 让请求分到多个实例。
  466. async function setInstance(ctx, mode) {
  467. if (mode !== "single" && mode !== "multi")
  468. throw localError(
  469. "INVALID_ARGS",
  470. "Expected single or multi",
  471. "Usage: zcode-site instance single|multi [--site <id>]",
  472. );
  473. const { site } = await resolveSite(ctx, { allowCreate: false });
  474. return summarize(await ctx.client.updateSite(site.id, { multiInstance: mode === "multi" }));
  475. }
  476. async function rename(ctx, name) {
  477. if (!name?.trim())
  478. throw localError(
  479. "MISSING_NAME",
  480. "Missing site name",
  481. "Usage: zcode-site rename [--site <id>] <name>",
  482. );
  483. const { site } = await resolveSite(ctx, { allowCreate: false });
  484. return summarize(await ctx.client.updateSite(site.id, { name: name.trim() }));
  485. }
  486. async function analyticsCommand(ctx) {
  487. const range = ctx.opts.range ?? "7d";
  488. if (!ANALYTICS_RANGES.includes(range))
  489. throw localError(
  490. "INVALID_ARGS",
  491. "--range must be 24h, 7d or 30d",
  492. "Usage: zcode-site analytics [--site <id>] [--range 24h|7d|30d]",
  493. );
  494. const { site } = await resolveSite(ctx, { allowCreate: false });
  495. for (let attempt = 1; ; attempt++) {
  496. const result = await ctx.client.analytics(site.id, range);
  497. if (result.status !== "computing") return { siteId: site.id, url: site.url, ...result };
  498. if (attempt >= ANALYTICS_ATTEMPTS)
  499. throw new CliError(
  500. "ANALYTICS_PENDING",
  501. "The analytics are still being computed",
  502. "Run the same command again in a minute.",
  503. 4,
  504. { siteId: site.id, range },
  505. );
  506. await ctx.sleep(ANALYTICS_RETRY_MS);
  507. }
  508. }
  509. // 改域名前缀:服务端规范化后生成新的 {前缀}-{4 位随机},旧地址立即失效,统计从零开始(契约 updateSite)。
  510. // 改前缀时服务端不兜底:规范化后不足 4 位直接报错,这里提前拦截,省一次请求。
  511. async function changePrefix(ctx, prefix) {
  512. if (!prefix?.trim())
  513. throw localError(
  514. "MISSING_PREFIX",
  515. "Missing domain prefix",
  516. "Usage: zcode-site prefix <prefix> [--site <id>]",
  517. );
  518. const normalized = normalizePrefix(prefix);
  519. if (normalized === "site" && !/^site$/i.test(prefix.trim()))
  520. throw localError(
  521. "INVALID_ARGS",
  522. "The prefix has fewer than 4 usable characters",
  523. "Use 4-30 lowercase letters, digits and -.",
  524. );
  525. const { site, bound } = await resolveSite(ctx, { allowCreate: false });
  526. const updated = await ctx.client.updateSite(site.id, { domainPrefix: prefix.trim() });
  527. if (bound) await writeBinding(ctx.cwd, updated);
  528. return { ...summarize(updated), previousUrl: site.url };
  529. }
  530. // 删除不可恢复,只接受显式的 --site,不按绑定文件猜目标;删掉的是本项目绑定的站点时一并删除绑定文件。
  531. async function deleteCommand(ctx) {
  532. const id = ctx.opts.site;
  533. if (!id)
  534. throw localError(
  535. "MISSING_SITE",
  536. "delete needs --site <id>",
  537. "Confirm with the user which site to delete, then pass --site <id>.",
  538. );
  539. await ctx.client.deleteSite(id);
  540. let unlinked = false;
  541. const binding = await readBinding(ctx.cwd).catch(() => undefined);
  542. if (binding?.siteId === id) {
  543. await rm(join(ctx.cwd, BINDING_FILE), { force: true });
  544. unlinked = true;
  545. }
  546. return { siteId: id, deleted: true, unlinked };
  547. }
  548. const HELP = `zcode-site: deploy and manage ZCode Sites. Run it from the project root.
  549. Output
  550. stdout: JSON, one object per line. deploy prints progress events first; the last line is the result.
  551. stderr on failure: one line {"error":{"code","message","hint","data"?}}. Follow hint.
  552. Exit codes
  553. 0 success
  554. 1 bad arguments, a local file or stage problem, or SITE_NOT_SELECTED
  555. 2 Sites credentials missing or rejected (not signed in, sign-in expired, or no credentials in this session)
  556. 3 quota, rate or size limit, or another deployment in progress
  557. 4 the deployment failed, or a server error
  558. Local command (no sign-in, nothing is uploaded)
  559. check <stage-dir> [--port <n>]
  560. Run "bash start.sh" in the stage with PORT (default 13000) and a temporary DATA_DIR, wait
  561. up to 90 s for GET / below 500, then stop it.
  562. Result: {status: "live", httpStatus, log} - the site should answer 200.
  563. {status: "skipped", reason} - the stage can't run on this machine (Linux binaries on
  564. macOS/Windows, or no bash); run the app from its normal local environment instead.
  565. START_FAILED: data {reason, httpStatus?, log}.
  566. Site commands
  567. deploy <stage-dir> [--new | --site <id>] [--name <name>] [--prefix <prefix>]
  568. [--allow-foreign-binaries] [--quiet]
  569. Pack the stage directory (its root becomes /app) and publish it. Packing runs first and
  570. checks the package contract: root start.sh with LF line endings, size, file count, path
  571. depth, reserved /.__zcode/, broken symlinks, .env files, dependencies present, and every
  572. native binary linux x86-64. It skips .git, .DS_Store, __pycache__ and .zcode-site.json.
  573. PACKAGE_CHECK_FAILED (exit 1): data.problems lists everything to fix; nothing was created
  574. or uploaded. Fix all of them, then deploy again.
  575. --allow-foreign-binaries: accept non-linux binaries; only after confirming each listed file
  576. is never loaded at runtime (e.g. prebuilt binaries for other platforms next to
  577. the linux-x64 one).
  578. Target site: --site <id>, else the site in .zcode-site.json, else with --new a new site.
  579. A new site is linked by writing .zcode-site.json; keep it and don't put it in the stage.
  580. --new is ignored (with a warning) when the project is already linked.
  581. Without --new or --site on an unlinked project: SITE_NOT_SELECTED if the account has sites,
  582. data.candidates [{id, name, url, status}]; ask the user, never pick one yourself.
  583. --name display name of a new site, any language (default: directory name). A name that
  584. fails the server's content review gets 3611 and nothing is created.
  585. --prefix domain prefix of a new site: 4-30 chars, lowercase a-z 0-9 and -. The domain is
  586. {prefix}-{4 random chars}. The server lowercases it, turns other characters into
  587. -, cuts it to 30 and falls back to "site" below 4 or when the prefix fails content
  588. review; a warning event says so.
  589. Ignored for an existing site; change its domain with \`prefix\`.
  590. --quiet print only the result.
  591. Events: {event: "packed", packageBytes, unpackedBytes, files, linuxBinaries}, then
  592. {event: "site_created" | "warning" | "deployment_started" | "uploading" | "log" | "status", ...}
  593. Result: {siteId, deploymentId, status: "success", url}
  594. Failure (exit 4): code is the failed stage reason, data has {siteId, deploymentId, failure}.
  595. PACKAGE_INVALID server preflight rejected the package; message names the file.
  596. WARMUP_FAILED GET / got no answer below 500 within 90 s; read logs, run check.
  597. UPLOAD_TIMEOUT deploy again.
  598. PUBLISH_FAILED, PUBLISH_TIMEOUT, INTERNAL platform side; retry later.
  599. The previous live version keeps serving after a failed deployment.
  600. status [--site <id>]
  601. Result: {id, name, url, status, offlineReason?, region, badgeHidden, badgeVisible, multiInstance,
  602. currentDeployment, latestDeployment} (deployments: {id, status, createdAt, finishedAt, failure}).
  603. status: pending = never deployed successfully, the URL shows nothing yet; online = the URL
  604. serves currentDeployment; offline = taken offline. offlineReason review_rejected means
  605. content review rejected the live version and took the site offline: online gets 3612,
  606. change the content and deploy again. A redeploy keeps the site online
  607. on the old version. Deployment progress is latestDeployment.status: preparing,
  608. uploading, publishing or verifying means still running (it ends within about 10
  609. minutes) - wait and check again, don't redeploy.
  610. logs <deploymentId> [--site <id>] [--offset <n>]
  611. Result: {entries: [{stage, level, message, ts}], nextOffset}; pass nextOffset to read on.
  612. offline [--site <id>] take the site offline; domain and records are kept. Result: as status.
  613. online [--site <id>] bring it back; a site never deployed successfully stays pending, and one whose
  614. live version was rejected by content review gets 3612. Result: as status.
  615. rename [--site <id>] <name> change the display name only; 3611 if it fails content review.
  616. Result: as status.
  617. badge hide|show [--site <id>] hide or show the "ZCode" badge on the site. Only paid plans can
  618. hide it (usage.badgeRemovable); free plans get 3608. badgeHidden is the user's choice,
  619. badgeVisible whether the badge actually shows. Result: as status.
  620. instance single|multi [--site <id>] single (default): all requests go to one instance, so
  621. memory and $DATA_DIR are shared by every request; at most 200 in flight, more get 429.
  622. multi: requests spread over several instances, nothing in memory or $DATA_DIR is shared;
  623. for stateless sites with heavy traffic. Takes effect without a redeploy (another region
  624. within 30 s). Result: as status (multiInstance).
  625. prefix <prefix> [--site <id>] change the domain to {prefix}-{4 new random chars}. The prefix is
  626. normalized like --prefix but never falls back: fewer than 4 usable characters is an error,
  627. and a prefix that fails content review gets 3614. The old address stops working at once
  628. (no redirect) and may go to another site; visit analytics start over. Confirm with the
  629. user first. Updates .zcode-site.json. Result: as status, plus previousUrl.
  630. delete --site <id> permanently delete the site: its address returns 404 at once and it can't
  631. be restored; this month's traffic and requests are not refunded. Needs an explicit
  632. --site; confirm with the user first. 3610 while a deployment is in progress. Removes
  633. .zcode-site.json when it points to this site.
  634. Result: {siteId, deleted: true, unlinked}.
  635. analytics [--site <id>] [--range 24h|7d|30d] visit analytics (default 7d), from browsers that
  636. ran the page; bots excluded, a few minutes of delay. Waits up to about a minute while
  637. the server computes them (ANALYTICS_PENDING after that, retry later); 3613 = retry later.
  638. Result: {siteId, url, status: "ready", range, generatedAt, partial, summary: {pv, uv,
  639. avgDurationSeconds, bounceRate}, series: [{start, pv, uv}], pages, referrers, devices,
  640. regions: [{key, pv, share}]}. summary and the lists are null when there were no visits;
  641. a referrer key "" is direct or unknown. Counting restarts when the prefix changes.
  642. list Result: {sites: [{id, name, url, status}]}
  643. usage Account traffic, requests and storage against the plan; canDeploy and exceededReasons.
  644. help this text.
  645. Commands without --site use the site in .zcode-site.json. Numeric error codes come from the Sites
  646. API (e.g. 3605 quota exceeded, 3610 another deployment in progress); their hint says what to do.`;
  647. // ---------- 入口 ----------
  648. export async function main(
  649. argv,
  650. {
  651. env = process.env,
  652. cwd = process.cwd(),
  653. fetchImpl,
  654. stdout = process.stdout,
  655. stderr = process.stderr,
  656. sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
  657. now = Date.now,
  658. } = {},
  659. ) {
  660. let parsed;
  661. try {
  662. parsed = parseArgs({
  663. args: argv,
  664. allowPositionals: true,
  665. options: {
  666. site: { type: "string" },
  667. new: { type: "boolean" },
  668. name: { type: "string" },
  669. prefix: { type: "string" },
  670. offset: { type: "string" },
  671. range: { type: "string" },
  672. port: { type: "string" },
  673. "allow-foreign-binaries": { type: "boolean" },
  674. quiet: { type: "boolean" },
  675. help: { type: "boolean", short: "h" },
  676. },
  677. });
  678. } catch (err) {
  679. return fail(stderr, localError("INVALID_ARGS", err.message, "Run `zcode-site help`."));
  680. }
  681. const [command, ...args] = parsed.positionals;
  682. if (!command || command === "help" || parsed.values.help) {
  683. stdout.write(`${HELP}\n`);
  684. return command || parsed.values.help ? 0 : 1;
  685. }
  686. if (command === "check") {
  687. try {
  688. const result = await check(cwd, args, parsed.values);
  689. stdout.write(`${JSON.stringify(result)}\n`);
  690. return 0;
  691. } catch (err) {
  692. return fail(stderr, err instanceof CliError ? err : internalError(err));
  693. }
  694. }
  695. const quiet = parsed.values.quiet;
  696. const out = { event: (e) => quiet || stdout.write(`${JSON.stringify(e)}\n`) };
  697. try {
  698. const endpoint = loadEndpoint(env);
  699. const client = createClient(endpoint, fetchImpl ?? createEndpointFetch(endpoint.address));
  700. const ctx = { client, cwd, opts: parsed.values, out, sleep, now };
  701. let result;
  702. switch (command) {
  703. case "deploy":
  704. result = await deploy(ctx, args[0]);
  705. break;
  706. case "status":
  707. result = summarize((await resolveSite(ctx, { allowCreate: false })).site);
  708. break;
  709. case "logs":
  710. result = await logsCommand(ctx, args[0]);
  711. break;
  712. case "offline":
  713. result = await setStatus(ctx, "offline");
  714. break;
  715. case "online":
  716. result = await setStatus(ctx, "online");
  717. break;
  718. case "usage":
  719. result = await client.usage();
  720. break;
  721. case "list":
  722. result = { sites: candidates(await allSites(client)) };
  723. break;
  724. case "rename":
  725. result = await rename(ctx, args.join(" "));
  726. break;
  727. case "badge":
  728. result = await setBadge(ctx, args[0]);
  729. break;
  730. case "instance":
  731. result = await setInstance(ctx, args[0]);
  732. break;
  733. case "analytics":
  734. result = await analyticsCommand(ctx);
  735. break;
  736. case "prefix":
  737. result = await changePrefix(ctx, args.join(" "));
  738. break;
  739. case "delete":
  740. result = await deleteCommand(ctx);
  741. break;
  742. default:
  743. throw localError(
  744. "UNKNOWN_COMMAND",
  745. `Unknown command: ${command}`,
  746. "Run `zcode-site help`.",
  747. );
  748. }
  749. stdout.write(`${JSON.stringify(result)}\n`);
  750. return 0;
  751. } catch (err) {
  752. return fail(stderr, err instanceof CliError ? err : internalError(err));
  753. }
  754. }
  755. function internalError(err) {
  756. return new CliError(
  757. "INTERNAL",
  758. err.message,
  759. "This is a bug in zcode-site; report it with the command you ran.",
  760. 4,
  761. );
  762. }
  763. async function check(cwd, [stageDir], opts) {
  764. if (!stageDir)
  765. throw localError(
  766. "INVALID_ARGS",
  767. "Missing stage directory",
  768. "Usage: zcode-site check <stage-dir> [--port <n>]",
  769. );
  770. const port = opts.port === undefined ? undefined : Number(opts.port);
  771. if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))
  772. throw localError("INVALID_ARGS", "--port must be a port number", "Pass e.g. --port 13000.");
  773. const checked = await checkStage(stageDir, { cwd, ...(port ? { port } : {}) });
  774. if (checked.error)
  775. throw localError(
  776. checked.error,
  777. checked.message,
  778. "Pass the stage directory that holds start.sh.",
  779. );
  780. if (checked.failed)
  781. throw new CliError(
  782. "START_FAILED",
  783. checked.failed.reason,
  784. "Read data.log and the site-deploy skill's troubleshooting reference, fix the stage, then check again.",
  785. 1,
  786. checked.failed,
  787. );
  788. return checked.result;
  789. }
  790. function fail(stderr, err) {
  791. const error = { code: err.code, message: err.message, hint: err.hint };
  792. if (err.data !== undefined) error.data = err.data;
  793. stderr.write(`${JSON.stringify({ error })}\n`);
  794. return err.exitCode;
  795. }
  796. if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
  797. process.exitCode = await main(process.argv.slice(2));
  798. }