@lark-apaas/fullstack-cli 1.1.71-alpha.20261103110320 → 1.1.71-alpha.20261103133134

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1330 -956
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/index.ts
2
- import fs32 from "fs";
3
- import path27 from "path";
2
+ import fs36 from "fs";
3
+ import path31 from "path";
4
4
  import { fileURLToPath as fileURLToPath5 } from "url";
5
5
  import { config as dotenvConfig } from "dotenv";
6
6
 
@@ -2478,8 +2478,8 @@ var genDbSchemaCommand = {
2478
2478
  };
2479
2479
 
2480
2480
  // src/commands/sync/run.handler.ts
2481
- import path6 from "path";
2482
- import fs9 from "fs";
2481
+ import path7 from "path";
2482
+ import fs10 from "fs";
2483
2483
  import { fileURLToPath as fileURLToPath3 } from "url";
2484
2484
 
2485
2485
  // src/config/sync.ts
@@ -2549,10 +2549,7 @@ function buildDefaultRules(opts) {
2549
2549
  },
2550
2550
  // 5. 注册 postinstall 脚本,自动恢复 action plugins
2551
2551
  {
2552
- type: "add-script",
2553
- name: "postinstall",
2554
- command: "fullstack-cli action-plugin init",
2555
- overwrite: false
2552
+ type: "action-plugin-lifecycle"
2556
2553
  },
2557
2554
  // 6. 替换 drizzle.config.ts(仅当文件存在时)
2558
2555
  {
@@ -2803,18 +2800,80 @@ function isNestjsProject(root, stack) {
2803
2800
  }
2804
2801
  }
2805
2802
 
2803
+ // src/commands/action-plugin/lifecycle.ts
2804
+ import fs9 from "fs";
2805
+ import path6 from "path";
2806
+ var ACTION_PLUGIN_RESTORE_COMMAND = "fullstack-cli action-plugin restore";
2807
+ var LEGACY_ACTION_PLUGIN_INIT_COMMAND = "fullstack-cli action-plugin init";
2808
+ var ACTION_PLUGIN_REENTRY_ENV = "FULLSTACK_CLI_ACTION_PLUGIN_REENTRY";
2809
+ var ACTION_PLUGIN_REENTRY_VALUE = "1";
2810
+ function normalizeCommandSegment(segment) {
2811
+ return segment.trim().replace(/\s+/g, " ");
2812
+ }
2813
+ function composeActionPluginLifecycle(pkg2) {
2814
+ const scripts = pkg2.scripts ?? {};
2815
+ const current = scripts.postinstall ?? "";
2816
+ const customSegments = [];
2817
+ for (const rawSegment of current.split(/\s*&&\s*/)) {
2818
+ const segment = rawSegment.trim();
2819
+ if (!segment) continue;
2820
+ const normalized = normalizeCommandSegment(segment);
2821
+ if (normalized === LEGACY_ACTION_PLUGIN_INIT_COMMAND || normalized === ACTION_PLUGIN_RESTORE_COMMAND) {
2822
+ continue;
2823
+ }
2824
+ customSegments.push(segment);
2825
+ }
2826
+ const next = [...customSegments, ACTION_PLUGIN_RESTORE_COMMAND].join(" && ");
2827
+ if (current === next) return false;
2828
+ pkg2.scripts = scripts;
2829
+ scripts.postinstall = next;
2830
+ return true;
2831
+ }
2832
+ function atomicWriteFile(filePath, content) {
2833
+ const directory = path6.dirname(filePath);
2834
+ const temporaryPath = path6.join(
2835
+ directory,
2836
+ `.${path6.basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
2837
+ );
2838
+ const mode = fs9.existsSync(filePath) ? fs9.statSync(filePath).mode : void 0;
2839
+ try {
2840
+ fs9.writeFileSync(
2841
+ temporaryPath,
2842
+ content,
2843
+ mode === void 0 ? void 0 : { mode }
2844
+ );
2845
+ fs9.renameSync(temporaryPath, filePath);
2846
+ } finally {
2847
+ if (fs9.existsSync(temporaryPath)) {
2848
+ fs9.rmSync(temporaryPath, { force: true });
2849
+ }
2850
+ }
2851
+ }
2852
+ function atomicWriteJson(filePath, value) {
2853
+ atomicWriteFile(filePath, `${JSON.stringify(value, null, 2)}
2854
+ `);
2855
+ }
2856
+ function ensureActionPluginLifecycle(packageJsonPath) {
2857
+ const pkg2 = JSON.parse(
2858
+ fs9.readFileSync(packageJsonPath, "utf-8")
2859
+ );
2860
+ if (!composeActionPluginLifecycle(pkg2)) return false;
2861
+ atomicWriteJson(packageJsonPath, pkg2);
2862
+ return true;
2863
+ }
2864
+
2806
2865
  // src/commands/sync/run.handler.ts
2807
2866
  async function run2(options) {
2808
2867
  const userProjectRoot = process.env.INIT_CWD || process.cwd();
2809
2868
  const __filename = fileURLToPath3(import.meta.url);
2810
- const __dirname2 = path6.dirname(__filename);
2811
- const pluginRoot = path6.resolve(__dirname2, "..");
2869
+ const __dirname2 = path7.dirname(__filename);
2870
+ const pluginRoot = path7.resolve(__dirname2, "..");
2812
2871
  if (userProjectRoot === pluginRoot) {
2813
2872
  console.log("[fullstack-cli] Skip syncing (installing plugin itself)");
2814
2873
  process.exit(0);
2815
2874
  }
2816
- const userPackageJson = path6.join(userProjectRoot, "package.json");
2817
- if (!fs9.existsSync(userPackageJson)) {
2875
+ const userPackageJson = path7.join(userProjectRoot, "package.json");
2876
+ if (!fs10.existsSync(userPackageJson)) {
2818
2877
  console.log("[fullstack-cli] Skip syncing (not a valid npm project)");
2819
2878
  process.exit(0);
2820
2879
  }
@@ -2853,11 +2912,11 @@ async function run2(options) {
2853
2912
  }
2854
2913
  async function syncRule(rule, pluginRoot, userProjectRoot) {
2855
2914
  if (rule.type === "typescript-exclude") {
2856
- excludeTypeScriptPath(path6.join(userProjectRoot, rule.to), rule.path);
2915
+ excludeTypeScriptPath(path7.join(userProjectRoot, rule.to), rule.path);
2857
2916
  return;
2858
2917
  }
2859
2918
  if (rule.type === "delete-file" || rule.type === "delete-directory") {
2860
- const destPath2 = path6.join(userProjectRoot, rule.to);
2919
+ const destPath2 = path7.join(userProjectRoot, rule.to);
2861
2920
  if (rule.type === "delete-file") {
2862
2921
  deleteFile(destPath2);
2863
2922
  } else {
@@ -2866,37 +2925,45 @@ async function syncRule(rule, pluginRoot, userProjectRoot) {
2866
2925
  return;
2867
2926
  }
2868
2927
  if (rule.type === "remove-line") {
2869
- const destPath2 = path6.join(userProjectRoot, rule.to);
2928
+ const destPath2 = path7.join(userProjectRoot, rule.to);
2870
2929
  removeLineFromFile(destPath2, rule.pattern);
2871
2930
  return;
2872
2931
  }
2932
+ if (rule.type === "action-plugin-lifecycle") {
2933
+ const packageJsonPath = path7.join(userProjectRoot, "package.json");
2934
+ const changed = ensureActionPluginLifecycle(packageJsonPath);
2935
+ console.log(
2936
+ changed ? "[fullstack-cli] \u2713 scripts.postinstall" : "[fullstack-cli] \u25CB scripts.postinstall (already registered)"
2937
+ );
2938
+ return;
2939
+ }
2873
2940
  if (rule.type === "add-script") {
2874
- const packageJsonPath = path6.join(userProjectRoot, "package.json");
2941
+ const packageJsonPath = path7.join(userProjectRoot, "package.json");
2875
2942
  addScript(packageJsonPath, rule.name, rule.command, rule.overwrite ?? false);
2876
2943
  return;
2877
2944
  }
2878
2945
  if (rule.type === "patch-script") {
2879
- const packageJsonPath = path6.join(userProjectRoot, "package.json");
2946
+ const packageJsonPath = path7.join(userProjectRoot, "package.json");
2880
2947
  patchScript(packageJsonPath, rule.name, rule.to, rule.ifStartsWith);
2881
2948
  return;
2882
2949
  }
2883
2950
  if (rule.type === "add-line") {
2884
- const destPath2 = path6.join(userProjectRoot, rule.to);
2951
+ const destPath2 = path7.join(userProjectRoot, rule.to);
2885
2952
  addLineToFile(destPath2, rule.line);
2886
2953
  return;
2887
2954
  }
2888
2955
  if (rule.type === "merge-json") {
2889
- const srcPath2 = path6.join(pluginRoot, rule.from);
2890
- const destPath2 = path6.join(userProjectRoot, rule.to);
2956
+ const srcPath2 = path7.join(pluginRoot, rule.from);
2957
+ const destPath2 = path7.join(userProjectRoot, rule.to);
2891
2958
  mergeJsonFile(srcPath2, destPath2, rule.arrayMerge);
2892
2959
  return;
2893
2960
  }
2894
2961
  if (!("from" in rule)) {
2895
2962
  return;
2896
2963
  }
2897
- const srcPath = path6.join(pluginRoot, rule.from);
2898
- const destPath = path6.join(userProjectRoot, rule.to);
2899
- if (!fs9.existsSync(srcPath)) {
2964
+ const srcPath = path7.join(pluginRoot, rule.from);
2965
+ const destPath = path7.join(userProjectRoot, rule.to);
2966
+ if (!fs10.existsSync(srcPath)) {
2900
2967
  console.warn(`[fullstack-cli] Source not found: ${rule.from}`);
2901
2968
  return;
2902
2969
  }
@@ -2913,68 +2980,68 @@ async function syncRule(rule, pluginRoot, userProjectRoot) {
2913
2980
  }
2914
2981
  }
2915
2982
  function syncFile(src, dest, overwrite = true, onlyIfExists = false) {
2916
- if (onlyIfExists && !fs9.existsSync(dest)) {
2917
- console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (skipped, target not exists)`);
2983
+ if (onlyIfExists && !fs10.existsSync(dest)) {
2984
+ console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (skipped, target not exists)`);
2918
2985
  return;
2919
2986
  }
2920
- const destDir = path6.dirname(dest);
2921
- if (!fs9.existsSync(destDir)) {
2922
- fs9.mkdirSync(destDir, { recursive: true });
2987
+ const destDir = path7.dirname(dest);
2988
+ if (!fs10.existsSync(destDir)) {
2989
+ fs10.mkdirSync(destDir, { recursive: true });
2923
2990
  }
2924
- if (fs9.existsSync(dest) && !overwrite) {
2925
- console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (skipped, already exists)`);
2991
+ if (fs10.existsSync(dest) && !overwrite) {
2992
+ console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (skipped, already exists)`);
2926
2993
  return;
2927
2994
  }
2928
- fs9.copyFileSync(src, dest);
2929
- console.log(`[fullstack-cli] \u2713 ${path6.basename(dest)}`);
2995
+ fs10.copyFileSync(src, dest);
2996
+ console.log(`[fullstack-cli] \u2713 ${path7.basename(dest)}`);
2930
2997
  }
2931
2998
  function syncDirectory(src, dest, overwrite = true) {
2932
- if (!fs9.existsSync(dest)) {
2933
- fs9.mkdirSync(dest, { recursive: true });
2999
+ if (!fs10.existsSync(dest)) {
3000
+ fs10.mkdirSync(dest, { recursive: true });
2934
3001
  }
2935
- const files = fs9.readdirSync(src);
3002
+ const files = fs10.readdirSync(src);
2936
3003
  let count = 0;
2937
3004
  files.forEach((file) => {
2938
- const srcFile = path6.join(src, file);
2939
- const destFile = path6.join(dest, file);
2940
- const stats = fs9.statSync(srcFile);
3005
+ const srcFile = path7.join(src, file);
3006
+ const destFile = path7.join(dest, file);
3007
+ const stats = fs10.statSync(srcFile);
2941
3008
  if (stats.isDirectory()) {
2942
3009
  syncDirectory(srcFile, destFile, overwrite);
2943
3010
  } else {
2944
- if (overwrite || !fs9.existsSync(destFile)) {
2945
- fs9.copyFileSync(srcFile, destFile);
2946
- console.log(`[fullstack-cli] \u2713 ${path6.relative(dest, destFile)}`);
3011
+ if (overwrite || !fs10.existsSync(destFile)) {
3012
+ fs10.copyFileSync(srcFile, destFile);
3013
+ console.log(`[fullstack-cli] \u2713 ${path7.relative(dest, destFile)}`);
2947
3014
  count++;
2948
3015
  }
2949
3016
  }
2950
3017
  });
2951
3018
  if (count > 0) {
2952
- console.log(`[fullstack-cli] Synced ${count} files to ${path6.basename(dest)}/`);
3019
+ console.log(`[fullstack-cli] Synced ${count} files to ${path7.basename(dest)}/`);
2953
3020
  }
2954
3021
  }
2955
3022
  function appendToFile(src, dest) {
2956
- const content = fs9.readFileSync(src, "utf-8");
3023
+ const content = fs10.readFileSync(src, "utf-8");
2957
3024
  let existingContent = "";
2958
- if (fs9.existsSync(dest)) {
2959
- existingContent = fs9.readFileSync(dest, "utf-8");
3025
+ if (fs10.existsSync(dest)) {
3026
+ existingContent = fs10.readFileSync(dest, "utf-8");
2960
3027
  }
2961
3028
  if (existingContent.includes(content.trim())) {
2962
- console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (already contains content)`);
3029
+ console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (already contains content)`);
2963
3030
  return;
2964
3031
  }
2965
- fs9.appendFileSync(dest, content);
2966
- console.log(`[fullstack-cli] \u2713 ${path6.basename(dest)} (appended)`);
3032
+ fs10.appendFileSync(dest, content);
3033
+ console.log(`[fullstack-cli] \u2713 ${path7.basename(dest)} (appended)`);
2967
3034
  }
2968
3035
  function setPermissions(permissions, projectRoot) {
2969
3036
  for (const [pattern, mode] of Object.entries(permissions)) {
2970
3037
  if (pattern === "**/*.sh") {
2971
- const scriptsDir = path6.join(projectRoot, "scripts");
2972
- if (fs9.existsSync(scriptsDir)) {
2973
- const files = fs9.readdirSync(scriptsDir);
3038
+ const scriptsDir = path7.join(projectRoot, "scripts");
3039
+ if (fs10.existsSync(scriptsDir)) {
3040
+ const files = fs10.readdirSync(scriptsDir);
2974
3041
  files.forEach((file) => {
2975
3042
  if (file.endsWith(".sh")) {
2976
- const filePath = path6.join(scriptsDir, file);
2977
- fs9.chmodSync(filePath, mode);
3043
+ const filePath = path7.join(scriptsDir, file);
3044
+ fs10.chmodSync(filePath, mode);
2978
3045
  }
2979
3046
  });
2980
3047
  }
@@ -2982,27 +3049,27 @@ function setPermissions(permissions, projectRoot) {
2982
3049
  }
2983
3050
  }
2984
3051
  function deleteFile(filePath) {
2985
- if (fs9.existsSync(filePath)) {
2986
- fs9.unlinkSync(filePath);
2987
- console.log(`[fullstack-cli] \u2713 ${path6.basename(filePath)} (deleted)`);
3052
+ if (fs10.existsSync(filePath)) {
3053
+ fs10.unlinkSync(filePath);
3054
+ console.log(`[fullstack-cli] \u2713 ${path7.basename(filePath)} (deleted)`);
2988
3055
  } else {
2989
- console.log(`[fullstack-cli] \u25CB ${path6.basename(filePath)} (not found)`);
3056
+ console.log(`[fullstack-cli] \u25CB ${path7.basename(filePath)} (not found)`);
2990
3057
  }
2991
3058
  }
2992
3059
  function deleteDirectory(dirPath) {
2993
- if (fs9.existsSync(dirPath)) {
2994
- fs9.rmSync(dirPath, { recursive: true });
2995
- console.log(`[fullstack-cli] \u2713 ${path6.basename(dirPath)} (deleted)`);
3060
+ if (fs10.existsSync(dirPath)) {
3061
+ fs10.rmSync(dirPath, { recursive: true });
3062
+ console.log(`[fullstack-cli] \u2713 ${path7.basename(dirPath)} (deleted)`);
2996
3063
  } else {
2997
- console.log(`[fullstack-cli] \u25CB ${path6.basename(dirPath)} (not found)`);
3064
+ console.log(`[fullstack-cli] \u25CB ${path7.basename(dirPath)} (not found)`);
2998
3065
  }
2999
3066
  }
3000
3067
  function addScript(packageJsonPath, name, command, overwrite) {
3001
- if (!fs9.existsSync(packageJsonPath)) {
3068
+ if (!fs10.existsSync(packageJsonPath)) {
3002
3069
  console.log(`[fullstack-cli] \u25CB package.json (not found)`);
3003
3070
  return;
3004
3071
  }
3005
- const content = fs9.readFileSync(packageJsonPath, "utf-8");
3072
+ const content = fs10.readFileSync(packageJsonPath, "utf-8");
3006
3073
  const pkg2 = JSON.parse(content);
3007
3074
  if (!pkg2.scripts) {
3008
3075
  pkg2.scripts = {};
@@ -3014,16 +3081,16 @@ function addScript(packageJsonPath, name, command, overwrite) {
3014
3081
  }
3015
3082
  }
3016
3083
  pkg2.scripts[name] = command;
3017
- fs9.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3084
+ fs10.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3018
3085
  console.log(`[fullstack-cli] \u2713 scripts.${name}`);
3019
3086
  }
3020
3087
  function patchScript(packageJsonPath, name, to, ifStartsWith) {
3021
- if (!fs9.existsSync(packageJsonPath)) {
3088
+ if (!fs10.existsSync(packageJsonPath)) {
3022
3089
  console.log(`[fullstack-cli] \u25CB package.json (not found)`);
3023
3090
  return;
3024
3091
  }
3025
3092
  try {
3026
- const content = fs9.readFileSync(packageJsonPath, "utf-8");
3093
+ const content = fs10.readFileSync(packageJsonPath, "utf-8");
3027
3094
  const pkg2 = JSON.parse(content);
3028
3095
  const current = pkg2.scripts?.[name];
3029
3096
  if (!current) {
@@ -3041,7 +3108,7 @@ function patchScript(packageJsonPath, name, to, ifStartsWith) {
3041
3108
  return;
3042
3109
  }
3043
3110
  pkg2.scripts[name] = to;
3044
- fs9.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3111
+ fs10.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3045
3112
  console.log(`[fullstack-cli] \u2713 Patched scripts.${name}`);
3046
3113
  } catch (error) {
3047
3114
  const message = error instanceof Error ? error.message : String(error);
@@ -3049,38 +3116,38 @@ function patchScript(packageJsonPath, name, to, ifStartsWith) {
3049
3116
  }
3050
3117
  }
3051
3118
  function addLineToFile(filePath, line) {
3052
- const fileName = path6.basename(filePath);
3053
- if (!fs9.existsSync(filePath)) {
3119
+ const fileName = path7.basename(filePath);
3120
+ if (!fs10.existsSync(filePath)) {
3054
3121
  console.log(`[fullstack-cli] \u25CB ${fileName} (not found, skipped)`);
3055
3122
  return;
3056
3123
  }
3057
- const content = fs9.readFileSync(filePath, "utf-8");
3124
+ const content = fs10.readFileSync(filePath, "utf-8");
3058
3125
  const lines = content.split("\n").map((l) => l.trim());
3059
3126
  if (lines.includes(line)) {
3060
3127
  console.log(`[fullstack-cli] \u25CB ${fileName} (line already exists: ${line})`);
3061
3128
  return;
3062
3129
  }
3063
3130
  const appendContent = (content.endsWith("\n") ? "" : "\n") + line + "\n";
3064
- fs9.appendFileSync(filePath, appendContent);
3131
+ fs10.appendFileSync(filePath, appendContent);
3065
3132
  console.log(`[fullstack-cli] \u2713 ${fileName} (added: ${line})`);
3066
3133
  }
3067
3134
  function mergeJsonFile(src, dest, arrayMerge) {
3068
- const fileName = path6.basename(dest);
3069
- if (!fs9.existsSync(src)) {
3135
+ const fileName = path7.basename(dest);
3136
+ if (!fs10.existsSync(src)) {
3070
3137
  console.warn(`[fullstack-cli] Source not found: ${src}`);
3071
3138
  return;
3072
3139
  }
3073
- const templateContent = JSON.parse(fs9.readFileSync(src, "utf-8"));
3074
- if (!fs9.existsSync(dest)) {
3075
- const destDir = path6.dirname(dest);
3076
- if (!fs9.existsSync(destDir)) {
3077
- fs9.mkdirSync(destDir, { recursive: true });
3140
+ const templateContent = JSON.parse(fs10.readFileSync(src, "utf-8"));
3141
+ if (!fs10.existsSync(dest)) {
3142
+ const destDir = path7.dirname(dest);
3143
+ if (!fs10.existsSync(destDir)) {
3144
+ fs10.mkdirSync(destDir, { recursive: true });
3078
3145
  }
3079
- fs9.writeFileSync(dest, JSON.stringify(templateContent, null, 2) + "\n");
3146
+ fs10.writeFileSync(dest, JSON.stringify(templateContent, null, 2) + "\n");
3080
3147
  console.log(`[fullstack-cli] \u2713 ${fileName} (created)`);
3081
3148
  return;
3082
3149
  }
3083
- const userContent = JSON.parse(fs9.readFileSync(dest, "utf-8"));
3150
+ const userContent = JSON.parse(fs10.readFileSync(dest, "utf-8"));
3084
3151
  const merged = deepMergeJson(userContent, templateContent, arrayMerge ?? {});
3085
3152
  const userStr = JSON.stringify(userContent, null, 2);
3086
3153
  const mergedStr = JSON.stringify(merged, null, 2);
@@ -3088,7 +3155,7 @@ function mergeJsonFile(src, dest, arrayMerge) {
3088
3155
  console.log(`[fullstack-cli] \u25CB ${fileName} (already up to date)`);
3089
3156
  return;
3090
3157
  }
3091
- fs9.writeFileSync(dest, mergedStr + "\n");
3158
+ fs10.writeFileSync(dest, mergedStr + "\n");
3092
3159
  console.log(`[fullstack-cli] \u2713 ${fileName} (merged)`);
3093
3160
  }
3094
3161
 
@@ -3247,12 +3314,12 @@ async function reportCreateInstanceEvent(pluginKey, version) {
3247
3314
 
3248
3315
  // src/utils/git.ts
3249
3316
  import { execSync, spawnSync as spawnSync3 } from "child_process";
3250
- import fs10 from "fs";
3251
- import path7 from "path";
3317
+ import fs11 from "fs";
3318
+ import path8 from "path";
3252
3319
  function isGitRepository(cwd = process.cwd()) {
3253
3320
  try {
3254
- const gitDir = path7.join(cwd, ".git");
3255
- if (fs10.existsSync(gitDir)) {
3321
+ const gitDir = path8.join(cwd, ".git");
3322
+ if (fs11.existsSync(gitDir)) {
3256
3323
  return true;
3257
3324
  }
3258
3325
  const result = spawnSync3("git", ["rev-parse", "--git-dir"], {
@@ -3281,7 +3348,7 @@ function getChangedFiles(cwd = process.cwd()) {
3281
3348
  function gitAddUpgradeFiles(cwd = process.cwd(), filesToStage) {
3282
3349
  const filteredFiles = [];
3283
3350
  for (const filePath of filesToStage) {
3284
- if (fs10.existsSync(path7.join(cwd, filePath))) {
3351
+ if (fs11.existsSync(path8.join(cwd, filePath))) {
3285
3352
  filteredFiles.push(filePath);
3286
3353
  continue;
3287
3354
  }
@@ -3366,20 +3433,20 @@ Auto-committed by fullstack-cli`;
3366
3433
  }
3367
3434
 
3368
3435
  // src/utils/package-json.ts
3369
- import fs11 from "fs";
3370
- import path8 from "path";
3436
+ import fs12 from "fs";
3437
+ import path9 from "path";
3371
3438
  function readPackageJson(cwd = process.cwd()) {
3372
- const pkgPath = path8.join(cwd, "package.json");
3373
- if (!fs11.existsSync(pkgPath)) {
3439
+ const pkgPath = path9.join(cwd, "package.json");
3440
+ if (!fs12.existsSync(pkgPath)) {
3374
3441
  throw new Error(`package.json not found at ${pkgPath}`);
3375
3442
  }
3376
- const content = fs11.readFileSync(pkgPath, "utf-8");
3443
+ const content = fs12.readFileSync(pkgPath, "utf-8");
3377
3444
  return JSON.parse(content);
3378
3445
  }
3379
3446
  function writePackageJson(pkg2, cwd = process.cwd()) {
3380
- const pkgPath = path8.join(cwd, "package.json");
3447
+ const pkgPath = path9.join(cwd, "package.json");
3381
3448
  const content = JSON.stringify(pkg2, null, 2) + "\n";
3382
- fs11.writeFileSync(pkgPath, content, "utf-8");
3449
+ fs12.writeFileSync(pkgPath, content, "utf-8");
3383
3450
  }
3384
3451
  function removeUpgradeScript(pkg2) {
3385
3452
  if (!pkg2.scripts?.upgrade) {
@@ -3424,15 +3491,15 @@ function cleanupPackageJson(cwd = process.cwd()) {
3424
3491
  }
3425
3492
 
3426
3493
  // src/commands/upgrade/shared/utils.ts
3427
- import path9 from "path";
3428
- import fs12 from "fs";
3494
+ import path10 from "path";
3495
+ import fs13 from "fs";
3429
3496
  import { fileURLToPath as fileURLToPath4 } from "url";
3430
3497
  function getCliVersion() {
3431
3498
  try {
3432
3499
  const __filename = fileURLToPath4(import.meta.url);
3433
- const __dirname2 = path9.dirname(__filename);
3434
- const pkgPath = path9.resolve(__dirname2, "../../../package.json");
3435
- const pkgContent = fs12.readFileSync(pkgPath, "utf-8");
3500
+ const __dirname2 = path10.dirname(__filename);
3501
+ const pkgPath = path10.resolve(__dirname2, "../../../package.json");
3502
+ const pkgContent = fs13.readFileSync(pkgPath, "utf-8");
3436
3503
  const pkg2 = JSON.parse(pkgContent);
3437
3504
  return pkg2.version || "unknown";
3438
3505
  } catch {
@@ -3493,7 +3560,7 @@ async function run3(options = {}) {
3493
3560
  }
3494
3561
 
3495
3562
  // src/commands/upgrade/deps/run.handler.ts
3496
- import { spawnSync as spawnSync5 } from "child_process";
3563
+ import { spawnSync as spawnSync4 } from "child_process";
3497
3564
  import fs14 from "fs";
3498
3565
  import path11 from "path";
3499
3566
 
@@ -3656,240 +3723,11 @@ function resolveGrayscaleVersions(_cwd, configJson) {
3656
3723
  return versions;
3657
3724
  }
3658
3725
 
3659
- // src/commands/upgrade/deps/drizzle-peer-migration.ts
3660
- import { spawnSync as spawnSync4 } from "child_process";
3661
- import fs13 from "fs";
3662
- import path10 from "path";
3663
- var DRIZZLE_SDKS = /* @__PURE__ */ new Set([
3664
- "@lark-apaas/fullstack-nestjs-core",
3665
- "@lark-apaas/nestjs-datapaas",
3666
- "@lark-apaas/express-core",
3667
- "@lark-apaas/express-datapaas"
3668
- ]);
3669
- var DEP_FIELDS = [
3670
- "dependencies",
3671
- "devDependencies",
3672
- "optionalDependencies",
3673
- "peerDependencies"
3674
- ];
3675
- var TRANSACTION_FILES = [
3676
- "package.json",
3677
- "package-lock.json",
3678
- "npm-shrinkwrap.json"
3679
- ];
3680
- function readJson(file) {
3681
- return JSON.parse(fs13.readFileSync(file, "utf8"));
3682
- }
3683
- function installedVersion(cwd, name) {
3684
- const file = path10.join(cwd, "node_modules", name, "package.json");
3685
- return fs13.existsSync(file) ? readJson(file).version : void 0;
3686
- }
3687
- function readSdkMetadata(cwd, name, spec) {
3688
- const result = spawnSync4(
3689
- "npm",
3690
- [
3691
- "view",
3692
- `${name}@${spec}`,
3693
- "version",
3694
- "peerDependencies",
3695
- "dist-tags",
3696
- "--json"
3697
- ],
3698
- {
3699
- cwd,
3700
- encoding: "utf8",
3701
- timeout: 3e4
3702
- }
3703
- );
3704
- if (result.error || result.status !== 0) {
3705
- throw new Error(
3706
- `Cannot read Drizzle peer for ${name}@${spec}: ${result.error?.message || result.stderr}`
3707
- );
3708
- }
3709
- const response = JSON.parse(result.stdout);
3710
- let metadata;
3711
- if (Array.isArray(response)) {
3712
- const config = spawnSync4("npm", ["config", "get", "tag"], {
3713
- cwd,
3714
- encoding: "utf8",
3715
- timeout: 3e4
3716
- });
3717
- if (config.error || config.status !== 0 || !config.stdout.trim()) {
3718
- throw new Error(
3719
- "Cannot determine the application npm tag; no files changed"
3720
- );
3721
- }
3722
- const tag = config.stdout.trim();
3723
- metadata = response.find((meta) => meta.version === meta["dist-tags"]?.[tag]) || response[response.length - 1];
3724
- } else {
3725
- metadata = response;
3726
- }
3727
- const peer = metadata?.peerDependencies?.["drizzle-orm"];
3728
- if (!metadata?.version || !peer || !/^\d+\.\d+\.\d+$/.test(peer)) {
3729
- throw new Error(
3730
- `${name}@${spec} has no verifiable exact drizzle-orm peer; no files changed`
3731
- );
3732
- }
3733
- return metadata;
3734
- }
3735
- function lockMatches(pkg2, lock, sdks, drizzleVersion) {
3736
- if (lock.packages?.["node_modules/drizzle-orm"]?.version !== drizzleVersion)
3737
- return false;
3738
- for (const field of DEP_FIELDS) {
3739
- for (const name of [...sdks.keys(), "drizzle-orm"]) {
3740
- const spec = pkg2[field]?.[name];
3741
- if (spec !== void 0) {
3742
- const rootDeps = lock.packages?.[""]?.[field];
3743
- if (rootDeps?.[name] !== spec) return false;
3744
- }
3745
- }
3746
- }
3747
- for (const [name, metadata] of sdks) {
3748
- if (lock.packages?.[`node_modules/${name}`]?.version !== metadata.version)
3749
- return false;
3750
- }
3751
- return true;
3752
- }
3753
- function runNpm(cwd, args) {
3754
- console.log(`[fullstack-cli] npm ${args.join(" ")}`);
3755
- const result = spawnSync4("npm", args, { cwd, stdio: "inherit" });
3756
- if (result.error || result.status !== 0) {
3757
- throw new Error(
3758
- `npm ${args[0]} failed: ${result.error?.message || `exit ${result.status}`}`
3759
- );
3760
- }
3761
- }
3762
- function upgradeDrizzlePeers(options) {
3763
- const { cwd, sdkTargets, npmArgs, dryRun, skipInstall } = options;
3764
- if (![...sdkTargets.keys()].some((name) => DRIZZLE_SDKS.has(name)))
3765
- return false;
3766
- const pkgFile = path10.join(cwd, "package.json");
3767
- const pkg2 = readJson(pkgFile);
3768
- const lockFile = path10.join(
3769
- cwd,
3770
- fs13.existsSync(path10.join(cwd, "npm-shrinkwrap.json")) ? "npm-shrinkwrap.json" : "package-lock.json"
3771
- );
3772
- const beforeLock = fs13.existsSync(lockFile) ? readJson(lockFile) : {};
3773
- const sdks = /* @__PURE__ */ new Map();
3774
- for (const field of DEP_FIELDS) {
3775
- for (const [name, spec] of Object.entries(pkg2[field] || {})) {
3776
- if (!DRIZZLE_SDKS.has(name) || sdks.has(name)) continue;
3777
- const target = sdkTargets.get(name) || beforeLock.packages?.[`node_modules/${name}`]?.version || installedVersion(cwd, name) || spec;
3778
- sdks.set(name, readSdkMetadata(cwd, name, target));
3779
- }
3780
- }
3781
- const peers = new Set(
3782
- [...sdks.values()].map((meta) => meta.peerDependencies["drizzle-orm"])
3783
- );
3784
- if (peers.size !== 1) {
3785
- throw new Error(
3786
- `SDK Drizzle peers conflict; upgrade these SDKs together: ${[...sdks].map(
3787
- ([name, meta]) => `${name}@${meta.version} \u2192 ${meta.peerDependencies["drizzle-orm"]}`
3788
- ).join(", ")}`
3789
- );
3790
- }
3791
- const drizzleVersion = [...peers][0];
3792
- for (const [name, metadata] of sdks) {
3793
- console.log(
3794
- `[fullstack-cli] ${name} \u2192 ${metadata.version}${sdkTargets.has(name) ? "" : " (retained)"}`
3795
- );
3796
- }
3797
- const fields = DEP_FIELDS.filter(
3798
- (field) => pkg2[field]?.["drizzle-orm"] !== void 0
3799
- );
3800
- if (fields.length === 0) fields.push("dependencies");
3801
- for (const field of fields) {
3802
- console.log(
3803
- `[fullstack-cli] ${field}.drizzle-orm: ${pkg2[field]?.["drizzle-orm"] || "(missing)"} \u2192 ${drizzleVersion}`
3804
- );
3805
- pkg2[field] ?? (pkg2[field] = {});
3806
- pkg2[field]["drizzle-orm"] = drizzleVersion;
3807
- }
3808
- if (dryRun) {
3809
- console.log(
3810
- "[fullstack-cli] Dry run: SDK + Drizzle + lock migration; no files changed"
3811
- );
3812
- return true;
3813
- }
3814
- if (skipInstall && lockMatches(pkg2, beforeLock, sdks, drizzleVersion) && installedVersion(cwd, "drizzle-orm") === drizzleVersion && fields.every(
3815
- (field) => readJson(pkgFile)[field]?.["drizzle-orm"] === drizzleVersion
3816
- )) {
3817
- console.log(
3818
- "[fullstack-cli] SDK, Drizzle and lock already match; skip installation"
3819
- );
3820
- return true;
3821
- }
3822
- const snapshots = TRANSACTION_FILES.map((name) => {
3823
- const file = path10.join(cwd, name);
3824
- return {
3825
- file,
3826
- content: fs13.existsSync(file) ? fs13.readFileSync(file) : null
3827
- };
3828
- });
3829
- const resolutionArgs = [...npmArgs];
3830
- if (resolutionArgs[0] === "install") {
3831
- for (const [name, meta] of sdks) {
3832
- if (sdkTargets.has(name) && beforeLock.packages?.[`node_modules/${name}`]?.version !== meta.version && !resolutionArgs.some((arg) => arg.startsWith(`${name}@`))) {
3833
- resolutionArgs.push(`${name}@${meta.version}`);
3834
- }
3835
- }
3836
- }
3837
- try {
3838
- fs13.writeFileSync(pkgFile, `${JSON.stringify(pkg2, null, 2)}
3839
- `);
3840
- runNpm(cwd, [
3841
- ...resolutionArgs,
3842
- "--package-lock-only",
3843
- "--ignore-scripts",
3844
- "--no-audit",
3845
- "--no-fund"
3846
- ]);
3847
- const resolvedPkg = readJson(pkgFile);
3848
- if (!lockMatches(
3849
- resolvedPkg,
3850
- readJson(lockFile),
3851
- sdks,
3852
- drizzleVersion
3853
- )) {
3854
- throw new Error(
3855
- "Resolved SDK/Drizzle versions or lock root do not match the migration plan"
3856
- );
3857
- }
3858
- runNpm(cwd, ["install", "--no-audit", "--no-fund"]);
3859
- if (!lockMatches(
3860
- readJson(pkgFile),
3861
- readJson(lockFile),
3862
- sdks,
3863
- drizzleVersion
3864
- ) || installedVersion(cwd, "drizzle-orm") !== drizzleVersion || [...sdks].some(
3865
- ([name, meta]) => installedVersion(cwd, name) !== meta.version
3866
- )) {
3867
- throw new Error(
3868
- "Installed SDK/Drizzle tree does not match the resolved lock"
3869
- );
3870
- }
3871
- } catch (error) {
3872
- for (const snapshot of snapshots) {
3873
- if (snapshot.content !== null)
3874
- fs13.writeFileSync(snapshot.file, snapshot.content);
3875
- else if (fs13.existsSync(snapshot.file)) fs13.unlinkSync(snapshot.file);
3876
- }
3877
- throw new Error(
3878
- `Drizzle migration failed; package.json and npm lockfiles restored. Run npm ci before retrying if installation started. ${error instanceof Error ? error.message : String(error)}`
3879
- );
3880
- }
3881
- return true;
3882
- }
3883
-
3884
3726
  // src/commands/upgrade/deps/run.handler.ts
3885
3727
  function parseSemver(version) {
3886
3728
  const match = version.match(/^(\d+)\.(\d+)\.(\d+)/);
3887
3729
  if (!match) return null;
3888
- return [
3889
- parseInt(match[1], 10),
3890
- parseInt(match[2], 10),
3891
- parseInt(match[3], 10)
3892
- ];
3730
+ return [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10)];
3893
3731
  }
3894
3732
  function compareSemver(a, b) {
3895
3733
  const va = parseSemver(a);
@@ -3937,28 +3775,13 @@ function findLarkAapaasPackages(cwd, filterPackages) {
3937
3775
  }
3938
3776
  return packages;
3939
3777
  }
3940
- function upgradePackages(packages, version, cwd, dryRun = false) {
3941
- const pkg2 = readPackageJson(cwd);
3942
- const sdkTargets = new Map(
3943
- packages.map((name) => [
3944
- name,
3945
- version || pkg2.dependencies?.[name] || pkg2.devDependencies?.[name] || "latest"
3946
- ])
3947
- );
3948
- const npmArgs = version ? ["install", ...packages.map((name) => `${name}@${version}`)] : ["update", ...packages];
3949
- if (upgradeDrizzlePeers({ cwd, sdkTargets, npmArgs, dryRun })) return;
3950
- if (dryRun) {
3951
- packages.forEach(
3952
- (name) => console.log(` - ${name} -> ${version || "latest compatible"}`)
3953
- );
3954
- return;
3955
- }
3778
+ function upgradePackages(packages, version, cwd) {
3956
3779
  if (version) {
3957
3780
  console.log(`[fullstack-cli] Upgrading to version ${version}...`);
3958
- packages.forEach((pkg3) => {
3959
- const target = `${pkg3}@${version}`;
3781
+ packages.forEach((pkg2) => {
3782
+ const target = `${pkg2}@${version}`;
3960
3783
  console.log(`[fullstack-cli] Installing ${target}...`);
3961
- const result = spawnSync5("npm", ["install", target], {
3784
+ const result = spawnSync4("npm", ["install", target], {
3962
3785
  cwd,
3963
3786
  stdio: "inherit"
3964
3787
  });
@@ -3968,66 +3791,48 @@ function upgradePackages(packages, version, cwd, dryRun = false) {
3968
3791
  });
3969
3792
  } else {
3970
3793
  console.log("[fullstack-cli] Upgrading to latest compatible versions...");
3971
- packages.forEach((pkg3) => {
3972
- console.log(`[fullstack-cli] Updating ${pkg3}...`);
3973
- const result = spawnSync5("npm", ["update", pkg3], {
3794
+ packages.forEach((pkg2) => {
3795
+ console.log(`[fullstack-cli] Updating ${pkg2}...`);
3796
+ const result = spawnSync4("npm", ["update", pkg2], {
3974
3797
  cwd,
3975
3798
  stdio: "inherit"
3976
3799
  });
3977
3800
  if (result.error || result.status !== 0) {
3978
- throw new Error(`Failed to update ${pkg3}`);
3801
+ throw new Error(`Failed to update ${pkg2}`);
3979
3802
  }
3980
3803
  });
3981
3804
  }
3982
3805
  }
3983
3806
  function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode) {
3984
3807
  const upgradePlan = [];
3985
- const sdkTargets = /* @__PURE__ */ new Map();
3986
3808
  for (const pkg2 of packages) {
3987
3809
  const version = grayscaleVersions.get(pkg2);
3988
3810
  if (version) {
3989
- sdkTargets.set(pkg2, version);
3990
3811
  let current = "";
3991
3812
  try {
3992
- const installedPkgPath = path11.join(
3993
- cwd,
3994
- "node_modules",
3995
- pkg2,
3996
- "package.json"
3997
- );
3998
- const installedPkg = JSON.parse(
3999
- fs14.readFileSync(installedPkgPath, "utf-8")
4000
- );
3813
+ const installedPkgPath = path11.join(cwd, "node_modules", pkg2, "package.json");
3814
+ const installedPkg = JSON.parse(fs14.readFileSync(installedPkgPath, "utf-8"));
4001
3815
  current = installedPkg.version || "";
4002
3816
  } catch (err) {
4003
3817
  const code = err?.code;
4004
3818
  if (code !== "ENOENT") {
4005
- console.warn(
4006
- `[fullstack-cli] Failed to read installed version of ${pkg2}: ${err instanceof Error ? err.message : String(err)}`
4007
- );
3819
+ console.warn(`[fullstack-cli] Failed to read installed version of ${pkg2}: ${err instanceof Error ? err.message : String(err)}`);
4008
3820
  }
4009
3821
  }
4010
3822
  if (mode === "destroy") {
4011
3823
  if (!isRangeVersion(version) && current === version) {
4012
- console.log(
4013
- `[fullstack-cli] ${pkg2}@${version} (already installed, skip)`
4014
- );
3824
+ console.log(`[fullstack-cli] ${pkg2}@${version} (already installed, skip)`);
4015
3825
  continue;
4016
3826
  }
4017
3827
  } else {
4018
3828
  if (isRangeVersion(version)) {
4019
3829
  if (current && satisfiesCaret(current, version)) {
4020
- sdkTargets.set(pkg2, current);
4021
- console.log(
4022
- `[fullstack-cli] ${pkg2}@${current} satisfies ${version} (skip)`
4023
- );
3830
+ console.log(`[fullstack-cli] ${pkg2}@${current} satisfies ${version} (skip)`);
4024
3831
  continue;
4025
3832
  }
4026
3833
  } else {
4027
3834
  if (current === version) {
4028
- console.log(
4029
- `[fullstack-cli] ${pkg2}@${version} (already installed, skip)`
4030
- );
3835
+ console.log(`[fullstack-cli] ${pkg2}@${version} (already installed, skip)`);
4031
3836
  continue;
4032
3837
  }
4033
3838
  }
@@ -4035,26 +3840,11 @@ function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode
4035
3840
  upgradePlan.push({ pkg: pkg2, version, current });
4036
3841
  }
4037
3842
  }
4038
- if (upgradeDrizzlePeers({
4039
- cwd,
4040
- sdkTargets,
4041
- npmArgs: [
4042
- "install",
4043
- ...upgradePlan.map(({ pkg: pkg2, version }) => `${pkg2}@${version}`)
4044
- ],
4045
- dryRun,
4046
- skipInstall: upgradePlan.length === 0
4047
- }))
4048
- return;
4049
3843
  if (upgradePlan.length === 0) {
4050
- console.log(
4051
- "[fullstack-cli] No grayscale versions matched current packages"
4052
- );
3844
+ console.log("[fullstack-cli] No grayscale versions matched current packages");
4053
3845
  return;
4054
3846
  }
4055
- console.log(
4056
- `[fullstack-cli] Grayscale upgrade plan (${upgradePlan.length} package(s)):`
4057
- );
3847
+ console.log(`[fullstack-cli] Grayscale upgrade plan (${upgradePlan.length} package(s)):`);
4058
3848
  upgradePlan.forEach(({ pkg: pkg2, version, current }) => {
4059
3849
  console.log(` - ${pkg2} ${current} -> ${version}`);
4060
3850
  });
@@ -4064,98 +3854,61 @@ function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode
4064
3854
  }
4065
3855
  const targets = upgradePlan.map(({ pkg: pkg2, version }) => `${pkg2}@${version}`);
4066
3856
  console.log(`[fullstack-cli] Installing ${targets.join(" ")}...`);
4067
- const result = spawnSync5("npm", ["install", ...targets], {
3857
+ const result = spawnSync4("npm", ["install", ...targets], {
4068
3858
  cwd,
4069
3859
  stdio: "inherit"
4070
3860
  });
4071
3861
  if (result.error || result.status !== 0) {
4072
- throw new Error(
4073
- `npm install failed: ${result.error?.message ?? `exit ${result.status}`}`
4074
- );
3862
+ console.warn(`[fullstack-cli] npm install failed: ${result.error?.message ?? `exit ${result.status}`}`);
4075
3863
  }
4076
3864
  }
4077
3865
  async function run4(options = {}) {
4078
3866
  const cwd = process.env.INIT_CWD || process.cwd();
4079
3867
  console.log("[fullstack-cli] Starting dependencies upgrade...");
4080
3868
  try {
4081
- console.log(
4082
- "[fullstack-cli] Step 1/3: Scanning @lark-apaas dependencies..."
4083
- );
3869
+ console.log("[fullstack-cli] Step 1/3: Scanning @lark-apaas dependencies...");
4084
3870
  const packages = findLarkAapaasPackages(cwd, options.packages);
4085
3871
  if (packages.length === 0) {
4086
3872
  console.log("[fullstack-cli] No @lark-apaas packages found");
4087
3873
  return;
4088
3874
  }
4089
- console.log(
4090
- `[fullstack-cli] Found ${packages.length} @lark-apaas package(s):`
4091
- );
3875
+ console.log(`[fullstack-cli] Found ${packages.length} @lark-apaas package(s):`);
4092
3876
  packages.forEach((p) => console.log(` - ${p}`));
4093
3877
  if (options.skipGrayscale) {
4094
- console.log(
4095
- "[fullstack-cli] Step 2/3: Skipping grayscale check (--skip-grayscale)"
4096
- );
3878
+ console.log("[fullstack-cli] Step 2/3: Skipping grayscale check (--skip-grayscale)");
4097
3879
  } else if (options.version) {
4098
- console.log(
4099
- "[fullstack-cli] Step 2/3: Skipping grayscale check (explicit --version provided)"
4100
- );
3880
+ console.log("[fullstack-cli] Step 2/3: Skipping grayscale check (explicit --version provided)");
4101
3881
  } else if (!options.grayscaleConfig) {
4102
- console.log(
4103
- "[fullstack-cli] Step 2/3: No grayscale config, falling back to default upgrade"
4104
- );
3882
+ console.log("[fullstack-cli] Step 2/3: No grayscale config, falling back to default upgrade");
4105
3883
  } else {
4106
3884
  console.log("[fullstack-cli] Step 2/3: Checking grayscale config...");
4107
- let grayscaleVersions;
4108
3885
  try {
4109
- grayscaleVersions = resolveGrayscaleVersions(
4110
- cwd,
4111
- options.grayscaleConfig
4112
- );
3886
+ const grayscaleVersions = resolveGrayscaleVersions(cwd, options.grayscaleConfig);
3887
+ if (grayscaleVersions) {
3888
+ console.log("[fullstack-cli] Step 3/3: Applying grayscale versions...");
3889
+ installGrayscaleVersions(packages, grayscaleVersions, cwd, !!options.dryRun, options.mode || "rebuild");
3890
+ if (!options.dryRun) {
3891
+ console.log(`[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s) via grayscale`);
3892
+ console.log("[fullstack-cli] Dependencies upgrade completed successfully \u2705");
3893
+ }
3894
+ } else {
3895
+ console.log("[fullstack-cli] Grayscale config provided but not available, skip upgrade");
3896
+ }
4113
3897
  } catch (error) {
4114
3898
  const msg = error instanceof Error ? error.message : String(error);
4115
- console.warn(
4116
- `[fullstack-cli] Grayscale check failed: ${msg}, skip upgrade`
4117
- );
4118
- return;
4119
- }
4120
- if (grayscaleVersions) {
4121
- console.log("[fullstack-cli] Step 3/3: Applying grayscale versions...");
4122
- installGrayscaleVersions(
4123
- packages,
4124
- grayscaleVersions,
4125
- cwd,
4126
- !!options.dryRun,
4127
- options.mode || "rebuild"
4128
- );
4129
- if (!options.dryRun) {
4130
- console.log(
4131
- `[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s) via grayscale`
4132
- );
4133
- console.log(
4134
- "[fullstack-cli] Dependencies upgrade completed successfully \u2705"
4135
- );
4136
- }
4137
- } else {
4138
- console.log(
4139
- "[fullstack-cli] Grayscale config provided but not available, skip upgrade"
4140
- );
3899
+ console.warn(`[fullstack-cli] Grayscale check failed: ${msg}, skip upgrade`);
4141
3900
  }
4142
3901
  return;
4143
3902
  }
4144
3903
  if (options.dryRun) {
4145
- console.log(
4146
- "[fullstack-cli] Dry run mode: would upgrade via npm update (no grayscale)"
4147
- );
4148
- upgradePackages(packages, options.version, cwd, true);
3904
+ console.log("[fullstack-cli] Dry run mode: would upgrade via npm update (no grayscale)");
3905
+ packages.forEach((p) => console.log(` - ${p} -> ${options.version || "latest compatible"}`));
4149
3906
  return;
4150
3907
  }
4151
3908
  console.log("[fullstack-cli] Step 3/3: Upgrading packages...");
4152
3909
  upgradePackages(packages, options.version, cwd);
4153
- console.log(
4154
- `[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s)`
4155
- );
4156
- console.log(
4157
- "[fullstack-cli] Dependencies upgrade completed successfully \u2705"
4158
- );
3910
+ console.log(`[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s)`);
3911
+ console.log("[fullstack-cli] Dependencies upgrade completed successfully \u2705");
4159
3912
  } catch (error) {
4160
3913
  const message = error instanceof Error ? error.message : String(error);
4161
3914
  console.error("[fullstack-cli] Failed to upgrade dependencies:", message);
@@ -4168,30 +3921,14 @@ var depsCommand = {
4168
3921
  name: "deps",
4169
3922
  description: "Upgrade @lark-apaas dependencies",
4170
3923
  register(parentCommand) {
4171
- parentCommand.command(this.name).description(this.description).option("--version <version>", "Upgrade to specific version").option(
4172
- "--target-version <version>",
4173
- "Upgrade SDKs to specific version (avoids global --version)"
4174
- ).option(
4175
- "--packages <packages>",
4176
- "Only upgrade specific packages (comma-separated)"
4177
- ).option("--skip-grayscale", "Skip grayscale version check").option(
4178
- "--grayscale-config <json>",
4179
- "Grayscale config JSON (injected by sandbox_console)"
4180
- ).option("--dry-run", "Show upgrade plan without executing").option(
4181
- "--mode <mode>",
4182
- "Execution mode: rebuild (default) or destroy",
4183
- "rebuild"
4184
- ).action(async (options) => {
4185
- await run4({
4186
- ...options,
4187
- version: options.targetVersion ?? options.version
4188
- });
3924
+ parentCommand.command(this.name).description(this.description).option("--version <version>", "Upgrade to specific version").option("--packages <packages>", "Only upgrade specific packages (comma-separated)").option("--skip-grayscale", "Skip grayscale version check").option("--grayscale-config <json>", "Grayscale config JSON (injected by sandbox_console)").option("--dry-run", "Show upgrade plan without executing").option("--mode <mode>", "Execution mode: rebuild (default) or destroy", "rebuild").action(async (options) => {
3925
+ await run4(options);
4189
3926
  });
4190
3927
  }
4191
3928
  };
4192
3929
 
4193
3930
  // src/commands/upgrade/global-deps/run.handler.ts
4194
- import { spawnSync as spawnSync6 } from "child_process";
3931
+ import { spawnSync as spawnSync5 } from "child_process";
4195
3932
  import fs15 from "fs";
4196
3933
  import path12 from "path";
4197
3934
  var MANAGED_GLOBAL_CLIS = [
@@ -4270,7 +4007,7 @@ async function run5(options = {}) {
4270
4007
  npmArgs.push("--registry", options.registry);
4271
4008
  }
4272
4009
  console.log(`[fullstack-cli] Running: npm ${npmArgs.join(" ")}`);
4273
- const result = spawnSync6("npm", npmArgs, { stdio: "inherit" });
4010
+ const result = spawnSync5("npm", npmArgs, { stdio: "inherit" });
4274
4011
  if (result.error || result.status !== 0) {
4275
4012
  console.warn(
4276
4013
  `[fullstack-cli] npm install -g failed: ${result.error?.message ?? `exit ${result.status}`}`
@@ -4308,175 +4045,127 @@ var upgradeCommand = {
4308
4045
  }
4309
4046
  };
4310
4047
 
4311
- // src/commands/action-plugin/utils.ts
4048
+ // src/commands/action-plugin/install-engine.ts
4049
+ import fs21 from "fs";
4050
+ import path18 from "path";
4051
+ import { spawnSync as spawnSync7 } from "child_process";
4052
+
4053
+ // src/commands/action-plugin/plugin-files.ts
4312
4054
  import fs16 from "fs";
4055
+ import os from "os";
4313
4056
  import path13 from "path";
4314
- import { spawnSync as spawnSync7, execSync as execSync2 } from "child_process";
4315
- function parsePluginName(input) {
4316
- const match = input.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
4317
- if (!match) {
4318
- throw new Error(
4319
- `Invalid plugin name format: ${input}. Expected format: @scope/name or @scope/name@version`
4320
- );
4321
- }
4057
+ import { execFileSync } from "child_process";
4058
+ function createStagingRoot() {
4059
+ return fs16.mkdtempSync(path13.join(os.tmpdir(), "fullstack-cli-action-plugin-"));
4060
+ }
4061
+ function snapshotFile(filePath) {
4322
4062
  return {
4323
- name: match[1],
4324
- version: match[2] || "latest"
4063
+ filePath,
4064
+ content: fs16.existsSync(filePath) ? fs16.readFileSync(filePath) : null
4325
4065
  };
4326
4066
  }
4327
- function getProjectRoot() {
4328
- return process.cwd();
4329
- }
4330
- function getPackageJsonPath() {
4331
- return path13.join(getProjectRoot(), "package.json");
4067
+ function restoreFile(snapshot) {
4068
+ if (snapshot.content === null) {
4069
+ if (fs16.existsSync(snapshot.filePath))
4070
+ fs16.rmSync(snapshot.filePath, { force: true });
4071
+ return;
4072
+ }
4073
+ atomicWriteFile(snapshot.filePath, snapshot.content);
4332
4074
  }
4333
- function getPluginPath(pluginName) {
4334
- return path13.join(getProjectRoot(), "node_modules", pluginName);
4075
+ function snapshotDirectory(targetPath, stagingRoot, snapshotName) {
4076
+ if (!fs16.existsSync(targetPath)) return { targetPath, backupPath: null };
4077
+ const backupPath = path13.join(stagingRoot, "snapshots", snapshotName);
4078
+ fs16.mkdirSync(path13.dirname(backupPath), { recursive: true });
4079
+ fs16.cpSync(targetPath, backupPath, { recursive: true, force: true });
4080
+ return { targetPath, backupPath };
4335
4081
  }
4336
- function readPackageJson2() {
4337
- const pkgPath = getPackageJsonPath();
4338
- if (!fs16.existsSync(pkgPath)) {
4339
- throw new Error("package.json not found in current directory");
4082
+ function restoreDirectory(snapshot) {
4083
+ if (fs16.existsSync(snapshot.targetPath)) {
4084
+ fs16.rmSync(snapshot.targetPath, { recursive: true, force: true });
4340
4085
  }
4341
- try {
4342
- const content = fs16.readFileSync(pkgPath, "utf-8");
4343
- return JSON.parse(content);
4344
- } catch {
4345
- throw new Error("Failed to parse package.json");
4086
+ if (snapshot.backupPath) {
4087
+ fs16.mkdirSync(path13.dirname(snapshot.targetPath), { recursive: true });
4088
+ fs16.cpSync(snapshot.backupPath, snapshot.targetPath, {
4089
+ recursive: true,
4090
+ force: true
4091
+ });
4346
4092
  }
4347
4093
  }
4348
- function writePackageJson2(pkg2) {
4349
- const pkgPath = getPackageJsonPath();
4350
- fs16.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
4094
+ function replaceDirectory(sourcePath, targetPath) {
4095
+ fs16.mkdirSync(path13.dirname(targetPath), { recursive: true });
4096
+ const incomingPath = `${targetPath}.fullstack-cli-${process.pid}-${Date.now()}`;
4097
+ try {
4098
+ if (fs16.existsSync(incomingPath)) {
4099
+ fs16.rmSync(incomingPath, { recursive: true, force: true });
4100
+ }
4101
+ fs16.cpSync(sourcePath, incomingPath, { recursive: true, force: true });
4102
+ if (fs16.existsSync(targetPath)) {
4103
+ fs16.rmSync(targetPath, { recursive: true, force: true });
4104
+ }
4105
+ fs16.renameSync(incomingPath, targetPath);
4106
+ } finally {
4107
+ if (fs16.existsSync(incomingPath)) {
4108
+ fs16.rmSync(incomingPath, { recursive: true, force: true });
4109
+ }
4110
+ }
4351
4111
  }
4352
- function readActionPlugins() {
4353
- const pkg2 = readPackageJson2();
4354
- return pkg2.actionPlugins || {};
4112
+ function extractTgzToDirectory(tgzPath, targetPath) {
4113
+ fs16.mkdirSync(path13.dirname(targetPath), { recursive: true });
4114
+ const unpackRoot = fs16.mkdtempSync(
4115
+ path13.join(path13.dirname(targetPath), "unpack-")
4116
+ );
4117
+ try {
4118
+ execFileSync("tar", ["-xzf", tgzPath, "-C", unpackRoot], { stdio: "pipe" });
4119
+ const packageDirectory = path13.join(unpackRoot, "package");
4120
+ let extractedPath = packageDirectory;
4121
+ if (!fs16.existsSync(packageDirectory)) {
4122
+ const entries = fs16.readdirSync(unpackRoot);
4123
+ if (entries.length !== 1) throw new Error("Unexpected tgz structure");
4124
+ extractedPath = path13.join(unpackRoot, entries[0]);
4125
+ }
4126
+ if (fs16.existsSync(targetPath)) {
4127
+ fs16.rmSync(targetPath, { recursive: true, force: true });
4128
+ }
4129
+ fs16.renameSync(extractedPath, targetPath);
4130
+ } finally {
4131
+ if (fs16.existsSync(unpackRoot)) {
4132
+ fs16.rmSync(unpackRoot, { recursive: true, force: true });
4133
+ }
4134
+ }
4355
4135
  }
4356
- function writeActionPlugins(plugins) {
4357
- const pkg2 = readPackageJson2();
4358
- pkg2.actionPlugins = plugins;
4359
- writePackageJson2(pkg2);
4136
+ function readPluginManifest(pluginPath2) {
4137
+ const manifestPath = path13.join(pluginPath2, "package.json");
4138
+ if (!fs16.existsSync(manifestPath)) {
4139
+ throw new Error(`Plugin manifest not found: ${manifestPath}`);
4140
+ }
4141
+ const manifest = JSON.parse(
4142
+ fs16.readFileSync(manifestPath, "utf-8")
4143
+ );
4144
+ if (!manifest.name || !manifest.version) {
4145
+ throw new Error(`Invalid plugin manifest: ${manifestPath}`);
4146
+ }
4147
+ return manifest;
4360
4148
  }
4361
- function isPluginInstalled(pluginName) {
4362
- const plugins = readActionPlugins();
4363
- return pluginName in plugins;
4149
+ function assertPluginIdentity(pluginPath2, expectedName, expectedVersion) {
4150
+ const manifest = readPluginManifest(pluginPath2);
4151
+ if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
4152
+ throw new Error(
4153
+ `Plugin identity mismatch: expected ${expectedName}@${expectedVersion}, got ${manifest.name}@${manifest.version}`
4154
+ );
4155
+ }
4156
+ return manifest;
4364
4157
  }
4365
- function getInstalledPluginVersion(pluginName) {
4366
- const plugins = readActionPlugins();
4367
- return plugins[pluginName] || null;
4368
- }
4369
- function npmInstall(tgzPath) {
4370
- console.log(`[action-plugin] Running npm install ${tgzPath}...`);
4371
- const result = spawnSync7("npm", ["install", tgzPath, "--no-save", "--no-package-lock", "--ignore-scripts"], {
4372
- cwd: getProjectRoot(),
4373
- stdio: "inherit"
4374
- });
4375
- if (result.error) {
4376
- throw new Error(`npm install failed: ${result.error.message}`);
4377
- }
4378
- if (result.status !== 0) {
4379
- throw new Error(`npm install failed with exit code ${result.status}`);
4380
- }
4381
- }
4382
- function getPackageVersion(pluginName) {
4383
- const pkgJsonPath = path13.join(getPluginPath(pluginName), "package.json");
4384
- if (!fs16.existsSync(pkgJsonPath)) {
4385
- return null;
4386
- }
4387
- try {
4388
- const content = fs16.readFileSync(pkgJsonPath, "utf-8");
4389
- const pkg2 = JSON.parse(content);
4390
- return pkg2.version || null;
4391
- } catch {
4392
- return null;
4393
- }
4394
- }
4395
- function readPluginPackageJson(pluginPath) {
4396
- const pkgJsonPath = path13.join(pluginPath, "package.json");
4397
- if (!fs16.existsSync(pkgJsonPath)) {
4398
- return null;
4399
- }
4400
- try {
4401
- const content = fs16.readFileSync(pkgJsonPath, "utf-8");
4402
- return JSON.parse(content);
4403
- } catch {
4404
- return null;
4405
- }
4406
- }
4407
- function extractTgzToNodeModules(tgzPath, pluginName) {
4408
- const nodeModulesPath = path13.join(getProjectRoot(), "node_modules");
4409
- const targetDir = path13.join(nodeModulesPath, pluginName);
4410
- const scopeDir = path13.dirname(targetDir);
4411
- if (!fs16.existsSync(scopeDir)) {
4412
- fs16.mkdirSync(scopeDir, { recursive: true });
4413
- }
4414
- if (fs16.existsSync(targetDir)) {
4415
- fs16.rmSync(targetDir, { recursive: true });
4416
- }
4417
- const tempDir = path13.join(nodeModulesPath, ".cache", "fullstack-cli", "extract-temp");
4418
- if (fs16.existsSync(tempDir)) {
4419
- fs16.rmSync(tempDir, { recursive: true });
4420
- }
4421
- fs16.mkdirSync(tempDir, { recursive: true });
4422
- try {
4423
- execSync2(`tar -xzf "${tgzPath}" -C "${tempDir}"`, { stdio: "pipe" });
4424
- const extractedDir = path13.join(tempDir, "package");
4425
- if (fs16.existsSync(extractedDir)) {
4426
- fs16.renameSync(extractedDir, targetDir);
4427
- } else {
4428
- const files = fs16.readdirSync(tempDir);
4429
- if (files.length === 1) {
4430
- fs16.renameSync(path13.join(tempDir, files[0]), targetDir);
4431
- } else {
4432
- throw new Error("Unexpected tgz structure");
4433
- }
4434
- }
4435
- return targetDir;
4436
- } finally {
4437
- if (fs16.existsSync(tempDir)) {
4438
- fs16.rmSync(tempDir, { recursive: true });
4439
- }
4440
- }
4441
- }
4442
- function checkMissingPeerDeps(peerDeps) {
4443
- if (!peerDeps || Object.keys(peerDeps).length === 0) {
4444
- return [];
4445
- }
4446
- const missing = [];
4447
- const nodeModulesPath = path13.join(getProjectRoot(), "node_modules");
4448
- for (const [depName, _version] of Object.entries(peerDeps)) {
4449
- const depPath = path13.join(nodeModulesPath, depName);
4450
- if (!fs16.existsSync(depPath)) {
4451
- missing.push(depName);
4452
- }
4453
- }
4454
- return missing;
4455
- }
4456
- function installMissingDeps(deps) {
4457
- if (deps.length === 0) {
4458
- return;
4459
- }
4460
- console.log(`[action-plugin] Installing missing dependencies: ${deps.join(", ")}`);
4461
- const result = spawnSync7("npm", ["install", ...deps, "--no-save", "--no-package-lock"], {
4462
- cwd: getProjectRoot(),
4463
- stdio: "inherit"
4464
- });
4465
- if (result.error) {
4466
- throw new Error(`npm install failed: ${result.error.message}`);
4467
- }
4468
- if (result.status !== 0) {
4469
- throw new Error(`npm install failed with exit code ${result.status}`);
4470
- }
4471
- }
4472
- function removePluginDirectory(pluginName) {
4473
- const pluginPath = getPluginPath(pluginName);
4474
- if (fs16.existsSync(pluginPath)) {
4475
- fs16.rmSync(pluginPath, { recursive: true });
4476
- console.log(`[action-plugin] Removed ${pluginName}`);
4477
- }
4158
+ function findMissingPeerDependencies(projectRoot, peerDependencies) {
4159
+ if (!peerDependencies) return [];
4160
+ return Object.keys(peerDependencies).filter(
4161
+ (dependency) => !fs16.existsSync(path13.join(projectRoot, "node_modules", dependency))
4162
+ );
4478
4163
  }
4479
4164
 
4165
+ // src/commands/action-plugin/plugin-preparation.ts
4166
+ import fs18 from "fs";
4167
+ import path15 from "path";
4168
+
4480
4169
  // src/commands/action-plugin/api-client.ts
4481
4170
  import { HttpClient as HttpClient2 } from "@lark-apaas/http-client";
4482
4171
  import fs17 from "fs";
@@ -4614,106 +4303,829 @@ function hasCachedPlugin(pluginKey, version) {
4614
4303
  const cachePath = getCachePath(pluginKey, version);
4615
4304
  return fs17.existsSync(cachePath);
4616
4305
  }
4617
- function listCachedPlugins() {
4618
- const cacheDir = getPluginCacheDir();
4619
- if (!fs17.existsSync(cacheDir)) {
4620
- return [];
4306
+ function listCachedPlugins() {
4307
+ const cacheDir = getPluginCacheDir();
4308
+ if (!fs17.existsSync(cacheDir)) {
4309
+ return [];
4310
+ }
4311
+ const files = fs17.readdirSync(cacheDir);
4312
+ const result = [];
4313
+ for (const file of files) {
4314
+ if (!file.endsWith(".tgz")) continue;
4315
+ const match = file.match(/^(.+)@(.+)\.tgz$/);
4316
+ if (!match) continue;
4317
+ const [, rawName, version] = match;
4318
+ const name = rawName.replace(/^_/, "@").replace(/_/, "/");
4319
+ const filePath = path14.join(cacheDir, file);
4320
+ const stat = fs17.statSync(filePath);
4321
+ result.push({
4322
+ name,
4323
+ version,
4324
+ filePath,
4325
+ size: stat.size,
4326
+ mtime: stat.mtime
4327
+ });
4328
+ }
4329
+ return result;
4330
+ }
4331
+ function cleanAllCache() {
4332
+ const cacheDir = getPluginCacheDir();
4333
+ if (!fs17.existsSync(cacheDir)) {
4334
+ return 0;
4335
+ }
4336
+ const files = fs17.readdirSync(cacheDir);
4337
+ let count = 0;
4338
+ for (const file of files) {
4339
+ if (file.endsWith(".tgz")) {
4340
+ fs17.unlinkSync(path14.join(cacheDir, file));
4341
+ count++;
4342
+ }
4343
+ }
4344
+ return count;
4345
+ }
4346
+ function cleanPluginCache(pluginKey, version) {
4347
+ const cacheDir = getPluginCacheDir();
4348
+ if (!fs17.existsSync(cacheDir)) {
4349
+ return 0;
4350
+ }
4351
+ const safeKey = pluginKey.replace(/[/@]/g, "_");
4352
+ const files = fs17.readdirSync(cacheDir);
4353
+ let count = 0;
4354
+ for (const file of files) {
4355
+ if (version) {
4356
+ if (file === `${safeKey}@${version}.tgz`) {
4357
+ fs17.unlinkSync(path14.join(cacheDir, file));
4358
+ count++;
4359
+ }
4360
+ } else {
4361
+ if (file.startsWith(`${safeKey}@`) && file.endsWith(".tgz")) {
4362
+ fs17.unlinkSync(path14.join(cacheDir, file));
4363
+ count++;
4364
+ }
4365
+ }
4366
+ }
4367
+ return count;
4368
+ }
4369
+
4370
+ // src/commands/action-plugin/plugin-preparation.ts
4371
+ function readPackageDocument(packageJsonPath) {
4372
+ return JSON.parse(
4373
+ fs18.readFileSync(packageJsonPath, "utf-8")
4374
+ );
4375
+ }
4376
+ function pluginPath(projectRoot, pluginName) {
4377
+ return path15.join(projectRoot, "node_modules", pluginName);
4378
+ }
4379
+ function rootDeclaresDependency(pkg2, dependency) {
4380
+ return Boolean(
4381
+ pkg2.dependencies?.[dependency] || pkg2.devDependencies?.[dependency]
4382
+ );
4383
+ }
4384
+ async function defaultMaterializePlugin(name, version, destination) {
4385
+ let tgzPath;
4386
+ let source;
4387
+ if (hasCachedPlugin(name, version)) {
4388
+ tgzPath = getCachePath(name, version);
4389
+ source = "cache";
4390
+ } else {
4391
+ const downloaded = await downloadPlugin(name, version);
4392
+ if (downloaded.version !== version) {
4393
+ throw new Error(
4394
+ `Downloaded version mismatch for ${name}: expected ${version}, got ${downloaded.version}`
4395
+ );
4396
+ }
4397
+ tgzPath = downloaded.tgzPath;
4398
+ source = "download";
4399
+ }
4400
+ fs18.mkdirSync(path15.dirname(destination), { recursive: true });
4401
+ extractTgzToDirectory(tgzPath, destination);
4402
+ return source;
4403
+ }
4404
+ function getPluginVersionAt(projectRoot, pluginName) {
4405
+ try {
4406
+ const manifest = JSON.parse(
4407
+ fs18.readFileSync(
4408
+ path15.join(pluginPath(projectRoot, pluginName), "package.json"),
4409
+ "utf-8"
4410
+ )
4411
+ );
4412
+ return assertPluginIdentity(
4413
+ pluginPath(projectRoot, pluginName),
4414
+ pluginName,
4415
+ manifest.version
4416
+ ).version;
4417
+ } catch {
4418
+ return null;
4419
+ }
4420
+ }
4421
+ async function preparePlugin(request, index, initialPackage, projectRoot, stagingRoot, options) {
4422
+ const existingVersion = getPluginVersionAt(projectRoot, request.name);
4423
+ const version = request.requestedVersion === "latest" ? await (options.resolveLatestVersion ?? (async (name) => (await getPluginVersion(name, "latest")).version))(request.name) : request.requestedVersion;
4424
+ let manifest;
4425
+ let stagedPath = null;
4426
+ let source = "existing";
4427
+ if (existingVersion === version) {
4428
+ manifest = assertPluginIdentity(
4429
+ pluginPath(projectRoot, request.name),
4430
+ request.name,
4431
+ version
4432
+ );
4433
+ } else {
4434
+ stagedPath = path15.join(stagingRoot, "prepared", String(index));
4435
+ source = await (options.materializePlugin ?? defaultMaterializePlugin)(
4436
+ request.name,
4437
+ version,
4438
+ stagedPath
4439
+ );
4440
+ manifest = assertPluginIdentity(stagedPath, request.name, version);
4441
+ }
4442
+ const missingUndeclaredPeers = {};
4443
+ for (const dependency of findMissingPeerDependencies(
4444
+ projectRoot,
4445
+ manifest.peerDependencies
4446
+ )) {
4447
+ if (!rootDeclaresDependency(initialPackage, dependency)) {
4448
+ missingUndeclaredPeers[dependency] = manifest.peerDependencies[dependency];
4449
+ }
4450
+ }
4451
+ return {
4452
+ ...request,
4453
+ version,
4454
+ manifest,
4455
+ stagedPath,
4456
+ missingUndeclaredPeers,
4457
+ source
4458
+ };
4459
+ }
4460
+ function findPeerRangeConflict(prepared) {
4461
+ const ranges = /* @__PURE__ */ new Map();
4462
+ for (const plugin of prepared) {
4463
+ for (const [dependency, range] of Object.entries(
4464
+ plugin.missingUndeclaredPeers
4465
+ )) {
4466
+ const existing = ranges.get(dependency);
4467
+ if (existing && existing !== range) {
4468
+ return `Conflicting peer dependency ranges for ${dependency}: ${existing} and ${range}`;
4469
+ }
4470
+ ranges.set(dependency, range);
4471
+ }
4472
+ }
4473
+ return null;
4474
+ }
4475
+ function collectPeerRanges(prepared) {
4476
+ const peers = /* @__PURE__ */ new Map();
4477
+ for (const plugin of prepared) {
4478
+ for (const [dependency, range] of Object.entries(
4479
+ plugin.missingUndeclaredPeers
4480
+ )) {
4481
+ peers.set(dependency, range);
4482
+ }
4483
+ }
4484
+ return peers;
4485
+ }
4486
+
4487
+ // src/commands/action-plugin/peer-lock.ts
4488
+ function resolveLockedDependency(packages, parentKey, dependency) {
4489
+ const candidates = [];
4490
+ let current = parentKey;
4491
+ while (current) {
4492
+ candidates.push(`${current}/node_modules/${dependency}`);
4493
+ const marker = current.lastIndexOf("/node_modules/");
4494
+ if (marker < 0) break;
4495
+ current = current.slice(0, marker);
4496
+ }
4497
+ candidates.push(`node_modules/${dependency}`);
4498
+ return candidates.find((candidate) => packages[candidate]) ?? null;
4499
+ }
4500
+ function collectLockClosure(packages, roots) {
4501
+ const closure = /* @__PURE__ */ new Set();
4502
+ const queue = [...roots].map((name) => `node_modules/${name}`).filter((key) => Boolean(packages[key]));
4503
+ while (queue.length > 0) {
4504
+ const key = queue.shift();
4505
+ if (closure.has(key)) continue;
4506
+ closure.add(key);
4507
+ const entry = packages[key];
4508
+ const dependencies = {
4509
+ ...entry.dependencies ?? {},
4510
+ ...entry.optionalDependencies ?? {}
4511
+ };
4512
+ for (const dependency of Object.keys(dependencies)) {
4513
+ const resolved = resolveLockedDependency(packages, key, dependency);
4514
+ if (resolved && !closure.has(resolved)) queue.push(resolved);
4515
+ }
4516
+ }
4517
+ return closure;
4518
+ }
4519
+ function cloneJson(value) {
4520
+ return JSON.parse(JSON.stringify(value));
4521
+ }
4522
+ function buildCommittedLock(initialSnapshot, npmSnapshot, initialPackage, allPeerNames, committedPeerNames) {
4523
+ var _a;
4524
+ if (npmSnapshot.content === null) {
4525
+ throw new Error(
4526
+ `npm did not produce lock state at ${npmSnapshot.filePath}`
4527
+ );
4528
+ }
4529
+ const npmLock = JSON.parse(npmSnapshot.content.toString("utf-8"));
4530
+ const npmPackages = npmLock.packages ?? {};
4531
+ if (initialSnapshot.content !== null) {
4532
+ const result2 = JSON.parse(
4533
+ initialSnapshot.content.toString("utf-8")
4534
+ );
4535
+ result2.packages ?? (result2.packages = {});
4536
+ const closure = collectLockClosure(npmPackages, committedPeerNames);
4537
+ for (const key of closure)
4538
+ result2.packages[key] = cloneJson(npmPackages[key]);
4539
+ const npmRoot = npmPackages[""] ?? {};
4540
+ const resultRoot = (_a = result2.packages)[""] ?? (_a[""] = {});
4541
+ const npmRootDependencies = npmRoot.dependencies ?? {};
4542
+ const resultRootDependencies = {
4543
+ ...resultRoot.dependencies ?? {}
4544
+ };
4545
+ for (const peer of committedPeerNames) {
4546
+ if (npmRootDependencies[peer])
4547
+ resultRootDependencies[peer] = npmRootDependencies[peer];
4548
+ }
4549
+ if (Object.keys(resultRootDependencies).length > 0) {
4550
+ resultRoot.dependencies = resultRootDependencies;
4551
+ }
4552
+ if (npmLock.dependencies) {
4553
+ result2.dependencies ?? (result2.dependencies = {});
4554
+ for (const peer of committedPeerNames) {
4555
+ if (npmLock.dependencies[peer]) {
4556
+ result2.dependencies[peer] = cloneJson(npmLock.dependencies[peer]);
4557
+ }
4558
+ }
4559
+ }
4560
+ return Buffer.from(`${JSON.stringify(result2, null, 2)}
4561
+ `);
4562
+ }
4563
+ const result = cloneJson(npmLock);
4564
+ const resultPackages = result.packages ?? {};
4565
+ const initialRoots = /* @__PURE__ */ new Set([
4566
+ ...Object.keys(initialPackage.dependencies ?? {}),
4567
+ ...Object.keys(initialPackage.devDependencies ?? {}),
4568
+ ...Object.keys(initialPackage.optionalDependencies ?? {})
4569
+ ]);
4570
+ const retainedClosure = collectLockClosure(npmPackages, [
4571
+ ...initialRoots,
4572
+ ...committedPeerNames
4573
+ ]);
4574
+ const uncommittedClosure = collectLockClosure(
4575
+ npmPackages,
4576
+ [...allPeerNames].filter((name) => !committedPeerNames.has(name))
4577
+ );
4578
+ for (const key of uncommittedClosure) {
4579
+ if (!retainedClosure.has(key)) delete resultPackages[key];
4580
+ }
4581
+ const rootEntry = resultPackages[""];
4582
+ if (rootEntry) {
4583
+ for (const section of [
4584
+ "dependencies",
4585
+ "devDependencies",
4586
+ "optionalDependencies"
4587
+ ]) {
4588
+ const values = rootEntry[section];
4589
+ if (!values) continue;
4590
+ for (const peer of allPeerNames) {
4591
+ if (!committedPeerNames.has(peer) && !initialRoots.has(peer))
4592
+ delete values[peer];
4593
+ }
4594
+ }
4595
+ }
4596
+ if (result.dependencies) {
4597
+ for (const peer of allPeerNames) {
4598
+ if (!committedPeerNames.has(peer) && !initialRoots.has(peer)) {
4599
+ delete result.dependencies[peer];
4600
+ }
4601
+ }
4602
+ }
4603
+ return Buffer.from(`${JSON.stringify(result, null, 2)}
4604
+ `);
4605
+ }
4606
+
4607
+ // src/commands/action-plugin/utils.ts
4608
+ import fs19 from "fs";
4609
+ import path16 from "path";
4610
+ import { spawnSync as spawnSync6, execSync as execSync2 } from "child_process";
4611
+ function parsePluginName(input) {
4612
+ const match = input.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
4613
+ if (!match) {
4614
+ throw new Error(
4615
+ `Invalid plugin name format: ${input}. Expected format: @scope/name or @scope/name@version`
4616
+ );
4617
+ }
4618
+ return {
4619
+ name: match[1],
4620
+ version: match[2] || "latest"
4621
+ };
4622
+ }
4623
+ function getProjectRoot() {
4624
+ return process.cwd();
4625
+ }
4626
+ function getPackageJsonPath() {
4627
+ return path16.join(getProjectRoot(), "package.json");
4628
+ }
4629
+ function getPluginPath(pluginName) {
4630
+ return path16.join(getProjectRoot(), "node_modules", pluginName);
4631
+ }
4632
+ function readPackageJson2() {
4633
+ const pkgPath = getPackageJsonPath();
4634
+ if (!fs19.existsSync(pkgPath)) {
4635
+ throw new Error("package.json not found in current directory");
4636
+ }
4637
+ try {
4638
+ const content = fs19.readFileSync(pkgPath, "utf-8");
4639
+ return JSON.parse(content);
4640
+ } catch {
4641
+ throw new Error("Failed to parse package.json");
4642
+ }
4643
+ }
4644
+ function writePackageJson2(pkg2) {
4645
+ const pkgPath = getPackageJsonPath();
4646
+ fs19.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
4647
+ }
4648
+ function readActionPlugins() {
4649
+ const pkg2 = readPackageJson2();
4650
+ return pkg2.actionPlugins || {};
4651
+ }
4652
+ function writeActionPlugins(plugins) {
4653
+ const pkg2 = readPackageJson2();
4654
+ pkg2.actionPlugins = plugins;
4655
+ writePackageJson2(pkg2);
4656
+ }
4657
+ function isPluginInstalled(pluginName) {
4658
+ const plugins = readActionPlugins();
4659
+ return pluginName in plugins;
4660
+ }
4661
+ function getInstalledPluginVersion(pluginName) {
4662
+ const plugins = readActionPlugins();
4663
+ return plugins[pluginName] || null;
4664
+ }
4665
+ function npmInstall(tgzPath) {
4666
+ console.log(`[action-plugin] Running npm install ${tgzPath}...`);
4667
+ const result = spawnSync6("npm", ["install", tgzPath, "--no-save", "--no-package-lock", "--ignore-scripts"], {
4668
+ cwd: getProjectRoot(),
4669
+ stdio: "inherit"
4670
+ });
4671
+ if (result.error) {
4672
+ throw new Error(`npm install failed: ${result.error.message}`);
4673
+ }
4674
+ if (result.status !== 0) {
4675
+ throw new Error(`npm install failed with exit code ${result.status}`);
4676
+ }
4677
+ }
4678
+ function getPackageVersion(pluginName) {
4679
+ const pkgJsonPath = path16.join(getPluginPath(pluginName), "package.json");
4680
+ if (!fs19.existsSync(pkgJsonPath)) {
4681
+ return null;
4682
+ }
4683
+ try {
4684
+ const content = fs19.readFileSync(pkgJsonPath, "utf-8");
4685
+ const pkg2 = JSON.parse(content);
4686
+ return pkg2.version || null;
4687
+ } catch {
4688
+ return null;
4689
+ }
4690
+ }
4691
+ function removePluginDirectory(pluginName) {
4692
+ const pluginPath2 = getPluginPath(pluginName);
4693
+ if (fs19.existsSync(pluginPath2)) {
4694
+ fs19.rmSync(pluginPath2, { recursive: true });
4695
+ console.log(`[action-plugin] Removed ${pluginName}`);
4696
+ }
4697
+ }
4698
+
4699
+ // src/commands/action-plugin/restore.handler.ts
4700
+ import fs20 from "fs";
4701
+ import path17 from "path";
4702
+ async function defaultMaterializePlugin2(name, version, destination) {
4703
+ let tgzPath;
4704
+ if (hasCachedPlugin(name, version)) {
4705
+ tgzPath = getCachePath(name, version);
4706
+ } else {
4707
+ const downloaded = await downloadPlugin(name, version);
4708
+ if (downloaded.version !== version) {
4709
+ throw new Error(
4710
+ `Downloaded version mismatch for ${name}: expected ${version}, got ${downloaded.version}`
4711
+ );
4712
+ }
4713
+ tgzPath = downloaded.tgzPath;
4714
+ }
4715
+ fs20.mkdirSync(path17.dirname(destination), { recursive: true });
4716
+ extractTgzToDirectory(tgzPath, destination);
4717
+ }
4718
+ async function restoreActionPlugins(plugins, options = {}) {
4719
+ const projectRoot = options.projectRoot ?? process.cwd();
4720
+ const stagingRoot = createStagingRoot();
4721
+ const results = [];
4722
+ try {
4723
+ for (const [index, [name, version]] of Object.entries(plugins).entries()) {
4724
+ const targetPath = path17.join(projectRoot, "node_modules", name);
4725
+ try {
4726
+ let manifest;
4727
+ try {
4728
+ manifest = assertPluginIdentity(targetPath, name, version);
4729
+ } catch {
4730
+ manifest = null;
4731
+ }
4732
+ if (manifest) {
4733
+ const missingPeers2 = findMissingPeerDependencies(
4734
+ projectRoot,
4735
+ manifest.peerDependencies
4736
+ );
4737
+ if (missingPeers2.length > 0) {
4738
+ throw new Error(
4739
+ `Missing peer dependencies: ${missingPeers2.join(", ")}`
4740
+ );
4741
+ }
4742
+ results.push({ name, version, success: true, skipped: true });
4743
+ continue;
4744
+ }
4745
+ const stagedPath = path17.join(stagingRoot, "prepared", String(index));
4746
+ await (options.materializePlugin ?? defaultMaterializePlugin2)(
4747
+ name,
4748
+ version,
4749
+ stagedPath
4750
+ );
4751
+ const stagedManifest = assertPluginIdentity(stagedPath, name, version);
4752
+ const missingPeers = findMissingPeerDependencies(
4753
+ projectRoot,
4754
+ stagedManifest.peerDependencies
4755
+ );
4756
+ if (missingPeers.length > 0) {
4757
+ throw new Error(
4758
+ `Missing peer dependencies: ${missingPeers.join(", ")}`
4759
+ );
4760
+ }
4761
+ const snapshot = snapshotDirectory(
4762
+ targetPath,
4763
+ stagingRoot,
4764
+ `restore-${index}`
4765
+ );
4766
+ try {
4767
+ replaceDirectory(stagedPath, targetPath);
4768
+ assertPluginIdentity(targetPath, name, version);
4769
+ } catch (error) {
4770
+ restoreDirectory(snapshot);
4771
+ throw error;
4772
+ }
4773
+ results.push({ name, version, success: true });
4774
+ } catch (error) {
4775
+ results.push({
4776
+ name,
4777
+ version,
4778
+ success: false,
4779
+ error: error instanceof Error ? error.message : String(error)
4780
+ });
4781
+ }
4782
+ }
4783
+ return results;
4784
+ } finally {
4785
+ fs20.rmSync(stagingRoot, { recursive: true, force: true });
4786
+ }
4787
+ }
4788
+ async function restore(options = {}) {
4789
+ console.log("[action-plugin] Restoring plugins from package.json...");
4790
+ const results = await restoreActionPlugins(readActionPlugins(), options);
4791
+ const failed = results.filter((result) => !result.success);
4792
+ for (const result of results) {
4793
+ if (result.success && !result.skipped) {
4794
+ console.log(
4795
+ `[action-plugin] \u2713 Restored ${result.name}@${result.version}`
4796
+ );
4797
+ } else if (!result.success) {
4798
+ console.error(
4799
+ `[action-plugin] \u2717 Failed to restore ${result.name}: ${result.error}`
4800
+ );
4801
+ }
4621
4802
  }
4622
- const files = fs17.readdirSync(cacheDir);
4623
- const result = [];
4624
- for (const file of files) {
4625
- if (!file.endsWith(".tgz")) continue;
4626
- const match = file.match(/^(.+)@(.+)\.tgz$/);
4627
- if (!match) continue;
4628
- const [, rawName, version] = match;
4629
- const name = rawName.replace(/^_/, "@").replace(/_/, "/");
4630
- const filePath = path14.join(cacheDir, file);
4631
- const stat = fs17.statSync(filePath);
4632
- result.push({
4633
- name,
4634
- version,
4635
- filePath,
4636
- size: stat.size,
4637
- mtime: stat.mtime
4638
- });
4803
+ if (failed.length > 0) process.exit(1);
4804
+ }
4805
+
4806
+ // src/commands/action-plugin/install-engine.ts
4807
+ var LOCK_FILE_NAMES = ["package-lock.json", "npm-shrinkwrap.json"];
4808
+ function defaultRunNpmInstall(projectRoot, specifiers, env) {
4809
+ const result = spawnSync7("npm", ["install", ...specifiers], {
4810
+ cwd: projectRoot,
4811
+ stdio: "inherit",
4812
+ env
4813
+ });
4814
+ if (result.error)
4815
+ throw new Error(`npm install failed: ${result.error.message}`);
4816
+ if (result.status !== 0) {
4817
+ throw new Error(`npm install failed with exit code ${result.status}`);
4639
4818
  }
4640
- return result;
4641
4819
  }
4642
- function cleanAllCache() {
4643
- const cacheDir = getPluginCacheDir();
4644
- if (!fs17.existsSync(cacheDir)) {
4645
- return 0;
4820
+ function preservePluginDirectories(projectRoot, packageDocument, requests, stagingRoot) {
4821
+ const names = /* @__PURE__ */ new Set([
4822
+ ...Object.keys(packageDocument.actionPlugins ?? {}),
4823
+ ...requests.map((request) => request.name)
4824
+ ]);
4825
+ return [...names].map(
4826
+ (name, index) => snapshotDirectory(
4827
+ pluginPath(projectRoot, name),
4828
+ stagingRoot,
4829
+ `npm-${index}`
4830
+ )
4831
+ );
4832
+ }
4833
+ function runNpmOnce(projectRoot, peerRanges, packageSnapshot, lockSnapshots, pluginSnapshots, options) {
4834
+ const specifiers = [...peerRanges].map(([name, range]) => `${name}@${range}`);
4835
+ const env = {
4836
+ ...process.env,
4837
+ [ACTION_PLUGIN_REENTRY_ENV]: ACTION_PLUGIN_REENTRY_VALUE
4838
+ };
4839
+ const capturedLocks = /* @__PURE__ */ new Map();
4840
+ let npmError;
4841
+ try {
4842
+ (options.runNpmInstall ?? ((specs, npmEnv) => defaultRunNpmInstall(projectRoot, specs, npmEnv)))(specifiers, env);
4843
+ for (const snapshot of lockSnapshots) {
4844
+ capturedLocks.set(snapshot.filePath, snapshotFile(snapshot.filePath));
4845
+ }
4846
+ } catch (error) {
4847
+ npmError = error;
4848
+ } finally {
4849
+ restoreFile(packageSnapshot);
4850
+ for (const snapshot of lockSnapshots) restoreFile(snapshot);
4851
+ for (const snapshot of pluginSnapshots) {
4852
+ if (npmError || snapshot.backupPath) restoreDirectory(snapshot);
4853
+ }
4646
4854
  }
4647
- const files = fs17.readdirSync(cacheDir);
4648
- let count = 0;
4649
- for (const file of files) {
4650
- if (file.endsWith(".tgz")) {
4651
- fs17.unlinkSync(path14.join(cacheDir, file));
4652
- count++;
4855
+ if (npmError) throw npmError;
4856
+ return { lockFiles: capturedLocks, pluginSnapshots };
4857
+ }
4858
+ function commitPluginPackage(packageJsonPath, plugin) {
4859
+ const latest = readPackageDocument(packageJsonPath);
4860
+ latest.actionPlugins = {
4861
+ ...latest.actionPlugins ?? {},
4862
+ [plugin.name]: plugin.version
4863
+ };
4864
+ for (const [dependency, range] of Object.entries(
4865
+ plugin.missingUndeclaredPeers
4866
+ )) {
4867
+ if (!rootDeclaresDependency(latest, dependency)) {
4868
+ latest.dependencies = {
4869
+ ...latest.dependencies ?? {},
4870
+ [dependency]: range
4871
+ };
4653
4872
  }
4654
4873
  }
4655
- return count;
4874
+ composeActionPluginLifecycle(latest);
4875
+ atomicWriteJson(packageJsonPath, latest);
4656
4876
  }
4657
- function cleanPluginCache(pluginKey, version) {
4658
- const cacheDir = getPluginCacheDir();
4659
- if (!fs17.existsSync(cacheDir)) {
4660
- return 0;
4877
+ function formatPreparationFailure(request, error) {
4878
+ return {
4879
+ name: request.name,
4880
+ version: request.requestedVersion,
4881
+ success: false,
4882
+ error: error instanceof Error ? error.message : String(error)
4883
+ };
4884
+ }
4885
+ async function restoreExistingDesiredState(initialPackage, requests, npmCapture, projectRoot, options) {
4886
+ const requestedNames = new Set(requests.map((request) => request.name));
4887
+ const desiredToRestore = Object.fromEntries(
4888
+ Object.entries(initialPackage.actionPlugins ?? {}).filter(
4889
+ ([name]) => !requestedNames.has(name)
4890
+ )
4891
+ );
4892
+ const restoreResults = await restoreActionPlugins(desiredToRestore, {
4893
+ projectRoot,
4894
+ materializePlugin: options.materializePlugin ? async (name, version, destination) => {
4895
+ await options.materializePlugin(name, version, destination);
4896
+ } : void 0
4897
+ });
4898
+ const restoreFailure = restoreResults.find((result) => !result.success);
4899
+ if (!restoreFailure) return null;
4900
+ for (const snapshot of npmCapture.pluginSnapshots) restoreDirectory(snapshot);
4901
+ return `Failed to restore ${restoreFailure.name}: ${restoreFailure.error}`;
4902
+ }
4903
+ function markPreparedPluginsFailed(preparedByIndex, results, message) {
4904
+ for (const [index, plugin] of preparedByIndex) {
4905
+ results.set(index, {
4906
+ name: plugin.name,
4907
+ version: plugin.version,
4908
+ success: false,
4909
+ error: message
4910
+ });
4661
4911
  }
4662
- const safeKey = pluginKey.replace(/[/@]/g, "_");
4663
- const files = fs17.readdirSync(cacheDir);
4664
- let count = 0;
4665
- for (const file of files) {
4666
- if (version) {
4667
- if (file === `${safeKey}@${version}.tgz`) {
4668
- fs17.unlinkSync(path14.join(cacheDir, file));
4669
- count++;
4912
+ }
4913
+ async function executePluginBatch(requests, mode, options = {}) {
4914
+ const projectRoot = options.projectRoot ?? process.cwd();
4915
+ const packageJsonPath = path18.join(projectRoot, "package.json");
4916
+ const stagingRoot = createStagingRoot();
4917
+ const initialPackage = readPackageDocument(packageJsonPath);
4918
+ const commandPackageSnapshot = snapshotFile(packageJsonPath);
4919
+ const commandLockSnapshots = LOCK_FILE_NAMES.map(
4920
+ (name) => snapshotFile(path18.join(projectRoot, name))
4921
+ );
4922
+ const preparedByIndex = /* @__PURE__ */ new Map();
4923
+ const results = /* @__PURE__ */ new Map();
4924
+ try {
4925
+ await Promise.all(
4926
+ requests.map(async (request, index) => {
4927
+ try {
4928
+ preparedByIndex.set(
4929
+ index,
4930
+ await preparePlugin(
4931
+ request,
4932
+ index,
4933
+ initialPackage,
4934
+ projectRoot,
4935
+ stagingRoot,
4936
+ options
4937
+ )
4938
+ );
4939
+ } catch (error) {
4940
+ results.set(index, formatPreparationFailure(request, error));
4941
+ }
4942
+ })
4943
+ );
4944
+ const prepared = [...preparedByIndex.values()];
4945
+ const conflict = findPeerRangeConflict(prepared);
4946
+ if (conflict) {
4947
+ return requests.map((request) => ({
4948
+ name: request.name,
4949
+ version: request.requestedVersion,
4950
+ success: false,
4951
+ error: conflict
4952
+ }));
4953
+ }
4954
+ const peerRanges = collectPeerRanges(prepared);
4955
+ let npmCapture = null;
4956
+ if (peerRanges.size > 0) {
4957
+ const pluginSnapshots = preservePluginDirectories(
4958
+ projectRoot,
4959
+ initialPackage,
4960
+ requests,
4961
+ stagingRoot
4962
+ );
4963
+ try {
4964
+ npmCapture = runNpmOnce(
4965
+ projectRoot,
4966
+ peerRanges,
4967
+ commandPackageSnapshot,
4968
+ commandLockSnapshots,
4969
+ pluginSnapshots,
4970
+ options
4971
+ );
4972
+ } catch (error) {
4973
+ const message = error instanceof Error ? error.message : String(error);
4974
+ markPreparedPluginsFailed(preparedByIndex, results, message);
4975
+ return requests.map(
4976
+ (request, index) => results.get(index) ?? formatPreparationFailure(request, error)
4977
+ );
4670
4978
  }
4671
- } else {
4672
- if (file.startsWith(`${safeKey}@`) && file.endsWith(".tgz")) {
4673
- fs17.unlinkSync(path14.join(cacheDir, file));
4674
- count++;
4979
+ const restoreFailure = await restoreExistingDesiredState(
4980
+ initialPackage,
4981
+ requests,
4982
+ npmCapture,
4983
+ projectRoot,
4984
+ options
4985
+ );
4986
+ if (restoreFailure) {
4987
+ markPreparedPluginsFailed(preparedByIndex, results, restoreFailure);
4988
+ return requests.map(
4989
+ (request, index) => results.get(index) ?? {
4990
+ name: request.name,
4991
+ version: request.requestedVersion,
4992
+ success: false,
4993
+ error: restoreFailure
4994
+ }
4995
+ );
4996
+ }
4997
+ }
4998
+ const committedPeers = /* @__PURE__ */ new Set();
4999
+ for (const [index, plugin] of [...preparedByIndex].sort(
5000
+ ([left], [right]) => left - right
5001
+ )) {
5002
+ const packageSnapshot = snapshotFile(packageJsonPath);
5003
+ const lockSnapshots = LOCK_FILE_NAMES.map(
5004
+ (name) => snapshotFile(path18.join(projectRoot, name))
5005
+ );
5006
+ const directorySnapshot = snapshotDirectory(
5007
+ pluginPath(projectRoot, plugin.name),
5008
+ stagingRoot,
5009
+ `transaction-${index}`
5010
+ );
5011
+ try {
5012
+ if (plugin.stagedPath) {
5013
+ replaceDirectory(
5014
+ plugin.stagedPath,
5015
+ pluginPath(projectRoot, plugin.name)
5016
+ );
5017
+ }
5018
+ const manifest = assertPluginIdentity(
5019
+ pluginPath(projectRoot, plugin.name),
5020
+ plugin.name,
5021
+ plugin.version
5022
+ );
5023
+ const missingPeers = findMissingPeerDependencies(
5024
+ projectRoot,
5025
+ manifest.peerDependencies
5026
+ );
5027
+ if (missingPeers.length > 0) {
5028
+ throw new Error(
5029
+ `Missing peer dependencies: ${missingPeers.join(", ")}`
5030
+ );
5031
+ }
5032
+ options.beforeCommit?.(plugin, index);
5033
+ const nextCommittedPeers = /* @__PURE__ */ new Set([
5034
+ ...committedPeers,
5035
+ ...Object.keys(plugin.missingUndeclaredPeers)
5036
+ ]);
5037
+ if (nextCommittedPeers.size > committedPeers.size) {
5038
+ if (!npmCapture)
5039
+ throw new Error(
5040
+ "Missing npm transaction state for peer dependencies"
5041
+ );
5042
+ for (const initialLock of commandLockSnapshots) {
5043
+ const npmLock = npmCapture.lockFiles.get(initialLock.filePath);
5044
+ if (!npmLock || initialLock.content === null && npmLock.content === null)
5045
+ continue;
5046
+ atomicWriteFile(
5047
+ initialLock.filePath,
5048
+ buildCommittedLock(
5049
+ initialLock,
5050
+ npmLock,
5051
+ initialPackage,
5052
+ new Set(peerRanges.keys()),
5053
+ nextCommittedPeers
5054
+ )
5055
+ );
5056
+ }
5057
+ }
5058
+ commitPluginPackage(packageJsonPath, plugin);
5059
+ options.afterCommit?.(plugin, index);
5060
+ for (const peer of nextCommittedPeers) committedPeers.add(peer);
5061
+ const skipped = plugin.source === "existing";
5062
+ results.set(index, {
5063
+ name: plugin.name,
5064
+ version: plugin.version,
5065
+ success: true,
5066
+ skipped
5067
+ });
5068
+ if (options.reportEvents !== false && mode === "install") {
5069
+ if (!skipped)
5070
+ reportInstallEvent(plugin.name, plugin.version).catch(() => {
5071
+ });
5072
+ reportCreateInstanceEvent(plugin.name, plugin.version).catch(
5073
+ () => {
5074
+ }
5075
+ );
5076
+ }
5077
+ } catch (error) {
5078
+ restoreFile(packageSnapshot);
5079
+ for (const lockSnapshot of lockSnapshots) restoreFile(lockSnapshot);
5080
+ restoreDirectory(directorySnapshot);
5081
+ results.set(index, {
5082
+ name: plugin.name,
5083
+ version: plugin.version,
5084
+ success: false,
5085
+ error: error instanceof Error ? error.message : String(error)
5086
+ });
4675
5087
  }
4676
5088
  }
5089
+ return requests.map(
5090
+ (request, index) => results.get(index) ?? {
5091
+ name: request.name,
5092
+ version: request.requestedVersion,
5093
+ success: false,
5094
+ error: "Plugin was not processed"
5095
+ }
5096
+ );
5097
+ } finally {
5098
+ fs21.rmSync(stagingRoot, { recursive: true, force: true });
4677
5099
  }
4678
- return count;
5100
+ }
5101
+ async function installPluginBatch(namesWithVersions, options = {}) {
5102
+ const requests = namesWithVersions.map((value) => parsePluginName(value));
5103
+ return executePluginBatch(
5104
+ requests.map(({ name, version }) => ({
5105
+ name,
5106
+ requestedVersion: version
5107
+ })),
5108
+ "install",
5109
+ options
5110
+ );
5111
+ }
5112
+ async function initPluginBatch(plugins, options = {}) {
5113
+ return executePluginBatch(
5114
+ Object.entries(plugins).map(([name, version]) => ({
5115
+ name,
5116
+ requestedVersion: version
5117
+ })),
5118
+ "init",
5119
+ options
5120
+ );
4679
5121
  }
4680
5122
 
4681
5123
  // src/commands/action-plugin/init.handler.ts
4682
- async function installOneForInit(name, version) {
4683
- try {
4684
- const installedVersion2 = getPackageVersion(name);
4685
- if (installedVersion2 === version) {
4686
- return { name, version, success: true, skipped: true };
4687
- }
4688
- let tgzPath;
4689
- let fromCache = false;
4690
- if (hasCachedPlugin(name, version)) {
4691
- console.log(`[action-plugin] \u21BB Restoring ${name}@${version} from cache...`);
4692
- tgzPath = getCachePath(name, version);
4693
- fromCache = true;
4694
- } else {
4695
- console.log(`[action-plugin] \u2193 Downloading ${name}@${version}...`);
4696
- const downloadResult = await downloadPlugin(name, version);
4697
- tgzPath = downloadResult.tgzPath;
4698
- }
4699
- const pluginDir = extractTgzToNodeModules(tgzPath, name);
4700
- const pluginPkg = readPluginPackageJson(pluginDir);
4701
- if (pluginPkg?.peerDependencies) {
4702
- const missingDeps = checkMissingPeerDeps(pluginPkg.peerDependencies);
4703
- if (missingDeps.length > 0) {
4704
- installMissingDeps(missingDeps);
4705
- }
4706
- }
4707
- const source = fromCache ? "from cache" : "downloaded";
4708
- console.log(`[action-plugin] \u2713 Installed ${name}@${version} (${source})`);
4709
- return { name, version, success: true };
4710
- } catch (error) {
4711
- const message = error instanceof Error ? error.message : String(error);
4712
- console.error(`[action-plugin] \u2717 Failed to install ${name}: ${message}`);
4713
- return { name, version, success: false, error: message };
5124
+ async function init(options = {}) {
5125
+ if (process.env[ACTION_PLUGIN_REENTRY_ENV] === ACTION_PLUGIN_REENTRY_VALUE) {
5126
+ await restore(options.restoreOptions);
5127
+ return;
4714
5128
  }
4715
- }
4716
- async function init() {
4717
5129
  console.log("[action-plugin] Reading plugins from package.json...");
4718
5130
  const plugins = readActionPlugins();
4719
5131
  const entries = Object.entries(plugins);
@@ -4723,131 +5135,84 @@ async function init() {
4723
5135
  }
4724
5136
  console.log(`[action-plugin] Found ${entries.length} plugin(s) to install
4725
5137
  `);
4726
- const results = [];
4727
- for (const [name, version] of entries) {
4728
- const result = await installOneForInit(name, version);
4729
- results.push(result);
5138
+ const results = await initPluginBatch(plugins, options);
5139
+ const failed = results.filter((result) => !result.success);
5140
+ const skipped = results.filter((result) => result.success && result.skipped);
5141
+ for (const result of results) {
5142
+ if (result.success && !result.skipped) {
5143
+ console.log(
5144
+ `[action-plugin] \u2713 Installed ${result.name}@${result.version}`
5145
+ );
5146
+ } else if (!result.success) {
5147
+ console.error(
5148
+ `[action-plugin] \u2717 Failed to install ${result.name}: ${result.error}`
5149
+ );
5150
+ }
4730
5151
  }
4731
- console.log("");
4732
- const successful = results.filter((r) => r.success && !r.skipped);
4733
- const skipped = results.filter((r) => r.skipped);
4734
- const failed = results.filter((r) => !r.success);
4735
- if (successful.length > 0 || skipped.length > 0) {
5152
+ if (failed.length === 0) {
4736
5153
  console.log(
4737
- `[action-plugin] \u2713 All plugins installed successfully (${successful.length + skipped.length}/${entries.length})`
5154
+ `[action-plugin] \u2713 All plugins installed successfully (${results.length}/${entries.length})`
4738
5155
  );
4739
5156
  if (skipped.length > 0) {
4740
- console.log(` Skipped (already installed): ${skipped.map((r) => r.name).join(", ")}`);
5157
+ console.log(
5158
+ ` Skipped (already installed): ${skipped.map((result) => result.name).join(", ")}`
5159
+ );
4741
5160
  }
5161
+ return;
4742
5162
  }
4743
- if (failed.length > 0) {
4744
- console.log(`[action-plugin] \u2717 Failed to install ${failed.length} plugin(s): ${failed.map((r) => r.name).join(", ")}`);
4745
- process.exit(1);
4746
- }
5163
+ console.log(
5164
+ `[action-plugin] \u2717 Failed to install ${failed.length} plugin(s): ${failed.map((result) => result.name).join(", ")}`
5165
+ );
5166
+ process.exit(1);
4747
5167
  }
4748
5168
 
4749
5169
  // src/commands/action-plugin/install.handler.ts
4750
- function syncActionPluginsRecord(name, version) {
4751
- const plugins = readActionPlugins();
4752
- if (plugins[name] !== version) {
4753
- plugins[name] = version;
4754
- writeActionPlugins(plugins);
4755
- console.log(`[action-plugin] Synced actionPlugins record: ${name}@${version}`);
4756
- }
4757
- }
4758
- async function installOne(nameWithVersion) {
4759
- const { name, version: requestedVersion } = parsePluginName(nameWithVersion);
4760
- try {
4761
- console.log(`[action-plugin] Installing ${name}@${requestedVersion}...`);
4762
- const actualVersion = getPackageVersion(name);
4763
- if (actualVersion && requestedVersion !== "latest") {
4764
- if (actualVersion === requestedVersion) {
4765
- console.log(`[action-plugin] Plugin ${name}@${requestedVersion} is already installed`);
4766
- syncActionPluginsRecord(name, actualVersion);
4767
- reportCreateInstanceEvent(name, actualVersion).catch(() => {
4768
- });
4769
- return { name, version: actualVersion, success: true, skipped: true };
4770
- }
4771
- }
4772
- let targetVersion = requestedVersion;
4773
- if (requestedVersion === "latest") {
4774
- const latestInfo = await getPluginVersion(name, "latest");
4775
- targetVersion = latestInfo.version;
4776
- if (actualVersion === targetVersion) {
4777
- console.log(`[action-plugin] Plugin ${name} is already up to date (version: ${actualVersion})`);
4778
- syncActionPluginsRecord(name, actualVersion);
4779
- reportCreateInstanceEvent(name, actualVersion).catch(() => {
4780
- });
4781
- return { name, version: actualVersion, success: true, skipped: true };
4782
- }
4783
- console.log(`[action-plugin] Found newer version: ${targetVersion} (installed: ${actualVersion || "none"})`);
4784
- }
4785
- let tgzPath;
4786
- let fromCache = false;
4787
- if (hasCachedPlugin(name, targetVersion)) {
4788
- console.log(`[action-plugin] \u21BB Using cached ${name}@${targetVersion}...`);
4789
- tgzPath = getCachePath(name, targetVersion);
4790
- fromCache = true;
4791
- } else {
4792
- console.log(`[action-plugin] \u2193 Downloading ${name}@${targetVersion}...`);
4793
- const downloadResult = await downloadPlugin(name, requestedVersion);
4794
- tgzPath = downloadResult.tgzPath;
4795
- }
4796
- console.log(`[action-plugin] Extracting to node_modules...`);
4797
- const pluginDir = extractTgzToNodeModules(tgzPath, name);
4798
- const pluginPkg = readPluginPackageJson(pluginDir);
4799
- if (pluginPkg?.peerDependencies) {
4800
- const missingDeps = checkMissingPeerDeps(pluginPkg.peerDependencies);
4801
- if (missingDeps.length > 0) {
4802
- installMissingDeps(missingDeps);
4803
- }
4804
- }
4805
- const installedVersion2 = getPackageVersion(name) || targetVersion;
4806
- const plugins = readActionPlugins();
4807
- plugins[name] = installedVersion2;
4808
- writeActionPlugins(plugins);
4809
- const source = fromCache ? "from cache" : "downloaded";
4810
- console.log(`[action-plugin] Successfully installed ${name}@${installedVersion2} (${source})`);
4811
- reportInstallEvent(name, installedVersion2).catch(() => {
4812
- });
4813
- reportCreateInstanceEvent(name, installedVersion2).catch(() => {
4814
- });
4815
- return { name, version: installedVersion2, success: true };
4816
- } catch (error) {
4817
- const message = error instanceof Error ? error.message : String(error);
4818
- console.error(`[action-plugin] Failed to install ${name}: ${message}`);
4819
- return { name, version: requestedVersion, success: false, error: message };
4820
- }
4821
- }
4822
- async function install(namesWithVersion) {
5170
+ async function install(namesWithVersion, options = {}) {
4823
5171
  if (namesWithVersion.length === 0) {
4824
5172
  console.error("[action-plugin] No plugin names provided");
4825
5173
  process.exit(1);
5174
+ return;
4826
5175
  }
4827
- const results = [];
4828
- for (const nameWithVersion of namesWithVersion) {
4829
- console.log(`[action-plugin] Processing ${nameWithVersion}...`);
4830
- const result = await installOne(nameWithVersion);
4831
- results.push(result);
5176
+ const results = await installPluginBatch(namesWithVersion, options);
5177
+ for (const result of results) {
5178
+ if (result.success && result.skipped) {
5179
+ console.log(
5180
+ `[action-plugin] Plugin ${result.name}@${result.version} is already installed`
5181
+ );
5182
+ } else if (result.success) {
5183
+ console.log(
5184
+ `[action-plugin] Successfully installed ${result.name}@${result.version}`
5185
+ );
5186
+ } else {
5187
+ console.error(
5188
+ `[action-plugin] Failed to install ${result.name}: ${result.error}`
5189
+ );
5190
+ }
4832
5191
  }
4833
5192
  if (namesWithVersion.length > 1) {
5193
+ const successful = results.filter(
5194
+ (result) => result.success && !result.skipped
5195
+ );
5196
+ const skipped = results.filter((result) => result.success && result.skipped);
5197
+ const failed = results.filter((result) => !result.success);
4834
5198
  console.log("\n[action-plugin] Installation summary:");
4835
- const successful = results.filter((r) => r.success && !r.skipped);
4836
- const skipped = results.filter((r) => r.skipped);
4837
- const failed = results.filter((r) => !r.success);
4838
5199
  if (successful.length > 0) {
4839
- console.log(` \u2713 Installed: ${successful.map((r) => `${r.name}@${r.version}`).join(", ")}`);
5200
+ console.log(
5201
+ ` \u2713 Installed: ${successful.map((result) => `${result.name}@${result.version}`).join(", ")}`
5202
+ );
4840
5203
  }
4841
5204
  if (skipped.length > 0) {
4842
- console.log(` \u25CB Skipped (up to date): ${skipped.map((r) => r.name).join(", ")}`);
5205
+ console.log(
5206
+ ` \u25CB Skipped (up to date): ${skipped.map((result) => result.name).join(", ")}`
5207
+ );
4843
5208
  }
4844
5209
  if (failed.length > 0) {
4845
- console.log(` \u2717 Failed: ${failed.map((r) => r.name).join(", ")}`);
5210
+ console.log(
5211
+ ` \u2717 Failed: ${failed.map((result) => result.name).join(", ")}`
5212
+ );
4846
5213
  }
4847
5214
  }
4848
- if (results.some((r) => !r.success)) {
4849
- process.exit(1);
4850
- }
5215
+ if (results.some((result) => !result.success)) process.exit(1);
4851
5216
  }
4852
5217
 
4853
5218
  // src/commands/action-plugin/update.handler.ts
@@ -4869,12 +5234,12 @@ async function updateOne(nameWithVersion) {
4869
5234
  return { name, oldVersion, newVersion: downloadResult.version, success: true, skipped: true };
4870
5235
  }
4871
5236
  npmInstall(tgzPath);
4872
- const installedVersion2 = getPackageVersion(name) || downloadResult.version;
5237
+ const installedVersion = getPackageVersion(name) || downloadResult.version;
4873
5238
  const plugins = readActionPlugins();
4874
- plugins[name] = installedVersion2;
5239
+ plugins[name] = installedVersion;
4875
5240
  writeActionPlugins(plugins);
4876
- console.log(`[action-plugin] Successfully updated ${name} to ${installedVersion2}`);
4877
- return { name, oldVersion, newVersion: installedVersion2, success: true };
5241
+ console.log(`[action-plugin] Successfully updated ${name} to ${installedVersion}`);
5242
+ return { name, oldVersion, newVersion: installedVersion, success: true };
4878
5243
  } catch (error) {
4879
5244
  const message = error instanceof Error ? error.message : String(error);
4880
5245
  console.error(`[action-plugin] Failed to update ${name}: ${message}`);
@@ -5032,6 +5397,15 @@ var initCommand = {
5032
5397
  });
5033
5398
  }
5034
5399
  };
5400
+ var restoreCommand = {
5401
+ name: "restore",
5402
+ description: "Restore action plugins without changing npm dependencies",
5403
+ register(program) {
5404
+ program.command(this.name).description(this.description).action(async () => {
5405
+ await restore();
5406
+ });
5407
+ }
5408
+ };
5035
5409
  var installCommand = {
5036
5410
  name: "install",
5037
5411
  description: "Install action plugin(s) (default: latest version)",
@@ -5093,49 +5467,49 @@ var cacheCleanCommand = {
5093
5467
  var actionPluginCommandGroup = {
5094
5468
  name: "action-plugin",
5095
5469
  description: "Manage action plugins",
5096
- commands: [initCommand, installCommand, updateCommand, removeCommand, listCommand, cacheListCommand, cacheCleanCommand]
5470
+ commands: [initCommand, restoreCommand, installCommand, updateCommand, removeCommand, listCommand, cacheListCommand, cacheCleanCommand]
5097
5471
  };
5098
5472
 
5099
5473
  // src/commands/capability/utils.ts
5100
- import fs18 from "fs";
5474
+ import fs22 from "fs";
5101
5475
  import { createRequire as createRequire2 } from "module";
5102
- import path15 from "path";
5476
+ import path19 from "path";
5103
5477
  var CAPABILITIES_DIR = "server/capabilities";
5104
5478
  var SHARED_CAPABILITIES_DIR = "shared/capabilities";
5105
5479
  function getProjectRoot2() {
5106
5480
  return process.cwd();
5107
5481
  }
5108
5482
  function getCapabilitiesDir() {
5109
- const sharedDir = path15.join(getProjectRoot2(), SHARED_CAPABILITIES_DIR);
5110
- if (fs18.existsSync(sharedDir)) {
5483
+ const sharedDir = path19.join(getProjectRoot2(), SHARED_CAPABILITIES_DIR);
5484
+ if (fs22.existsSync(sharedDir)) {
5111
5485
  return sharedDir;
5112
5486
  }
5113
- return path15.join(getProjectRoot2(), CAPABILITIES_DIR);
5487
+ return path19.join(getProjectRoot2(), CAPABILITIES_DIR);
5114
5488
  }
5115
5489
  function getCapabilityPath(id) {
5116
- return path15.join(getCapabilitiesDir(), `${id}.json`);
5490
+ return path19.join(getCapabilitiesDir(), `${id}.json`);
5117
5491
  }
5118
5492
  function getPluginManifestPath(pluginKey) {
5119
- return path15.join(getProjectRoot2(), "node_modules", pluginKey, "manifest.json");
5493
+ return path19.join(getProjectRoot2(), "node_modules", pluginKey, "manifest.json");
5120
5494
  }
5121
5495
  function capabilitiesDirExists() {
5122
- return fs18.existsSync(getCapabilitiesDir());
5496
+ return fs22.existsSync(getCapabilitiesDir());
5123
5497
  }
5124
5498
  function listCapabilityIds() {
5125
5499
  const dir = getCapabilitiesDir();
5126
- if (!fs18.existsSync(dir)) {
5500
+ if (!fs22.existsSync(dir)) {
5127
5501
  return [];
5128
5502
  }
5129
- const files = fs18.readdirSync(dir);
5503
+ const files = fs22.readdirSync(dir);
5130
5504
  return files.filter((f) => f.endsWith(".json") && f !== "capabilities.json").map((f) => f.replace(/\.json$/, ""));
5131
5505
  }
5132
5506
  function readCapability(id) {
5133
5507
  const filePath = getCapabilityPath(id);
5134
- if (!fs18.existsSync(filePath)) {
5508
+ if (!fs22.existsSync(filePath)) {
5135
5509
  throw new Error(`Capability not found: ${id}`);
5136
5510
  }
5137
5511
  try {
5138
- const content = fs18.readFileSync(filePath, "utf-8");
5512
+ const content = fs22.readFileSync(filePath, "utf-8");
5139
5513
  return JSON.parse(content);
5140
5514
  } catch (error) {
5141
5515
  if (error instanceof SyntaxError) {
@@ -5160,13 +5534,13 @@ function readAllCapabilities() {
5160
5534
  }
5161
5535
  return capabilities;
5162
5536
  }
5163
- function readPluginManifest(pluginKey) {
5537
+ function readPluginManifest2(pluginKey) {
5164
5538
  const manifestPath = getPluginManifestPath(pluginKey);
5165
- if (!fs18.existsSync(manifestPath)) {
5539
+ if (!fs22.existsSync(manifestPath)) {
5166
5540
  throw new Error(`Plugin not installed: ${pluginKey} (manifest.json not found)`);
5167
5541
  }
5168
5542
  try {
5169
- const content = fs18.readFileSync(manifestPath, "utf-8");
5543
+ const content = fs22.readFileSync(manifestPath, "utf-8");
5170
5544
  return JSON.parse(content);
5171
5545
  } catch (error) {
5172
5546
  if (error instanceof SyntaxError) {
@@ -5183,7 +5557,7 @@ function hasValidParamsSchema(paramsSchema) {
5183
5557
  }
5184
5558
  async function loadPlugin(pluginKey) {
5185
5559
  try {
5186
- const userRequire = createRequire2(path15.join(getProjectRoot2(), "package.json"));
5560
+ const userRequire = createRequire2(path19.join(getProjectRoot2(), "package.json"));
5187
5561
  const resolvedPath = userRequire.resolve(pluginKey);
5188
5562
  const pluginModule = await import(resolvedPath);
5189
5563
  const pluginPackage = pluginModule.default ?? pluginModule;
@@ -5202,7 +5576,7 @@ async function loadPlugin(pluginKey) {
5202
5576
  }
5203
5577
  async function hydrateCapability(capability) {
5204
5578
  try {
5205
- const manifest = readPluginManifest(capability.pluginKey);
5579
+ const manifest = readPluginManifest2(capability.pluginKey);
5206
5580
  if (!manifest.actions || manifest.actions.length === 0) {
5207
5581
  throw new Error(`Plugin ${capability.pluginKey} has no actions defined`);
5208
5582
  }
@@ -5346,9 +5720,9 @@ var capabilityCommandGroup = {
5346
5720
  import { execFile } from "child_process";
5347
5721
 
5348
5722
  // src/commands/component/registry-preparer.ts
5349
- import fs19 from "fs";
5350
- import path16 from "path";
5351
- import os from "os";
5723
+ import fs23 from "fs";
5724
+ import path20 from "path";
5725
+ import os2 from "os";
5352
5726
 
5353
5727
  // src/commands/component/service.ts
5354
5728
  import { mapValues } from "es-toolkit";
@@ -5407,7 +5781,7 @@ async function sendInstallEvent(key) {
5407
5781
  }
5408
5782
 
5409
5783
  // src/commands/component/registry-preparer.ts
5410
- var REGISTRY_TEMP_DIR = path16.join(os.tmpdir(), "miaoda-registry");
5784
+ var REGISTRY_TEMP_DIR = path20.join(os2.tmpdir(), "miaoda-registry");
5411
5785
  function parseComponentKey(key) {
5412
5786
  const match = key.match(/^@([^/]+)\/(.+)$/);
5413
5787
  if (!match) {
@@ -5419,11 +5793,11 @@ function parseComponentKey(key) {
5419
5793
  }
5420
5794
  function getLocalRegistryPath(key) {
5421
5795
  const { scope, name } = parseComponentKey(key);
5422
- return path16.join(REGISTRY_TEMP_DIR, scope, `${name}.json`);
5796
+ return path20.join(REGISTRY_TEMP_DIR, scope, `${name}.json`);
5423
5797
  }
5424
5798
  function ensureDir(dirPath) {
5425
- if (!fs19.existsSync(dirPath)) {
5426
- fs19.mkdirSync(dirPath, { recursive: true });
5799
+ if (!fs23.existsSync(dirPath)) {
5800
+ fs23.mkdirSync(dirPath, { recursive: true });
5427
5801
  }
5428
5802
  }
5429
5803
  async function prepareRecursive(key, visited) {
@@ -5456,8 +5830,8 @@ async function prepareRecursive(key, visited) {
5456
5830
  registryDependencies: deps.map((dep) => getLocalRegistryPath(dep))
5457
5831
  };
5458
5832
  const localPath = getLocalRegistryPath(key);
5459
- ensureDir(path16.dirname(localPath));
5460
- fs19.writeFileSync(localPath, JSON.stringify(rewrittenItem, null, 2), "utf-8");
5833
+ ensureDir(path20.dirname(localPath));
5834
+ fs23.writeFileSync(localPath, JSON.stringify(rewrittenItem, null, 2), "utf-8");
5461
5835
  debug("\u4FDD\u5B58\u5230: %s", localPath);
5462
5836
  }
5463
5837
  async function prepareComponentRegistryItems(id) {
@@ -5467,18 +5841,18 @@ async function prepareComponentRegistryItems(id) {
5467
5841
  }
5468
5842
  function cleanupTempDir() {
5469
5843
  try {
5470
- if (fs19.existsSync(REGISTRY_TEMP_DIR)) {
5471
- fs19.rmSync(REGISTRY_TEMP_DIR, { recursive: true, force: true });
5844
+ if (fs23.existsSync(REGISTRY_TEMP_DIR)) {
5845
+ fs23.rmSync(REGISTRY_TEMP_DIR, { recursive: true, force: true });
5472
5846
  }
5473
5847
  } catch {
5474
5848
  }
5475
5849
  }
5476
5850
  function getDownloadedRegistryItem(itemId) {
5477
5851
  const localPath = getLocalRegistryPath(itemId);
5478
- if (!fs19.existsSync(localPath)) {
5852
+ if (!fs23.existsSync(localPath)) {
5479
5853
  return null;
5480
5854
  }
5481
- const content = fs19.readFileSync(localPath, "utf-8");
5855
+ const content = fs23.readFileSync(localPath, "utf-8");
5482
5856
  return JSON.parse(content);
5483
5857
  }
5484
5858
 
@@ -5646,58 +6020,58 @@ var componentCommandGroup = {
5646
6020
  };
5647
6021
 
5648
6022
  // src/commands/migration/version-manager.ts
5649
- import fs20 from "fs";
5650
- import path17 from "path";
6023
+ import fs24 from "fs";
6024
+ import path21 from "path";
5651
6025
  var PACKAGE_JSON = "package.json";
5652
6026
  var VERSION_FIELD = "migrationVersion";
5653
6027
  function getPackageJsonPath2() {
5654
- return path17.join(process.cwd(), PACKAGE_JSON);
6028
+ return path21.join(process.cwd(), PACKAGE_JSON);
5655
6029
  }
5656
6030
  function getCurrentVersion() {
5657
6031
  const pkgPath = getPackageJsonPath2();
5658
- if (!fs20.existsSync(pkgPath)) {
6032
+ if (!fs24.existsSync(pkgPath)) {
5659
6033
  throw new Error("package.json not found");
5660
6034
  }
5661
- const pkg2 = JSON.parse(fs20.readFileSync(pkgPath, "utf-8"));
6035
+ const pkg2 = JSON.parse(fs24.readFileSync(pkgPath, "utf-8"));
5662
6036
  return pkg2[VERSION_FIELD] ?? 0;
5663
6037
  }
5664
6038
  function setCurrentVersion(version) {
5665
6039
  const pkgPath = getPackageJsonPath2();
5666
- const pkg2 = JSON.parse(fs20.readFileSync(pkgPath, "utf-8"));
6040
+ const pkg2 = JSON.parse(fs24.readFileSync(pkgPath, "utf-8"));
5667
6041
  pkg2[VERSION_FIELD] = version;
5668
- fs20.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
6042
+ fs24.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
5669
6043
  }
5670
6044
 
5671
6045
  // src/commands/migration/versions/v001_capability/json-migrator/detector.ts
5672
- import fs22 from "fs";
5673
- import path19 from "path";
6046
+ import fs26 from "fs";
6047
+ import path23 from "path";
5674
6048
 
5675
6049
  // src/commands/migration/versions/v001_capability/utils.ts
5676
- import fs21 from "fs";
5677
- import path18 from "path";
6050
+ import fs25 from "fs";
6051
+ import path22 from "path";
5678
6052
  var CAPABILITIES_DIR2 = "server/capabilities";
5679
6053
  function getProjectRoot3() {
5680
6054
  return process.cwd();
5681
6055
  }
5682
6056
  function getCapabilitiesDir2() {
5683
- return path18.join(getProjectRoot3(), CAPABILITIES_DIR2);
6057
+ return path22.join(getProjectRoot3(), CAPABILITIES_DIR2);
5684
6058
  }
5685
6059
  function getPluginManifestPath2(pluginKey) {
5686
- return path18.join(getProjectRoot3(), "node_modules", pluginKey, "manifest.json");
6060
+ return path22.join(getProjectRoot3(), "node_modules", pluginKey, "manifest.json");
5687
6061
  }
5688
6062
 
5689
6063
  // src/commands/migration/versions/v001_capability/json-migrator/detector.ts
5690
6064
  function detectJsonMigration() {
5691
6065
  const capabilitiesDir = getCapabilitiesDir2();
5692
- const oldFilePath = path19.join(capabilitiesDir, "capabilities.json");
5693
- if (!fs22.existsSync(oldFilePath)) {
6066
+ const oldFilePath = path23.join(capabilitiesDir, "capabilities.json");
6067
+ if (!fs26.existsSync(oldFilePath)) {
5694
6068
  return {
5695
6069
  needsMigration: false,
5696
6070
  reason: "capabilities.json not found"
5697
6071
  };
5698
6072
  }
5699
6073
  try {
5700
- const content = fs22.readFileSync(oldFilePath, "utf-8");
6074
+ const content = fs26.readFileSync(oldFilePath, "utf-8");
5701
6075
  const parsed = JSON.parse(content);
5702
6076
  if (!Array.isArray(parsed)) {
5703
6077
  return {
@@ -5748,8 +6122,8 @@ async function check(options) {
5748
6122
  }
5749
6123
 
5750
6124
  // src/commands/migration/versions/v001_capability/json-migrator/index.ts
5751
- import fs23 from "fs";
5752
- import path20 from "path";
6125
+ import fs27 from "fs";
6126
+ import path24 from "path";
5753
6127
 
5754
6128
  // src/commands/migration/versions/v001_capability/mapping.ts
5755
6129
  var DEFAULT_PLUGIN_VERSION = "1.0.0";
@@ -5979,18 +6353,18 @@ function transformCapabilities(oldCapabilities) {
5979
6353
  // src/commands/migration/versions/v001_capability/json-migrator/index.ts
5980
6354
  function loadExistingCapabilities() {
5981
6355
  const capabilitiesDir = getCapabilitiesDir2();
5982
- if (!fs23.existsSync(capabilitiesDir)) {
6356
+ if (!fs27.existsSync(capabilitiesDir)) {
5983
6357
  return [];
5984
6358
  }
5985
- const files = fs23.readdirSync(capabilitiesDir);
6359
+ const files = fs27.readdirSync(capabilitiesDir);
5986
6360
  const capabilities = [];
5987
6361
  for (const file of files) {
5988
6362
  if (file === "capabilities.json" || !file.endsWith(".json")) {
5989
6363
  continue;
5990
6364
  }
5991
6365
  try {
5992
- const filePath = path20.join(capabilitiesDir, file);
5993
- const content = fs23.readFileSync(filePath, "utf-8");
6366
+ const filePath = path24.join(capabilitiesDir, file);
6367
+ const content = fs27.readFileSync(filePath, "utf-8");
5994
6368
  const capability = JSON.parse(content);
5995
6369
  if (capability.id && capability.pluginKey) {
5996
6370
  capabilities.push(capability);
@@ -6048,9 +6422,9 @@ async function migrateJsonFiles(options) {
6048
6422
  }
6049
6423
  const capabilitiesDir = getCapabilitiesDir2();
6050
6424
  for (const cap of newCapabilities) {
6051
- const filePath = path20.join(capabilitiesDir, `${cap.id}.json`);
6425
+ const filePath = path24.join(capabilitiesDir, `${cap.id}.json`);
6052
6426
  const content = JSON.stringify(cap, null, 2);
6053
- fs23.writeFileSync(filePath, content, "utf-8");
6427
+ fs27.writeFileSync(filePath, content, "utf-8");
6054
6428
  console.log(` \u2713 Created: ${cap.id}.json`);
6055
6429
  }
6056
6430
  return {
@@ -6062,11 +6436,11 @@ async function migrateJsonFiles(options) {
6062
6436
  }
6063
6437
 
6064
6438
  // src/commands/migration/versions/v001_capability/plugin-installer/detector.ts
6065
- import fs24 from "fs";
6439
+ import fs28 from "fs";
6066
6440
  function isPluginInstalled2(pluginKey) {
6067
6441
  const actionPlugins = readActionPlugins();
6068
6442
  const manifestPath = getPluginManifestPath2(pluginKey);
6069
- return fs24.existsSync(manifestPath) && !!actionPlugins[pluginKey];
6443
+ return fs28.existsSync(manifestPath) && !!actionPlugins[pluginKey];
6070
6444
  }
6071
6445
  function detectPluginsToInstall(capabilities) {
6072
6446
  const pluginKeys = /* @__PURE__ */ new Set();
@@ -6142,12 +6516,12 @@ async function installPlugins(capabilities, options) {
6142
6516
  }
6143
6517
 
6144
6518
  // src/commands/migration/versions/v001_capability/code-migrator/index.ts
6145
- import path22 from "path";
6519
+ import path26 from "path";
6146
6520
  import { Project as Project3 } from "ts-morph";
6147
6521
 
6148
6522
  // src/commands/migration/versions/v001_capability/code-migrator/scanner.ts
6149
- import fs25 from "fs";
6150
- import path21 from "path";
6523
+ import fs29 from "fs";
6524
+ import path25 from "path";
6151
6525
  var EXCLUDED_DIRS = [
6152
6526
  "node_modules",
6153
6527
  "dist",
@@ -6162,9 +6536,9 @@ var EXCLUDED_PATTERNS = [
6162
6536
  /\.d\.ts$/
6163
6537
  ];
6164
6538
  function scanDirectory(dir, files = []) {
6165
- const entries = fs25.readdirSync(dir, { withFileTypes: true });
6539
+ const entries = fs29.readdirSync(dir, { withFileTypes: true });
6166
6540
  for (const entry of entries) {
6167
- const fullPath = path21.join(dir, entry.name);
6541
+ const fullPath = path25.join(dir, entry.name);
6168
6542
  if (entry.isDirectory()) {
6169
6543
  if (EXCLUDED_DIRS.includes(entry.name)) {
6170
6544
  continue;
@@ -6180,14 +6554,14 @@ function scanDirectory(dir, files = []) {
6180
6554
  return files;
6181
6555
  }
6182
6556
  function scanServerFiles() {
6183
- const serverDir = path21.join(getProjectRoot3(), "server");
6184
- if (!fs25.existsSync(serverDir)) {
6557
+ const serverDir = path25.join(getProjectRoot3(), "server");
6558
+ if (!fs29.existsSync(serverDir)) {
6185
6559
  return [];
6186
6560
  }
6187
6561
  return scanDirectory(serverDir);
6188
6562
  }
6189
6563
  function hasCapabilityImport(filePath) {
6190
- const content = fs25.readFileSync(filePath, "utf-8");
6564
+ const content = fs29.readFileSync(filePath, "utf-8");
6191
6565
  return /import\s+.*from\s+['"][^'"]*capabilities[^'"]*['"]/.test(content);
6192
6566
  }
6193
6567
  function scanFilesToMigrate() {
@@ -6564,7 +6938,7 @@ function analyzeFile(project, filePath, actionNameMap) {
6564
6938
  const callSites = analyzeCallSites(sourceFile, imports);
6565
6939
  const classInfo = analyzeClass(sourceFile);
6566
6940
  const { canMigrate, reason } = canAutoMigrate(classInfo);
6567
- const relativePath = path22.relative(getProjectRoot3(), filePath);
6941
+ const relativePath = path26.relative(getProjectRoot3(), filePath);
6568
6942
  return {
6569
6943
  filePath: relativePath,
6570
6944
  imports,
@@ -6575,7 +6949,7 @@ function analyzeFile(project, filePath, actionNameMap) {
6575
6949
  };
6576
6950
  }
6577
6951
  function migrateFile(project, analysis, dryRun) {
6578
- const absolutePath = path22.join(getProjectRoot3(), analysis.filePath);
6952
+ const absolutePath = path26.join(getProjectRoot3(), analysis.filePath);
6579
6953
  if (!analysis.canAutoMigrate) {
6580
6954
  return {
6581
6955
  filePath: analysis.filePath,
@@ -6678,17 +7052,17 @@ function getSuggestion(analysis) {
6678
7052
  }
6679
7053
 
6680
7054
  // src/commands/migration/versions/v001_capability/cleanup.ts
6681
- import fs26 from "fs";
6682
- import path23 from "path";
7055
+ import fs30 from "fs";
7056
+ import path27 from "path";
6683
7057
  function cleanupOldFiles(capabilities, dryRun) {
6684
7058
  const deletedFiles = [];
6685
7059
  const errors = [];
6686
7060
  const capabilitiesDir = getCapabilitiesDir2();
6687
- const oldJsonPath = path23.join(capabilitiesDir, "capabilities.json");
6688
- if (fs26.existsSync(oldJsonPath)) {
7061
+ const oldJsonPath = path27.join(capabilitiesDir, "capabilities.json");
7062
+ if (fs30.existsSync(oldJsonPath)) {
6689
7063
  try {
6690
7064
  if (!dryRun) {
6691
- fs26.unlinkSync(oldJsonPath);
7065
+ fs30.unlinkSync(oldJsonPath);
6692
7066
  }
6693
7067
  deletedFiles.push("capabilities.json");
6694
7068
  } catch (error) {
@@ -6696,11 +7070,11 @@ function cleanupOldFiles(capabilities, dryRun) {
6696
7070
  }
6697
7071
  }
6698
7072
  for (const cap of capabilities) {
6699
- const tsFilePath = path23.join(capabilitiesDir, `${cap.id}.ts`);
6700
- if (fs26.existsSync(tsFilePath)) {
7073
+ const tsFilePath = path27.join(capabilitiesDir, `${cap.id}.ts`);
7074
+ if (fs30.existsSync(tsFilePath)) {
6701
7075
  try {
6702
7076
  if (!dryRun) {
6703
- fs26.unlinkSync(tsFilePath);
7077
+ fs30.unlinkSync(tsFilePath);
6704
7078
  }
6705
7079
  deletedFiles.push(`${cap.id}.ts`);
6706
7080
  } catch (error) {
@@ -6716,8 +7090,8 @@ function cleanupOldFiles(capabilities, dryRun) {
6716
7090
  }
6717
7091
 
6718
7092
  // src/commands/migration/versions/v001_capability/report-generator.ts
6719
- import fs27 from "fs";
6720
- import path24 from "path";
7093
+ import fs31 from "fs";
7094
+ import path28 from "path";
6721
7095
  var REPORT_FILE = "capability-migration-report.md";
6722
7096
  function printSummary(result) {
6723
7097
  const { jsonMigration, pluginInstallation, codeMigration, cleanup } = result;
@@ -6880,15 +7254,15 @@ async function generateReport(result) {
6880
7254
  }
6881
7255
  lines.push("");
6882
7256
  const logDir = process.env.LOG_DIR || "logs";
6883
- if (!fs27.existsSync(logDir)) {
7257
+ if (!fs31.existsSync(logDir)) {
6884
7258
  return;
6885
7259
  }
6886
- const reportDir = path24.join(logDir, "migration");
6887
- if (!fs27.existsSync(reportDir)) {
6888
- fs27.mkdirSync(reportDir, { recursive: true });
7260
+ const reportDir = path28.join(logDir, "migration");
7261
+ if (!fs31.existsSync(reportDir)) {
7262
+ fs31.mkdirSync(reportDir, { recursive: true });
6889
7263
  }
6890
- const reportPath = path24.join(reportDir, REPORT_FILE);
6891
- fs27.writeFileSync(reportPath, lines.join("\n"), "utf-8");
7264
+ const reportPath = path28.join(reportDir, REPORT_FILE);
7265
+ fs31.writeFileSync(reportPath, lines.join("\n"), "utf-8");
6892
7266
  console.log(`\u{1F4C4} Report generated: ${reportPath}`);
6893
7267
  }
6894
7268
 
@@ -7420,10 +7794,10 @@ var migrationCommand = {
7420
7794
  };
7421
7795
 
7422
7796
  // src/commands/read-logs/index.ts
7423
- import path25 from "path";
7797
+ import path29 from "path";
7424
7798
 
7425
7799
  // src/commands/read-logs/std-utils.ts
7426
- import fs28 from "fs";
7800
+ import fs32 from "fs";
7427
7801
  function formatStdPrefixTime(localTime) {
7428
7802
  const match = localTime.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
7429
7803
  if (!match) return localTime;
@@ -7453,11 +7827,11 @@ function stripPrefixFromStdLine(line) {
7453
7827
  return `[${time}] ${content}`;
7454
7828
  }
7455
7829
  function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarker) {
7456
- const stat = fs28.statSync(filePath);
7830
+ const stat = fs32.statSync(filePath);
7457
7831
  if (stat.size === 0) {
7458
7832
  return { lines: [], markerFound: false, totalLinesCount: 0 };
7459
7833
  }
7460
- const fd = fs28.openSync(filePath, "r");
7834
+ const fd = fs32.openSync(filePath, "r");
7461
7835
  const chunkSize = 64 * 1024;
7462
7836
  let position = stat.size;
7463
7837
  let remainder = "";
@@ -7471,7 +7845,7 @@ function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarke
7471
7845
  const length = Math.min(chunkSize, position);
7472
7846
  position -= length;
7473
7847
  const buffer = Buffer.alloc(length);
7474
- fs28.readSync(fd, buffer, 0, length, position);
7848
+ fs32.readSync(fd, buffer, 0, length, position);
7475
7849
  let chunk = buffer.toString("utf8");
7476
7850
  if (remainder) {
7477
7851
  chunk += remainder;
@@ -7513,7 +7887,7 @@ function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarke
7513
7887
  }
7514
7888
  }
7515
7889
  } finally {
7516
- fs28.closeSync(fd);
7890
+ fs32.closeSync(fd);
7517
7891
  }
7518
7892
  return { lines: collected.reverse(), markerFound, totalLinesCount };
7519
7893
  }
@@ -7534,21 +7908,21 @@ function readServerStdSegment(filePath, maxLines, offset) {
7534
7908
  }
7535
7909
 
7536
7910
  // src/commands/read-logs/tail.ts
7537
- import fs29 from "fs";
7911
+ import fs33 from "fs";
7538
7912
  function fileExists(filePath) {
7539
7913
  try {
7540
- fs29.accessSync(filePath, fs29.constants.F_OK | fs29.constants.R_OK);
7914
+ fs33.accessSync(filePath, fs33.constants.F_OK | fs33.constants.R_OK);
7541
7915
  return true;
7542
7916
  } catch {
7543
7917
  return false;
7544
7918
  }
7545
7919
  }
7546
7920
  function readFileTailLines(filePath, maxLines) {
7547
- const stat = fs29.statSync(filePath);
7921
+ const stat = fs33.statSync(filePath);
7548
7922
  if (stat.size === 0) {
7549
7923
  return [];
7550
7924
  }
7551
- const fd = fs29.openSync(filePath, "r");
7925
+ const fd = fs33.openSync(filePath, "r");
7552
7926
  const chunkSize = 64 * 1024;
7553
7927
  const chunks = [];
7554
7928
  let position = stat.size;
@@ -7558,13 +7932,13 @@ function readFileTailLines(filePath, maxLines) {
7558
7932
  const length = Math.min(chunkSize, position);
7559
7933
  position -= length;
7560
7934
  const buffer = Buffer.alloc(length);
7561
- fs29.readSync(fd, buffer, 0, length, position);
7935
+ fs33.readSync(fd, buffer, 0, length, position);
7562
7936
  chunks.unshift(buffer.toString("utf8"));
7563
7937
  const chunkLines = buffer.toString("utf8").split("\n").length - 1;
7564
7938
  collectedLines += chunkLines;
7565
7939
  }
7566
7940
  } finally {
7567
- fs29.closeSync(fd);
7941
+ fs33.closeSync(fd);
7568
7942
  }
7569
7943
  const content = chunks.join("");
7570
7944
  const allLines = content.split("\n");
@@ -7580,11 +7954,11 @@ function readFileTailLines(filePath, maxLines) {
7580
7954
  return allLines.slice(allLines.length - maxLines);
7581
7955
  }
7582
7956
  function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
7583
- const stat = fs29.statSync(filePath);
7957
+ const stat = fs33.statSync(filePath);
7584
7958
  if (stat.size === 0) {
7585
7959
  return { lines: [], totalLinesCount: 0 };
7586
7960
  }
7587
- const fd = fs29.openSync(filePath, "r");
7961
+ const fd = fs33.openSync(filePath, "r");
7588
7962
  const chunkSize = 64 * 1024;
7589
7963
  let position = stat.size;
7590
7964
  let remainder = "";
@@ -7596,7 +7970,7 @@ function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
7596
7970
  const length = Math.min(chunkSize, position);
7597
7971
  position -= length;
7598
7972
  const buffer = Buffer.alloc(length);
7599
- fs29.readSync(fd, buffer, 0, length, position);
7973
+ fs33.readSync(fd, buffer, 0, length, position);
7600
7974
  let chunk = buffer.toString("utf8");
7601
7975
  if (remainder) {
7602
7976
  chunk += remainder;
@@ -7627,7 +8001,7 @@ function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
7627
8001
  }
7628
8002
  }
7629
8003
  } finally {
7630
- fs29.closeSync(fd);
8004
+ fs33.closeSync(fd);
7631
8005
  }
7632
8006
  return { lines: collected.reverse(), totalLinesCount };
7633
8007
  }
@@ -7769,7 +8143,7 @@ function readDevStdSegment(filePath, maxLines, offset) {
7769
8143
  }
7770
8144
 
7771
8145
  // src/commands/read-logs/json-lines.ts
7772
- import fs30 from "fs";
8146
+ import fs34 from "fs";
7773
8147
 
7774
8148
  // src/commands/read-logs/structured-log.ts
7775
8149
  function normalizeLevelName(value) {
@@ -7845,11 +8219,11 @@ function buildWantedLevelSet(levels) {
7845
8219
  return set.size > 0 ? set : null;
7846
8220
  }
7847
8221
  function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
7848
- const stat = fs30.statSync(filePath);
8222
+ const stat = fs34.statSync(filePath);
7849
8223
  if (stat.size === 0) {
7850
8224
  return { lines: [], totalLinesCount: 0 };
7851
8225
  }
7852
- const fd = fs30.openSync(filePath, "r");
8226
+ const fd = fs34.openSync(filePath, "r");
7853
8227
  const chunkSize = 64 * 1024;
7854
8228
  let position = stat.size;
7855
8229
  let remainder = "";
@@ -7864,7 +8238,7 @@ function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
7864
8238
  const length = Math.min(chunkSize, position);
7865
8239
  position -= length;
7866
8240
  const buffer = Buffer.alloc(length);
7867
- fs30.readSync(fd, buffer, 0, length, position);
8241
+ fs34.readSync(fd, buffer, 0, length, position);
7868
8242
  let chunk = buffer.toString("utf8");
7869
8243
  if (remainder) {
7870
8244
  chunk += remainder;
@@ -7926,7 +8300,7 @@ function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
7926
8300
  }
7927
8301
  }
7928
8302
  } finally {
7929
- fs30.closeSync(fd);
8303
+ fs34.closeSync(fd);
7930
8304
  }
7931
8305
  return { lines: collected.reverse(), totalLinesCount };
7932
8306
  }
@@ -7969,11 +8343,11 @@ function extractTraceId(obj) {
7969
8343
  function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
7970
8344
  const wanted = traceId.trim();
7971
8345
  if (!wanted) return { lines: [], totalLinesCount: 0 };
7972
- const stat = fs30.statSync(filePath);
8346
+ const stat = fs34.statSync(filePath);
7973
8347
  if (stat.size === 0) {
7974
8348
  return { lines: [], totalLinesCount: 0 };
7975
8349
  }
7976
- const fd = fs30.openSync(filePath, "r");
8350
+ const fd = fs34.openSync(filePath, "r");
7977
8351
  const chunkSize = 64 * 1024;
7978
8352
  let position = stat.size;
7979
8353
  let remainder = "";
@@ -7986,7 +8360,7 @@ function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
7986
8360
  const length = Math.min(chunkSize, position);
7987
8361
  position -= length;
7988
8362
  const buffer = Buffer.alloc(length);
7989
- fs30.readSync(fd, buffer, 0, length, position);
8363
+ fs34.readSync(fd, buffer, 0, length, position);
7990
8364
  let chunk = buffer.toString("utf8");
7991
8365
  if (remainder) {
7992
8366
  chunk += remainder;
@@ -8039,7 +8413,7 @@ function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
8039
8413
  }
8040
8414
  }
8041
8415
  } finally {
8042
- fs30.closeSync(fd);
8416
+ fs34.closeSync(fd);
8043
8417
  }
8044
8418
  return { lines: collected.reverse(), totalLinesCount };
8045
8419
  }
@@ -8048,11 +8422,11 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
8048
8422
  if (!wantedLevelSet) {
8049
8423
  return { lines: [], totalLinesCount: 0 };
8050
8424
  }
8051
- const stat = fs30.statSync(filePath);
8425
+ const stat = fs34.statSync(filePath);
8052
8426
  if (stat.size === 0) {
8053
8427
  return { lines: [], totalLinesCount: 0 };
8054
8428
  }
8055
- const fd = fs30.openSync(filePath, "r");
8429
+ const fd = fs34.openSync(filePath, "r");
8056
8430
  const chunkSize = 64 * 1024;
8057
8431
  let position = stat.size;
8058
8432
  let remainder = "";
@@ -8064,7 +8438,7 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
8064
8438
  const length = Math.min(chunkSize, position);
8065
8439
  position -= length;
8066
8440
  const buffer = Buffer.alloc(length);
8067
- fs30.readSync(fd, buffer, 0, length, position);
8441
+ fs34.readSync(fd, buffer, 0, length, position);
8068
8442
  let chunk = buffer.toString("utf8");
8069
8443
  if (remainder) {
8070
8444
  chunk += remainder;
@@ -8111,7 +8485,7 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
8111
8485
  }
8112
8486
  }
8113
8487
  } finally {
8114
- fs30.closeSync(fd);
8488
+ fs34.closeSync(fd);
8115
8489
  }
8116
8490
  return { lines: collected.reverse(), totalLinesCount };
8117
8491
  }
@@ -8604,30 +8978,30 @@ async function readLogsJsonResult(options) {
8604
8978
  };
8605
8979
  }
8606
8980
  function resolveLogFilePath(logDir, type) {
8607
- const base = path25.isAbsolute(logDir) ? logDir : path25.join(process.cwd(), logDir);
8981
+ const base = path29.isAbsolute(logDir) ? logDir : path29.join(process.cwd(), logDir);
8608
8982
  if (type === "server") {
8609
- return path25.join(base, "server.log");
8983
+ return path29.join(base, "server.log");
8610
8984
  }
8611
8985
  if (type === "trace") {
8612
- return path25.join(base, "trace.log");
8986
+ return path29.join(base, "trace.log");
8613
8987
  }
8614
8988
  if (type === "server-std") {
8615
- return path25.join(base, "server.std.log");
8989
+ return path29.join(base, "server.std.log");
8616
8990
  }
8617
8991
  if (type === "client-std") {
8618
- return path25.join(base, "client.std.log");
8992
+ return path29.join(base, "client.std.log");
8619
8993
  }
8620
8994
  if (type === "dev") {
8621
- return path25.join(base, "dev.log");
8995
+ return path29.join(base, "dev.log");
8622
8996
  }
8623
8997
  if (type === "dev-std") {
8624
- return path25.join(base, "dev.std.log");
8998
+ return path29.join(base, "dev.std.log");
8625
8999
  }
8626
9000
  if (type === "install-dep-std") {
8627
- return path25.join(base, "install-dep.std.log");
9001
+ return path29.join(base, "install-dep.std.log");
8628
9002
  }
8629
9003
  if (type === "browser") {
8630
- return path25.join(base, "browser.log");
9004
+ return path29.join(base, "browser.log");
8631
9005
  }
8632
9006
  throw new Error(`Unsupported log type: ${type}`);
8633
9007
  }
@@ -8797,10 +9171,10 @@ function camelToKebab(str) {
8797
9171
  }
8798
9172
 
8799
9173
  // src/commands/build/upload-static.handler.ts
8800
- import * as fs31 from "fs";
8801
- import * as os2 from "os";
8802
- import * as path26 from "path";
8803
- import { execFileSync } from "child_process";
9174
+ import * as fs35 from "fs";
9175
+ import * as os3 from "os";
9176
+ import * as path30 from "path";
9177
+ import { execFileSync as execFileSync2 } from "child_process";
8804
9178
  function readCredentialsFromEnv() {
8805
9179
  const uploadPrefix = process.env.STATIC_UPLOAD_PREFIX;
8806
9180
  const uploadID = process.env.STATIC_UPLOAD_ID;
@@ -8823,8 +9197,8 @@ async function uploadStatic(options) {
8823
9197
  endpoint = UPLOAD_STATIC_DEFAULTS.endpoint,
8824
9198
  region = UPLOAD_STATIC_DEFAULTS.region
8825
9199
  } = options;
8826
- const resolvedStaticDir = path26.resolve(staticDir);
8827
- if (!fs31.existsSync(resolvedStaticDir)) {
9200
+ const resolvedStaticDir = path30.resolve(staticDir);
9201
+ if (!fs35.existsSync(resolvedStaticDir)) {
8828
9202
  console.error(`${LOG_PREFIX} \u76EE\u5F55\u4E0D\u5B58\u5728: ${resolvedStaticDir}\uFF0C\u8DF3\u8FC7\u4E0A\u4F20`);
8829
9203
  return;
8830
9204
  }
@@ -8857,8 +9231,8 @@ async function uploadStatic(options) {
8857
9231
  ({ AccessKeyID: accessKeyID, SecretAccessKey: secretAccessKey, SessionToken: sessionToken } = uploadCredential);
8858
9232
  }
8859
9233
  console.error(`${LOG_PREFIX} \u4E0A\u4F20\u76EE\u6807: ${uploadPrefix}`);
8860
- const confPath = path26.join(os2.tmpdir(), `.tosutilconfig-static-${process.pid}`);
8861
- fs31.writeFileSync(confPath, "");
9234
+ const confPath = path30.join(os3.tmpdir(), `.tosutilconfig-static-${process.pid}`);
9235
+ fs35.writeFileSync(confPath, "");
8862
9236
  try {
8863
9237
  console.error(`${LOG_PREFIX} \u914D\u7F6E tosutil...`);
8864
9238
  configureTosutil(resolvedTosutil, confPath, {
@@ -8872,7 +9246,7 @@ async function uploadStatic(options) {
8872
9246
  uploadToTos(resolvedTosutil, confPath, resolvedStaticDir, uploadPrefix);
8873
9247
  } finally {
8874
9248
  try {
8875
- fs31.unlinkSync(confPath);
9249
+ fs35.unlinkSync(confPath);
8876
9250
  } catch {
8877
9251
  }
8878
9252
  }
@@ -8892,11 +9266,11 @@ async function uploadStatic(options) {
8892
9266
  }
8893
9267
  }
8894
9268
  function resolveTosutilPath(tosutilPath) {
8895
- if (path26.isAbsolute(tosutilPath)) {
8896
- return fs31.existsSync(tosutilPath) ? tosutilPath : null;
9269
+ if (path30.isAbsolute(tosutilPath)) {
9270
+ return fs35.existsSync(tosutilPath) ? tosutilPath : null;
8897
9271
  }
8898
9272
  try {
8899
- const resolved = execFileSync("which", [tosutilPath], { encoding: "utf-8" }).trim();
9273
+ const resolved = execFileSync2("which", [tosutilPath], { encoding: "utf-8" }).trim();
8900
9274
  return resolved || null;
8901
9275
  } catch {
8902
9276
  return null;
@@ -8918,14 +9292,14 @@ async function fetchPreUpload(appId, bucketId) {
8918
9292
  }
8919
9293
  function configureTosutil(tosutilPath, confPath, config) {
8920
9294
  const { endpoint, region, accessKeyID, secretAccessKey, sessionToken } = config;
8921
- execFileSync(
9295
+ execFileSync2(
8922
9296
  tosutilPath,
8923
9297
  ["config", "-conf", confPath, "-e", endpoint, "-i", accessKeyID, "-k", secretAccessKey, "-t", sessionToken, "-re", region],
8924
9298
  { stdio: "pipe" }
8925
9299
  );
8926
9300
  }
8927
9301
  function uploadToTos(tosutilPath, confPath, sourceDir, destUrl) {
8928
- execFileSync(
9302
+ execFileSync2(
8929
9303
  tosutilPath,
8930
9304
  ["cp", "-conf", confPath, sourceDir, destUrl, "-r", "-flat", "-j", "5", "-p", "3", "-ps", "10485760", "-f"],
8931
9305
  { stdio: "inherit" }
@@ -8938,7 +9312,7 @@ async function resolveBucketId(appId) {
8938
9312
  return bucketId;
8939
9313
  }
8940
9314
  function isDirEmpty(dirPath) {
8941
- const entries = fs31.readdirSync(dirPath);
9315
+ const entries = fs35.readdirSync(dirPath);
8942
9316
  return entries.length === 0;
8943
9317
  }
8944
9318
 
@@ -9034,13 +9408,13 @@ var commands = [
9034
9408
 
9035
9409
  // src/index.ts
9036
9410
  for (const filename of [".env.local", ".env"]) {
9037
- const envPath = path27.join(process.cwd(), filename);
9038
- if (fs32.existsSync(envPath)) {
9411
+ const envPath = path31.join(process.cwd(), filename);
9412
+ if (fs36.existsSync(envPath)) {
9039
9413
  dotenvConfig({ path: envPath });
9040
9414
  }
9041
9415
  }
9042
- var __dirname = path27.dirname(fileURLToPath5(import.meta.url));
9043
- var pkg = JSON.parse(fs32.readFileSync(path27.join(__dirname, "../package.json"), "utf-8"));
9416
+ var __dirname = path31.dirname(fileURLToPath5(import.meta.url));
9417
+ var pkg = JSON.parse(fs36.readFileSync(path31.join(__dirname, "../package.json"), "utf-8"));
9044
9418
  var cli = new FullstackCLI(pkg.version);
9045
9419
  cli.useAll(commands);
9046
9420
  cli.run();