shoplazza-ai-dev-cli 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/_chunks/test.mjs +247 -34
  2. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { loadConfig, runLogin } from "../cli.mjs";
2
2
  import { readFileSync } from "fs";
3
+ import * as readline from "readline";
3
4
  function parseGlobalFlags(args) {
4
5
  const flags = { json: false };
5
6
  const rest = [];
@@ -272,19 +273,73 @@ async function runTaxonomy(client, args, json) {
272
273
  process.exitCode = 2;
273
274
  }
274
275
  }
276
+ function askConfirm(prompt) {
277
+ const rl = readline.createInterface({
278
+ input: process.stdin,
279
+ output: process.stderr
280
+ });
281
+ return new Promise((resolve) => {
282
+ rl.question(prompt, (answer) => {
283
+ rl.close();
284
+ resolve(answer.trim().toLowerCase());
285
+ });
286
+ });
287
+ }
288
+ async function syncWithGuard(client, url, payload, json, confirmUnlink) {
289
+ try {
290
+ return await client.post(url, payload);
291
+ } catch (err) {
292
+ if (!(err instanceof ApiError) || err.status !== 409 || err.code !== "SYNC_UNLINK_GUARD") throw err;
293
+ const preview = err.data?.["unlink_preview"] ?? [];
294
+ const msg = err.message;
295
+ console.error(`\n⚠ ${msg}`);
296
+ console.error("将被移除的用例:");
297
+ for (const cid of preview) console.error(` - ${cid}`);
298
+ if (!confirmUnlink) {
299
+ console.error("\n如确认移除,请加 --confirm-unlink 重试。");
300
+ process.exitCode = 1;
301
+ return null;
302
+ }
303
+ if (json || !process.stdin.isTTY) {
304
+ console.error("\n非交互模式,不自动重发。请在交互终端使用 --confirm-unlink。");
305
+ process.exitCode = 1;
306
+ return null;
307
+ }
308
+ if (await askConfirm(`确认移除 ${preview.length} 条用例?(y/N) `) !== "y") {
309
+ console.error("已取消。");
310
+ process.exitCode = 1;
311
+ return null;
312
+ }
313
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
314
+ printError("Sync payload must be a JSON object (not array or primitive)");
315
+ process.exitCode = 1;
316
+ return null;
317
+ }
318
+ const body = {
319
+ ...payload,
320
+ force_unlink: true
321
+ };
322
+ return await client.post(url, body);
323
+ }
324
+ }
275
325
  async function create$4(client, args, json) {
276
326
  const { named } = parseNamedArgs(args);
277
327
  const reqId = requireArg(named, "req-id", "req_id");
278
328
  const title = requireArg(named, "title", "title");
279
- const bl = typeof named["bl"] === "string" ? named["bl"] : void 0;
329
+ const bl = requireArg(named, "bl", "business_line");
280
330
  const modulePaths = asArray(named["module-paths"]);
331
+ if (modulePaths.length === 0) {
332
+ printError("Missing required flag: --module-paths <path1,path2,...>");
333
+ process.exitCode = 2;
334
+ return;
335
+ }
281
336
  const feishuUrl = typeof named["feishu-url"] === "string" ? named["feishu-url"] : void 0;
282
337
  const body = {
283
338
  req_id: reqId,
284
- title
339
+ title,
340
+ business_line: bl,
341
+ module_paths: modulePaths
285
342
  };
286
- if (bl) body["business_line"] = bl;
287
- if (modulePaths.length) body["module_paths"] = modulePaths;
288
343
  if (feishuUrl) body["feishu_ticket_url"] = feishuUrl;
289
344
  const data = await client.post("/api/test/requirements", body);
290
345
  if (json) {
@@ -306,22 +361,75 @@ async function sync$1(client, args, json) {
306
361
  return;
307
362
  }
308
363
  const payload = readFileInput(requireArg(named, "file", "path"));
309
- const data = await client.post(`/api/test/requirements/${encodeURIComponent(reqId)}/cases:sync`, payload);
364
+ const confirmUnlink = named["confirm-unlink"] !== void 0;
365
+ const data = await syncWithGuard(client, `/api/test/requirements/${encodeURIComponent(reqId)}/cases:sync`, payload, json, confirmUnlink);
366
+ if (!data) return;
310
367
  if (json) {
311
368
  printJson(data);
312
369
  return;
313
370
  }
314
- const s = data.summary;
371
+ const s = data["summary"];
372
+ const results = data["results"];
315
373
  printSuccess(`Synced ${(s["created"] ?? 0) + (s["referenced"] ?? 0) + (s["updated"] ?? 0) + (s["skipped"] ?? 0)} cases to ${reqId}`);
316
374
  printKV([
317
- ["Created", `${s["created"] ?? 0}${data.results.filter((r) => r.action === "created").map((r) => ` (${r.case_id})`).join("")}`],
375
+ ["Created", `${s["created"] ?? 0}${results.filter((r) => r.action === "created").map((r) => ` (${r.case_id})`).join("")}`],
318
376
  ["Referenced", s["referenced"] ?? 0],
319
377
  ["Updated", s["updated"] ?? 0],
320
378
  ["Existing (linked)", s["skipped"] ?? 0],
321
379
  ["Unlinked", s["unlinked"] ?? 0],
322
380
  ["Failed", s["failed"] ?? 0]
323
381
  ]);
324
- for (const r of data.results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
382
+ for (const r of results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
383
+ }
384
+ async function get$2(client, args, json) {
385
+ const { positional } = parseNamedArgs(args);
386
+ const reqId = positional[0];
387
+ if (!reqId) {
388
+ printError("Usage: test requirements get <req_id>");
389
+ process.exitCode = 2;
390
+ return;
391
+ }
392
+ const [detail, casesData] = await Promise.all([client.get(`/api/test/requirements/${encodeURIComponent(reqId)}`), client.get(`/api/test/requirements/${encodeURIComponent(reqId)}/cases`)]);
393
+ if (json) {
394
+ printJson({
395
+ ...detail,
396
+ cases: casesData.items
397
+ });
398
+ return;
399
+ }
400
+ printKV([
401
+ ["Req ID", detail["req_id"]],
402
+ ["Title", detail["title"]],
403
+ ["Status", detail["status"]],
404
+ ["Case Set ID", detail["case_set_id"] ?? "—"],
405
+ ["Created By", detail["created_by_name"] || "—"],
406
+ ["Created At", detail["created_at"]]
407
+ ]);
408
+ const cases = casesData.items;
409
+ if (cases.length) {
410
+ console.log(`\n Cases (${cases.length}):`);
411
+ printTable(cases, [
412
+ {
413
+ key: "case_id",
414
+ label: "Case ID",
415
+ width: 12
416
+ },
417
+ {
418
+ key: "title",
419
+ label: "Title"
420
+ },
421
+ {
422
+ key: "case_type",
423
+ label: "Type",
424
+ width: 5
425
+ },
426
+ {
427
+ key: "priority",
428
+ label: "Pri",
429
+ width: 4
430
+ }
431
+ ]);
432
+ } else console.log("\n No cases linked.");
325
433
  }
326
434
  async function list$2(client, args, json) {
327
435
  const { named } = parseNamedArgs(args);
@@ -363,18 +471,50 @@ async function runRequirements(client, args, json) {
363
471
  const subArgs = args.slice(1);
364
472
  switch (action) {
365
473
  case "create": return create$4(client, subArgs, json);
474
+ case "get": return get$2(client, subArgs, json);
366
475
  case "sync": return sync$1(client, subArgs, json);
367
476
  case "list": return list$2(client, subArgs, json);
368
477
  case "--help":
369
478
  case "-h":
370
479
  case void 0:
371
- console.log(`requirements commands:\n create Create a requirement\n sync Sync cases to requirement (channel 1)\n list List requirements`);
480
+ console.log(`requirements commands:\n create Create a requirement\n get Get requirement detail with cases\n sync Sync cases to requirement (channel 1)\n list List requirements`);
372
481
  return;
373
482
  default:
374
483
  printError(`Unknown requirements action: ${action}`);
375
484
  process.exitCode = 2;
376
485
  }
377
486
  }
487
+ const VALID_CASE_TYPES = ["api", "e2e"];
488
+ const VALID_PRIORITIES = [
489
+ "P0",
490
+ "P1",
491
+ "P2",
492
+ "P3"
493
+ ];
494
+ const VALID_PLAN_TYPES = [
495
+ "requirement",
496
+ "regression",
497
+ "smoke"
498
+ ];
499
+ const VALID_ENVS = [
500
+ "local",
501
+ "dev",
502
+ "stg",
503
+ "prod",
504
+ "auto"
505
+ ];
506
+ const VALID_MARK_STATUSES = [
507
+ "passed",
508
+ "failed",
509
+ "skipped",
510
+ "blocked"
511
+ ];
512
+ const VALID_USER_KINDS = [
513
+ "regression",
514
+ "flow",
515
+ "baseline",
516
+ "custom"
517
+ ];
378
518
  async function create$3(client, args, json) {
379
519
  const { named } = parseNamedArgs(args);
380
520
  const body = {
@@ -382,19 +522,43 @@ async function create$3(client, args, json) {
382
522
  business_line: requireArg(named, "bl", "business_line"),
383
523
  module_path: requireArg(named, "module-path", "module_path"),
384
524
  case_type: requireArg(named, "type", "case_type"),
385
- expected: requireArg(named, "expected", "expected"),
386
- steps: Array.isArray(named["steps"]) ? named["steps"] : named["steps"] ? [named["steps"]] : []
525
+ steps: (() => {
526
+ const raw = requireArg(named, "steps", "steps");
527
+ try {
528
+ const parsed = JSON.parse(raw);
529
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("steps must be a non-empty JSON array");
530
+ for (let i = 0; i < parsed.length; i++) {
531
+ const s = parsed[i];
532
+ if (!s.step?.trim()) throw new Error(`steps[${i}].step is empty`);
533
+ if (!s.expected?.trim()) throw new Error(`steps[${i}].expected is empty`);
534
+ }
535
+ return parsed;
536
+ } catch (e) {
537
+ printError(`Invalid --steps: ${e.message}`);
538
+ process.exitCode = 2;
539
+ return null;
540
+ }
541
+ })()
387
542
  };
388
- if (typeof named["priority"] === "string") body["priority"] = named["priority"];
389
- if (typeof named["precondition"] === "string") body["precondition"] = named["precondition"];
390
- if (typeof named["source"] === "string") body["source"] = named["source"];
391
- const tags = asArray(named["tags"]);
392
- if (tags.length) body["tags"] = tags;
393
- if (!body["steps"] || body["steps"].length === 0) {
394
- printError("At least one --steps required");
543
+ if (body["steps"] === null) return;
544
+ const caseType = body["case_type"];
545
+ if (!VALID_CASE_TYPES.includes(caseType)) {
546
+ printError(`Invalid --type "${caseType}": must be ${VALID_CASE_TYPES.join("|")}`);
395
547
  process.exitCode = 2;
396
548
  return;
397
549
  }
550
+ if (typeof named["priority"] === "string") {
551
+ if (!VALID_PRIORITIES.includes(named["priority"])) {
552
+ printError(`Invalid --priority "${named["priority"]}": must be ${VALID_PRIORITIES.join("|")}`);
553
+ process.exitCode = 2;
554
+ return;
555
+ }
556
+ body["priority"] = named["priority"];
557
+ }
558
+ body["precondition"] = requireArg(named, "precondition", "precondition");
559
+ if (typeof named["source"] === "string") body["source"] = named["source"];
560
+ const tags = asArray(named["tags"]);
561
+ if (tags.length) body["tags"] = tags;
398
562
  const data = await client.post("/api/test/cases", body);
399
563
  if (json) {
400
564
  printJson(data);
@@ -493,10 +657,19 @@ async function runCases(client, args, json) {
493
657
  }
494
658
  async function create$2(client, args, json) {
495
659
  const { named } = parseNamedArgs(args);
660
+ const name = requireArg(named, "name", "name");
661
+ const kind = requireArg(named, "kind", "regression|flow|baseline|custom");
662
+ if (!VALID_USER_KINDS.includes(kind)) {
663
+ printError(`Invalid --kind "${kind}": must be ${VALID_USER_KINDS.join("|")} (requirement and smoke are system-managed)`);
664
+ process.exitCode = 2;
665
+ return;
666
+ }
667
+ const moduleId = requireArg(named, "module", "module_id (integer)");
496
668
  const body = {
497
- name: requireArg(named, "name", "name"),
498
- kind: requireArg(named, "kind", "regression|flow|baseline|custom"),
499
- selection_mode: "manual"
669
+ name,
670
+ kind,
671
+ selection_mode: "manual",
672
+ primary_module_id: parseInt(moduleId, 10)
500
673
  };
501
674
  const data = await client.post("/api/test/case-sets", body);
502
675
  if (json) {
@@ -584,22 +757,25 @@ async function sync(client, args, json) {
584
757
  return;
585
758
  }
586
759
  const payload = readFileInput(requireArg(named, "file", "path"));
587
- const data = await client.post(`/api/test/case-sets/${setId}/cases:sync`, payload);
760
+ const confirmUnlink = named["confirm-unlink"] !== void 0;
761
+ const data = await syncWithGuard(client, `/api/test/case-sets/${setId}/cases:sync`, payload, json, confirmUnlink);
762
+ if (!data) return;
588
763
  if (json) {
589
764
  printJson(data);
590
765
  return;
591
766
  }
592
- const s = data.summary;
767
+ const s = data["summary"];
768
+ const results = data["results"];
593
769
  printSuccess(`Synced ${(s["created"] ?? 0) + (s["referenced"] ?? 0) + (s["updated"] ?? 0) + (s["skipped"] ?? 0)} cases to set ${setId}`);
594
770
  printKV([
595
- ["Created", `${s["created"] ?? 0}${data.results.filter((r) => r.action === "created").map((r) => ` (${r.case_id})`).join("")}`],
771
+ ["Created", `${s["created"] ?? 0}${results.filter((r) => r.action === "created").map((r) => ` (${r.case_id})`).join("")}`],
596
772
  ["Referenced", s["referenced"] ?? 0],
597
773
  ["Updated", s["updated"] ?? 0],
598
774
  ["Existing (linked)", s["skipped"] ?? 0],
599
775
  ["Unlinked", s["unlinked"] ?? 0],
600
776
  ["Failed", s["failed"] ?? 0]
601
777
  ]);
602
- for (const r of data.results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
778
+ for (const r of results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
603
779
  }
604
780
  async function runCaseSets(client, args, json) {
605
781
  const action = args[0];
@@ -612,7 +788,7 @@ async function runCaseSets(client, args, json) {
612
788
  case "--help":
613
789
  case "-h":
614
790
  case void 0:
615
- console.log(`case-sets commands:\n create Create a case set (--name, --kind)\n get Get case set detail with members\n members Batch add/remove members (--add/--remove)\n sync Sync cases to a set (--file <path>)`);
791
+ console.log(`case-sets commands:\n create Create a case set (--name, --kind [--module <id>])\n get Get case set detail with members\n members Batch add/remove members (--add/--remove)\n sync Sync cases to a set (--file <path>)`);
616
792
  return;
617
793
  default:
618
794
  printError(`Unknown case-sets action: ${action}`);
@@ -621,19 +797,43 @@ async function runCaseSets(client, args, json) {
621
797
  }
622
798
  async function create$1(client, args, json) {
623
799
  const { named } = parseNamedArgs(args);
624
- const body = { type: requireArg(named, "type", "requirement|regression|smoke") };
800
+ const planType = requireArg(named, "type", "requirement|regression|smoke");
801
+ if (!VALID_PLAN_TYPES.includes(planType)) {
802
+ printError(`Invalid --type "${planType}": must be ${VALID_PLAN_TYPES.join("|")}`);
803
+ process.exitCode = 2;
804
+ return;
805
+ }
806
+ const body = { type: planType };
625
807
  if (typeof named["title"] === "string") body["title"] = named["title"];
626
808
  if (typeof named["from-set"] === "string") body["from_case_set"] = Number(named["from-set"]);
627
809
  if (typeof named["case-ids"] === "string") body["case_ids"] = named["case-ids"].split(",").map((s) => s.trim());
628
810
  if (typeof named["req-id"] === "string") body["req_id"] = named["req-id"];
629
- if (typeof named["env"] === "string") body["env"] = named["env"];
811
+ if (typeof named["env"] === "string") {
812
+ if (!VALID_ENVS.includes(named["env"])) {
813
+ printError(`Invalid --env "${named["env"]}": must be ${VALID_ENVS.join("|")}`);
814
+ process.exitCode = 2;
815
+ return;
816
+ }
817
+ body["env"] = named["env"];
818
+ }
630
819
  const tags = asArray(named["tags"]);
631
820
  if (tags.length) body["tags"] = tags;
632
- if (body["from_case_set"] !== void 0 && body["case_ids"]) {
633
- printError("--from-set and --case-ids are mutually exclusive");
821
+ const sources = [
822
+ body["case_ids"] ? "case-ids" : null,
823
+ body["from_case_set"] !== void 0 ? "from-set" : null,
824
+ body["req_id"] ? "req-id" : null
825
+ ].filter(Boolean);
826
+ if (sources.length === 0) {
827
+ printError("Must specify one of --case-ids, --from-set, or --req-id");
634
828
  process.exitCode = 2;
635
829
  return;
636
830
  }
831
+ if (sources.length > 1) {
832
+ printError(`--${sources.join(", --")} are mutually exclusive`);
833
+ process.exitCode = 2;
834
+ return;
835
+ }
836
+ if (body["case_ids"]) console.error("⚠ 建议使用 --req-id 或 --from-set 从用例集拉取,避免手工枚举遗漏");
637
837
  const data = await client.post("/api/test/test-plans", body);
638
838
  if (json) {
639
839
  printJson(data);
@@ -751,17 +951,23 @@ async function mark(client, args, json) {
751
951
  process.exitCode = 2;
752
952
  return;
753
953
  }
954
+ const status = requireArg(named, "status", "passed|failed|skipped|blocked");
955
+ if (!VALID_MARK_STATUSES.includes(status)) {
956
+ printError(`Invalid --status "${status}": must be ${VALID_MARK_STATUSES.join("|")}`);
957
+ process.exitCode = 2;
958
+ return;
959
+ }
754
960
  const body = {
755
961
  plan_id: planId,
756
962
  case_id: caseId,
757
- status: requireArg(named, "status", "passed|failed|skipped|blocked")
963
+ status
758
964
  };
759
965
  if (typeof named["remark"] === "string") body["remark"] = named["remark"];
760
966
  if (typeof named["evidence-url"] === "string") body["evidence_url"] = named["evidence-url"];
761
967
  if (typeof named["duration-ms"] === "string") {
762
968
  const n = Number(named["duration-ms"]);
763
- if (Number.isNaN(n)) {
764
- printError("--duration-ms must be a number");
969
+ if (Number.isNaN(n) || n < 0 || n > 36e5) {
970
+ printError("--duration-ms must be a number in range 0~3600000");
765
971
  process.exitCode = 2;
766
972
  return;
767
973
  }
@@ -823,7 +1029,14 @@ async function create(client, args, json) {
823
1029
  return;
824
1030
  }
825
1031
  const body = { plan_id: planId };
826
- if (typeof named["type"] === "string") body["type"] = named["type"];
1032
+ if (typeof named["type"] === "string") {
1033
+ if (!VALID_PLAN_TYPES.includes(named["type"])) {
1034
+ printError(`Invalid --type "${named["type"]}": must be ${VALID_PLAN_TYPES.join("|")}`);
1035
+ process.exitCode = 2;
1036
+ return;
1037
+ }
1038
+ body["type"] = named["type"];
1039
+ }
827
1040
  if (typeof named["conclusion"] === "string") body["conclusion"] = named["conclusion"];
828
1041
  if (typeof named["risk-notes"] === "string") body["risk_notes"] = named["risk-notes"];
829
1042
  const data = await client.post("/api/test/reports", body);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shoplazza-ai-dev-cli",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Shoplazza AI Dev CLI: install, publish and manage AI agent skills/rules",
5
5
  "type": "module",
6
6
  "bin": {