plugin-git-manager 1.3.3 → 1.4.0

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 (44) hide show
  1. package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
  2. package/dist/client/{317.17ed0018e3e7db00.js → 317.2d0d33871e24ee24.js} +1 -1
  3. package/dist/client/{434.b2eeaaef33aae6e0.js → 434.2401f7257495b66e.js} +1 -1
  4. package/dist/client/{453.fc3042c9740d8fab.js → 453.58657b9ba0904477.js} +1 -1
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/{434.19c7579c06b9077c.js → 434.32b0a07b821b9329.js} +1 -1
  7. package/dist/client-v2/{453.5e507c94c59277b1.js → 453.f9a0ec6d8e1bd1cc.js} +1 -1
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +10 -9
  10. package/dist/locale/en-US.json +27 -1
  11. package/dist/locale/vi-VN.json +27 -1
  12. package/dist/locale/zh-CN.json +30 -1
  13. package/dist/node_modules/simple-git/package.json +1 -1
  14. package/dist/node_modules/zod/package.json +1 -1
  15. package/dist/server/actions/chat-context.js +282 -0
  16. package/dist/server/actions/git-actions.js +99 -4
  17. package/dist/server/actions/gitlab-api.js +86 -7
  18. package/dist/server/chat-context-admission.js +187 -0
  19. package/dist/server/plugin.js +8 -0
  20. package/dist/server/request-method-policy.js +2 -0
  21. package/package.json +2 -2
  22. package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
  23. package/src/client/__tests__/ai-context.test.tsx +119 -0
  24. package/src/client/ai-context.tsx +3 -113
  25. package/src/client/context/GitManagerContext.tsx +18 -2
  26. package/src/client/index.tsx +3 -5
  27. package/src/client-v2/ai-context.tsx +135 -72
  28. package/src/client-v2/components/GitContextPicker.tsx +418 -0
  29. package/src/client-v2/git-context-api.ts +59 -0
  30. package/src/client-v2/plugin.tsx +2 -4
  31. package/src/locale/en-US.json +27 -1
  32. package/src/locale/vi-VN.json +27 -1
  33. package/src/locale/zh-CN.json +30 -1
  34. package/src/server/__tests__/chat-context-admission.test.ts +276 -0
  35. package/src/server/__tests__/chat-context-options.test.ts +144 -0
  36. package/src/server/__tests__/git-chat-context.test.ts +138 -0
  37. package/src/server/__tests__/git-security.test.ts +52 -0
  38. package/src/server/__tests__/smoke.test.ts +200 -0
  39. package/src/server/actions/chat-context.ts +302 -0
  40. package/src/server/actions/git-actions.ts +119 -6
  41. package/src/server/actions/gitlab-api.ts +97 -4
  42. package/src/server/chat-context-admission.ts +182 -0
  43. package/src/server/plugin.ts +11 -0
  44. package/src/server/request-method-policy.ts +2 -0
@@ -0,0 +1,282 @@
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 chat_context_exports = {};
28
+ __export(chat_context_exports, {
29
+ chatContextContent: () => chatContextContent,
30
+ chatContextOptions: () => chatContextOptions,
31
+ loadChatContext: () => loadChatContext
32
+ });
33
+ module.exports = __toCommonJS(chat_context_exports);
34
+ var import_repository_access = require("../repository-access");
35
+ var import_git_actions = require("./git-actions");
36
+ var import_gitlab_api = require("./gitlab-api");
37
+ const MAX_FILES = 50;
38
+ const MAX_DIFF_BYTES = 24 * 1024;
39
+ const REPOSITORY_FIELDS = ["id", "name", "defaultBranch", "status"];
40
+ const KINDS = ["repository", "merge-request", "commit"];
41
+ const ACTIONS = {
42
+ repository: [],
43
+ "merge-request": ["mergeRequests", "mergeRequestDetail"],
44
+ commit: ["branches", "log", "commitDetail", "diff"]
45
+ };
46
+ function rolesFor(ctx) {
47
+ var _a, _b, _c;
48
+ const roles = (_a = ctx.state) == null ? void 0 : _a.currentRoles;
49
+ if (!((_c = (_b = ctx.state) == null ? void 0 : _b.currentUser) == null ? void 0 : _c.id) || !Array.isArray(roles) || roles.some((role) => typeof role !== "string")) {
50
+ return ctx.throw(403, "Permission denied");
51
+ }
52
+ return roles;
53
+ }
54
+ function allowedField(permission, field) {
55
+ if (!permission) return false;
56
+ const params = permission.params || {};
57
+ for (const key of ["fields", "whitelist"]) {
58
+ const value = params[key];
59
+ if (value !== void 0 && !Array.isArray(value)) return false;
60
+ if (Array.isArray(value) && value.length && !value.includes(field) && !value.includes("*")) return false;
61
+ }
62
+ for (const key of ["except", "blacklist"]) {
63
+ const value = params[key];
64
+ if (value !== void 0 && !Array.isArray(value)) return false;
65
+ if (Array.isArray(value) && (value.includes(field) || value.includes("*"))) return false;
66
+ }
67
+ return true;
68
+ }
69
+ function intersectScopes(scopes) {
70
+ const restricted = scopes.filter((scope) => !scope.unrestricted);
71
+ if (!restricted.length) return { unrestricted: true, ids: [] };
72
+ const [first, ...rest] = restricted;
73
+ return {
74
+ unrestricted: false,
75
+ ids: first.ids.filter((id) => rest.every((scope) => scope.ids.some((other) => String(other) === String(id))))
76
+ };
77
+ }
78
+ async function permissionsFor(ctx, roles) {
79
+ if (roles.includes("root")) {
80
+ return new Map(
81
+ [
82
+ "gitRepositories:list",
83
+ "gitRepositories:get",
84
+ ...Object.values(ACTIONS).flat().map((name) => `gitManager:${name}`)
85
+ ].map((action) => [action, { params: {} }])
86
+ );
87
+ }
88
+ const pairs = [
89
+ ["gitRepositories", "list"],
90
+ ["gitRepositories", "get"],
91
+ ...Array.from(new Set(Object.values(ACTIONS).flat())).map((name) => ["gitManager", name])
92
+ ];
93
+ const values = await Promise.all(
94
+ pairs.map(
95
+ async ([resource, action]) => [`${resource}:${action}`, await ctx.app.acl.can({ roles, resource, action })]
96
+ )
97
+ );
98
+ return new Map(values);
99
+ }
100
+ function accessFor(permissions, kind) {
101
+ const list = permissions.get("gitRepositories:list") || null;
102
+ const get = permissions.get("gitRepositories:get") || null;
103
+ const required = [list, get, ...ACTIONS[kind].map((action) => permissions.get(`gitManager:${action}`) || null)];
104
+ if (required.some((permission) => !permission)) return null;
105
+ const scopes = required.map((permission) => {
106
+ var _a;
107
+ return (0, import_repository_access.resolveRepositoryScope)((_a = permission == null ? void 0 : permission.params) == null ? void 0 : _a.filter);
108
+ });
109
+ if (scopes.some((scope2) => !scope2.supported)) return null;
110
+ const scope = intersectScopes(scopes);
111
+ if (!scope.unrestricted && !scope.ids.length) return null;
112
+ const fields = REPOSITORY_FIELDS.filter((field) => allowedField(list, field) && allowedField(get, field));
113
+ if (!fields.includes("id")) return null;
114
+ return { scope, fields };
115
+ }
116
+ function scopeFilter(scope) {
117
+ return scope.unrestricted ? {} : { id: { $in: scope.ids } };
118
+ }
119
+ function readRepositoryValue(record, field) {
120
+ if (!record || typeof record !== "object") return void 0;
121
+ const value = record;
122
+ return typeof value.get === "function" ? value.get(field) : value[field];
123
+ }
124
+ function repositorySummary(record, fields) {
125
+ return Object.fromEntries(fields.map((field) => [field, readRepositoryValue(record, field)]));
126
+ }
127
+ function kindFrom(value) {
128
+ return typeof value === "string" && KINDS.includes(value) ? value : void 0;
129
+ }
130
+ function positiveInteger(value, fallback, max) {
131
+ const parsed = Number(value);
132
+ return Number.isSafeInteger(parsed) && parsed > 0 ? Math.min(parsed, max) : fallback;
133
+ }
134
+ async function chatContextOptions(ctx, next) {
135
+ const roles = rolesFor(ctx);
136
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
137
+ const kind = kindFrom(params.kind);
138
+ if (params.kind !== void 0 && !kind) ctx.throw(400, "Invalid chat context type");
139
+ const permissions = await permissionsFor(ctx, roles);
140
+ const accesses = Object.fromEntries(KINDS.map((name) => [name, accessFor(permissions, name)]));
141
+ const repo = ctx.db.getRepository("gitRepositories");
142
+ const capabilityValues = await Promise.all(
143
+ KINDS.map(async (name) => {
144
+ const access2 = accesses[name];
145
+ return Boolean(access2 && await repo.findOne({ filter: scopeFilter(access2.scope), fields: ["id"] }));
146
+ })
147
+ );
148
+ const capabilities = Object.fromEntries(KINDS.map((name, index) => [name, capabilityValues[index]]));
149
+ const page = positiveInteger(params.page, 1, 1e5);
150
+ const pageSize = positiveInteger(params.pageSize, 20, 100);
151
+ const access = kind ? accesses[kind] : null;
152
+ const search = typeof params.search === "string" ? params.search.trim().slice(0, 200) : "";
153
+ const repositoryId = params.repositoryId;
154
+ if (repositoryId !== void 0 && (typeof repositoryId !== "string" && typeof repositoryId !== "number" || !String(repositoryId).trim())) {
155
+ ctx.throw(400, "Invalid repository");
156
+ }
157
+ let records = [];
158
+ if (access && (!search || access.fields.includes("name"))) {
159
+ const conditions = [scopeFilter(access.scope)];
160
+ if (search) conditions.push({ name: { $includes: search } });
161
+ if (typeof repositoryId === "string" || typeof repositoryId === "number") conditions.push({ id: repositoryId });
162
+ const filter = conditions.length === 1 ? conditions[0] : { $and: conditions };
163
+ records = await repo.find({
164
+ filter,
165
+ fields: access.fields,
166
+ sort: ["id"],
167
+ limit: pageSize + 1,
168
+ offset: (page - 1) * pageSize
169
+ });
170
+ }
171
+ ctx.body = {
172
+ success: true,
173
+ data: {
174
+ capabilities,
175
+ items: records.slice(0, pageSize).map((record) => repositorySummary(record, (access == null ? void 0 : access.fields) || [])),
176
+ page,
177
+ pageSize,
178
+ hasMore: records.length > pageSize
179
+ }
180
+ };
181
+ await next();
182
+ }
183
+ function boundedDiff(value, limit) {
184
+ const bytes = Buffer.from(value, "utf8");
185
+ if (bytes.length <= limit) return { value, truncated: false, bytes: bytes.length };
186
+ const text = bytes.subarray(0, limit).toString("utf8").replace(/\uFFFD$/, "");
187
+ return { value: text, truncated: true, bytes: Buffer.byteLength(text, "utf8") };
188
+ }
189
+ async function loadChatContext(ctx, params) {
190
+ const roles = rolesFor(ctx);
191
+ const kind = kindFrom(params.kind);
192
+ const repositoryId = params.repositoryId;
193
+ if (!kind || typeof repositoryId !== "number" && typeof repositoryId !== "string" || !String(repositoryId).trim()) {
194
+ return ctx.throw(400, "Invalid chat context");
195
+ }
196
+ const access = accessFor(await permissionsFor(ctx, roles), kind);
197
+ if (!access || !access.scope.unrestricted && !(0, import_repository_access.scopeIncludesRepository)({ id: { $in: access.scope.ids } }, repositoryId)) {
198
+ return ctx.throw(403, "Permission denied");
199
+ }
200
+ const repository = await ctx.db.getRepository("gitRepositories").findOne({
201
+ filter: { $and: [scopeFilter(access.scope), { id: repositoryId }] },
202
+ fields: access.fields
203
+ });
204
+ if (!repository) return ctx.throw(404, "Repository not found");
205
+ const summary = repositorySummary(repository, access.fields);
206
+ const repositoryName = summary.name;
207
+ let content;
208
+ if (kind === "repository") {
209
+ content = {
210
+ type: "git-repository",
211
+ repositoryId,
212
+ name: summary.name,
213
+ defaultBranch: summary.defaultBranch,
214
+ status: summary.status
215
+ };
216
+ } else if (kind === "commit") {
217
+ const commitHash = typeof params.commitHash === "string" ? params.commitHash : "";
218
+ const commit = await (0, import_git_actions.readChatCommit)(ctx, commitHash, MAX_FILES, MAX_DIFF_BYTES, repositoryId);
219
+ content = {
220
+ type: "git-commit",
221
+ repositoryId,
222
+ repositoryName,
223
+ ...commit,
224
+ hash: commit.commitSha,
225
+ files: commit.files.map((file) => ({ ...file, file: file.newPath })),
226
+ limitations: commit.limitations.map((limitation) => ctx.t(limitation, { ns: "plugin-git-manager" }))
227
+ };
228
+ } else {
229
+ const mrIid = Number(params.mrIid);
230
+ if (!Number.isSafeInteger(mrIid) || mrIid <= 0) return ctx.throw(400, "Invalid merge request");
231
+ const result = await (0, import_gitlab_api.readChatMergeRequest)(ctx, mrIid, repositoryId);
232
+ let remaining = MAX_DIFF_BYTES;
233
+ let truncated = result.files.length > MAX_FILES;
234
+ const changes = result.files.slice(0, MAX_FILES).map((file) => {
235
+ const diff = typeof file.diff === "string" && !file.unavailable ? boundedDiff(file.diff, remaining) : void 0;
236
+ if (diff) {
237
+ remaining -= diff.bytes;
238
+ truncated ||= diff.truncated;
239
+ }
240
+ return {
241
+ oldPath: file.oldPath,
242
+ newPath: file.newPath,
243
+ status: file.status,
244
+ newFile: file.status === "added",
245
+ deletedFile: file.status === "removed",
246
+ renamedFile: file.status === "renamed",
247
+ diff: diff == null ? void 0 : diff.value
248
+ };
249
+ });
250
+ const limitations = [...result.limitations];
251
+ if (truncated) limitations.push("Additional changed files or diff content were omitted.");
252
+ if (limitations.length) truncated = true;
253
+ content = {
254
+ type: "git-merge-request",
255
+ repositoryId,
256
+ repositoryName,
257
+ mrIid,
258
+ title: result.title,
259
+ description: result.description,
260
+ state: result.state,
261
+ sourceBranch: result.sourceBranch,
262
+ targetBranch: result.targetBranch,
263
+ author: result.author,
264
+ files: changes.map(({ diff: _diff, ...file }) => file),
265
+ changes,
266
+ truncated,
267
+ limitations: limitations.map((limitation) => ctx.t(limitation, { ns: "plugin-git-manager" }))
268
+ };
269
+ }
270
+ return content;
271
+ }
272
+ async function chatContextContent(ctx, next) {
273
+ const content = await loadChatContext(ctx, (0, import_repository_access.getEffectiveActionParams)(ctx));
274
+ ctx.body = { success: true, data: content };
275
+ await next();
276
+ }
277
+ // Annotate the CommonJS export names for ESM import in node:
278
+ 0 && (module.exports = {
279
+ chatContextContent,
280
+ chatContextOptions,
281
+ loadChatContext
282
+ });
@@ -52,6 +52,7 @@ __export(git_actions_exports, {
52
52
  log: () => log,
53
53
  pull: () => pull,
54
54
  push: () => push,
55
+ readChatCommit: () => readChatCommit,
55
56
  status: () => status,
56
57
  validateBranch: () => validateBranch,
57
58
  validateLocalPath: () => validateLocalPath,
@@ -206,8 +207,8 @@ function getGit(ctx, localPath) {
206
207
  assertGitAvailable(ctx);
207
208
  return createGit(localPath);
208
209
  }
209
- async function getRepo(ctx) {
210
- const { repositoryId } = getGitActionParams(ctx);
210
+ async function getRepo(ctx, requestedRepositoryId) {
211
+ const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
211
212
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
212
213
  filterByTk: repositoryId
213
214
  });
@@ -348,14 +349,27 @@ async function status(ctx, next) {
348
349
  async function log(ctx, next) {
349
350
  const repo = await getRepo(ctx);
350
351
  const localPath = validateLocalPath(repo.get("localPath"));
351
- const { maxCount = 50, file } = getGitActionParams(ctx);
352
+ const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
352
353
  const parsed = Number.parseInt(String(maxCount), 10);
353
354
  const options = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
354
355
  if (file) {
355
356
  if (file.includes("..")) ctx.throw(400, "Invalid file path");
356
357
  options.file = file;
357
358
  }
358
- const result = await getGit(ctx, localPath).log(options);
359
+ const args = [];
360
+ if (branch) args.push(validateBranch(branch));
361
+ if (skip !== void 0) {
362
+ const parsedSkip = Number(skip);
363
+ if (!Number.isSafeInteger(parsedSkip) || parsedSkip < 0 || parsedSkip > 1e6) {
364
+ ctx.throw(400, "Invalid history offset");
365
+ }
366
+ args.push(`--skip=${parsedSkip}`);
367
+ }
368
+ const result = args.length ? await getGit(ctx, localPath).log([
369
+ ...args,
370
+ `--max-count=${options.maxCount}`,
371
+ ...file ? ["--follow", "--", file] : []
372
+ ]) : await getGit(ctx, localPath).log(options);
359
373
  ctx.body = { success: true, data: result };
360
374
  await next();
361
375
  }
@@ -470,6 +484,86 @@ async function commitDetail(ctx, next) {
470
484
  };
471
485
  await next();
472
486
  }
487
+ async function readLimitedGitOutput(localPath, args, maxBytes) {
488
+ return new Promise((resolve, reject) => {
489
+ const process2 = (0, import_child_process.spawn)(GIT_BINARY, args, {
490
+ cwd: localPath,
491
+ env: gitProcessEnvironment(),
492
+ windowsHide: true,
493
+ stdio: ["ignore", "pipe", "ignore"]
494
+ });
495
+ const chunks = [];
496
+ let size = 0;
497
+ let truncated = false;
498
+ process2.stdout.on("data", (chunk) => {
499
+ const remaining = maxBytes - size;
500
+ if (remaining > 0) {
501
+ const data = chunk.subarray(0, remaining);
502
+ chunks.push(data);
503
+ size += data.length;
504
+ }
505
+ if (chunk.length > remaining) {
506
+ truncated = true;
507
+ process2.kill();
508
+ }
509
+ });
510
+ process2.on("error", reject);
511
+ process2.on("close", (code) => {
512
+ if (code !== 0 && !truncated) {
513
+ reject(new Error("Unable to read commit diff"));
514
+ return;
515
+ }
516
+ const text = Buffer.concat(chunks).toString("utf8").replace(/\uFFFD$/, "");
517
+ resolve({ text, truncated });
518
+ });
519
+ });
520
+ }
521
+ async function readChatCommit(ctx, commitHash, maxFiles, maxBytes, repositoryId) {
522
+ if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, "Invalid commit hash");
523
+ const repo = await getRepo(ctx, repositoryId);
524
+ const localPath = validateLocalPath(repo.get("localPath"));
525
+ const git = getGit(ctx, localPath);
526
+ const hash = (await git.raw(["rev-parse", "--verify", `${commitHash}^{commit}`])).trim();
527
+ const [metadata, parentLine] = await Promise.all([
528
+ git.raw(["show", "-s", "--format=%H%x00%an%x00%aI%x00%s%x00%b", hash]),
529
+ git.raw(["rev-list", "--parents", "-n", "1", hash])
530
+ ]);
531
+ const [, author, date, subject, body] = metadata.split("\0");
532
+ const parent = parentLine.trim().split(/\s+/)[1];
533
+ const namesArgs = parent ? ["diff", "--name-status", "-z", "-M", parent, hash, "--"] : ["diff-tree", "--root", "--no-commit-id", "-r", "--name-status", "-z", "-M", hash, "--"];
534
+ const tokens = (await git.raw(namesArgs)).split("\0");
535
+ const files = [];
536
+ for (let index = 0; index < tokens.length && tokens[index]; ) {
537
+ const status2 = tokens[index++];
538
+ const oldPath = tokens[index++];
539
+ const newPath = /^[RC]/.test(status2) ? tokens[index++] : oldPath;
540
+ if (!oldPath || !newPath) break;
541
+ files.push({ oldPath, newPath, status: status2 });
542
+ }
543
+ const selectedFiles = files.slice(0, maxFiles);
544
+ const paths = Array.from(new Set(selectedFiles.flatMap((file) => [file.oldPath, file.newPath]))).map(
545
+ (file) => `:(literal)${file}`
546
+ );
547
+ const patchArgs = parent ? ["diff", "--no-ext-diff", "--no-textconv", "--no-color", parent, hash, "--", ...paths] : ["show", "--format=", "--no-ext-diff", "--no-textconv", "--no-color", hash, "--", ...paths];
548
+ const patch = paths.length ? await readLimitedGitOutput(localPath, patchArgs, maxBytes) : { text: "", truncated: false };
549
+ const limitations = [];
550
+ if (files.length > maxFiles) limitations.push("Additional changed files were omitted.");
551
+ if (patch.truncated) limitations.push("The diff was truncated to the configured limit.");
552
+ if (/^Binary files .* differ$|^GIT binary patch$/m.test(patch.text)) {
553
+ limitations.push("Binary file contents are not included in the diff.");
554
+ }
555
+ return {
556
+ commitSha: hash,
557
+ author,
558
+ date,
559
+ subject,
560
+ body: body == null ? void 0 : body.trim(),
561
+ files: selectedFiles,
562
+ diff: patch.text,
563
+ truncated: patch.truncated || files.length > maxFiles,
564
+ limitations
565
+ };
566
+ }
473
567
  // Annotate the CommonJS export names for ESM import in node:
474
568
  0 && (module.exports = {
475
569
  acquireLock,
@@ -488,6 +582,7 @@ async function commitDetail(ctx, next) {
488
582
  log,
489
583
  pull,
490
584
  push,
585
+ readChatCommit,
491
586
  status,
492
587
  validateBranch,
493
588
  validateLocalPath,
@@ -28,7 +28,8 @@ var gitlab_api_exports = {};
28
28
  __export(gitlab_api_exports, {
29
29
  mergeRequestDetail: () => mergeRequestDetail,
30
30
  mergeRequestNotes: () => mergeRequestNotes,
31
- mergeRequests: () => mergeRequests
31
+ mergeRequests: () => mergeRequests,
32
+ readChatMergeRequest: () => readChatMergeRequest
32
33
  });
33
34
  module.exports = __toCommonJS(gitlab_api_exports);
34
35
  var import_repository_access = require("../repository-access");
@@ -56,12 +57,18 @@ async function gitlabFetch(apiBase, endpoint, pat, params) {
56
57
  }
57
58
  const totalPages = response.headers.get("x-total-pages");
58
59
  const total = response.headers.get("x-total");
60
+ const nextPage = response.headers.get("x-next-page");
59
61
  const data = await response.json();
60
- return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
62
+ return {
63
+ data,
64
+ totalPages: totalPages ? parseInt(totalPages, 10) : null,
65
+ total: total ? parseInt(total, 10) : null,
66
+ hasMore: nextPage !== null ? Boolean(nextPage) : null
67
+ };
61
68
  }
62
- async function getRepoApiContext(ctx) {
69
+ async function getRepoApiContext(ctx, requestedRepositoryId) {
63
70
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
64
- const { repositoryId } = params;
71
+ const repositoryId = requestedRepositoryId ?? params.repositoryId;
65
72
  if (typeof repositoryId !== "string" && typeof repositoryId !== "number") ctx.throw(400, "repositoryId is required");
66
73
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
67
74
  filterByTk: repositoryId
@@ -106,7 +113,8 @@ async function githubFetch(endpoint, pat, params) {
106
113
  }
107
114
  }
108
115
  const data = await response.json();
109
- return { data, totalPages, total: null };
116
+ const hasMore = linkHeader ? linkHeader.split(",").some((link) => link.includes('rel="next"')) : false;
117
+ return { data, totalPages, total: null, hasMore };
110
118
  }
111
119
  async function mergeRequests(ctx, next) {
112
120
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
@@ -217,7 +225,8 @@ async function mergeRequests(ctx, next) {
217
225
  page: parseInt(String(page), 10),
218
226
  perPage: parseInt(String(perPage), 10),
219
227
  total: result.total,
220
- totalPages: result.totalPages
228
+ totalPages: result.totalPages,
229
+ hasMore: result.hasMore ?? (result.totalPages !== null ? Number(page) < result.totalPages : result.data.length >= Math.min(parseInt(String(perPage), 10) || 20, 100))
221
230
  }
222
231
  };
223
232
  await next();
@@ -339,6 +348,75 @@ async function mergeRequestDetail(ctx, next) {
339
348
  };
340
349
  await next();
341
350
  }
351
+ async function readChatMergeRequest(ctx, mrIid, repositoryId) {
352
+ var _a, _b, _c, _d, _e;
353
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
354
+ if (isGitHub) {
355
+ 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 })
358
+ ]);
359
+ const item2 = request2.data;
360
+ if (!Array.isArray(fileResult.data)) throw new Error("Unable to read merge request changes");
361
+ const files2 = fileResult.data.map(
362
+ (file) => ({
363
+ oldPath: file.previous_filename || file.filename,
364
+ newPath: file.filename,
365
+ status: file.status,
366
+ diff: file.patch
367
+ })
368
+ );
369
+ const limitations2 = [];
370
+ if (typeof item2.changed_files === "number" && item2.changed_files > files2.length) {
371
+ limitations2.push("Additional changed files were omitted by the provider.");
372
+ }
373
+ if (files2.some((file) => !file.diff)) {
374
+ limitations2.push("The provider omitted patches for one or more files, including binary or large files.");
375
+ }
376
+ return {
377
+ title: item2.title,
378
+ description: item2.body,
379
+ state: item2.state === "open" ? "opened" : item2.merged_at ? "merged" : "closed",
380
+ sourceBranch: (_a = item2.head) == null ? void 0 : _a.ref,
381
+ targetBranch: (_b = item2.base) == null ? void 0 : _b.ref,
382
+ author: (_c = item2.user) == null ? void 0 : _c.login,
383
+ files: files2,
384
+ limitations: limitations2
385
+ };
386
+ }
387
+ if (!pat) ctx.throw(400, "Personal Access Token is required for GitLab API access");
388
+ 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)
391
+ ]);
392
+ const item = request.data;
393
+ const changeData = changeResult.data || {};
394
+ if (!Array.isArray(changeData.changes)) throw new Error("Unable to read merge request changes");
395
+ const files = changeData.changes.map(
396
+ (file) => ({
397
+ oldPath: file.old_path,
398
+ newPath: file.new_path,
399
+ status: file.new_file ? "added" : file.deleted_file ? "removed" : file.renamed_file ? "renamed" : "modified",
400
+ diff: file.diff,
401
+ unavailable: file.collapsed || file.too_large || file.binary || !file.diff
402
+ })
403
+ );
404
+ const limitations = [];
405
+ if (changeData.overflow) limitations.push("The provider omitted additional changed files or patches.");
406
+ if (files.some((file) => file.unavailable)) {
407
+ limitations.push("The provider omitted patches for one or more files, including binary or large files.");
408
+ }
409
+ return {
410
+ title: item.title,
411
+ description: item.description,
412
+ state: item.state,
413
+ sourceBranch: item.source_branch,
414
+ targetBranch: item.target_branch,
415
+ author: ((_d = item.author) == null ? void 0 : _d.username) || ((_e = item.author) == null ? void 0 : _e.name),
416
+ files,
417
+ limitations
418
+ };
419
+ }
342
420
  async function mergeRequestNotes(ctx, next) {
343
421
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
344
422
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
@@ -398,5 +476,6 @@ async function mergeRequestNotes(ctx, next) {
398
476
  0 && (module.exports = {
399
477
  mergeRequestDetail,
400
478
  mergeRequestNotes,
401
- mergeRequests
479
+ mergeRequests,
480
+ readChatMergeRequest
402
481
  });