plugin-git-manager 1.4.0 → 1.4.1

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 (53) hide show
  1. package/dist/client/317.e7b1d59371812c30.js +10 -0
  2. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  3. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  4. package/dist/client/454.625da741a7e1161f.js +10 -0
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  7. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  8. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  9. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/locale/en-US.json +12 -1
  12. package/dist/locale/vi-VN.json +12 -1
  13. package/dist/locale/zh-CN.json +12 -1
  14. package/dist/node_modules/simple-git/package.json +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/git-actions.js +299 -87
  17. package/dist/server/actions/gitlab-api.js +19 -12
  18. package/dist/server/actions/subtree.js +20 -10
  19. package/dist/server/plugin.js +134 -10
  20. package/dist/server/repository-access.js +2 -2
  21. package/dist/server/request-method-policy.js +2 -1
  22. package/dist/server/services/review-source.js +2 -1
  23. package/dist/server/utils/cluster-git.js +181 -0
  24. package/package.json +2 -2
  25. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  26. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  27. package/src/client/components/CommitHistory.tsx +19 -7
  28. package/src/client/components/FileExplorer.tsx +80 -34
  29. package/src/client/components/GitManagerSettings.tsx +21 -5
  30. package/src/client/components/GitOperations.tsx +25 -4
  31. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  32. package/src/client/components/RepositoryConfig.tsx +28 -6
  33. package/src/client/context/GitManagerContext.tsx +156 -13
  34. package/src/client/workflowRoutes.ts +11 -0
  35. package/src/locale/en-US.json +12 -1
  36. package/src/locale/vi-VN.json +12 -1
  37. package/src/locale/zh-CN.json +12 -1
  38. package/src/server/__tests__/git-actions.test.ts +329 -4
  39. package/src/server/__tests__/smoke.test.ts +32 -1
  40. package/src/server/actions/git-actions.ts +322 -96
  41. package/src/server/actions/gitlab-api.ts +20 -14
  42. package/src/server/actions/subtree.ts +23 -6
  43. package/src/server/plugin.ts +152 -3
  44. package/src/server/repository-access.ts +2 -2
  45. package/src/server/request-method-policy.ts +1 -0
  46. package/src/server/services/review-source.ts +3 -2
  47. package/src/server/utils/cluster-git.ts +209 -0
  48. package/dist/client/317.2d0d33871e24ee24.js +0 -10
  49. package/dist/client/434.2401f7257495b66e.js +0 -10
  50. package/dist/client/453.58657b9ba0904477.js +0 -10
  51. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  52. package/dist/client-v2/434.32b0a07b821b9329.js +0 -10
  53. package/dist/client-v2/453.f9a0ec6d8e1bd1cc.js +0 -10
@@ -231,14 +231,22 @@ async function mergeRequests(ctx, next) {
231
231
  };
232
232
  await next();
233
233
  }
234
+ function parseMrIid(value, ctx) {
235
+ if (value === void 0 || value === null || value === "") {
236
+ ctx.throw(400, "mrIid is required");
237
+ }
238
+ const text = String(value).trim();
239
+ const parsed = typeof value === "number" ? value : Number(text);
240
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(parsed) || parsed < 1) {
241
+ ctx.throw(400, "Invalid merge request ID");
242
+ }
243
+ return parsed;
244
+ }
234
245
  async function mergeRequestDetail(ctx, next) {
235
246
  var _a, _b, _c;
236
247
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
237
248
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
238
- const { mrIid } = params;
239
- if (!mrIid) {
240
- ctx.throw(400, "mrIid is required");
241
- }
249
+ const mrIid = parseMrIid(params.mrIid, ctx);
242
250
  let data;
243
251
  if (isGitHub) {
244
252
  const [prResult, filesResult] = await Promise.all([
@@ -350,11 +358,12 @@ async function mergeRequestDetail(ctx, next) {
350
358
  }
351
359
  async function readChatMergeRequest(ctx, mrIid, repositoryId) {
352
360
  var _a, _b, _c, _d, _e;
361
+ const validMrIid = parseMrIid(mrIid, ctx);
353
362
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
354
363
  if (isGitHub) {
355
364
  const [request2, fileResult] = await Promise.all([
356
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
357
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat, { page: 1, per_page: 51 })
365
+ githubFetch(`/repos/${projectPath}/pulls/${validMrIid}`, pat),
366
+ githubFetch(`/repos/${projectPath}/pulls/${validMrIid}/files`, pat, { page: 1, per_page: 51 })
358
367
  ]);
359
368
  const item2 = request2.data;
360
369
  if (!Array.isArray(fileResult.data)) throw new Error("Unable to read merge request changes");
@@ -386,8 +395,8 @@ async function readChatMergeRequest(ctx, mrIid, repositoryId) {
386
395
  }
387
396
  if (!pat) ctx.throw(400, "Personal Access Token is required for GitLab API access");
388
397
  const [request, changeResult] = await Promise.all([
389
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
390
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat)
398
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}`, pat),
399
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}/changes`, pat)
391
400
  ]);
392
401
  const item = request.data;
393
402
  const changeData = changeResult.data || {};
@@ -420,10 +429,8 @@ async function readChatMergeRequest(ctx, mrIid, repositoryId) {
420
429
  async function mergeRequestNotes(ctx, next) {
421
430
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
422
431
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
423
- const { mrIid, page = 1, perPage = 50 } = params;
424
- if (!mrIid) {
425
- ctx.throw(400, "mrIid is required");
426
- }
432
+ const { page = 1, perPage = 50 } = params;
433
+ const mrIid = parseMrIid(params.mrIid, ctx);
427
434
  let notes = [];
428
435
  const pagination = {
429
436
  page: parseInt(String(page), 10),
@@ -288,6 +288,7 @@ async function loadConfigAndRepository(ctx, configId) {
288
288
  return { configRecord, config, repo, account };
289
289
  }
290
290
  async function subtreeOptions(ctx, next) {
291
+ var _a;
291
292
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
292
293
  const repositoryId = params.repositoryId;
293
294
  if (!repositoryId) ctx.throw(400, "repositoryId is required");
@@ -300,7 +301,8 @@ async function subtreeOptions(ctx, next) {
300
301
  if (!account) ctx.throw(400, "Repository has no Git account configured");
301
302
  const localPath = (0, import_git_actions.validateLocalPath)(stringValue(repo.get("localPath")));
302
303
  const repoUrl = stringValue(repo.get("repoUrl"));
303
- const git = (0, import_git_actions.createGit)(localPath);
304
+ const git = await (0, import_git_actions.getGit)(ctx, localPath);
305
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
304
306
  try {
305
307
  const data = await (0, import_git_actions.withAuth)(
306
308
  git,
@@ -328,23 +330,27 @@ async function subtreeOptions(ctx, next) {
328
330
  return { branches: Array.from(new Set(branches)).sort(), folders };
329
331
  },
330
332
  account.username,
331
- remoteName
333
+ remoteName,
334
+ lockManager
332
335
  );
333
336
  ctx.body = { success: true, data };
334
337
  } catch (error) {
338
+ const status = (error == null ? void 0 : error.status) === 503 ? 503 : 400;
335
339
  const safeError = (0, import_redact.redactError)(error);
336
- ctx.throw(400, ctx.t(safeError.message, { ns: "plugin-git-manager" }));
340
+ ctx.throw(status, ctx.t(safeError.message, { ns: "plugin-git-manager" }));
337
341
  }
338
342
  await next();
339
343
  }
340
344
  async function subtreePreview(ctx, next) {
345
+ var _a;
341
346
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
342
347
  const configId = params.configId;
343
348
  if (!configId) ctx.throw(400, "configId is required");
344
349
  const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
345
350
  const localPath = (0, import_git_actions.validateLocalPath)(stringValue(repo.get("localPath")));
346
351
  const repoUrl = stringValue(repo.get("repoUrl"));
347
- const git = (0, import_git_actions.createGit)(localPath);
352
+ const git = await (0, import_git_actions.getGit)(ctx, localPath);
353
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
348
354
  try {
349
355
  const preview = await (0, import_git_actions.withAuth)(
350
356
  git,
@@ -353,17 +359,19 @@ async function subtreePreview(ctx, next) {
353
359
  account.pat,
354
360
  () => createPreview(git, config),
355
361
  account.username,
356
- config.remoteName
362
+ config.remoteName,
363
+ lockManager
357
364
  );
358
365
  ctx.body = { success: true, data: preview };
359
366
  } catch (error) {
367
+ const status = (error == null ? void 0 : error.status) === 503 ? 503 : 400;
360
368
  const safeError = (0, import_redact.redactError)(error);
361
- ctx.throw(400, ctx.t(safeError.message, { ns: "plugin-git-manager" }));
369
+ ctx.throw(status, ctx.t(safeError.message, { ns: "plugin-git-manager" }));
362
370
  }
363
371
  await next();
364
372
  }
365
373
  async function subtreeRunOnAppProcess(ctx, next) {
366
- var _a, _b;
374
+ var _a, _b, _c;
367
375
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
368
376
  const runParams = {
369
377
  configId: params.configId,
@@ -378,7 +386,8 @@ async function subtreeRunOnAppProcess(ctx, next) {
378
386
  const { config, repo, account } = await loadConfigAndRepository(ctx, runParams.configId);
379
387
  const localPath = (0, import_git_actions.validateLocalPath)(stringValue(repo.get("localPath")));
380
388
  const repoUrl = stringValue(repo.get("repoUrl"));
381
- const git = (0, import_git_actions.createGit)(localPath);
389
+ const git = await (0, import_git_actions.getGit)(ctx, localPath);
390
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
382
391
  const runsRepository = ctx.db.getRepository("gitSubtreeRuns");
383
392
  const startedAt = /* @__PURE__ */ new Date();
384
393
  const run = await runsRepository.create({
@@ -388,7 +397,7 @@ async function subtreeRunOnAppProcess(ctx, next) {
388
397
  executionMode: SUBTREE_EXECUTION_MODE,
389
398
  status: "running",
390
399
  startedAt,
391
- triggeredById: (_b = (_a = ctx.state) == null ? void 0 : _a.currentUser) == null ? void 0 : _b.id
400
+ triggeredById: (_c = (_b = ctx.state) == null ? void 0 : _b.currentUser) == null ? void 0 : _c.id
392
401
  }
393
402
  });
394
403
  try {
@@ -415,7 +424,8 @@ async function subtreeRunOnAppProcess(ctx, next) {
415
424
  return { preview, targetAfterSha };
416
425
  },
417
426
  account.username,
418
- config.remoteName
427
+ config.remoteName,
428
+ lockManager
419
429
  );
420
430
  const finishedAt = /* @__PURE__ */ new Date();
421
431
  await runsRepository.update({
@@ -43,6 +43,7 @@ __export(plugin_exports, {
43
43
  });
44
44
  module.exports = __toCommonJS(plugin_exports);
45
45
  var import_server = require("@nocobase/server");
46
+ var fs = __toESM(require("fs"));
46
47
  var import_path = require("path");
47
48
  var import_sequelize = require("sequelize");
48
49
  var gitActions = __toESM(require("./actions/git-actions"));
@@ -65,6 +66,7 @@ var import_repository_access = require("./repository-access");
65
66
  var import_chat_context_admission = require("./chat-context-admission");
66
67
  var import_redact = require("./utils/redact");
67
68
  var import_url_security = require("./utils/url-security");
69
+ var import_cluster_git = require("./utils/cluster-git");
68
70
  const GIT_CONFIGURATION_URL_FIELDS = /* @__PURE__ */ new Set(["repoUrl", "baseUrl"]);
69
71
  function isConcurrentSchemaChange(error) {
70
72
  var _a, _b, _c;
@@ -83,6 +85,13 @@ class PluginGitManagerServer extends import_server.Plugin {
83
85
  skillHubContentService;
84
86
  reviewService;
85
87
  legacyPostService;
88
+ gitAutoRestoreTimer = null;
89
+ stopGitAutoRestore() {
90
+ if (this.gitAutoRestoreTimer) {
91
+ clearTimeout(this.gitAutoRestoreTimer);
92
+ this.gitAutoRestoreTimer = null;
93
+ }
94
+ }
86
95
  async afterAdd() {
87
96
  this.reviewService = new import_review_service.GitReviewService(this.app);
88
97
  this.legacyPostService = new import_legacy_post_service.LegacyPostService(this.app);
@@ -154,7 +163,9 @@ class PluginGitManagerServer extends import_server.Plugin {
154
163
  subtreePreview: subtreeActions.subtreePreview,
155
164
  subtreeOptions: subtreeActions.subtreeOptions,
156
165
  subtreeRun: subtreeActions.subtreeRunOnAppProcess,
157
- subtreeReplace: subtreeActions.subtreeRunOnAppProcess
166
+ subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
167
+ runtimeStatus: gitActions.runtimeStatus,
168
+ installGit: gitActions.installGit
158
169
  }
159
170
  });
160
171
  this.app.acl.allow("gitManager", "chatContextOptions", "loggedIn");
@@ -170,7 +181,7 @@ class PluginGitManagerServer extends import_server.Plugin {
170
181
  ]
171
182
  });
172
183
  for (const [action, aliases] of [
173
- ["fileContent", ["reviewCutoverStatus"]],
184
+ ["fileContent", ["reviewCutoverStatus", "runtimeStatus"]],
174
185
  [
175
186
  "triggerReview",
176
187
  [
@@ -226,31 +237,50 @@ class PluginGitManagerServer extends import_server.Plugin {
226
237
  (0, import_ai_tools.registerGitReviewAiTools)(this.app);
227
238
  this.app.on("afterLoad", () => (0, import_chat_context_admission.registerGitChatContextStrategies)(this.app));
228
239
  this.app.on("afterStart", async () => {
240
+ var _a2;
229
241
  await ensureAutoReviewFlowSchema(this.app).catch(
230
242
  (err) => {
231
- var _a2, _b2;
232
- return (_b2 = (_a2 = this.app.log) == null ? void 0 : _a2.error) == null ? void 0 : _b2.call(_a2, "plugin-git-manager: ensure schema error", err);
243
+ var _a3, _b2;
244
+ return (_b2 = (_a3 = this.app.log) == null ? void 0 : _a3.error) == null ? void 0 : _b2.call(_a3, "plugin-git-manager: ensure schema error", err);
233
245
  }
234
246
  );
235
247
  await this.ensureReviewSchema().catch(
236
248
  (error) => {
237
- var _a2, _b2;
238
- return (_b2 = (_a2 = this.app.log) == null ? void 0 : _a2.error) == null ? void 0 : _b2.call(_a2, "plugin-git-manager: review schema error", error);
249
+ var _a3, _b2;
250
+ return (_b2 = (_a3 = this.app.log) == null ? void 0 : _a3.error) == null ? void 0 : _b2.call(_a3, "plugin-git-manager: review schema error", error);
239
251
  }
240
252
  );
241
253
  this.reviewService.start();
242
254
  subtreeActions.recoverStuckSubtreeRuns(this.app).catch((err) => {
243
- var _a2, _b2;
244
- return (_b2 = (_a2 = this.app.log) == null ? void 0 : _a2.error) == null ? void 0 : _b2.call(_a2, "plugin-git-manager: recover subtree runs error", err);
255
+ var _a3, _b2;
256
+ return (_b2 = (_a3 = this.app.log) == null ? void 0 : _a3.error) == null ? void 0 : _b2.call(_a3, "plugin-git-manager: recover subtree runs error", err);
245
257
  });
246
258
  (0, import_poller.startPoller)(this.app);
259
+ this.stopGitAutoRestore();
260
+ const restoreTimer = setTimeout(async () => {
261
+ this.gitAutoRestoreTimer = null;
262
+ if (gitActions.isGitAvailable()) return;
263
+ const clusterStatus = await (0, import_cluster_git.readClusterGitStatus)(this.app).catch(() => void 0);
264
+ if ((clusterStatus == null ? void 0 : clusterStatus.available) && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
265
+ await (0, import_cluster_git.dispatchClusterGitInstall)(this.app).catch(
266
+ (err) => {
267
+ var _a3, _b2;
268
+ return (_b2 = (_a3 = this.app.log) == null ? void 0 : _a3.warn) == null ? void 0 : _b2.call(_a3, "plugin-git-manager: startup git restore via Cluster Manager failed", err);
269
+ }
270
+ );
271
+ }
272
+ }, 5e3);
273
+ (_a2 = restoreTimer.unref) == null ? void 0 : _a2.call(restoreTimer);
274
+ this.gitAutoRestoreTimer = restoreTimer;
247
275
  });
248
276
  this.app.on("beforeStop", () => {
277
+ this.stopGitAutoRestore();
249
278
  (0, import_review.unregisterReviewQueue)(this.app);
250
279
  this.reviewService.stop();
251
280
  (0, import_poller.stopPoller)(this.app);
252
281
  });
253
282
  this.app.on("beforeDestroy", () => {
283
+ this.stopGitAutoRestore();
254
284
  (0, import_review.unregisterReviewQueue)(this.app);
255
285
  this.reviewService.stop();
256
286
  (0, import_poller.stopPoller)(this.app);
@@ -284,6 +314,7 @@ class PluginGitManagerServer extends import_server.Plugin {
284
314
  "gitManager:subtreePreview",
285
315
  "gitManager:subtreeOptions",
286
316
  "gitManager:reviewCutoverStatus",
317
+ "gitManager:runtimeStatus",
287
318
  "workflowGitReview:status"
288
319
  ]
289
320
  });
@@ -321,6 +352,7 @@ class PluginGitManagerServer extends import_server.Plugin {
321
352
  "gitManager:reviewResetPostClaim",
322
353
  "gitManager:reviewCancelQueued",
323
354
  "gitManager:reviewLegacyReleaseHold",
355
+ "gitManager:installGit",
324
356
  "workflowGitReview:setup",
325
357
  "workflowGitReview:repair"
326
358
  ]
@@ -331,7 +363,7 @@ class PluginGitManagerServer extends import_server.Plugin {
331
363
  });
332
364
  this.app.acl.registerSnippet({
333
365
  name: `pm.${this.name}.repositories`,
334
- actions: ["gitRepositories:*", "gitAccounts:*"]
366
+ actions: ["gitRepositories:*", "gitAccounts:*", "gitManager:runtimeStatus", "gitManager:installGit"]
335
367
  });
336
368
  this.app.acl.registerSnippet({
337
369
  name: `pm.${this.name}.manage`,
@@ -348,7 +380,7 @@ class PluginGitManagerServer extends import_server.Plugin {
348
380
  ]
349
381
  });
350
382
  this.app.resourceManager.use(async (ctx, next) => {
351
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
383
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
352
384
  const resource = (_a2 = ctx.action) == null ? void 0 : _a2.resourceName;
353
385
  if (resource === "gitSubtreeConfigs" && ["create", "update"].includes((_b2 = ctx.action) == null ? void 0 : _b2.actionName) && ((_c = ctx.action.params) == null ? void 0 : _c.values)) {
354
386
  try {
@@ -403,6 +435,96 @@ class PluginGitManagerServer extends import_server.Plugin {
403
435
  if (((_m = ctx.request.body) == null ? void 0 : _m.pat) === "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022") {
404
436
  delete ctx.request.body.pat;
405
437
  }
438
+ const mergedValues = {
439
+ ...requestBody && typeof requestBody === "object" && !Array.isArray(requestBody) ? requestBody : {},
440
+ ...(requestBody == null ? void 0 : requestBody.values) && typeof requestBody.values === "object" && !Array.isArray(requestBody.values) ? requestBody.values : {},
441
+ ...(actionParams == null ? void 0 : actionParams.values) && typeof actionParams.values === "object" && !Array.isArray(actionParams.values) ? actionParams.values : {}
442
+ };
443
+ try {
444
+ if (resource === "gitAccounts") {
445
+ let existingAccount = null;
446
+ if (((_n = ctx.action) == null ? void 0 : _n.actionName) === "update" && (actionParams == null ? void 0 : actionParams.filterByTk) != null) {
447
+ existingAccount = await ctx.db.getRepository("gitAccounts").findOne({ filterByTk: actionParams.filterByTk });
448
+ }
449
+ const provider = String(mergedValues.provider ?? (existingAccount == null ? void 0 : existingAccount.get("provider")) ?? "gitlab").trim();
450
+ const rawBaseUrl = mergedValues.baseUrl !== void 0 ? mergedValues.baseUrl : existingAccount == null ? void 0 : existingAccount.get("baseUrl");
451
+ const baseUrl = typeof rawBaseUrl === "string" && rawBaseUrl.trim() ? rawBaseUrl.trim() : null;
452
+ if (baseUrl) {
453
+ (0, import_url_security.assertUrlHasNoUserInfo)(baseUrl);
454
+ let parsedBase;
455
+ try {
456
+ parsedBase = new URL(baseUrl);
457
+ } catch {
458
+ throw new Error("Invalid repository or account URL");
459
+ }
460
+ if (parsedBase.protocol !== "https:") {
461
+ throw new Error("Only HTTPS repository and account URLs are allowed");
462
+ }
463
+ if (provider === "github" && parsedBase.origin !== "https://github.com") {
464
+ throw new Error("GitHub accounts currently require github.com");
465
+ }
466
+ }
467
+ }
468
+ if (resource === "gitRepositories") {
469
+ if (mergedValues.localPath !== void 0) {
470
+ gitActions.validateLocalPath(String(mergedValues.localPath));
471
+ }
472
+ if (mergedValues.repoUrl !== void 0) {
473
+ gitActions.validateRepoUrl(String(mergedValues.repoUrl).trim());
474
+ }
475
+ if (mergedValues.defaultBranch !== void 0 && String(mergedValues.defaultBranch).trim()) {
476
+ gitActions.validateBranch(String(mergedValues.defaultBranch).trim());
477
+ }
478
+ if (mergedValues.repoUrl !== void 0 || mergedValues.gitAccountId !== void 0) {
479
+ let existingRepo = null;
480
+ if (((_o = ctx.action) == null ? void 0 : _o.actionName) === "update" && (actionParams == null ? void 0 : actionParams.filterByTk) != null) {
481
+ existingRepo = await ctx.db.getRepository("gitRepositories").findOne({ filterByTk: actionParams.filterByTk });
482
+ }
483
+ const effectiveRepoUrl = String(
484
+ mergedValues.repoUrl !== void 0 ? mergedValues.repoUrl : (existingRepo == null ? void 0 : existingRepo.get("repoUrl")) || ""
485
+ ).trim();
486
+ const effectiveAccountId = mergedValues.gitAccountId !== void 0 ? mergedValues.gitAccountId : existingRepo == null ? void 0 : existingRepo.get("gitAccountId");
487
+ if (effectiveRepoUrl && (typeof effectiveAccountId === "number" || typeof effectiveAccountId === "string") && String(effectiveAccountId).trim()) {
488
+ const account = await ctx.db.getRepository("gitAccounts").findOne({ filterByTk: effectiveAccountId });
489
+ if (account) {
490
+ const baseUrl = String(account.get("baseUrl") || "").trim() || null;
491
+ const provider = String(account.get("provider") || "gitlab").trim();
492
+ (0, import_url_security.assertAccountRepositoryUrl)(effectiveRepoUrl, baseUrl, provider);
493
+ }
494
+ }
495
+ }
496
+ }
497
+ } catch (error) {
498
+ const message = error instanceof Error ? error.message : String(error);
499
+ ctx.throw(400, ctx.t(message, { ns: this.name }));
500
+ }
501
+ }
502
+ if (resource === "gitRepositories" && ((_p = ctx.action) == null ? void 0 : _p.actionName) === "destroy") {
503
+ const targetRepos = await ctx.db.getRepository("gitRepositories").find({
504
+ filterByTk: (_q = ctx.action.params) == null ? void 0 : _q.filterByTk,
505
+ filter: (_r = ctx.action.params) == null ? void 0 : _r.filter,
506
+ fields: ["id", "localPath"]
507
+ });
508
+ const localPaths = Array.from(
509
+ new Set(
510
+ targetRepos.map((item) => item.get("localPath")).filter((value) => typeof value === "string" && Boolean(value.trim()))
511
+ )
512
+ );
513
+ await next();
514
+ for (const rawLocalPath of localPaths) {
515
+ const remainingCount = await ctx.db.getRepository("gitRepositories").count({
516
+ filter: { localPath: rawLocalPath }
517
+ });
518
+ if (remainingCount > 0) continue;
519
+ try {
520
+ const resolvedPath = gitActions.validateLocalPath(rawLocalPath);
521
+ if (fs.existsSync(resolvedPath)) {
522
+ fs.rmSync(resolvedPath, { recursive: true, force: true });
523
+ }
524
+ } catch {
525
+ }
526
+ }
527
+ return;
406
528
  }
407
529
  return next();
408
530
  });
@@ -447,11 +569,13 @@ class PluginGitManagerServer extends import_server.Plugin {
447
569
  }, 3e5);
448
570
  }
449
571
  async beforeDisable() {
572
+ this.stopGitAutoRestore();
450
573
  (0, import_review.unregisterReviewQueue)(this.app);
451
574
  this.reviewService.stop();
452
575
  (0, import_poller.stopPoller)(this.app);
453
576
  }
454
577
  async beforeUnload() {
578
+ this.stopGitAutoRestore();
455
579
  (0, import_review.unregisterReviewQueue)(this.app);
456
580
  this.reviewService.stop();
457
581
  (0, import_poller.stopPoller)(this.app);
@@ -589,8 +589,8 @@ async function enforceRepositoryAccess(ctx, next) {
589
589
  const reviewId = asRepositoryId(params.reviewId);
590
590
  if (reviewId == null) return ctx.throw(400, "reviewId is required");
591
591
  repositoryId = await repositoryIdFromReview(ctx, reviewId);
592
- } else if (actionName === "pollNow") {
593
- repositoryId = asRepositoryId(params.repositoryId);
592
+ } else if (actionName === "pollNow" || actionName === "installGit") {
593
+ repositoryId = actionName === "pollNow" ? asRepositoryId(params.repositoryId) : void 0;
594
594
  if (repositoryId == null) {
595
595
  const allowed2 = await hasUnrestrictedRepositoryAccess({
596
596
  acl: ctx.app.acl,
@@ -44,7 +44,8 @@ const READ_ACTIONS = /* @__PURE__ */ new Set([
44
44
  "chatContextContent",
45
45
  "pollerStatus",
46
46
  "rolePermissions",
47
- "reviewCutoverStatus"
47
+ "reviewCutoverStatus",
48
+ "runtimeStatus"
48
49
  ]);
49
50
  async function enforceGitRequestMethod(ctx, next) {
50
51
  var _a, _b;
@@ -97,7 +97,8 @@ async function resolveReviewProjectKey(db, repo) {
97
97
  return (await provider(db, repo)).projectKey;
98
98
  }
99
99
  async function validateCheckoutProject(db, repo, expectedProjectKey) {
100
- const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
100
+ const localPath = (0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || ""));
101
+ const git = await (0, import_git_actions.assertLocalGitReady)(localPath);
101
102
  let origin;
102
103
  try {
103
104
  origin = (await git.raw(["remote", "get-url", "origin"])).trim();
@@ -0,0 +1,181 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var cluster_git_exports = {};
28
+ __export(cluster_git_exports, {
29
+ dispatchClusterGitInstall: () => dispatchClusterGitInstall,
30
+ readClusterGitStatus: () => readClusterGitStatus,
31
+ resetClusterGitDispatchCooldownForTests: () => resetClusterGitDispatchCooldownForTests
32
+ });
33
+ module.exports = __toCommonJS(cluster_git_exports);
34
+ const CLUSTER_INSTALL_CHANNEL = "cluster-manager.install-packages";
35
+ const AUTO_RESTORE_LOCK_KEY = "git-manager:cluster-git-install";
36
+ const AUTO_RESTORE_COOLDOWN_MS = 45e3;
37
+ let lastDispatchAt = 0;
38
+ function parseAptPackages(raw) {
39
+ if (typeof raw !== "string" || !raw.trim()) return [];
40
+ return Array.from(
41
+ new Set(
42
+ raw.split(/[\r\n,]+/).map((item) => item.trim()).filter(Boolean)
43
+ )
44
+ );
45
+ }
46
+ function hasGitInWhitelist(raw) {
47
+ if (!raw) return false;
48
+ try {
49
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
50
+ return Array.isArray(parsed == null ? void 0 : parsed.apt) && parsed.apt.includes("git");
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+ function normalizeStatus(raw) {
56
+ if (raw === "running" || raw === "succeeded" || raw === "failed") return raw;
57
+ return "idle";
58
+ }
59
+ function isClusterManagerEnabled(app) {
60
+ var _a, _b, _c;
61
+ if (!((_b = (_a = app == null ? void 0 : app.db) == null ? void 0 : _a.getCollection) == null ? void 0 : _b.call(_a, "workerPackagesConfigs"))) return false;
62
+ if (!((_c = app.pm) == null ? void 0 : _c.get)) return true;
63
+ return Boolean(app.pm.get("plugin-cluster-manager") || app.pm.get("cluster-manager"));
64
+ }
65
+ async function readClusterGitStatus(app) {
66
+ var _a, _b;
67
+ if (!isClusterManagerEnabled(app)) {
68
+ return {
69
+ available: false,
70
+ gitConfigured: false,
71
+ previouslyInitialized: false,
72
+ status: "idle",
73
+ progressPercent: 0
74
+ };
75
+ }
76
+ const repo = (_b = (_a = app == null ? void 0 : app.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "workerPackagesConfigs");
77
+ if (!repo) {
78
+ return {
79
+ available: false,
80
+ gitConfigured: false,
81
+ previouslyInitialized: false,
82
+ status: "idle",
83
+ progressPercent: 0
84
+ };
85
+ }
86
+ const config = await repo.findOne();
87
+ if (!config) {
88
+ return {
89
+ available: true,
90
+ gitConfigured: false,
91
+ previouslyInitialized: false,
92
+ status: "idle",
93
+ progressPercent: 0
94
+ };
95
+ }
96
+ const aptPackages = parseAptPackages(config.get("aptPackages"));
97
+ const whitelisted = hasGitInWhitelist(config.get("packageWhitelist"));
98
+ const status = normalizeStatus(config.get("initStatus"));
99
+ const rawPercent = Number(config.get("initProgressPercent") ?? 0);
100
+ return {
101
+ available: true,
102
+ gitConfigured: aptPackages.includes("git") || whitelisted,
103
+ previouslyInitialized: Boolean(config.get("lastInitAt") || whitelisted || status === "succeeded"),
104
+ status,
105
+ progressPercent: Number.isFinite(rawPercent) ? Math.min(Math.max(rawPercent, 0), 100) : 0
106
+ };
107
+ }
108
+ async function dispatchClusterGitInstall(app, options = {}) {
109
+ var _a, _b, _c;
110
+ if (!isClusterManagerEnabled(app)) {
111
+ return { dispatched: false, reason: "Cluster Manager plugin is not enabled" };
112
+ }
113
+ const pubSub = app == null ? void 0 : app.pubSubManager;
114
+ const connected = pubSub ? pubSub.isConnected ? await pubSub.isConnected() : true : false;
115
+ if (!pubSub || !connected) {
116
+ return { dispatched: false, reason: "Cluster PubSub is not connected" };
117
+ }
118
+ const repo = (_b = (_a = app == null ? void 0 : app.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "workerPackagesConfigs");
119
+ if (!repo) {
120
+ return { dispatched: false, reason: "Cluster package configuration repository is unavailable" };
121
+ }
122
+ const runDispatch = async () => {
123
+ var _a2, _b2;
124
+ const now = Date.now();
125
+ if (!options.force && now - lastDispatchAt < AUTO_RESTORE_COOLDOWN_MS) {
126
+ return { dispatched: false, reason: "Recent install dispatch still in cooldown" };
127
+ }
128
+ let config = await repo.findOne();
129
+ if (!config) {
130
+ if (!options.ensureGitInConfig) {
131
+ return { dispatched: false, reason: "Cluster package configuration has not been initialized" };
132
+ }
133
+ config = await repo.create({ values: { aptPackages: "git" } });
134
+ }
135
+ const currentStatus = normalizeStatus(config.get("initStatus"));
136
+ if (!options.force && currentStatus === "running") {
137
+ return { dispatched: false, reason: "Cluster package installation is already running" };
138
+ }
139
+ const aptPackages = parseAptPackages(config.get("aptPackages"));
140
+ if (!aptPackages.includes("git")) {
141
+ if (!options.ensureGitInConfig && !hasGitInWhitelist(config.get("packageWhitelist"))) {
142
+ return { dispatched: false, reason: "git is not configured in Cluster Manager packages" };
143
+ }
144
+ if (options.ensureGitInConfig) {
145
+ aptPackages.push("git");
146
+ }
147
+ }
148
+ const aptMirrorUrl = String(config.get("aptMirrorUrl") || process.env.APT_MIRROR_URL || "").trim() || void 0;
149
+ await repo.update({
150
+ filterByTk: config.get("id"),
151
+ values: {
152
+ ...options.ensureGitInConfig ? { aptPackages: aptPackages.join("\n") } : {},
153
+ initStatus: "running",
154
+ lastInitAt: /* @__PURE__ */ new Date(),
155
+ initProgressPercent: 5,
156
+ initProgressLog: "Installing git on app/worker nodes via Cluster Manager..."
157
+ }
158
+ });
159
+ await pubSub.publish(CLUSTER_INSTALL_CHANNEL, {
160
+ targetRole: "all",
161
+ packages: { apt: ["git"] },
162
+ registryConfig: { aptMirrorUrl }
163
+ });
164
+ lastDispatchAt = Date.now();
165
+ (_b2 = (_a2 = app == null ? void 0 : app.log) == null ? void 0 : _a2.info) == null ? void 0 : _b2.call(_a2, "plugin-git-manager: dispatched git installation via Cluster Manager");
166
+ return { dispatched: true };
167
+ };
168
+ if ((_c = app == null ? void 0 : app.lockManager) == null ? void 0 : _c.runExclusive) {
169
+ return app.lockManager.runExclusive(AUTO_RESTORE_LOCK_KEY, runDispatch, 3e4);
170
+ }
171
+ return runDispatch();
172
+ }
173
+ function resetClusterGitDispatchCooldownForTests() {
174
+ lastDispatchAt = 0;
175
+ }
176
+ // Annotate the CommonJS export names for ESM import in node:
177
+ 0 && (module.exports = {
178
+ dispatchClusterGitInstall,
179
+ readClusterGitStatus,
180
+ resetClusterGitDispatchCooldownForTests
181
+ });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "Git Manager",
4
4
  "displayName.zh-CN": "Git 管理器",
5
5
  "description": "Manage Git repositories with PAT authentication - pull, push, fetch, diff, file browsing",
6
- "version": "1.4.0",
6
+ "version": "1.4.1",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [
@@ -53,7 +53,7 @@
53
53
  "url": "git+https://github.com/OrgGem/nocobase-beta.git",
54
54
  "directory": "packages/plugins/plugin-git-manager"
55
55
  },
56
- "gitHead": "36c3d44696c81e16199e8dd5e1b13314a4c62a96",
56
+ "gitHead": "14cdd027ade7f31b9cc416cfbd338ed0e1b70ccb",
57
57
  "publishConfig": {
58
58
  "access": "public",
59
59
  "registry": "https://registry.npmjs.org/"