bpmax-cli 0.2.1-beta.92 → 0.2.1-beta.93

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.
package/dist/bin.js CHANGED
@@ -540,7 +540,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
540
540
  // package.json
541
541
  var package_default = {
542
542
  name: "bpmax-cli",
543
- version: "0.2.1-beta.92",
543
+ version: "0.2.1-beta.93",
544
544
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
545
545
  type: "module",
546
546
  bin: {
@@ -44124,6 +44124,7 @@ import { readdir as readdir8, readFile as readFile25, stat as stat16 } from "fs/
44124
44124
  import { join as join2 } from "path";
44125
44125
 
44126
44126
  // src/core/plugin-spec.ts
44127
+ var EN_NAME_PREFIX = "plugin_";
44127
44128
  var EN_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;
44128
44129
  var SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
44129
44130
  var SAFE_PLUGIN_SKILL_NAME = /^bpmax-[A-Za-z0-9][A-Za-z0-9_-]*$/;
@@ -44131,7 +44132,8 @@ var REQUIRED_CONFIG_FIELDS = ["name", "en_name", "description", "version"];
44131
44132
  function isRecord22(value) {
44132
44133
  return typeof value === "object" && value !== null && !Array.isArray(value);
44133
44134
  }
44134
- function validateConfigShape(raw) {
44135
+ function validateConfigShape(raw, options = {}) {
44136
+ const requirePluginPrefix = options.requirePluginPrefix ?? true;
44135
44137
  if (!isRecord22(raw)) {
44136
44138
  return {
44137
44139
  config: {},
@@ -44157,6 +44159,13 @@ function validateConfigShape(raw) {
44157
44159
  message: `en_name \u5FC5\u987B\u5339\u914D /^[A-Za-z][A-Za-z0-9_]*$/\uFF0C\u5F53\u524D\u4E3A\uFF1A${raw.en_name}`,
44158
44160
  path: "config.json"
44159
44161
  });
44162
+ } else if (requirePluginPrefix && typeof raw.en_name === "string" && !raw.en_name.startsWith(EN_NAME_PREFIX)) {
44163
+ issues.push({
44164
+ rule: "L2",
44165
+ level: "error",
44166
+ message: `en_name \u5FC5\u987B\u4EE5 plugin_ \u5F00\u5934\uFF0C\u5F53\u524D\u4E3A\uFF1A${raw.en_name}`,
44167
+ path: "config.json"
44168
+ });
44160
44169
  }
44161
44170
  return { config: raw, issues };
44162
44171
  }
@@ -44586,6 +44595,18 @@ async function checkMigrationPairs(pluginDir, issues) {
44586
44595
  path: missingDir
44587
44596
  });
44588
44597
  }
44598
+ async function checkRequiredMigration(pluginDir, issues) {
44599
+ const migrationFiles = (await listFilesIfDirectory(pluginDir, "server/migrations")).filter(
44600
+ (file) => /\.(js|cjs|mjs)$/i.test(file)
44601
+ );
44602
+ if (migrationFiles.length > 0) return;
44603
+ issues.push({
44604
+ rule: "L16",
44605
+ level: "error",
44606
+ message: "\u7F3A\u5C11\u53EF\u6267\u884C\u8FC1\u79FB\uFF1Aserver/migrations/ \u4E0B\u81F3\u5C11\u9700\u8981\u4E00\u4E2A .js \u8FC1\u79FB\u3002\u5E73\u53F0\u5B89\u88C5\u4E00\u5B9A\u4F1A\u6267\u884C migrate_prod up:<en_name>\uFF0C\u6CA1\u6709\u8FC1\u79FB\u4F1A\u5BFC\u81F4\u5B89\u88C5\u5931\u8D25\u4E14\u63A5\u53E3\u4E0D\u56DE\u9519\u3002\u8BF7\u751F\u6210 server/migrations/<\u65F6\u95F4\u6233>-init.js \u4E0E\u914D\u5957 sqls/<\u65F6\u95F4\u6233>-init-{up,down}.sql\uFF08\u65E0\u4E1A\u52A1\u8868\u65F6\u7528 SELECT 1 \u7684 no-op\uFF09\u3002",
44607
+ path: "server/migrations"
44608
+ });
44609
+ }
44589
44610
  async function checkFrontendLanguages(pluginDir, issues) {
44590
44611
  let root;
44591
44612
  for (const candidate of LANGUAGE_ROOTS) {
@@ -44635,6 +44656,78 @@ function checkMenuPermissions(config, issues) {
44635
44656
  path: "config.json"
44636
44657
  });
44637
44658
  }
44659
+ var CONTROLLER_ROOT = "server/src/controller";
44660
+ var AUTH_TOKENS = ["AuthLogin", "checkPermission", "assertPermission"];
44661
+ var REST_BASE_FILE = /(^|[._-])rest(\.[cm]?[jt]sx?)?$/i;
44662
+ var PLATFORM_PERMISSION_PREFIXES = [
44663
+ "organization",
44664
+ "user",
44665
+ "scheduled_task",
44666
+ "finance",
44667
+ "admin",
44668
+ "project",
44669
+ "step",
44670
+ "config",
44671
+ "cli",
44672
+ "bbs",
44673
+ "api"
44674
+ ];
44675
+ function isPlatformPermission(permission) {
44676
+ const top = permission.split(".")[0];
44677
+ return PLATFORM_PERMISSION_PREFIXES.includes(top);
44678
+ }
44679
+ async function checkControllerAuth(pluginDir, config, issues) {
44680
+ if (!await isDirectory(join2(pluginDir, CONTROLLER_ROOT))) return;
44681
+ const controllerFiles = (await walkFiles(pluginDir, CONTROLLER_ROOT)).filter((file) => {
44682
+ if (!hasSourceExtension(file)) return false;
44683
+ const base = file.split("/").pop() || "";
44684
+ return !REST_BASE_FILE.test(base.replace(/\.(ts|js)$/, ""));
44685
+ });
44686
+ if (controllerFiles.length === 0) return;
44687
+ const unauthenticated = [];
44688
+ for (const file of controllerFiles) {
44689
+ let content;
44690
+ try {
44691
+ content = await readFile25(join2(pluginDir, file), "utf8");
44692
+ } catch {
44693
+ continue;
44694
+ }
44695
+ if (!AUTH_TOKENS.some((token) => content.includes(token))) {
44696
+ unauthenticated.push(file);
44697
+ }
44698
+ }
44699
+ if (unauthenticated.length === 0) return;
44700
+ const enName = typeof config.en_name === "string" ? config.en_name.trim() : "<en_name>";
44701
+ issues.push({
44702
+ rule: "L14",
44703
+ level: "error",
44704
+ message: `\u63A7\u5236\u5668\u6587\u4EF6\u7F3A\u5C11\u9274\u6743\uFF1A${formatMissing(unauthenticated, " ")} \u672A\u51FA\u73B0 AuthLogin / checkPermission / assertPermission\u3002\u8BF7\u7ED9\u63A7\u5236\u5668\u65B9\u6CD5\u52A0 @think.AuthLogin()\uFF0C\u5E76\u5728\u9700\u8981\u6743\u9650\u70B9\u7684\u65B9\u6CD5\u91CC\u8C03\u7528 assertPermission(this.ctx, '${enName}.view')\u3002`,
44705
+ path: CONTROLLER_ROOT
44706
+ });
44707
+ }
44708
+ function checkMenuPermissionPrefix(config, issues) {
44709
+ const entries = config.guide_menu_entries;
44710
+ if (!Array.isArray(entries)) return;
44711
+ const enName = typeof config.en_name === "string" ? config.en_name.trim() : "";
44712
+ const expectedPrefix = enName ? `${enName}.` : "";
44713
+ const invalid = [];
44714
+ entries.forEach((entry, index) => {
44715
+ if (!isRecord22(entry)) return;
44716
+ const permission = entry.permission;
44717
+ if (typeof permission !== "string" || permission.trim() === "") return;
44718
+ const point = permission.trim();
44719
+ if (isPlatformPermission(point)) return;
44720
+ if (expectedPrefix && point.startsWith(expectedPrefix)) return;
44721
+ invalid.push(`${index}\uFF08${point}\uFF09`);
44722
+ });
44723
+ if (invalid.length === 0) return;
44724
+ issues.push({
44725
+ rule: "L14",
44726
+ level: "error",
44727
+ message: `guide_menu_entries \u7684 permission \u5F15\u7528\u4E86\u975E\u672C\u63D2\u4EF6\u6743\u9650\u70B9\uFF1A${formatMissing(invalid, " ")}\u3002\u81EA\u5B9A\u4E49\u6743\u9650\u70B9\u5FC5\u987B\u4EE5 ${expectedPrefix || "<en_name>."} \u5F00\u5934\uFF1B\u5E73\u53F0\u5185\u7F6E\u6743\u9650\u70B9\u4F7F\u7528 ${PLATFORM_PERMISSION_PREFIXES.map((prefix) => `${prefix}.*`).join("\u3001")}\u3002`,
44728
+ path: "config.json"
44729
+ });
44730
+ }
44638
44731
  function hasDimensionConclusion(content, dimension) {
44639
44732
  return content.split(/\r?\n/).some((line) => {
44640
44733
  if (!line.includes(dimension)) return false;
@@ -44727,6 +44820,92 @@ async function checkPlatformCollision(pluginDir, platformSrc, issues, notices) {
44727
44820
  }
44728
44821
  }
44729
44822
  }
44823
+ var PLACEHOLDER_ASSERTIONS = [
44824
+ /expect\s*\(\s*1\s*\+\s*1\s*\)/,
44825
+ /expect\s*\(\s*1\s*\)\s*\.toBe\s*\(\s*1\s*\)/,
44826
+ /expect\s*\(\s*true\s*\)\s*\.toBe\s*\(\s*true\s*\)/,
44827
+ /expect\s*\(\s*['"]['"]\s*\)\s*\.toBe\s*\(\s*['"]['"]\s*\)/
44828
+ ];
44829
+ var ASSERTION_CALL = /expect\s*\(|assert\s*[.(]|\.should\s*[.(]/;
44830
+ var NAKED_THROW_GLOBAL = /throw\s+(new\s+)?Error\s*\(/g;
44831
+ var ERROR_CODE_MARKERS = /\.code\b|\bcode\s*:|\.status\b|\bstatus\s*:|pluginError|HttpException/;
44832
+ function findNakedThrows(content) {
44833
+ const lines = [];
44834
+ const source = content;
44835
+ NAKED_THROW_GLOBAL.lastIndex = 0;
44836
+ let match;
44837
+ while ((match = NAKED_THROW_GLOBAL.exec(source)) !== null) {
44838
+ const start = match.index;
44839
+ const close = source.indexOf(");", start);
44840
+ const statement = source.slice(start, close === -1 ? Math.min(source.length, start + 400) : close + 2);
44841
+ if (!ERROR_CODE_MARKERS.test(statement)) {
44842
+ lines.push(source.slice(0, start).split(/\r?\n/).length);
44843
+ }
44844
+ }
44845
+ return lines;
44846
+ }
44847
+ function stripPlaceholderAssertions(content) {
44848
+ let stripped = content;
44849
+ for (const pattern of PLACEHOLDER_ASSERTIONS) {
44850
+ stripped = stripped.replace(new RegExp(pattern.source, "g"), "");
44851
+ }
44852
+ return { stripped, removed: stripped !== content };
44853
+ }
44854
+ async function listFilesIfDirectory(pluginDir, relative3) {
44855
+ try {
44856
+ return await walkFiles(pluginDir, relative3);
44857
+ } catch (error) {
44858
+ if (isEnoent(error) || isNotDirectory(error)) return [];
44859
+ throw error;
44860
+ }
44861
+ }
44862
+ async function hasBackendApi(pluginDir) {
44863
+ return (await listFilesIfDirectory(pluginDir, "server/src/controller/api")).length > 0;
44864
+ }
44865
+ async function checkBackendApiQuality(pluginDir, issues) {
44866
+ if (!await hasBackendApi(pluginDir)) return;
44867
+ const testFiles = (await listFilesIfDirectory(pluginDir, "server/test")).filter(
44868
+ (file) => hasSourceExtension(file)
44869
+ );
44870
+ for (const file of testFiles) {
44871
+ let content;
44872
+ try {
44873
+ content = await readFile25(join2(pluginDir, file), "utf8");
44874
+ } catch {
44875
+ continue;
44876
+ }
44877
+ const { stripped, removed } = stripPlaceholderAssertions(content);
44878
+ const hasRealAssertion = ASSERTION_CALL.test(stripped);
44879
+ if (removed && !hasRealAssertion) {
44880
+ issues.push({
44881
+ rule: "L15",
44882
+ level: "error",
44883
+ message: "server/test \u4E0B\u53EA\u6709 expect(1 + 1) \u4E4B\u7C7B\u7684\u5360\u4F4D\u65AD\u8A00\uFF1B\u8BF7\u6539\u4E3A\u5BF9 service/controller \u771F\u5B9E\u884C\u4E3A\u7684\u65AD\u8A00\uFF08\u6B63\u5E38\u8F93\u5165\u3001\u975E\u6CD5\u8F93\u5165\u3001\u5206\u9875\u4E0A\u9650\u3001\u9519\u8BEF\u7801\uFF09",
44884
+ path: file
44885
+ });
44886
+ }
44887
+ }
44888
+ const controllerDirs = ["server/src/controller"];
44889
+ for (const dir of controllerDirs) {
44890
+ for (const file of await listFilesIfDirectory(pluginDir, dir)) {
44891
+ if (!hasSourceExtension(file)) continue;
44892
+ let content;
44893
+ try {
44894
+ content = await readFile25(join2(pluginDir, file), "utf8");
44895
+ } catch {
44896
+ continue;
44897
+ }
44898
+ for (const line of findNakedThrows(content)) {
44899
+ issues.push({
44900
+ rule: "L15",
44901
+ level: "warn",
44902
+ message: `controller \u7B2C ${line} \u884C\u51FA\u73B0\u88F8 throw new Error \u4E14\u6CA1\u6709\u9519\u8BEF\u7801\uFF1B\u8BF7\u6539\u7528 pluginError/asserts \u6216\u5E26 code \u7684\u7ED3\u6784\u5316\u9519\u8BEF`,
44903
+ path: file
44904
+ });
44905
+ }
44906
+ }
44907
+ }
44908
+ }
44730
44909
  async function lintPlugin(pluginDir, options = {}) {
44731
44910
  const issues = [];
44732
44911
  const notices = [];
@@ -44754,9 +44933,13 @@ async function lintPlugin(pluginDir, options = {}) {
44754
44933
  await checkSkillDeclarations(pluginDir, config, issues);
44755
44934
  checkGuideMenu(config, issues);
44756
44935
  await checkMigrationPairs(pluginDir, issues);
44936
+ await checkRequiredMigration(pluginDir, issues);
44757
44937
  await checkFrontendLanguages(pluginDir, issues);
44758
44938
  checkMenuPermissions(config, issues);
44939
+ checkMenuPermissionPrefix(config, issues);
44940
+ await checkControllerAuth(pluginDir, config, issues);
44759
44941
  await checkEnterpriseReadiness(pluginDir, issues);
44942
+ await checkBackendApiQuality(pluginDir, issues);
44760
44943
  await checkPlatformCollision(pluginDir, options.platformSrc, issues, notices);
44761
44944
  return buildReport(pluginDir, issues, notices);
44762
44945
  }
@@ -44849,6 +45032,9 @@ function pluginArtifactName(identity) {
44849
45032
  }
44850
45033
  return `${identity.en_name}-${identity.version}.zip`;
44851
45034
  }
45035
+ function pluginMigrationEntries(files) {
45036
+ return files.filter((relative3) => relative3.startsWith("migrations/") && !relative3.endsWith("/"));
45037
+ }
44852
45038
  async function createPluginZip(distDir) {
44853
45039
  const all = await listFilesRecursive(distDir);
44854
45040
  const files = all.filter((relative3) => {
@@ -44860,6 +45046,13 @@ async function createPluginZip(distDir) {
44860
45046
  if (!files.includes("config.json")) {
44861
45047
  throw new Error("Plugin dist must contain config.json at its root; the zip top level must be config.json.");
44862
45048
  }
45049
+ const migrations = pluginMigrationEntries(files);
45050
+ const migrationJs = migrations.filter((relative3) => /\.(js|cjs|mjs)$/i.test(relative3));
45051
+ if (migrationJs.length === 0) {
45052
+ throw new Error(
45053
+ "Plugin zip must contain at least one migrations/*.js at the zip root. The platform always runs migrate_prod up:<en_name>; without it installation fails server-side while the API reports no error and the CLI waits until timeout. Keep migrations under server/migrations/ so compile.sh lifts them to dist/migrations/."
45054
+ );
45055
+ }
44863
45056
  const zip = new JSZip4();
44864
45057
  for (const relative3 of files) {
44865
45058
  zip.file(relative3, await readFile26(path26.join(distDir, relative3)), { date: FIXED_ENTRY_DATE });
@@ -44951,7 +45144,12 @@ async function buildPlugin(options) {
44951
45144
  version: identity.version,
44952
45145
  lint,
44953
45146
  compile,
44954
- artifact: { path: artifactPath, size: info.size, files: zipped.files.length }
45147
+ artifact: {
45148
+ path: artifactPath,
45149
+ size: info.size,
45150
+ files: zipped.files.length,
45151
+ migrations: pluginMigrationEntries(zipped.files)
45152
+ }
44955
45153
  };
44956
45154
  }
44957
45155
 
@@ -45105,7 +45303,7 @@ async function readPluginManifestFromZip(buffer) {
45105
45303
  const message = error instanceof Error ? error.message : String(error);
45106
45304
  throw new Error(`Invalid plugin config.json in zip: ${message}`);
45107
45305
  }
45108
- const { config, issues } = validateConfigShape(raw);
45306
+ const { config, issues } = validateConfigShape(raw, { requirePluginPrefix: false });
45109
45307
  if (issues.length > 0) {
45110
45308
  throw new Error(`Invalid plugin config.json: ${issues.map((issue3) => issue3.message).join("; ")}`);
45111
45309
  }
@@ -45114,6 +45312,18 @@ async function readPluginManifestFromZip(buffer) {
45114
45312
  const name = typeof config.name === "string" && config.name.trim() ? config.name.trim() : void 0;
45115
45313
  return name ? { en_name: enName, version, name } : { en_name: enName, version };
45116
45314
  }
45315
+ async function inspectPluginZip(buffer) {
45316
+ const zip = await JSZip5.loadAsync(buffer);
45317
+ const files = Object.values(zip.files).filter((entry) => !entry.dir).map((entry) => entry.name.replace(/^\.?\//, ""));
45318
+ const migrations = files.filter((name) => name.startsWith("migrations/"));
45319
+ const migrationJs = migrations.filter((name) => /\.(js|cjs|mjs)$/i.test(name));
45320
+ if (migrationJs.length === 0) {
45321
+ throw new Error(
45322
+ "plugin.install.migrations_missing: zip \u6839\u76EE\u5F55\u6CA1\u6709 migrations/*.js\u3002\u5E73\u53F0\u5B89\u88C5\u4E00\u5B9A\u4F1A\u6267\u884C migrate_prod up:<en_name>\uFF0C\u7F3A\u8FC1\u79FB\u4F1A\u5BFC\u81F4\u540E\u7AEF\u5B89\u88C5\u5931\u8D25\u800C\u63A5\u53E3\u4E0D\u56DE\u9519\u3001CLI \u7B49\u5230\u8D85\u65F6\u3002\u6E90\u7801\u8FC1\u79FB\u5E94\u653E\u5728 server/migrations/\uFF0C\u7531 compile.sh \u7684 `cp -r server/migrations dist/` \u62AC\u5230 dist \u6839\u76EE\u5F55\uFF1B\u8BF7\u91CD\u65B0 `bpmax-cli plugin build` \u5E76\u786E\u8BA4 `unzip -l` \u91CC\u6709 migrations/<\u65F6\u95F4\u6233>-init.js\u3002"
45323
+ );
45324
+ }
45325
+ return { files, migrations };
45326
+ }
45117
45327
  function absoluteZipUrl(origin, relativePath) {
45118
45328
  const normalizedOrigin = origin.trim().replace(/\/+$/, "");
45119
45329
  const originUrl = new URL(normalizedOrigin);
@@ -45224,6 +45434,8 @@ function rollbackGuidance(enName) {
45224
45434
  return [
45225
45435
  "No automatic rollback is available. Uninstalling a plugin does not drop its tables or data.",
45226
45436
  "To return to the previous build, reinstall the previous zip manually.",
45437
+ // 平台 plugin_migrate 的 scope 是 `plugin_${pluginName}`,en_name 已带前缀,
45438
+ // 所以真实 scope 是 `plugin_plugin_x`,不能写成 `down:<en_name>`。
45227
45439
  `If the failed build shipped migrations, run "yarn migrate_prod down:plugin_${enName}" manually after reviewing the migration.`
45228
45440
  ].join(" ");
45229
45441
  }
@@ -45254,6 +45466,19 @@ async function executeInstall(input) {
45254
45466
  before_version: input.beforeVersion,
45255
45467
  rollback_guidance: rollbackGuidance(input.manifest.en_name)
45256
45468
  };
45469
+ const preflightStarted = Date.now();
45470
+ try {
45471
+ await inspectPluginZip(input.zipBuffer);
45472
+ steps.push({ step: "preflight", status: "ok", duration_ms: Date.now() - preflightStarted });
45473
+ } catch (error) {
45474
+ steps.push({
45475
+ step: "preflight",
45476
+ status: "failed",
45477
+ duration_ms: Date.now() - preflightStarted,
45478
+ error: errorMessage3(error)
45479
+ });
45480
+ return { ...base, ok: false, status: "failed", steps };
45481
+ }
45257
45482
  const upload = await runStep("upload", timeouts.uploadMs, () => input.transport.uploadZip(input.zipBuffer, `${input.manifest.en_name}-${input.manifest.version}.zip`));
45258
45483
  steps.push(upload.trace);
45259
45484
  if (!upload.ok) {
@@ -45516,6 +45741,11 @@ var DEFAULT_CAPABILITIES = {
45516
45741
  plugin_skill: true,
45517
45742
  cli_capability: true
45518
45743
  };
45744
+ function normalizePluginEnName(value) {
45745
+ const trimmed = value.trim();
45746
+ if (!trimmed) return "";
45747
+ return trimmed.startsWith(EN_NAME_PREFIX) ? trimmed : `${EN_NAME_PREFIX}${trimmed}`;
45748
+ }
45519
45749
  function deriveSkillName(enName) {
45520
45750
  return `bpmax-${enName.replace(/_/g, "-").toLowerCase()}`;
45521
45751
  }
@@ -45554,9 +45784,9 @@ function resolveCreateAnswers(sources) {
45554
45784
  `plugin.create.missing_answers: \u7F3A\u5C11\u5FC5\u7B54\u9879\uFF1A${missing.join("\u3001")}\u3002\u8BF7\u901A\u8FC7\u4EA4\u4E92\u56DE\u7B54\u6216 --from answers.json \u63D0\u4F9B\u3002`
45555
45785
  );
45556
45786
  }
45557
- const enName = sources.en_name.trim();
45558
- if (!EN_NAME_PATTERN.test(enName)) {
45559
- throw new Error(`plugin.create.invalid_en_name: en_name \u5FC5\u987B\u5339\u914D /^[A-Za-z][A-Za-z0-9_]*$/\uFF0C\u5F53\u524D\u4E3A\uFF1A${enName}`);
45787
+ const enName = normalizePluginEnName(sources.en_name);
45788
+ if (enName === EN_NAME_PREFIX || !EN_NAME_PATTERN.test(enName)) {
45789
+ throw new Error(`plugin.create.invalid_en_name: en_name \u5FC5\u987B\u5339\u914D /^[A-Za-z][A-Za-z0-9_]*$/\uFF08\u4F1A\u81EA\u52A8\u8865 plugin_ \u524D\u7F00\uFF09\uFF0C\u5F53\u524D\u4E3A\uFF1A${enName}`);
45560
45790
  }
45561
45791
  const version = (sources.version ?? "1.0.0").trim();
45562
45792
  if (!SEMVER_PATTERN.test(version)) {
@@ -46400,7 +46630,7 @@ function renderCompileScript(answers) {
46400
46630
  'ROOT=$(cd "$(dirname "$0")" && pwd)',
46401
46631
  'cd "$ROOT"',
46402
46632
  "",
46403
- `echo "[plugin_${answers.en_name}] clean"`,
46633
+ `echo "[${answers.en_name}] clean"`,
46404
46634
  "rm -rf dist frontend/dist server/dist",
46405
46635
  "",
46406
46636
  'echo "[1/4] build frontend"',
@@ -46532,10 +46762,521 @@ function renderPlanFiles(answers) {
46532
46762
  return [{ path: "docs/plugin-plan.md", content: renderPlanDoc(answers) }];
46533
46763
  }
46534
46764
 
46535
- // src/core/templates/plugin-server.ts
46765
+ // src/core/templates/plugin-server-permissions.ts
46536
46766
  function js2(value) {
46537
46767
  return JSON.stringify(value);
46538
46768
  }
46769
+ function permissionsEnabled(answers) {
46770
+ return Boolean(answers.capabilities.backend_api || answers.capabilities.menu_entry);
46771
+ }
46772
+ function permissionConfigPath(answers) {
46773
+ return `server/src/config/${answers.en_name}_permissions.ts`;
46774
+ }
46775
+ function permissionAccessPath(answers) {
46776
+ return `server/src/service/${answers.en_name}_access.ts`;
46777
+ }
46778
+ function renderPermissionConfig(answers) {
46779
+ const prefix = `${answers.en_name}.`;
46780
+ const owner = `${answers.en_name}`;
46781
+ const ownerMarker = `[owner=${owner}]`;
46782
+ const category = answers.name;
46783
+ const viewDescription = `\u67E5\u770B${answers.name}\u7684\u6570\u636E ${ownerMarker}`;
46784
+ const manageDescription = `\u7BA1\u7406${answers.name}\u7684\u914D\u7F6E\u4E0E\u6570\u636E ${ownerMarker}`;
46785
+ return `// \u672C\u63D2\u4EF6\u7684\u6743\u9650\u70B9\u5355\u4E00\u4E8B\u5B9E\u6E90\uFF1A\u5B89\u88C5\u3001\u63A7\u5236\u5668\u6821\u9A8C\u3001\u83DC\u5355\u914D\u7F6E\u90FD\u4ECE\u8FD9\u91CC\u53D6 key\u3002
46786
+ // \u4E0D\u8981\u5728\u5176\u4ED6\u6587\u4EF6\u91CC\u91CD\u590D\u5199\u6743\u9650\u70B9\u5B57\u7B26\u4E32\uFF0C\u907F\u514D\u6539\u540D\u540E\u6F0F\u6539\u3002
46787
+ export interface PermissionPointDefinition {
46788
+ key: string;
46789
+ name: string;
46790
+ category: string;
46791
+ description: string;
46792
+ }
46793
+
46794
+ export const PLUGIN_NAME = ${js2(owner)};
46795
+ export const OWNER_MARKER = ${js2(ownerMarker)};
46796
+ export const PERMISSION_PREFIX = ${js2(prefix)};
46797
+
46798
+ export const PERMISSION_POINTS: PermissionPointDefinition[] = [
46799
+ {
46800
+ key: ${js2(`${prefix}view`)},
46801
+ name: ${js2(`${answers.name}\u67E5\u770B`)},
46802
+ category: ${js2(category)},
46803
+ description: ${js2(viewDescription)},
46804
+ },
46805
+ {
46806
+ key: ${js2(`${prefix}manage`)},
46807
+ name: ${js2(`${answers.name}\u7BA1\u7406`)},
46808
+ category: ${js2(category)},
46809
+ description: ${js2(manageDescription)},
46810
+ },
46811
+ ];
46812
+
46813
+ export const PLUGIN_PERMISSION_KEYS: string[] = PERMISSION_POINTS.map((point) => point.key);
46814
+ `;
46815
+ }
46816
+ function renderAccessService(answers) {
46817
+ const owner = `${answers.en_name}`;
46818
+ const upper = answers.en_name.toUpperCase();
46819
+ const unauthenticatedCode = `${upper}_UNAUTHENTICATED`;
46820
+ const forbiddenCode = `${upper}_FORBIDDEN`;
46821
+ const permissionsConfig = `../config/${answers.en_name}_permissions`;
46822
+ return `import {
46823
+ OWNER_MARKER,
46824
+ PERMISSION_POINTS,
46825
+ PLUGIN_PERMISSION_KEYS,
46826
+ } from ${js2(permissionsConfig)};
46827
+
46828
+ declare const think: any;
46829
+
46830
+ export interface PermissionRegistrationOptions {
46831
+ organizationId: number | string;
46832
+ userId?: number | string;
46833
+ }
46834
+
46835
+ export interface PermissionRegistrationResult {
46836
+ organizationId: number;
46837
+ configurationUpdates: number;
46838
+ pointUpdates: number;
46839
+ }
46840
+
46841
+ /** \u7EDF\u4E00\u7684 403 \u8FD4\u56DE\u7ED3\u6784\uFF1B\u63A7\u5236\u5668\u62FF\u5230\u540E\u8BBE\u7F6E\u72B6\u6001\u7801\u5E76 fail\uFF0C\u4E0D\u8981\u629B\u88F8\u9519\u7ED9\u6846\u67B6\u3002 */
46842
+ export interface PermissionDenial {
46843
+ statusCode: 403;
46844
+ code: string;
46845
+ message: string;
46846
+ }
46847
+
46848
+ const UNAUTHENTICATED_CODE = ${js2(unauthenticatedCode)};
46849
+ const FORBIDDEN_CODE = ${js2(forbiddenCode)};
46850
+
46851
+ function denial(code: string, message: string): PermissionDenial {
46852
+ return { statusCode: 403, code, message };
46853
+ }
46854
+
46855
+ function readUser(ctx: any): any {
46856
+ if (!ctx) return {};
46857
+ return ctx.userInfo || (ctx.state && ctx.state.user) || ctx.user || {};
46858
+ }
46859
+
46860
+ function parsePermissionContent(value: unknown): Record<string, any> {
46861
+ if (value && typeof value === 'object') return value as Record<string, any>;
46862
+ if (typeof value === 'string' && value.trim()) {
46863
+ try {
46864
+ const parsed = JSON.parse(value);
46865
+ return parsed && typeof parsed === 'object' ? parsed : {};
46866
+ } catch (_) {
46867
+ return {};
46868
+ }
46869
+ }
46870
+ return {};
46871
+ }
46872
+
46873
+ function mergePermissionConfiguration(value: unknown): Record<string, any> {
46874
+ const current = parsePermissionContent(value);
46875
+ // \u5E73\u53F0 configuration(type='permissions').content \u7684\u5951\u7EA6\u662F
46876
+ // { permissions: [{ name, key, points }] }\uFF0Crole.permissions.custom \u5B58\u7684\u662F\u8FD9\u91CC\u7684 key
46877
+ // \uFF08\u6743\u9650\u7EC4 key\uFF09\uFF0C\u4E0D\u662F\u5177\u4F53\u6743\u9650\u70B9\u3002\u5199\u5165 custom \u4F1A\u8BA9\u89D2\u8272\u65E0\u6CD5\u89E3\u6790\u5230\u6743\u9650\u70B9\u3002
46878
+ const groups = Array.isArray(current.permissions)
46879
+ ? current.permissions.filter((item: any) => item && typeof item === 'object').map((item: any) => ({ ...item }))
46880
+ : [];
46881
+ const groupKey = ${js2(answers.en_name)};
46882
+ const nextGroup = {
46883
+ name: ${js2(`${answers.name}\u6743\u9650`)},
46884
+ key: groupKey,
46885
+ points: [...PLUGIN_PERMISSION_KEYS],
46886
+ };
46887
+ const existingIndex = groups.findIndex((item: any) => item.key === groupKey);
46888
+ if (existingIndex >= 0) {
46889
+ groups[existingIndex] = { ...groups[existingIndex], ...nextGroup };
46890
+ } else {
46891
+ groups.push(nextGroup);
46892
+ }
46893
+ // \u4FDD\u7559 content \u4E0A\u7684\u5176\u4ED6\u5B57\u6BB5\uFF08\u5E73\u53F0\u53EF\u80FD\u8FFD\u52A0\u81EA\u5B9A\u4E49\u914D\u7F6E\uFF09\uFF0C\u53EA\u589E\u91CF\u7EF4\u62A4 permissions\u3002
46894
+ return { ...current, permissions: groups };
46895
+ }
46896
+
46897
+ function positiveOrganizationId(value: unknown): number {
46898
+ const id = Number(value || 0);
46899
+ if (!Number.isSafeInteger(id) || id <= 0) {
46900
+ throw new Error(${js2(`${owner}: a positive BPMAX organization id is required`)});
46901
+ }
46902
+ return id;
46903
+ }
46904
+
46905
+ /**
46906
+ * \u628A\u672C\u63D2\u4EF6\u6743\u9650\u70B9\u5E42\u7B49\u6CE8\u518C\u5230\u6307\u5B9A\u7EC4\u7EC7\u3002
46907
+ *
46908
+ * - configuration(type='permissions') \u4E0D\u5B58\u5728\u65F6\u521B\u5EFA\uFF0C\u5B58\u5728\u65F6\u6309\u6743\u9650\u7EC4 key \u589E\u91CF\u8865\u9F50 points\uFF1B
46909
+ * - point \u8868\u6309 point key \u552F\u4E00\u5B9A\u4F4D\uFF1A\u672C\u63D2\u4EF6\u7684\u70B9\u66F4\u65B0\u4E3A\u6700\u65B0\u5B9A\u4E49\uFF0C\u5176\u4ED6\u63D2\u4EF6\u7684\u540C\u540D\u70B9\u76F4\u63A5\u629B\u9519\uFF0C
46910
+ * \u7EDD\u4E0D\u8986\u76D6\uFF1B
46911
+ * - \u91CD\u590D\u5B89\u88C5\u8FD4\u56DE\u7684 updates \u4E3A 0\u3002
46912
+ */
46913
+ export async function registerPermissionPoints(
46914
+ thinkRuntime: any,
46915
+ options: PermissionRegistrationOptions,
46916
+ ): Promise<PermissionRegistrationResult> {
46917
+ if (!thinkRuntime || typeof thinkRuntime.model !== 'function') {
46918
+ throw new Error(${js2(`${owner}: ThinkJS runtime with model() is required`)});
46919
+ }
46920
+ const organizationId = positiveOrganizationId(options && options.organizationId);
46921
+ const userId = Number((options && options.userId) || 0);
46922
+
46923
+ const configurationModel = thinkRuntime.model('configuration');
46924
+ const pointModel = thinkRuntime.model('point');
46925
+
46926
+ const configurations = await configurationModel
46927
+ .setRelation(false)
46928
+ .where({ organization_id: organizationId, type: 'permissions', is_del: 0 })
46929
+ .select();
46930
+ const configurationRows = Array.isArray(configurations) ? configurations : [];
46931
+ if (configurationRows.length > 1) {
46932
+ throw new Error(
46933
+ ${js2(`${owner}: organization `)} +
46934
+ organizationId +
46935
+ ${js2(" has duplicate active permissions configurations")},
46936
+ );
46937
+ }
46938
+
46939
+ const merged = mergePermissionConfiguration(
46940
+ configurationRows.length ? configurationRows[0].content : {},
46941
+ );
46942
+ let configurationUpdates = 0;
46943
+ if (!configurationRows.length) {
46944
+ await configurationModel.add({
46945
+ name: ${js2(`${answers.name}\u6743\u9650`)},
46946
+ type: 'permissions',
46947
+ content: merged,
46948
+ organization_id: organizationId,
46949
+ workspace: 'default',
46950
+ user_id: userId,
46951
+ is_del: 0,
46952
+ });
46953
+ configurationUpdates += 1;
46954
+ } else if (
46955
+ JSON.stringify(merged) !==
46956
+ JSON.stringify(parsePermissionContent(configurationRows[0].content))
46957
+ ) {
46958
+ await configurationModel
46959
+ .where({ id: configurationRows[0].id })
46960
+ .update({ content: merged });
46961
+ configurationUpdates += 1;
46962
+ }
46963
+ if (typeof configurationModel.clearCache === 'function') {
46964
+ configurationModel.clearCache('permissions', organizationId);
46965
+ }
46966
+
46967
+ const existing = await pointModel
46968
+ .setRelation(false)
46969
+ .where({ point: ['IN', PLUGIN_PERMISSION_KEYS] })
46970
+ .select();
46971
+ const existingByPoint = new Map<string, any>(
46972
+ (Array.isArray(existing) ? existing : []).map((row: any) => [row.point, row]),
46973
+ );
46974
+
46975
+ let pointUpdates = 0;
46976
+ for (const definition of PERMISSION_POINTS) {
46977
+ const payload = {
46978
+ name: definition.name,
46979
+ point: definition.key,
46980
+ category: definition.category,
46981
+ desc: definition.description,
46982
+ type: 0,
46983
+ is_del: 0,
46984
+ };
46985
+ const row = existingByPoint.get(definition.key);
46986
+ if (row) {
46987
+ if (!String(row.desc || '').includes(OWNER_MARKER)) {
46988
+ throw new Error(
46989
+ ${js2(`permission point `)} +
46990
+ definition.key +
46991
+ ${js2(` already exists without `)} +
46992
+ OWNER_MARKER +
46993
+ ${js2(" ownership; refusing to overwrite it")},
46994
+ );
46995
+ }
46996
+ if (
46997
+ row.name !== payload.name ||
46998
+ row.category !== payload.category ||
46999
+ row.desc !== payload.desc ||
47000
+ Number(row.type || 0) !== 0 ||
47001
+ Number(row.is_del || 0) !== 0
47002
+ ) {
47003
+ await pointModel.where({ id: row.id }).update(payload);
47004
+ pointUpdates += 1;
47005
+ }
47006
+ } else {
47007
+ await pointModel.add({
47008
+ ...payload,
47009
+ organization_id: organizationId,
47010
+ user_id: userId,
47011
+ });
47012
+ pointUpdates += 1;
47013
+ }
47014
+ }
47015
+
47016
+ return { organizationId, configurationUpdates, pointUpdates };
47017
+ }
47018
+
47019
+ // \u8FDB\u7A0B\u5185\u6309\u7EC4\u7EC7\u7F13\u5B58\u6CE8\u518C\u7ED3\u679C\uFF1A\u6CE8\u518C\u6210\u529F\u4E00\u6B21\u540E\u4E0D\u518D\u6BCF\u6B21\u8BF7\u6C42\u90FD\u8BFB\u5199 configuration/point\u3002
47020
+ // \u53EA\u7F13\u5B58\u6210\u529F\uFF0C\u5931\u8D25\u4E0B\u6B21\u8BF7\u6C42\u8FD8\u4F1A\u91CD\u8BD5\uFF0C\u907F\u514D\u4E00\u6B21\u77AC\u65F6 DB \u9519\u8BEF\u8BA9\u7EC4\u7EC7\u6C38\u4E45\u7F3A\u6743\u9650\u70B9\u3002
47021
+ const registeredOrganizations = new Set<string>();
47022
+
47023
+ /**
47024
+ * \u9996\u6B21\u8BBF\u95EE\u65F6\u515C\u5E95\u6CE8\u518C\u672C\u63D2\u4EF6\u6743\u9650\u70B9\u3002
47025
+ *
47026
+ * \u5B89\u88C5\u94A9\u5B50\u53EA\u80FD\u679A\u4E3E\u300C\u5B89\u88C5\u5F53\u4E0B\u5DF2\u7ECF plugin_active \u7684\u7EC4\u7EC7\u300D\uFF1B\u4E4B\u540E\u65B0\u589E\u7684\u7EC4\u7EC7\u3001\u91CD\u88C5\u3001
47027
+ * \u6216\u5B89\u88C5\u65F6\u7EC4\u7EC7\u8FD8\u6CA1\u843D plugin_active \u7684\u60C5\u51B5\u90FD\u4E0D\u4F1A\u518D\u8DD1\u94A9\u5B50\u3002\u8FD9\u91CC\u5728\u63A7\u5236\u5668\u6743\u9650\u6821\u9A8C\u524D
47028
+ * \u6309\u5F53\u524D\u767B\u5F55\u7528\u6237\u7684\u7EC4\u7EC7\u5E42\u7B49\u8865\u4E00\u6B21\u3002
47029
+ *
47030
+ * \u5931\u8D25\u53EA\u8BB0\u5F55\u65E5\u5FD7\u3001\u7EDD\u4E0D\u5411\u8BF7\u6C42\u629B\u9519\uFF1A\u6743\u9650\u70B9\u6CE8\u518C\u5931\u8D25\u4E0D\u5E94\u8BE5\u8BA9\u6574\u4E2A\u63A5\u53E3 500\uFF1B
47031
+ * \u6743\u9650\u6821\u9A8C\u4ECD\u6309 point \u8868\u73B0\u72B6\u6267\u884C\uFF08\u7F3A\u6743\u9650\u70B9\u5C31 403\uFF0C\u8BED\u4E49\u6B63\u786E\uFF09\u3002
47032
+ */
47033
+ export async function ensurePermissionPointsRegistered(
47034
+ thinkRuntime: any,
47035
+ ctx: any,
47036
+ ): Promise<{ registered: boolean; organizationId: number | null; error?: string }> {
47037
+ const user = readUser(ctx);
47038
+ const organizationId = Number(user.organization_id || user.organizationId || 0);
47039
+ if (!Number.isSafeInteger(organizationId) || organizationId <= 0) {
47040
+ return { registered: false, organizationId: null };
47041
+ }
47042
+ const cacheKey = String(organizationId);
47043
+ if (registeredOrganizations.has(cacheKey)) {
47044
+ return { registered: true, organizationId };
47045
+ }
47046
+ try {
47047
+ await registerPermissionPoints(thinkRuntime, {
47048
+ organizationId,
47049
+ userId: Number(user.id || 0),
47050
+ });
47051
+ registeredOrganizations.add(cacheKey);
47052
+ return { registered: true, organizationId };
47053
+ } catch (error) {
47054
+ const message = error instanceof Error ? error.message : String(error);
47055
+ try {
47056
+ const logger =
47057
+ (thinkRuntime &&
47058
+ ((thinkRuntime.logger && typeof thinkRuntime.logger.warn === 'function' && thinkRuntime.logger) ||
47059
+ (thinkRuntime.createContextLog && thinkRuntime.createContextLog(${js2(`${owner}.access `)})))) ||
47060
+ null;
47061
+ if (logger) logger.warn(${js2(`${owner} lazy permission registration failed organization=`)} + organizationId + ': ' + message);
47062
+ } catch (_) {
47063
+ // \u65E5\u5FD7\u5931\u8D25\u4E0D\u80FD\u5F71\u54CD\u8BF7\u6C42
47064
+ }
47065
+ return { registered: false, organizationId, error: message };
47066
+ }
47067
+ }
47068
+
47069
+ export function hasPoint(ctx: any, point: string): boolean {
47070
+ const user = readUser(ctx);
47071
+ if (Array.isArray(user.points) && user.points.includes(point)) return true;
47072
+ try {
47073
+ return Boolean(typeof ctx.checkPermission === 'function' && ctx.checkPermission(point));
47074
+ } catch (_) {
47075
+ return false;
47076
+ }
47077
+ }
47078
+
47079
+ /**
47080
+ * \u8D85\u7EA7\u7BA1\u7406\u5458\uFF1A\u5E73\u53F0 organization.admin \u6743\u9650\u70B9\u6216\u7528\u6237\u6807\u8BB0\u4E3A superuser\u3002
47081
+ * \u8FD4\u56DE true \u6216\u7EDF\u4E00 403 \u7ED3\u6784\uFF0C\u8C03\u7528\u65B9\u65E0\u9700\u81EA\u5DF1\u6784\u9020\u9519\u8BEF\u3002
47082
+ */
47083
+ export function requireSuperAdmin(ctx: any): true | PermissionDenial {
47084
+ const user = readUser(ctx);
47085
+ if (!Number(user.id || 0)) {
47086
+ return denial(UNAUTHENTICATED_CODE, '\u8BF7\u5148\u767B\u5F55\u540E\u518D\u8BBF\u95EE');
47087
+ }
47088
+ if (user.is_superuser || user.isSuperUser) return true;
47089
+ if (Array.isArray(user.points) && user.points.includes('organization.admin')) {
47090
+ return true;
47091
+ }
47092
+ if (hasPoint(ctx, 'organization.admin')) return true;
47093
+ try {
47094
+ const permissionService =
47095
+ typeof think !== 'undefined' &&
47096
+ think &&
47097
+ typeof think.service === 'function' &&
47098
+ think.service('permission');
47099
+ if (
47100
+ permissionService &&
47101
+ typeof permissionService.isSuperUser === 'function' &&
47102
+ permissionService.isSuperUser(user)
47103
+ ) {
47104
+ return true;
47105
+ }
47106
+ } catch (_) {
47107
+ // \u5E73\u53F0\u672A\u6CE8\u5165 permission service \u65F6\u6309\u65E0\u6743\u9650\u5904\u7406
47108
+ }
47109
+ return denial(FORBIDDEN_CODE, '\u4EC5\u8D85\u7EA7\u7BA1\u7406\u5458\u53EF\u6267\u884C\u8BE5\u64CD\u4F5C');
47110
+ }
47111
+
47112
+ /**
47113
+ * \u6743\u9650\u70B9\u6821\u9A8C\uFF1A
47114
+ * - \u672A\u767B\u5F55 \u2192 UNAUTHENTICATED\uFF1B
47115
+ * - \u7F3A\u5C11\u6743\u9650\u70B9\u4E14\u4E0D\u662F\u8D85\u7BA1 \u2192 FORBIDDEN\uFF1B
47116
+ * - \u901A\u8FC7 \u2192 true\u3002
47117
+ *
47118
+ * \u63A7\u5236\u5668\u7528\u6CD5\uFF1A
47119
+ * const denied = assertPermission(this.ctx, PERMISSION_POINTS[0].key);
47120
+ * if (denied !== true) { this.ctx.status = denied.statusCode; return this.fail(denied.statusCode, denied.message, { code: denied.code }); }
47121
+ */
47122
+ export function assertPermission(ctx: any, point: string): true | PermissionDenial {
47123
+ const user = readUser(ctx);
47124
+ if (!Number(user.id || 0)) {
47125
+ return denial(UNAUTHENTICATED_CODE, '\u8BF7\u5148\u767B\u5F55\u540E\u518D\u8BBF\u95EE');
47126
+ }
47127
+ if (hasPoint(ctx, point)) return true;
47128
+ if (requireSuperAdmin(ctx) === true) return true;
47129
+ return denial(FORBIDDEN_CODE, ${js2("\u7F3A\u5C11\u6743\u9650\u70B9 ")} + point);
47130
+ }
47131
+ `;
47132
+ }
47133
+ function renderPermissionFiles(answers) {
47134
+ if (!permissionsEnabled(answers)) return [];
47135
+ return [
47136
+ { path: permissionConfigPath(answers), content: renderPermissionConfig(answers) },
47137
+ { path: permissionAccessPath(answers), content: renderAccessService(answers) }
47138
+ ];
47139
+ }
47140
+ function renderPermissionInstall(answers) {
47141
+ const owner = `${answers.en_name}`;
47142
+ const accessModule = `../service/${answers.en_name}_access`;
47143
+ return `import { registerPermissionPoints } from ${js2(accessModule)};
47144
+
47145
+ declare const think: any;
47146
+
47147
+ // \u5B89\u88C5\u65F6\u5C3D\u91CF\u5BF9\u6240\u6709\u5DF2\u6FC0\u6D3B\u7EC4\u7EC7\u6CE8\u518C\u6743\u9650\u70B9\u3002
47148
+ // \u6CE8\u518C\u5931\u8D25\u53EA\u8BB0\u65E5\u5FD7\u3001\u4E0D\u629B\u9519\uFF1A\u5B89\u88C5\u4E0D\u5E94\u8BE5\u56E0\u4E3A\u6743\u9650\u70B9\u5199\u5E93\u5931\u8D25\u800C\u6574\u4F53\u5931\u8D25\uFF1B
47149
+ // \u672A\u8986\u76D6\u7684\u7EC4\u7EC7\uFF08\u65B0\u589E\u7EC4\u7EC7\u3001\u91CD\u88C5\u3001\u5B89\u88C5\u65F6\u8FD8\u6CA1\u843D plugin_active\uFF09\u4F1A\u5728\u9996\u6B21\u8BBF\u95EE\u65F6
47150
+ // \u7531 ensurePermissionPointsRegistered \u515C\u5E95\u8865\u6CE8\u518C\u3002
47151
+ export default async (ctx: any = {}) => {
47152
+ const userInfo = (ctx && (ctx.userInfo || (ctx.state && ctx.state.user))) || {};
47153
+ const configurationModel = think.model('configuration');
47154
+ const rows = await configurationModel
47155
+ .setRelation(false)
47156
+ .field('organization_id')
47157
+ .where({ type: 'plugin_active', is_del: 0 })
47158
+ .select();
47159
+
47160
+ const organizationIds: number[] = [];
47161
+ const collect = (value: unknown) => {
47162
+ const id = Number(value || 0);
47163
+ if (Number.isSafeInteger(id) && id > 0 && !organizationIds.includes(id)) {
47164
+ organizationIds.push(id);
47165
+ }
47166
+ };
47167
+ for (const row of Array.isArray(rows) ? rows : []) {
47168
+ collect(row && row.organization_id);
47169
+ }
47170
+ // \u5B89\u88C5\u8BF7\u6C42\u672C\u8EAB\u53EF\u80FD\u53D1\u751F\u5728 plugin_active \u843D\u5E93\u4E4B\u524D\uFF0C\u8865\u4E0A\u5F53\u524D\u7EC4\u7EC7\u3002
47171
+ collect(userInfo.organization_id || userInfo.organizationId);
47172
+
47173
+ if (organizationIds.length === 0) {
47174
+ think.logger.warn(
47175
+ ${js2(`${owner}: no active organization found; permission points will be registered on first access`)},
47176
+ );
47177
+ return;
47178
+ }
47179
+
47180
+ for (const organizationId of organizationIds) {
47181
+ try {
47182
+ const result = await registerPermissionPoints(think, {
47183
+ organizationId,
47184
+ userId: userInfo.id || 0,
47185
+ });
47186
+ think.logger.info(
47187
+ ${js2(`${owner} permissions registered organization=`)} +
47188
+ organizationId +
47189
+ ' configurationUpdates=' +
47190
+ result.configurationUpdates +
47191
+ ' pointUpdates=' +
47192
+ result.pointUpdates,
47193
+ );
47194
+ } catch (error) {
47195
+ const message = error instanceof Error ? error.message : String(error);
47196
+ think.logger.error(
47197
+ ${js2(`${owner} permission registration failed organization=`)} +
47198
+ organizationId +
47199
+ ': ' +
47200
+ message +
47201
+ ${js2("; will retry on first access")},
47202
+ );
47203
+ }
47204
+ }
47205
+ };
47206
+ `;
47207
+ }
47208
+ function renderPermissionUninstall(answers) {
47209
+ const owner = `${answers.en_name}`;
47210
+ const permissionsConfig = `../config/${answers.en_name}_permissions`;
47211
+ return `import { PLUGIN_NAME, PLUGIN_PERMISSION_KEYS } from ${js2(permissionsConfig)};
47212
+
47213
+ declare const think: any;
47214
+
47215
+ function parseContent(value: unknown): Record<string, any> {
47216
+ if (value && typeof value === 'object') return value as Record<string, any>;
47217
+ if (typeof value === 'string' && value.trim()) {
47218
+ try {
47219
+ const parsed = JSON.parse(value);
47220
+ return parsed && typeof parsed === 'object' ? parsed : {};
47221
+ } catch (_) {
47222
+ return {};
47223
+ }
47224
+ }
47225
+ return {};
47226
+ }
47227
+
47228
+ // \u5378\u8F7D\u662F\u5C3D\u529B\u800C\u4E3A\uFF1A\u70B9\u8F6F\u5220\u4E0E\u6743\u9650\u7EC4\u79FB\u9664\u5404\u81EA\u5931\u8D25\u90FD\u53EA\u8BB0\u65E5\u5FD7\uFF0C
47229
+ // \u4E0D\u80FD\u8BA9\u4E00\u6B21\u5199\u5E93\u5931\u8D25\u628A\u6574\u4E2A\u5378\u8F7D\u6D41\u7A0B\u5361\u4F4F\u3002
47230
+ export default async () => {
47231
+ const pointModel = think.model('point');
47232
+ try {
47233
+ await pointModel
47234
+ .setRelation(false)
47235
+ .where({ point: ['IN', PLUGIN_PERMISSION_KEYS] })
47236
+ .update({ is_del: 1 });
47237
+ think.logger.info(${js2(`${owner} permission points disabled`)});
47238
+ } catch (error) {
47239
+ const message = error instanceof Error ? error.message : String(error);
47240
+ think.logger.error(${js2(`${owner} permission point cleanup failed: `)} + message + ${js2("; uninstall continues")});
47241
+ }
47242
+
47243
+ // configuration(type='permissions').content.permissions \u91CC\u7684\u5206\u7EC4\u6309 key \u5E42\u7B49\u79FB\u9664\uFF1A
47244
+ // \u53EA\u5220\u672C\u63D2\u4EF6\u5206\u7EC4\uFF0C\u4FDD\u7559\u5176\u5B83\u5206\u7EC4\u4E0E content \u4E0A\u7684\u672A\u77E5\u5B57\u6BB5\uFF0C\u5E76\u6E05\u6389\u6743\u9650\u7F13\u5B58\u3002
47245
+ try {
47246
+ const configurationModel = think.model('configuration');
47247
+ const rows = await configurationModel
47248
+ .setRelation(false)
47249
+ .where({ type: 'permissions', is_del: 0 })
47250
+ .select();
47251
+ let removed = 0;
47252
+ for (const row of Array.isArray(rows) ? rows : []) {
47253
+ const content = parseContent(row && row.content);
47254
+ if (!Array.isArray(content.permissions)) continue;
47255
+ const nextGroups = content.permissions.filter(
47256
+ (group: any) => !(group && typeof group === 'object' && group.key === PLUGIN_NAME),
47257
+ );
47258
+ if (nextGroups.length === content.permissions.length) continue;
47259
+ await configurationModel
47260
+ .where({ id: row.id })
47261
+ .update({ content: { ...content, permissions: nextGroups } });
47262
+ if (typeof configurationModel.clearCache === 'function') {
47263
+ configurationModel.clearCache('permissions', row.organization_id);
47264
+ }
47265
+ removed += 1;
47266
+ }
47267
+ think.logger.info(${js2(`${owner} permission group removed; configurations=`)} + removed);
47268
+ } catch (error) {
47269
+ const message = error instanceof Error ? error.message : String(error);
47270
+ think.logger.error(${js2(`${owner} permission group cleanup failed: `)} + message + ${js2("; uninstall continues")});
47271
+ }
47272
+ };
47273
+ `;
47274
+ }
47275
+
47276
+ // src/core/templates/plugin-server.ts
47277
+ function js3(value) {
47278
+ return JSON.stringify(value);
47279
+ }
46539
47280
  function json(value) {
46540
47281
  return `${JSON.stringify(value, null, 2)}
46541
47282
  `;
@@ -46597,35 +47338,364 @@ function renderDbMigrateRc() {
46597
47338
  return json({ configFile: "config/database.json", "sql-file": true });
46598
47339
  }
46599
47340
  function renderInstall(answers) {
47341
+ if (permissionsEnabled(answers)) {
47342
+ return renderPermissionInstall(answers);
47343
+ }
46600
47344
  return `export default async () => {
46601
- think.logger.info(${js2(`plugin_${answers.en_name} installed`)});
47345
+ think.logger.info(${js3(`${answers.en_name} installed`)});
46602
47346
  };
46603
47347
  `;
46604
47348
  }
46605
47349
  function renderUninstall(answers) {
47350
+ if (permissionsEnabled(answers)) {
47351
+ return renderPermissionUninstall(answers);
47352
+ }
46606
47353
  return `export default async () => {
46607
- think.logger.info(${js2(`plugin_${answers.en_name} uninstalled`)});
47354
+ think.logger.info(${js3(`${answers.en_name} uninstalled`)});
46608
47355
  };
46609
47356
  `;
46610
47357
  }
46611
47358
  function renderController(answers) {
46612
- return `declare const think: any;
47359
+ const hasDatabase = answers.capabilities.database_table;
47360
+ const serviceName = `${answers.en_name}_service`;
47361
+ const accessModule = `../../service/${answers.en_name}_access`;
47362
+ const errorsModule = `../../service/${answers.en_name}_errors`;
47363
+ const permissionsConfig = `../../config/${answers.en_name}_permissions`;
47364
+ const createRoute = hasDatabase ? `
47365
+ @think.Post('/items')
47366
+ @think.AuthLogin()
47367
+ async createItem() {
47368
+ return this.respond('createItem', PERMISSION_POINTS[1].key, async () => {
47369
+ const { confirmed } = this.post();
47370
+ asserts(confirmed === true, 'PLUGIN_INVALID_ARGUMENT', 'confirmed \u5FC5\u987B\u4E3A true');
47371
+ const service = think.service(${js3(serviceName)});
47372
+ return service.createItem({ confirmed });
47373
+ });
47374
+ }
47375
+ ` : "";
47376
+ return `import BaseRest from '../rest.js';
47377
+ import {
47378
+ assertPermission,
47379
+ ensurePermissionPointsRegistered,
47380
+ } from ${js3(accessModule)};
47381
+ import { asserts, toErrorDetail } from ${js3(errorsModule)};
47382
+ import { PERMISSION_POINTS } from ${js3(permissionsConfig)};
47383
+
47384
+ declare const think: any;
47385
+
47386
+ // createContextLog \u8BA9\u6BCF\u6761\u65E5\u5FD7\u5E26\u4E0A\u8BF7\u6C42\u4E0A\u4E0B\u6587\uFF0C\u4FBF\u4E8E\u6309 trace \u4E32\u8054\u3002
47387
+ const logger = think.createContextLog(${js3(`${answers.en_name}.controller `)});
47388
+
47389
+ interface ServiceFailure {
47390
+ code: string;
47391
+ message: string;
47392
+ status: number;
47393
+ }
47394
+
47395
+ interface ServiceResult<T> {
47396
+ ok: boolean;
47397
+ data?: T;
47398
+ error?: ServiceFailure;
47399
+ }
46613
47400
 
46614
47401
  // \u5FC5\u987B\u5BFC\u51FA\u300C\u7C7B\u300D\u800C\u4E0D\u662F think.Controller({...}) \u7684\u8C03\u7528\u7ED3\u679C\uFF1A
46615
47402
  // ThinkJS \u542F\u52A8\u671F require \u65F6\u4F1A\u5BF9\u5BFC\u51FA\u7684\u7C7B\u6267\u884C new\uFF0C\u8C03\u7528\u5F62\u5F0F\u4F1A\u629B
46616
47403
  // TypeError: Class constructor Controller cannot be invoked without 'new'\u3002
46617
- export default class extends think.Controller {
46618
- async indexAction() {
46619
- return this.success({ plugin: ${js2(answers.en_name)} });
47404
+ //
47405
+ // \u5FC5\u987B\u7EE7\u627F\u5E73\u53F0 BaseRest\uFF08\u5B89\u88C5\u540E\u4F4D\u4E8E app/controller/rest.js\uFF09\uFF1A
47406
+ // \u5B83\u7684 constructor \u4ECE\u63A7\u5236\u5668\u6587\u4EF6\u540D\u63A8\u5BFC this.resource\uFF0C\u5E76\u521D\u59CB\u5316 modelInstance\u3002
47407
+ // \u5E73\u53F0 @think.RestController() \u7528 this.resource \u8BA1\u7B97 subPath\uFF08/api/<resource>/...\uFF09\uFF0C
47408
+ // resource \u7F3A\u5931\u65F6\u88C5\u9970\u5668\u8DEF\u7531\u6C38\u8FDC\u5339\u914D\u4E0D\u4E0A\uFF0C\u4F1A\u56DE\u843D\u5230\u4E0D\u5B58\u5728\u7684 getAction \u76F4\u63A5 500\u3002
47409
+ @think.RestController()
47410
+ export default class extends BaseRest {
47411
+ [x: string]: any;
47412
+
47413
+ // AuthLogin \u53EA\u4FDD\u8BC1\u300C\u5DF2\u767B\u5F55\u300D\uFF1B\u6743\u9650\u70B9\u6821\u9A8C\u5728 respond \u91CC\u7EDF\u4E00\u505A\uFF0C
47414
+ // \u672A\u767B\u5F55 401\u3001\u65E0\u6743\u9650 403\uFF0C\u4E0D\u4F1A\u51FA\u73B0\u300C\u767B\u5F55\u4E86\u4F46\u6CA1\u6743\u9650\u4E5F\u80FD\u8BFB\u300D\u7684\u63A5\u53E3\u3002
47415
+ @think.Get('/projects')
47416
+ @think.AuthLogin()
47417
+ async listProjects() {
47418
+ return this.respond('listProjects', PERMISSION_POINTS[0].key, async () => {
47419
+ const service = think.service(${js3(serviceName)});
47420
+ return service.listProjects({
47421
+ page: this.get('page'),
47422
+ pageSize: this.get('pageSize'),
47423
+ keyword: this.get('keyword'),
47424
+ });
47425
+ });
47426
+ }
47427
+
47428
+ @think.Get('/projects/:id')
47429
+ @think.AuthLogin()
47430
+ async getProject() {
47431
+ return this.respond('getProject', PERMISSION_POINTS[0].key, async () => {
47432
+ const { id } = this.params;
47433
+ asserts(id !== undefined && id !== null && String(id).trim() !== '', 'PLUGIN_INVALID_ARGUMENT', 'id \u4E0D\u80FD\u4E3A\u7A7A');
47434
+ const service = think.service(${js3(serviceName)});
47435
+ return service.getProject(id);
47436
+ });
47437
+ }
47438
+ ${createRoute}
47439
+ // \u7EDF\u4E00\u51FA\u53E3\uFF1A\u5148\u6821\u9A8C\u6743\u9650\u70B9\uFF0C\u518D\u628A service \u7684\u7ED3\u6784\u5316\u9519\u8BEF\u6620\u5C04\u6210\u5E73\u53F0 fail(errno, message)\uFF0C
47440
+ // \u672A\u9884\u671F\u5F02\u5E38\u7EDF\u4E00 500\uFF0C\u907F\u514D\u628A\u5185\u90E8\u5806\u6808\u76F4\u63A5\u56DE\u7ED9\u8C03\u7528\u65B9\u3002
47441
+ private async respond<T>(
47442
+ action: string,
47443
+ point: string,
47444
+ run: () => Promise<ServiceResult<T> | T>,
47445
+ ) {
47446
+ // \u5B89\u88C5\u94A9\u5B50\u53EA\u8986\u76D6\u5B89\u88C5\u5F53\u4E0B\u5DF2\u6FC0\u6D3B\u7684\u7EC4\u7EC7\uFF1B\u65B0\u589E/\u91CD\u88C5\u7EC4\u7EC7\u5728\u9996\u6B21\u8BBF\u95EE\u65F6\u515C\u5E95\u6CE8\u518C\u3002
47447
+ // \u5931\u8D25\u53EA\u8BB0\u65E5\u5FD7\uFF0C\u4E0D\u963B\u65AD\u8BF7\u6C42\uFF08\u6743\u9650\u6821\u9A8C\u4ECD\u6309\u73B0\u6709 point \u5224\u65AD\uFF09\u3002
47448
+ const registration = await ensurePermissionPointsRegistered(think, this.ctx);
47449
+ if (!registration.registered && registration.error) {
47450
+ logger.warn(action + ' permission registration skipped:' + registration.error);
47451
+ }
47452
+ const denied = assertPermission(this.ctx, point);
47453
+ if (denied !== true) {
47454
+ logger.warn(action + ' denied code:' + denied.code);
47455
+ this.ctx.status = denied.statusCode;
47456
+ // \u5E73\u53F0 ctx.fail \u7684\u7B7E\u540D\u662F fail(errno, errmsg, data)\uFF1Berrno \u5FC5\u987B\u5728\u7B2C\u4E00\u4F4D\uFF0C
47457
+ // \u4E1A\u52A1\u7801\u653E\u8FDB data.code \u4F9B\u524D\u7AEF\u8BC6\u522B\u3002
47458
+ return this.fail(denied.statusCode, denied.message, { code: denied.code });
47459
+ }
47460
+ try {
47461
+ const result: any = await run();
47462
+ if (result && result.ok === false) {
47463
+ logger.warn(action + ' rejected code:' + result.error.code);
47464
+ return this.fail(result.error.status || 400, result.error.message, {
47465
+ code: result.error.code,
47466
+ });
47467
+ }
47468
+ const data = result && result.ok === true ? result.data : result;
47469
+ const userId = this.ctx && this.ctx.userInfo ? this.ctx.userInfo.id : 0;
47470
+ logger.info(action + ' success user_id:' + (userId || 0));
47471
+ return this.success(data);
47472
+ } catch (error) {
47473
+ const detail = toErrorDetail(error);
47474
+ logger.error(action + ' failed code:' + detail.code + ' message:' + detail.message);
47475
+ return this.fail(detail.status, detail.message, { code: detail.code });
47476
+ }
46620
47477
  }
46621
47478
  }
46622
47479
  `;
46623
47480
  }
47481
+ function renderErrors(answers) {
47482
+ return `export interface PluginErrorDetail {
47483
+ code: string;
47484
+ message: string;
47485
+ status: number;
47486
+ }
47487
+
47488
+ // \u7ED3\u6784\u5316\u4E1A\u52A1\u9519\u8BEF\uFF1Aservice \u8FD4\u56DE toJSON()\uFF0Ccontroller \u518D\u6620\u5C04\u6210\u5E73\u53F0 fail(errno, message)\u3002
47489
+ export class PluginError extends Error {
47490
+ readonly code: string;
47491
+ readonly status: number;
47492
+
47493
+ constructor(code: string, message: string, status = 400) {
47494
+ super(message);
47495
+ this.name = 'PluginError';
47496
+ this.code = code;
47497
+ this.status = status;
47498
+ }
47499
+
47500
+ toJSON(): PluginErrorDetail {
47501
+ return { code: this.code, message: this.message, status: this.status };
47502
+ }
47503
+ }
47504
+
47505
+ export function pluginError(code: string, message: string, status = 400): PluginError {
47506
+ return new PluginError(code, message, status);
47507
+ }
47508
+
47509
+ // \u5165\u53C2\u6821\u9A8C\u7528\u65AD\u8A00\uFF1A\u5931\u8D25\u5373\u629B\u7ED3\u6784\u5316\u9519\u8BEF\uFF0C\u4E0D\u629B\u88F8 Error\u3002
47510
+ export function asserts(
47511
+ condition: unknown,
47512
+ code: string,
47513
+ message: string,
47514
+ status = 400,
47515
+ ): asserts condition {
47516
+ if (!condition) throw new PluginError(code, message, status);
47517
+ }
47518
+
47519
+ export const MAX_PAGE_SIZE = 100;
47520
+ export const DEFAULT_PAGE_SIZE = 20;
47521
+
47522
+ export interface Paging {
47523
+ page: number;
47524
+ pageSize: number;
47525
+ offset: number;
47526
+ }
47527
+
47528
+ function parsePositiveInt(value: unknown, fallback?: number): number {
47529
+ if (value === undefined || value === null || value === '') {
47530
+ if (fallback !== undefined) return fallback;
47531
+ throw pluginError('PLUGIN_INVALID_PAGING', '\u5206\u9875\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A');
47532
+ }
47533
+ const parsed = Number(value);
47534
+ if (!Number.isInteger(parsed) || parsed <= 0) {
47535
+ throw pluginError('PLUGIN_INVALID_PAGING', '\u5206\u9875\u53C2\u6570\u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF1A' + String(value));
47536
+ }
47537
+ return parsed;
47538
+ }
47539
+
47540
+ export function normalizePositiveInt(value: unknown, field: string): number {
47541
+ const parsed = Number(value);
47542
+ if (!Number.isInteger(parsed) || parsed <= 0) {
47543
+ throw pluginError('PLUGIN_INVALID_ARGUMENT', field + ' \u5FC5\u987B\u662F\u6B63\u6574\u6570');
47544
+ }
47545
+ return parsed;
47546
+ }
47547
+
47548
+ export function normalizeText(value: unknown, field: string, maxLength: number): string {
47549
+ if (typeof value !== 'string' || value.trim() === '') {
47550
+ throw pluginError('PLUGIN_INVALID_ARGUMENT', field + ' \u4E0D\u80FD\u4E3A\u7A7A');
47551
+ }
47552
+ const trimmed = value.trim();
47553
+ if (trimmed.length > maxLength) {
47554
+ throw pluginError('PLUGIN_INVALID_ARGUMENT', field + ' \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ' + maxLength);
47555
+ }
47556
+ return trimmed;
47557
+ }
47558
+
47559
+ // pageSize \u8D85\u8FC7\u4E0A\u9650\u65F6\u622A\u65AD\u800C\u4E0D\u662F\u62A5\u9519\uFF0C\u907F\u514D\u8C03\u7528\u65B9\u4F20\u5927\u503C\u62D6\u57AE\u67E5\u8BE2\u3002
47560
+ export function normalizePaging(
47561
+ input: { page?: unknown; pageSize?: unknown } = {},
47562
+ maxPageSize = MAX_PAGE_SIZE,
47563
+ ): Paging {
47564
+ const page = parsePositiveInt(input.page, 1);
47565
+ const requested = parsePositiveInt(input.pageSize, DEFAULT_PAGE_SIZE);
47566
+ const pageSize = Math.min(requested, maxPageSize);
47567
+ return { page, pageSize, offset: (page - 1) * pageSize };
47568
+ }
47569
+
47570
+ export function toErrorDetail(
47571
+ error: unknown,
47572
+ fallbackCode = 'PLUGIN_INTERNAL_ERROR',
47573
+ ): PluginErrorDetail {
47574
+ if (error instanceof PluginError) return error.toJSON();
47575
+ if (error && typeof error === 'object' && typeof (error as any).code === 'string') {
47576
+ return {
47577
+ code: (error as any).code,
47578
+ message: (error as any).message || '\u670D\u52A1\u5185\u90E8\u9519\u8BEF',
47579
+ status: Number((error as any).status) || 500,
47580
+ };
47581
+ }
47582
+ const message = error instanceof Error ? error.message : String(error || '');
47583
+ return { code: fallbackCode, message: message || '\u670D\u52A1\u5185\u90E8\u9519\u8BEF', status: 500 };
47584
+ }
47585
+ `;
47586
+ }
46624
47587
  function renderService(answers) {
46625
- return `export class PluginService {
46626
- async ping() {
46627
- return { ok: true, plugin: ${js2(answers.en_name)} };
47588
+ const hasDatabase = answers.capabilities.database_table;
47589
+ const modelName = `${answers.en_name}_model`;
47590
+ const itemModel = hasDatabase ? `
47591
+ private get itemModel(): any {
47592
+ // \u5199\u64CD\u4F5C\u663E\u5F0F\u8D70\u63D2\u4EF6\u81EA\u5DF1\u7684\u8868\uFF1B\u6D4B\u8BD5\u53EF\u6CE8\u5165 itemModel \u907F\u514D\u8FDE\u5E93\u3002
47593
+ return this.deps.itemModel || think.model(${js3(modelName)});
47594
+ }
47595
+ ` : "";
47596
+ const createItem = hasDatabase ? `
47597
+ // \u4E8B\u52A1\u793A\u4F8B\uFF1A\u5199\u63D2\u4EF6\u8868\u3002\u5E73\u53F0 Base model \u7684 beforeAdd \u4F1A\u81EA\u52A8\u8865 create_time/update_time\uFF0C
47598
+ // guid \u4E5F\u4F1A\u81EA\u52A8\u751F\u6210\uFF1B\u4E1A\u52A1\u5B57\u6BB5\u5148\u52A0\u5230 migrations/<\u65F6\u95F4\u6233>-create-plugin-${answers.en_name}-up.sql
47599
+ // \u518D\u5728\u8FD9\u91CC\u4E00\u8D77\u5199\u5165\uFF0C\u4E0D\u8981\u5199\u5165\u4E0D\u5B58\u5728\u7684\u5217\u3002
47600
+ async createItem(input: { confirmed?: unknown } = {}): Promise<ServiceResult<{ id: number }>> {
47601
+ try {
47602
+ asserts(input.confirmed === true, 'PLUGIN_INVALID_ARGUMENT', 'confirmed \u5FC5\u987B\u4E3A true');
47603
+ const itemModel = this.itemModel;
47604
+ const id = await itemModel.transaction(async () => {
47605
+ return itemModel.add({ is_del: 0 });
47606
+ });
47607
+ return { ok: true, data: { id: Number(id) } };
47608
+ } catch (error) {
47609
+ return { ok: false, error: toErrorDetail(error) };
47610
+ }
47611
+ }
47612
+ ` : "";
47613
+ return `import {
47614
+ asserts,
47615
+ normalizePaging,
47616
+ normalizePositiveInt,
47617
+ pluginError,
47618
+ toErrorDetail,
47619
+ type PluginErrorDetail,
47620
+ } from './${answers.en_name}_errors';
47621
+
47622
+ declare const think: any;
47623
+
47624
+ export type ServiceResult<T> =
47625
+ | { ok: true; data: T }
47626
+ | { ok: false; error: PluginErrorDetail };
47627
+
47628
+ export interface ListProjectsInput {
47629
+ page?: unknown;
47630
+ pageSize?: unknown;
47631
+ keyword?: unknown;
47632
+ }
47633
+
47634
+ export interface ServiceDeps {
47635
+ projectModel?: any;
47636
+ itemModel?: any;
47637
+ }
47638
+
47639
+ // \u4E0D\u7EE7\u627F think.Service\uFF1Athink.service() \u53EA\u8981\u6C42\u9ED8\u8BA4\u5BFC\u51FA\u53EF new \u7684\u7C7B\uFF0C
47640
+ // \u4F9D\u8D56\u6CE8\u5165\u8BA9\u5355\u6D4B\u53EF\u4EE5\u4E0D\u542F\u52A8\u5E73\u53F0\u3001\u4E5F\u4E0D\u8FDE\u6570\u636E\u5E93\u3002
47641
+ export default class PluginService {
47642
+ constructor(private readonly deps: ServiceDeps = {}) {}
47643
+
47644
+ private get projectModel(): any {
47645
+ // \u5E73\u53F0\u8868\u53EA\u8BFB\u793A\u4F8B\uFF1Athink.model('project')\u3002
47646
+ return this.deps.projectModel || think.model('project');
47647
+ }
47648
+ ${itemModel}
47649
+ async listProjects(input: ListProjectsInput = {}): Promise<ServiceResult<{
47650
+ list: any[];
47651
+ total: number;
47652
+ page: number;
47653
+ pageSize: number;
47654
+ }>> {
47655
+ try {
47656
+ const paging = normalizePaging({ page: input.page, pageSize: input.pageSize });
47657
+ const keyword = typeof input.keyword === 'string' ? input.keyword.trim() : '';
47658
+ let query = this.projectModel.where({ is_del: 0 });
47659
+ if (keyword) {
47660
+ // think-model 1.5.4 \u7684 where \u53EA\u63A5\u53D7\u5355\u4E2A\u5BF9\u8C61/\u5B57\u7B26\u4E32\u53C2\u6570\uFF1B
47661
+ // \u4E09\u53C2\u6570\u5F62\u5F0F where(field, op, value) \u4F1A\u88AB\u5FFD\u7565\uFF0C\u641C\u7D22\u9759\u9ED8\u5931\u6548\u3002
47662
+ query = query.where({ name: ['like', '%' + keyword + '%'] });
47663
+ }
47664
+ const result = await query
47665
+ .field('id,name,create_time')
47666
+ .page(paging.page, paging.pageSize)
47667
+ .order('id DESC')
47668
+ .countSelect();
47669
+ return {
47670
+ ok: true,
47671
+ data: {
47672
+ list: Array.isArray(result && result.data) ? result.data : [],
47673
+ total: Number(result && result.count) || 0,
47674
+ page: paging.page,
47675
+ pageSize: paging.pageSize,
47676
+ },
47677
+ };
47678
+ } catch (error) {
47679
+ return { ok: false, error: toErrorDetail(error) };
47680
+ }
47681
+ }
47682
+
47683
+ async getProject(projectId: unknown): Promise<ServiceResult<any>> {
47684
+ try {
47685
+ const id = normalizePositiveInt(projectId, 'project_id');
47686
+ const project = await this.projectModel
47687
+ .where({ id, is_del: 0 })
47688
+ .field('id,name,create_time')
47689
+ .find();
47690
+ if (!project || !project.id) {
47691
+ return { ok: false, error: pluginError('PLUGIN_NOT_FOUND', '\u9879\u76EE\u4E0D\u5B58\u5728\uFF1A' + id, 404).toJSON() };
47692
+ }
47693
+ return { ok: true, data: project };
47694
+ } catch (error) {
47695
+ return { ok: false, error: toErrorDetail(error) };
47696
+ }
46628
47697
  }
47698
+ ${createItem}
46629
47699
  }
46630
47700
  `;
46631
47701
  }
@@ -46635,7 +47705,7 @@ import ModelBase from './base';
46635
47705
 
46636
47706
  export default class extends ModelBase {
46637
47707
  get tableName() {
46638
- return ${js2(`plugin_${answers.en_name}`)};
47708
+ return ${js3(`${answers.en_name}`)};
46639
47709
  }
46640
47710
  }
46641
47711
  `;
@@ -46649,27 +47719,45 @@ export default {
46649
47719
  enable: true,
46650
47720
  immediate: false,
46651
47721
  handle: async () => {
46652
- think.logger.info(${js2(`plugin_${answers.en_name} cron tick`)});
47722
+ think.logger.info(${js3(`${answers.en_name} cron tick`)});
46653
47723
  },
46654
47724
  };
46655
47725
  `;
46656
47726
  }
46657
47727
  function renderHook(answers) {
46658
47728
  return `think.addPluginHook('step_active', async function (data: unknown) {
46659
- think.logger.info(${js2(`plugin_${answers.en_name} hook`)}, data);
47729
+ think.logger.info(${js3(`${answers.en_name} hook`)}, data);
46660
47730
  return data;
46661
47731
  });
46662
47732
  `;
46663
47733
  }
47734
+ function renderInitMigrationUp(answers) {
47735
+ return `-- \u65E0\u4E1A\u52A1\u8868\u63D2\u4EF6\u7684\u6700\u5C0F\u53EF\u7528\u8FC1\u79FB\u3002
47736
+ -- \u5E73\u53F0\u5B89\u88C5\u4E00\u5B9A\u4F1A\u6267\u884C migrate_prod up:${answers.en_name}\uFF0C\u6CA1\u6709\u53EF\u6267\u884C\u8FC1\u79FB\u4F1A\u76F4\u63A5\u5931\u8D25\uFF0C
47737
+ -- \u56E0\u6B64\u6240\u6709\u63D2\u4EF6\u90FD\u751F\u6210\u8FD9\u6761 no-op\uFF1B\u9700\u8981\u4E1A\u52A1\u8868\u65F6\u53E6\u52A0\u8FC1\u79FB\u6587\u4EF6\uFF0C\u4E0D\u8981\u6539\u8FD9\u91CC\u3002
47738
+ SELECT 1;
47739
+ `;
47740
+ }
47741
+ function renderInitMigrationDown(answers) {
47742
+ return `-- \u4E0E init \u8FC1\u79FB\u914D\u5957\u7684\u7A7A\u56DE\u6EDA\uFF0C\u4FDD\u8BC1 db-migrate \u7684 up/down \u6210\u5BF9\u3002
47743
+ SELECT 1;
47744
+ `;
47745
+ }
46664
47746
  function renderMigrationUp(answers) {
46665
- return `CREATE TABLE IF NOT EXISTS ${`plugin_${answers.en_name}`} (
46666
- id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
46667
- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
47747
+ const table = `${answers.en_name}`;
47748
+ return `CREATE TABLE IF NOT EXISTS \`${table}\` (
47749
+ \`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
47750
+ \`guid\` VARCHAR(36) NULL,
47751
+ \`is_del\` TINYINT NOT NULL DEFAULT 0,
47752
+ \`create_time\` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
47753
+ \`update_time\` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
47754
+ PRIMARY KEY (\`id\`),
47755
+ KEY \`idx_${answers.en_name}_is_del\` (\`is_del\`)
46668
47756
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
46669
47757
  `;
46670
47758
  }
46671
47759
  function renderMigrationDown(answers) {
46672
- return `DROP TABLE IF EXISTS ${`plugin_${answers.en_name}`};
47760
+ return `DROP TABLE IF EXISTS \`${answers.en_name}\`;
46673
47761
  `;
46674
47762
  }
46675
47763
  function renderMigrationJs(base) {
@@ -46696,7 +47784,7 @@ exports.up = function (db) {
46696
47784
  var filePath = path.join(
46697
47785
  __dirname,
46698
47786
  'sqls',
46699
- ${js2(`${base}-up.sql`)}
47787
+ ${js3(`${base}-up.sql`)}
46700
47788
  );
46701
47789
  return new Promise(function (resolve, reject) {
46702
47790
  fs.readFile(filePath, { encoding: 'utf-8' }, function (err, data) {
@@ -46712,7 +47800,7 @@ exports.down = function (db) {
46712
47800
  var filePath = path.join(
46713
47801
  __dirname,
46714
47802
  'sqls',
46715
- ${js2(`${base}-down.sql`)}
47803
+ ${js3(`${base}-down.sql`)}
46716
47804
  );
46717
47805
  return new Promise(function (resolve, reject) {
46718
47806
  fs.readFile(filePath, { encoding: 'utf-8' }, function (err, data) {
@@ -46729,8 +47817,144 @@ exports._meta = {
46729
47817
  };
46730
47818
  `;
46731
47819
  }
47820
+ function renderServiceTest(answers) {
47821
+ const hasDatabase = answers.capabilities.database_table;
47822
+ const createItemTests = hasDatabase ? `
47823
+ it('createItem \u7F3A\u5C11 confirmed \u65F6\u8FD4\u56DE PLUGIN_INVALID_ARGUMENT', async () => {
47824
+ const item = fakeItemModel();
47825
+ const service = new PluginService({ projectModel: fakeProjectModel([]).model, itemModel: item.model });
47826
+ const result = await service.createItem({});
47827
+ expect(result.ok).toBe(false);
47828
+ expect(result.ok ? '' : result.error.code).toBe('PLUGIN_INVALID_ARGUMENT');
47829
+ expect(item.calls).toHaveLength(0);
47830
+ });
47831
+
47832
+ it('createItem \u901A\u8FC7\u4E8B\u52A1\u5199\u5165\uFF0C\u5E73\u53F0 Base model \u81EA\u52A8\u8865\u5BA1\u8BA1\u5B57\u6BB5', async () => {
47833
+ const item = fakeItemModel();
47834
+ const service = new PluginService({ projectModel: fakeProjectModel([]).model, itemModel: item.model });
47835
+ const result = await service.createItem({ confirmed: true });
47836
+ expect(result).toEqual({ ok: true, data: { id: 123 } });
47837
+ expect(item.transactionCount).toBe(1);
47838
+ expect(item.calls).toHaveLength(1);
47839
+ expect(item.calls[0].is_del).toBe(0);
47840
+ });
47841
+ ` : "";
47842
+ return `import {
47843
+ MAX_PAGE_SIZE,
47844
+ normalizePaging,
47845
+ toErrorDetail,
47846
+ } from '../src/service/${answers.en_name}_errors';
47847
+ import PluginService from '../src/service/${answers.en_name}_service';
47848
+
47849
+ function fakeProjectModel(rows: any[]) {
47850
+ const query: any = {
47851
+ where() {
47852
+ return query;
47853
+ },
47854
+ field() {
47855
+ return query;
47856
+ },
47857
+ page() {
47858
+ return query;
47859
+ },
47860
+ order() {
47861
+ return query;
47862
+ },
47863
+ countSelect: async () => ({ count: rows.length, data: rows }),
47864
+ find: async () => rows[0] || {},
47865
+ };
47866
+ return { model: query };
47867
+ }
47868
+
47869
+ function fakeItemModel() {
47870
+ const calls: any[] = [];
47871
+ let transactionCount = 0;
47872
+ const model: any = {
47873
+ transaction: async (run: () => Promise<any>) => {
47874
+ transactionCount += 1;
47875
+ return run();
47876
+ },
47877
+ add: async (payload: any) => {
47878
+ calls.push(payload);
47879
+ return 123;
47880
+ },
47881
+ };
47882
+ return {
47883
+ model,
47884
+ calls,
47885
+ get transactionCount() {
47886
+ return transactionCount;
47887
+ },
47888
+ };
47889
+ }
47890
+
47891
+ describe('normalizePaging \u5206\u9875\u5F52\u4E00\u5316', () => {
47892
+ it('\u7F3A\u7701 page=1\u3001pageSize=20\u3001offset=0', () => {
47893
+ expect(normalizePaging({})).toEqual({ page: 1, pageSize: 20, offset: 0 });
47894
+ });
47895
+
47896
+ it('pageSize \u8D85\u8FC7\u4E0A\u9650\u65F6\u622A\u65AD\u4E3A 100', () => {
47897
+ expect(normalizePaging({ page: 2, pageSize: 5000 })).toEqual({
47898
+ page: 2,
47899
+ pageSize: MAX_PAGE_SIZE,
47900
+ offset: MAX_PAGE_SIZE,
47901
+ });
47902
+ });
47903
+
47904
+ it('\u975E\u6CD5 page/pageSize \u8FD4\u56DE PLUGIN_INVALID_PAGING', () => {
47905
+ for (const input of [{ page: 0 }, { page: -1 }, { page: 'abc' }, { pageSize: 0 }]) {
47906
+ try {
47907
+ normalizePaging(input);
47908
+ throw new Error('expected normalizePaging to throw');
47909
+ } catch (error) {
47910
+ expect(toErrorDetail(error).code).toBe('PLUGIN_INVALID_PAGING');
47911
+ }
47912
+ }
47913
+ });
47914
+ });
47915
+
47916
+ describe('PluginService \u4E1A\u52A1\u884C\u4E3A', () => {
47917
+ it('listProjects \u8FD4\u56DE\u5206\u9875\u7ED3\u6784\u4E0E\u771F\u5B9E\u6570\u636E', async () => {
47918
+ const project = fakeProjectModel([{ id: 1, name: '\u793A\u4F8B\u9879\u76EE' }]);
47919
+ const service = new PluginService({ projectModel: project.model });
47920
+ const result = await service.listProjects({ page: 1, pageSize: 5000 });
47921
+ expect(result).toEqual({
47922
+ ok: true,
47923
+ data: { list: [{ id: 1, name: '\u793A\u4F8B\u9879\u76EE' }], total: 1, page: 1, pageSize: MAX_PAGE_SIZE },
47924
+ });
47925
+ });
47926
+
47927
+ it('listProjects \u975E\u6CD5\u5206\u9875\u8FD4\u56DE\u7ED3\u6784\u5316\u9519\u8BEF\u800C\u4E0D\u662F\u629B\u88F8 Error', async () => {
47928
+ const service = new PluginService({ projectModel: fakeProjectModel([]).model });
47929
+ const result = await service.listProjects({ page: 0 });
47930
+ expect(result.ok).toBe(false);
47931
+ expect(result.ok ? '' : result.error.code).toBe('PLUGIN_INVALID_PAGING');
47932
+ });
47933
+
47934
+ it('getProject \u53C2\u6570\u975E\u6CD5\u8FD4\u56DE PLUGIN_INVALID_ARGUMENT', async () => {
47935
+ const service = new PluginService({ projectModel: fakeProjectModel([]).model });
47936
+ const result = await service.getProject('abc');
47937
+ expect(result.ok).toBe(false);
47938
+ expect(result.ok ? '' : result.error.code).toBe('PLUGIN_INVALID_ARGUMENT');
47939
+ });
47940
+
47941
+ it('getProject \u67E5\u4E0D\u5230\u65F6\u8FD4\u56DE 404 PLUGIN_NOT_FOUND', async () => {
47942
+ const service = new PluginService({ projectModel: fakeProjectModel([]).model });
47943
+ const result = await service.getProject(999);
47944
+ expect(result.ok).toBe(false);
47945
+ if (!result.ok) {
47946
+ expect(result.error.code).toBe('PLUGIN_NOT_FOUND');
47947
+ expect(result.error.status).toBe(404);
47948
+ }
47949
+ });
47950
+ ${createItemTests}});
47951
+ `;
47952
+ }
46732
47953
  function renderServerTest(answers) {
46733
- return `describe(${js2(`plugin_${answers.en_name} scaffold`)}, () => {
47954
+ if (answers.capabilities.backend_api) {
47955
+ return renderServiceTest(answers);
47956
+ }
47957
+ return `describe(${js3(`${answers.en_name} scaffold`)}, () => {
46734
47958
  it('loads', () => {
46735
47959
  expect(1 + 1).toBe(2);
46736
47960
  });
@@ -46739,35 +47963,52 @@ function renderServerTest(answers) {
46739
47963
  }
46740
47964
  function renderServerFiles(answers) {
46741
47965
  const en = answers.en_name;
46742
- const base = `20260101000000-create-plugin-${en}`;
47966
+ const initBase = `20260101000000-init-${en}`;
47967
+ const tableBase = `20260101000100-create-${en}`;
47968
+ const testPath = answers.capabilities.backend_api ? `server/test/${en}_service.test.ts` : `server/test/${en}.test.ts`;
46743
47969
  const files = [
46744
47970
  { path: "server/package.json", content: renderPackageJson2(answers) },
46745
47971
  { path: "server/.babelrc", content: renderBabelrc() },
46746
47972
  { path: "server/.db-migraterc", content: renderDbMigrateRc() },
46747
47973
  { path: "server/config/database.json", content: renderDatabaseConfig() },
47974
+ // 平台按 `plugin_${pluginName}_install.js` / `plugin_${pluginName}_uninstall.js`
47975
+ // 解析钩子,pluginName 就是 en_name(已带 `plugin_`)。因此这里的文件名必须是
47976
+ // 双前缀的 `plugin_plugin_x_install.ts`;其余 controller/service/路由/权限点/
47977
+ // 表名仍保持单前缀。详见 docs 里「钩子文件名」说明。
46748
47978
  { path: `server/src/install/plugin_${en}_install.ts`, content: renderInstall(answers) },
46749
47979
  { path: `server/src/install/plugin_${en}_uninstall.ts`, content: renderUninstall(answers) },
46750
- { path: `server/test/plugin_${en}.test.ts`, content: renderServerTest(answers) },
47980
+ { path: testPath, content: renderServerTest(answers) },
46751
47981
  {
46752
47982
  path: "test/README.md",
46753
47983
  content: "\u5E73\u53F0 jest \u53EA\u5339\u914D `server/test/**/*.test.ts`\uFF0C\u670D\u52A1\u7AEF\u6D4B\u8BD5\u9AA8\u67B6\u5DF2\u653E\u5728 `server/test/`\uFF1B\u6839\u76EE\u5F55 `test/` \u4EC5\u4FDD\u7559\u7ED9\u4E0D\u7ECF\u8FC7\u5E73\u53F0\u6D4B\u8BD5\u8FD0\u884C\u5668\u7684\u4E34\u65F6\u811A\u672C\u3002\n"
46754
47984
  }
46755
47985
  ];
46756
47986
  if (answers.capabilities.backend_api) {
46757
- files.push({ path: `server/src/controller/api/plugin_${en}.ts`, content: renderController(answers) });
46758
- files.push({ path: `server/src/service/plugin_${en}_service.ts`, content: renderService(answers) });
47987
+ files.push({ path: `server/src/controller/api/${en}.ts`, content: renderController(answers) });
47988
+ files.push({ path: `server/src/service/${en}_service.ts`, content: renderService(answers) });
47989
+ files.push({ path: `server/src/service/${en}_errors.ts`, content: renderErrors(answers) });
46759
47990
  }
47991
+ files.push(...renderPermissionFiles(answers));
47992
+ files.push({
47993
+ path: `server/migrations/sqls/${initBase}-up.sql`,
47994
+ content: renderInitMigrationUp(answers)
47995
+ });
47996
+ files.push({
47997
+ path: `server/migrations/sqls/${initBase}-down.sql`,
47998
+ content: renderInitMigrationDown(answers)
47999
+ });
48000
+ files.push({ path: `server/migrations/${initBase}.js`, content: renderMigrationJs(initBase) });
46760
48001
  if (answers.capabilities.database_table) {
46761
- files.push({ path: `server/src/model/plugin_${en}_model.ts`, content: renderModel(answers) });
46762
- files.push({ path: `server/migrations/sqls/${base}-up.sql`, content: renderMigrationUp(answers) });
46763
- files.push({ path: `server/migrations/sqls/${base}-down.sql`, content: renderMigrationDown(answers) });
46764
- files.push({ path: `server/migrations/${base}.js`, content: renderMigrationJs(base) });
48002
+ files.push({ path: `server/src/model/${en}_model.ts`, content: renderModel(answers) });
48003
+ files.push({ path: `server/migrations/sqls/${tableBase}-up.sql`, content: renderMigrationUp(answers) });
48004
+ files.push({ path: `server/migrations/sqls/${tableBase}-down.sql`, content: renderMigrationDown(answers) });
48005
+ files.push({ path: `server/migrations/${tableBase}.js`, content: renderMigrationJs(tableBase) });
46765
48006
  }
46766
48007
  if (answers.capabilities.cron_job) {
46767
- files.push({ path: `server/src/config/crontab_job/plugin_${en}_job.ts`, content: renderCronJob(answers) });
48008
+ files.push({ path: `server/src/config/crontab_job/${en}_job.ts`, content: renderCronJob(answers) });
46768
48009
  }
46769
48010
  if (answers.capabilities.flow_hook) {
46770
- files.push({ path: `server/src/bootstrap/hooks/plugin_${en}_hook.ts`, content: renderHook(answers) });
48011
+ files.push({ path: `server/src/bootstrap/hooks/${en}_hook.ts`, content: renderHook(answers) });
46771
48012
  }
46772
48013
  return files;
46773
48014
  }
@@ -46789,8 +48030,8 @@ function callInstructions(answers) {
46789
48030
  const lines = [];
46790
48031
  if (answers.capabilities.backend_api) {
46791
48032
  lines.push(
46792
- `- \u540E\u7AEF\u63A5\u53E3\uFF1A\u8C03\u7528\u63D2\u4EF6\u670D\u52A1\u7AEF controller \`plugin_${answers.en_name}\`\uFF08\`server/src/controller/api/plugin_${answers.en_name}.ts\`\uFF09\u7684 \`indexAction\`\uFF0C\u8FD4\u56DE \`{ "plugin": "${answers.en_name}" }\`\u3002`,
46793
- `- \u63D2\u4EF6\u670D\u52A1\uFF1A\u4E1A\u52A1\u903B\u8F91\u5199\u5728 \`server/src/service/plugin_${answers.en_name}_service.ts\`\uFF0C\u65B0\u589E\u63A5\u53E3\u590D\u7528\u540C\u4E00\u4E2A service\uFF0C\u4E0D\u8981\u5728 controller \u91CC\u76F4\u63A5\u62FC SQL\u3002`
48033
+ `- \u540E\u7AEF\u63A5\u53E3\uFF1A\u8C03\u7528\u63D2\u4EF6\u670D\u52A1\u7AEF controller \`${answers.en_name}\`\uFF08\`server/src/controller/api/${answers.en_name}.ts\`\uFF09\u7684 \`GET /api/${answers.en_name}/projects\`\uFF08\u5217\u8868\uFF09\u4E0E \`GET /api/${answers.en_name}/projects/:id\`\uFF08\u8BE6\u60C5\uFF09\uFF0C\u8FD4\u56DE \`{ list, total, page, pageSize }\` / \u5355\u6761\u9879\u76EE\u3002`,
48034
+ `- \u63D2\u4EF6\u670D\u52A1\uFF1A\u4E1A\u52A1\u903B\u8F91\u5199\u5728 \`server/src/service/${answers.en_name}_service.ts\`\uFF0C\u65B0\u589E\u63A5\u53E3\u590D\u7528\u540C\u4E00\u4E2A service\uFF0C\u4E0D\u8981\u5728 controller \u91CC\u76F4\u63A5\u62FC SQL\u3002`
46794
48035
  );
46795
48036
  } else {
46796
48037
  lines.push(
@@ -46807,12 +48048,12 @@ function callInstructions(answers) {
46807
48048
  }
46808
48049
  if (answers.capabilities.cron_job) {
46809
48050
  lines.push(
46810
- `- \u5B9A\u65F6\u4EFB\u52A1\uFF1A\`server/src/config/crontab_job/plugin_${answers.en_name}_job.ts\` \u7531\u5E73\u53F0\u6309\u8BA1\u5212\u89E6\u53D1\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5\u8C03\u7528\u3002`
48051
+ `- \u5B9A\u65F6\u4EFB\u52A1\uFF1A\`server/src/config/crontab_job/${answers.en_name}_job.ts\` \u7531\u5E73\u53F0\u6309\u8BA1\u5212\u89E6\u53D1\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5\u8C03\u7528\u3002`
46811
48052
  );
46812
48053
  }
46813
48054
  if (answers.capabilities.flow_hook) {
46814
48055
  lines.push(
46815
- `- \u6D41\u7A0B\u94A9\u5B50\uFF1A\`server/src/bootstrap/hooks/plugin_${answers.en_name}_hook.ts\` \u5728\u5BA1\u6279\u6D41\u7A0B\u8282\u70B9\u4E0A\u81EA\u52A8\u89E6\u53D1\uFF0C\u4E0D\u8981\u7ED5\u5F00\u6D41\u7A0B\u624B\u5DE5\u6539\u72B6\u6001\u3002`
48056
+ `- \u6D41\u7A0B\u94A9\u5B50\uFF1A\`server/src/bootstrap/hooks/${answers.en_name}_hook.ts\` \u5728\u5BA1\u6279\u6D41\u7A0B\u8282\u70B9\u4E0A\u81EA\u52A8\u89E6\u53D1\uFF0C\u4E0D\u8981\u7ED5\u5F00\u6D41\u7A0B\u624B\u5DE5\u6539\u72B6\u6001\u3002`
46816
48057
  );
46817
48058
  }
46818
48059
  if (lines.length === 0) {
@@ -46830,7 +48071,7 @@ function forbiddenLines(answers) {
46830
48071
  ];
46831
48072
  if (answers.capabilities.database_table) {
46832
48073
  lines.push(
46833
- `- \u4E0D\u5F97\u76F4\u63A5\u6539\u52A8 \`plugin_${answers.en_name}\` \u8868\u7ED3\u6784\uFF1B\u8868\u7ED3\u6784\u53D8\u66F4\u5FC5\u987B\u901A\u8FC7 \`server/migrations/\` \u8FC1\u79FB\u5B8C\u6210\u3002`
48074
+ `- \u4E0D\u5F97\u76F4\u63A5\u6539\u52A8 \`${answers.en_name}\` \u8868\u7ED3\u6784\uFF1B\u8868\u7ED3\u6784\u53D8\u66F4\u5FC5\u987B\u901A\u8FC7 \`server/migrations/\` \u8FC1\u79FB\u5B8C\u6210\u3002`
46834
48075
  );
46835
48076
  }
46836
48077
  return lines;
@@ -47042,7 +48283,7 @@ async function shouldIntroduceGit(rootDir) {
47042
48283
  async function previewPluginDir(input) {
47043
48284
  const rootDir = await canonicalPath(resolve3(input.rootDir));
47044
48285
  const target = await resolveGitTarget(
47045
- { rootDir, enName: input.enName, enabled: input.git !== false },
48286
+ { rootDir, enName: normalizePluginEnName(input.enName), enabled: input.git !== false },
47046
48287
  false
47047
48288
  );
47048
48289
  return target.targetDir;
@@ -47123,18 +48364,18 @@ async function requiredEnName(prompter, initialValue) {
47123
48364
  const answer = ensureValue2(
47124
48365
  prompter,
47125
48366
  await prompter.text({
47126
- message: "\u63D2\u4EF6\u82F1\u6587\u6807\u8BC6 en_name\uFF08\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\uFF09",
48367
+ message: "\u63D2\u4EF6\u82F1\u6587\u6807\u8BC6 en_name\uFF08\u4EE5 plugin_ \u5F00\u5934\uFF1B\u6F0F\u5199\u4F1A\u81EA\u52A8\u8865\uFF0C\u53EA\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\uFF09",
47127
48368
  placeholder: "plugin_demo",
47128
48369
  initialValue: fallback,
47129
48370
  validate: (value) => {
47130
- const candidate2 = (value ?? "").trim();
47131
- if (!candidate2) return "en_name \u4E3A\u5FC5\u7B54\u9879";
48371
+ const candidate2 = normalizePluginEnName(value ?? "");
48372
+ if (!candidate2 || candidate2 === "plugin_") return "en_name \u4E3A\u5FC5\u7B54\u9879";
47132
48373
  return EN_NAME_PATTERN.test(candidate2) ? void 0 : "\u5FC5\u987B\u5339\u914D /^[A-Za-z][A-Za-z0-9_]*$/";
47133
48374
  }
47134
48375
  })
47135
48376
  );
47136
- const candidate = answer.trim();
47137
- if (EN_NAME_PATTERN.test(candidate)) return candidate;
48377
+ const candidate = normalizePluginEnName(answer);
48378
+ if (candidate !== "plugin_" && EN_NAME_PATTERN.test(candidate)) return candidate;
47138
48379
  fallback = void 0;
47139
48380
  }
47140
48381
  }
@@ -48229,19 +49470,34 @@ function normalizeActivationOverview(value) {
48229
49470
  ...plugin,
48230
49471
  en_name: String(plugin.en_name || "").trim(),
48231
49472
  default_active: plugin.default_active === true,
48232
- active_workspaces: stringArray(plugin.active_workspaces)
49473
+ active_workspaces: stringArray(plugin.active_workspaces).filter((workspace) => workspace.trim() !== "")
48233
49474
  })).filter((plugin) => plugin.en_name) : [];
48234
- const workspaces = Array.isArray(source.workspaces) ? source.workspaces.map(record2).map((workspace) => ({
48235
- ...workspace,
48236
- key: String(workspace.key || "").trim(),
48237
- active_plugins: stringArray(workspace.active_plugins)
48238
- })).filter((workspace) => workspace.key) : [];
49475
+ const workspaceByKey = /* @__PURE__ */ new Map();
49476
+ for (const item of source.workspaces) {
49477
+ const candidate = record2(item);
49478
+ const key = String(candidate.key || "").trim();
49479
+ if (!key) continue;
49480
+ const existing = workspaceByKey.get(key);
49481
+ if (existing) {
49482
+ const incomingPlugins = stringArray(candidate.active_plugins);
49483
+ if (!sameStrings(existing.active_plugins, incomingPlugins)) {
49484
+ process.stderr.write(
49485
+ `[warn] plugin.activation.duplicate_workspace: \u91CD\u590D\u5DE5\u4F5C\u533A key "${key}" \u7684 active_plugins \u4E0E\u9996\u6761\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u5FFD\u7565\u540E\u8005\uFF08${incomingPlugins.join(",") || "\u7A7A"}\uFF09\uFF0C\u4FDD\u7559\u9996\u6761\uFF08${existing.active_plugins.join(",") || "\u7A7A"}\uFF09\u3002
49486
+ `
49487
+ );
49488
+ }
49489
+ continue;
49490
+ }
49491
+ workspaceByKey.set(key, {
49492
+ ...candidate,
49493
+ key,
49494
+ active_plugins: stringArray(candidate.active_plugins)
49495
+ });
49496
+ }
49497
+ const workspaces = [...workspaceByKey.values()];
48239
49498
  if (plugins.length !== source.plugins.length || new Set(plugins.map((plugin) => plugin.en_name)).size !== plugins.length) {
48240
49499
  throw new Error("plugin.activation.invalid_readback: plugins \u5305\u542B\u7A7A\u6216\u91CD\u590D en_name\u3002");
48241
49500
  }
48242
- if (workspaces.length !== source.workspaces.length || new Set(workspaces.map((workspace) => workspace.key)).size !== workspaces.length) {
48243
- throw new Error("plugin.activation.invalid_readback: workspaces \u5305\u542B\u7A7A\u6216\u91CD\u590D key\u3002");
48244
- }
48245
49501
  const installed = new Set(plugins.map((plugin) => plugin.en_name));
48246
49502
  const workspaceKeys = new Set(workspaces.map((workspace) => workspace.key));
48247
49503
  const defaultPlugins = stringArray(source.default_plugins);
@@ -48249,7 +49505,7 @@ function normalizeActivationOverview(value) {
48249
49505
  ...defaultPlugins,
48250
49506
  ...workspaces.flatMap((workspace) => workspace.active_plugins)
48251
49507
  ].filter((pluginName) => !installed.has(pluginName));
48252
- const invalidWorkspaceRefs = plugins.flatMap((plugin) => plugin.active_workspaces).filter((workspace) => !workspaceKeys.has(workspace));
49508
+ const invalidWorkspaceRefs = plugins.flatMap((plugin) => plugin.active_workspaces).filter((workspace) => workspace && !workspaceKeys.has(workspace));
48253
49509
  if (invalidPluginRefs.length || invalidWorkspaceRefs.length) {
48254
49510
  throw new Error("plugin.activation.invalid_readback: overview \u542B\u672A\u5B89\u88C5\u63D2\u4EF6\u6216\u4E0D\u5B58\u5728\u5DE5\u4F5C\u533A\u7684\u6FC0\u6D3B\u5F15\u7528\u3002");
48255
49511
  }
@@ -48350,6 +49606,61 @@ async function submitActivationMutation(client, profileName, data, verify) {
48350
49606
  retry_guidance: submitError ? "\u63D0\u4EA4\u548C\u56DE\u8BFB\u5747\u5931\u8D25\uFF0C\u7ED3\u679C\u672A\u77E5\u3002\u6062\u590D\u53EA\u8BFB\u8BBF\u95EE\u540E\u5148\u6267\u884C overview\uFF1B\u4E0D\u5F97\u76F4\u63A5\u91CD\u8BD5\u5199\u5165\u3002" : "\u63D0\u4EA4\u5DF2\u53D1\u9001\u4F46\u56DE\u8BFB\u5931\u8D25\u3002\u6062\u590D\u53EA\u8BFB\u8BBF\u95EE\u540E\u5148\u6267\u884C overview\uFF1B\u4E0D\u5F97\u518D\u6B21\u63D0\u4EA4\u3002"
48351
49607
  };
48352
49608
  }
49609
+ function installationActivationHint(profileName, pluginName) {
49610
+ return `bpmax-cli plugin activation workspace set --workspace WORKSPACE_KEY --plugin ${pluginName} --confirm --profile ${profileName}`;
49611
+ }
49612
+ async function activateInstalledPlugin(client, profileName, workspaceKey, pluginName) {
49613
+ let before;
49614
+ try {
49615
+ before = await readActivationOverview(client);
49616
+ } catch (error) {
49617
+ return {
49618
+ ok: false,
49619
+ status: "activation_overview_failed",
49620
+ error: errorMessage6(error),
49621
+ retry_guidance: "\u5B89\u88C5\u5DF2\u6210\u529F\u4F46\u65E0\u6CD5\u8BFB\u53D6\u6FC0\u6D3B\u72B6\u6001\uFF1B\u5148\u6267\u884C activation overview \u6838\u5BF9\uFF0C\u518D\u624B\u52A8\u6FC0\u6D3B\u3002"
49622
+ };
49623
+ }
49624
+ let targets;
49625
+ try {
49626
+ targets = validateActivationTargets(before, { plugins: [pluginName], workspaces: [workspaceKey] });
49627
+ } catch (error) {
49628
+ return {
49629
+ ok: false,
49630
+ status: "activation_target_invalid",
49631
+ error: errorMessage6(error),
49632
+ retry_guidance: "\u5B89\u88C5\u5DF2\u6210\u529F\u4F46\u6FC0\u6D3B\u76EE\u6807\u4E0D\u5B58\u5728\u6216\u63D2\u4EF6\u672A\u51FA\u73B0\u5728\u5B89\u88C5\u5217\u8868\uFF1B\u6838\u5BF9 workspace key \u4E0E\u63D2\u4EF6\u540D\u540E\u91CD\u8BD5\u6FC0\u6D3B\u3002"
49633
+ };
49634
+ }
49635
+ const workspace = targets.workspaces[0];
49636
+ const current = before.workspaces.find((item) => item.key === workspace)?.active_plugins || [];
49637
+ if (current.includes(pluginName)) {
49638
+ return {
49639
+ ok: true,
49640
+ status: "already_active",
49641
+ workspace,
49642
+ plugin: pluginName,
49643
+ remote_submitted: false,
49644
+ readback_confirmed: true,
49645
+ actual_effective_plugins: uniqueSorted([...current, ...before.default_plugins])
49646
+ };
49647
+ }
49648
+ const requested = uniqueSorted([...current, pluginName]);
49649
+ const expected = uniqueSorted([...requested, ...before.default_plugins]);
49650
+ const result = await submitActivationMutation(
49651
+ client,
49652
+ profileName,
49653
+ { action: "set_workspace_plugins", workspace_key: workspace, plugin_names: requested },
49654
+ (after) => {
49655
+ const actual = after.workspaces.find((item) => item.key === workspace)?.active_plugins || [];
49656
+ return {
49657
+ verified: sameStrings(actual, expected),
49658
+ details: { actual_effective_plugins: actual }
49659
+ };
49660
+ }
49661
+ );
49662
+ return { ...result, workspace, plugin: pluginName, expected_effective_plugins: expected };
49663
+ }
48353
49664
  function defaultAgent2(options) {
48354
49665
  return options.agent || process.env.BPMAX_CLI_AGENT || "codex";
48355
49666
  }
@@ -48369,7 +49680,7 @@ function registerPluginCommands(program2) {
48369
49680
  return;
48370
49681
  }
48371
49682
  const fileSources = options.from ? await readAnswerSourcesFile(resolve4(options.from)) : void 0;
48372
- if (enName && fileSources?.en_name && enName.trim() !== fileSources.en_name) {
49683
+ if (enName && fileSources?.en_name && normalizePluginEnName(enName) !== normalizePluginEnName(fileSources.en_name)) {
48373
49684
  throw new Error(
48374
49685
  `plugin.create.en_name_conflict: \u4F4D\u7F6E\u53C2\u6570 ${enName} \u4E0E answers.json \u7684 en_name ${fileSources.en_name} \u4E0D\u4E00\u81F4\u3002`
48375
49686
  );
@@ -48811,7 +50122,7 @@ function registerPluginCommands(program2) {
48811
50122
  process.exitCode = 1;
48812
50123
  }
48813
50124
  });
48814
- plugin.command("install <zip>").description("Upload, register, restart, and read back one plugin zip on a remote environment").option("--dry-run", "Print the full install plan and target environment without changing anything").option("--yes", "Skip the interactive confirmation (required in non-interactive shells)").option("--profile <profile>", "Profile name").option("--target <profile>", "Alias for --profile").option("--timeout <seconds>", "Install and restart step timeout seconds", "30").option("--format <format>", "Output format", "json").action(async (zipPath, options) => {
50125
+ plugin.command("install <zip>").description("Upload, register, restart, and read back one plugin zip on a remote environment").option("--dry-run", "Print the full install plan and target environment without changing anything").option("--yes", "Skip the interactive confirmation (required in non-interactive shells)").option("--profile <profile>", "Profile name").option("--target <profile>", "Alias for --profile").option("--activate <workspace>", "After a successful install, activate the plugin in this workspace key and read back the effective plugin list").option("--timeout <seconds>", "Install and restart step timeout seconds", "30").option("--format <format>", "Output format", "json").action(async (zipPath, options) => {
48815
50126
  const seconds = Number(options.timeout);
48816
50127
  if (!Number.isFinite(seconds) || seconds <= 0) {
48817
50128
  throw new Error("--timeout must be a positive number of seconds.");
@@ -48819,6 +50130,17 @@ function registerPluginCommands(program2) {
48819
50130
  const profile = resolveProfile(await loadConfig(), options.profile || options.target);
48820
50131
  const buffer = await readFile31(resolve4(zipPath));
48821
50132
  const manifest = await readPluginManifestFromZip(buffer);
50133
+ const validationWarnings = [];
50134
+ let zipFiles = null;
50135
+ let zipMigrations = null;
50136
+ try {
50137
+ const inspection = await inspectPluginZip(buffer);
50138
+ zipFiles = inspection.files;
50139
+ zipMigrations = inspection.migrations;
50140
+ } catch (error) {
50141
+ validationWarnings.push(errorMessage6(error));
50142
+ }
50143
+ const activationWorkspace = options.activate?.trim();
48822
50144
  const timeouts = {
48823
50145
  ...DEFAULT_INSTALL_TIMEOUTS,
48824
50146
  installMs: seconds * 1e3,
@@ -48837,7 +50159,9 @@ function registerPluginCommands(program2) {
48837
50159
  beforeError = error instanceof Error ? error.message : String(error);
48838
50160
  }
48839
50161
  const plan = {
48840
- ok: true,
50162
+ // 校验失败时 ok 必须同步为 false,自动化调用才能据此判断不可安装;
50163
+ // dry-run 仍正常退出(不设置 exitCode),由调用方读取 ok/validation。
50164
+ ok: validationWarnings.length === 0,
48841
50165
  action: "plugin_install",
48842
50166
  status: options.dryRun ? "dry_run" : "confirm_required",
48843
50167
  profile: profile.name,
@@ -48847,12 +50171,26 @@ function registerPluginCommands(program2) {
48847
50171
  target_version: manifest.version,
48848
50172
  before_version: beforeVersion,
48849
50173
  before_error: beforeError,
50174
+ activate_workspace: activationWorkspace || null,
50175
+ zip_files: zipFiles,
50176
+ zip_migrations: zipMigrations,
50177
+ validation: {
50178
+ ok: validationWarnings.length === 0,
50179
+ warnings: validationWarnings
50180
+ },
50181
+ warnings: validationWarnings,
48850
50182
  steps: [
50183
+ "inspect zip: require config.json + migrations/*.js at zip root",
48851
50184
  "POST /api/upload (multipart field=file)",
48852
50185
  "POST /api/plugin/upload {installZipUrl: <origin> + <upload path>}",
48853
50186
  "PUT /api/plugin/restart",
48854
50187
  "GET /api/dict (poll until alive)",
48855
- "GET /api/plugin/all (read back version)"
50188
+ "GET /api/plugin/all (read back version)",
50189
+ ...activationWorkspace ? [
50190
+ `GET /api/plugin/activation_overview (resolve workspace ${activationWorkspace})`,
50191
+ "PUT /api/plugin/activation {action: set_workspace_plugins}",
50192
+ "GET /api/plugin/activation_overview (read back effective plugins)"
50193
+ ] : []
48856
50194
  ],
48857
50195
  remote_submitted: false
48858
50196
  };
@@ -48890,14 +50228,52 @@ function registerPluginCommands(program2) {
48890
50228
  beforeVersion,
48891
50229
  timeouts
48892
50230
  });
48893
- printResult(options.format, { ...plan, ...result });
48894
50231
  if (!result.ok) {
50232
+ printResult(options.format, {
50233
+ ...plan,
50234
+ ...result,
50235
+ activation_hint: activationWorkspace ? void 0 : installationActivationHint(profile.name, manifest.en_name)
50236
+ });
48895
50237
  process.exitCode = 1;
50238
+ return;
48896
50239
  }
50240
+ if (!activationWorkspace) {
50241
+ printResult(options.format, {
50242
+ ...plan,
50243
+ ...result,
50244
+ activated_workspaces: [],
50245
+ activation_hint: installationActivationHint(profile.name, manifest.en_name),
50246
+ activation_notice: "\u5B89\u88C5\u6210\u529F\uFF0C\u4F46\u5C1A\u672A\u6FC0\u6D3B\uFF1B\u9700\u5728\u76EE\u6807\u5DE5\u4F5C\u533A\u6FC0\u6D3B\u540E\u83DC\u5355\u4E0E\u63A5\u53E3\u624D\u4F1A\u751F\u6548\u3002"
50247
+ });
50248
+ return;
50249
+ }
50250
+ const activation2 = await activateInstalledPlugin(
50251
+ createApiClient(profile),
50252
+ profile.name,
50253
+ activationWorkspace,
50254
+ manifest.en_name
50255
+ );
50256
+ const activationOk = activation2.ok === true;
50257
+ printResult(options.format, {
50258
+ ...plan,
50259
+ ...result,
50260
+ // 安装已成功,不因激活失败回滚;但整体不能按全成功返回。
50261
+ ok: activationOk,
50262
+ status: activationOk ? result.status : "installed_activate_failed",
50263
+ install_ok: true,
50264
+ activation_ok: activationOk,
50265
+ activated_workspaces: activationOk ? [activationWorkspace] : [],
50266
+ activation: activation2,
50267
+ ...activationOk ? {} : {
50268
+ activation_error: activation2.error || activation2.status,
50269
+ retry_guidance: `\u5B89\u88C5\u5DF2\u6210\u529F\u3001\u6FC0\u6D3B\u5931\u8D25\uFF0C\u672A\u56DE\u6EDA\u3002\u4FEE\u590D\u540E\u53EF\u6267\u884C\uFF1A` + installationActivationHint(profile.name, manifest.en_name)
50270
+ }
50271
+ });
50272
+ if (!activationOk) process.exitCode = 1;
48897
50273
  });
48898
50274
  plugin.command("logs").description(
48899
50275
  "Query remote test-environment logs. Plugin filtering is message-text only: plugin code runs inside huanpingtong-server, so there is no structured fields.plugin. Requires KIBANA_USERNAME and KIBANA_PASSWORD environment variables (never stored in the repo)."
48900
- ).option("--plugin <en_name>", "Filter by plugin_<en_name> text inside the log message").option("--env <env>", "Environment alias, e.g. test, shitoutest, yuanrongtest", "test").option("--since <since>", "Lower time bound", "now-30m").option("--until <until>", "Upper time bound").option("--grep <text>", "Required message text, repeatable", collect2, []).option("--trace <trace>", "Trace id or request id").option("--app <app>", "Application name for fields.app, e.g. huanpingtong").option("--level <level>", "Level-like text filter, repeatable", collect2, []).option("--size <n>", "Number of hits", "20").option("--json", "Print the raw JSON result").option("--timeout <seconds>", "Kibana request timeout seconds", "30").option("--script <path>", "Override the query_kibana_logs.py path").action(async (options) => {
50276
+ ).option("--plugin <en_name>", "Filter by <en_name> text inside the log message").option("--env <env>", "Environment alias, e.g. test, shitoutest, yuanrongtest", "test").option("--since <since>", "Lower time bound", "now-30m").option("--until <until>", "Upper time bound").option("--grep <text>", "Required message text, repeatable", collect2, []).option("--trace <trace>", "Trace id or request id").option("--app <app>", "Application name for fields.app, e.g. huanpingtong").option("--level <level>", "Level-like text filter, repeatable", collect2, []).option("--size <n>", "Number of hits", "20").option("--json", "Print the raw JSON result").option("--timeout <seconds>", "Kibana request timeout seconds", "30").option("--script <path>", "Override the query_kibana_logs.py path").action(async (options) => {
48901
50277
  const size = Number(options.size);
48902
50278
  if (!Number.isInteger(size) || size <= 0) {
48903
50279
  throw new Error("invalid_size: --size \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002");
@@ -54664,6 +56040,8 @@ var WHATS_NEW_ENTRIES = [
54664
56040
  "\u7528 CLI \u5B8C\u6210\u63D2\u4EF6\u5168\u6D41\u7A0B\uFF1Abpmax-cli plugin create / build / dev / test",
54665
56041
  "\u65B0\u589E\u63D2\u4EF6\u9759\u6001\u68C0\u67E5\uFF1Abpmax-cli plugin lint",
54666
56042
  "\u88C5\u5230\u73AF\u5883\u5E76\u56DE\u8BFB\u7ED3\u679C\uFF1Abpmax-cli plugin install\uFF0C\u8FDC\u7AEF\u65E5\u5FD7\u7528 bpmax-cli plugin logs \u67E5\u770B",
56043
+ "\u5B89\u88C5\u540E\u76F4\u63A5\u751F\u6548\uFF1Abpmax-cli plugin install <zip> --activate <workspace> \u81EA\u52A8\u6FC0\u6D3B\u5230\u76EE\u6807\u5DE5\u4F5C\u533A",
56044
+ "\u6240\u6709\u63D2\u4EF6\u81EA\u5E26\u6700\u5C0F\u6570\u636E\u5E93\u8FC1\u79FB\uFF0C\u7F3A\u8FC1\u79FB\u4F1A\u5728 build / install \u524D\u62E6\u4E0B",
54667
56045
  "\u63D2\u4EF6\u5F00\u53D1 Skill \u968F\u63D2\u4EF6\u4E0B\u53D1\uFF1Abpmax-cli plugin skills list\u3001bpmax-cli plugin skills check"
54668
56046
  ]
54669
56047
  }