koishi-plugin-githubsth 1.0.1-beta → 1.0.1-test10

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.
@@ -3,6 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.apply = apply;
4
4
  function apply(ctx) {
5
5
  const logger = ctx.logger('githubsth');
6
+ // Allow . in repo name (e.g. koishi.js) but disallow / inside parts.
7
+ // owner: [\w-]+ (alphanumeric, underscore, dash)
8
+ // repo: [\w-\.]+ (alphanumeric, underscore, dash, dot)
6
9
  const repoRegex = /^[\w-]+\/[\w-\.]+$/;
7
10
  ctx.command('githubsth.trust', '管理信任仓库', { authority: 3 })
8
11
  .alias('gh.trust');
@@ -10,9 +13,11 @@ function apply(ctx) {
10
13
  .action(async ({ session }, repo) => {
11
14
  if (!repo)
12
15
  return '请指定仓库名称 (owner/repo)。';
13
- if (!repoRegex.test(repo))
16
+ if (!repoRegex.test(repo)) {
14
17
  return '仓库名称格式不正确 (应为 owner/repo)。';
18
+ }
15
19
  try {
20
+ logger.debug(`Adding trusted repo: ${repo}`);
16
21
  // Check existence first to avoid UNIQUE constraint error log from driver
17
22
  const existing = await ctx.database.get('github_trusted_repo', { repo });
18
23
  if (existing.length > 0) {
@@ -27,18 +32,17 @@ function apply(ctx) {
27
32
  return `已添加信任仓库: ${repo}`;
28
33
  }
29
34
  catch (e) {
35
+ logger.warn('Failed to add trusted repo:', e);
30
36
  if (e.code === 'SQLITE_CONSTRAINT') {
31
37
  return '该仓库已在信任列表中。';
32
38
  }
33
- logger.warn(e);
34
- return '添加失败,请查看日志。';
39
+ return `添加失败: ${e.message}`;
35
40
  }
36
41
  });
37
42
  ctx.command('githubsth.trust.remove <repo>', '移除信任仓库')
38
43
  .action(async ({ session }, repo) => {
39
44
  if (!repo)
40
45
  return '请指定仓库名称 (owner/repo)。';
41
- // No regex check here needed strictly, but good for consistency
42
46
  const result = await ctx.database.remove('github_trusted_repo', { repo });
43
47
  if (result.matched === 0)
44
48
  return '未找到该信任仓库。';
@@ -35,6 +35,19 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.apply = apply;
37
37
  const repo = __importStar(require("./repo"));
38
+ const admin = __importStar(require("./admin"));
39
+ const subscribe = __importStar(require("./subscribe"));
38
40
  function apply(ctx, config) {
41
+ console.log('Applying githubsth commands...');
42
+ // Register parent command to show help
43
+ ctx.command('githubsth', 'GitHub 推送通知')
44
+ .action(({ session }) => {
45
+ session?.execute('help githubsth');
46
+ });
39
47
  ctx.plugin(repo, config);
48
+ console.log('githubsth.repo loaded');
49
+ ctx.plugin(admin, config);
50
+ console.log('githubsth.admin loaded');
51
+ ctx.plugin(subscribe, config);
52
+ console.log('githubsth.subscribe loaded');
40
53
  }
@@ -1,3 +1,8 @@
1
1
  import { Context } from 'koishi';
2
2
  import { Config } from '../config';
3
+ declare module 'koishi' {
4
+ interface Context {
5
+ github?: any;
6
+ }
7
+ }
3
8
  export declare function apply(ctx: Context, config: Config): void;
@@ -10,10 +10,28 @@ function apply(ctx, config) {
10
10
  const fullRepo = name || (config.defaultOwner ? `${config.defaultOwner}/${config.defaultRepo}` : name);
11
11
  if (!fullRepo)
12
12
  return session?.text('.specify_repo');
13
- // 在实际实现中,我们将在此处使用 GitHub API。
14
- // 由于我们没有 API 客户端的具体设置细节(例如 Octokit 或适配器内部实现),
15
- // 我们将返回一个占位符,以确认命令结构正常工作。
16
- // TODO: 使用 session.bot 或专用服务实现实际的 GitHub API 调用。
17
- return session?.text('.repo_info', [fullRepo.split('/')[0], fullRepo.split('/')[1] || '?', 'Demo Description', '100']);
13
+ try {
14
+ let data;
15
+ if (ctx.github && typeof ctx.github.request === 'function') {
16
+ // If adapter provides a request method (hypothetical, based on common adapter patterns)
17
+ data = await ctx.github.request('GET /repos/:owner/:repo', {
18
+ owner: fullRepo.split('/')[0],
19
+ repo: fullRepo.split('/')[1]
20
+ });
21
+ }
22
+ else {
23
+ const headers = {
24
+ 'User-Agent': 'Koishi-Plugin-GithubSth'
25
+ };
26
+ data = await ctx.http.get(`https://api.github.com/repos/${fullRepo}`, { headers });
27
+ }
28
+ return session?.text('.repo_info', [data.owner.login, data.name, data.description || '无描述', data.stargazers_count]);
29
+ }
30
+ catch (e) {
31
+ if (e.response?.status === 404) {
32
+ return session?.text('.not_found');
33
+ }
34
+ return session?.text('.error', [e.message]);
35
+ }
18
36
  });
19
37
  }
package/lib/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Config } from './config';
3
3
  export declare const name = "githubsth";
4
4
  export declare const inject: {
5
5
  required: string[];
6
+ optional: string[];
6
7
  };
7
8
  export * from './config';
8
9
  export declare function apply(ctx: Context, config: Config): void;
package/lib/index.js CHANGED
@@ -42,29 +42,54 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.inject = exports.name = void 0;
43
43
  exports.apply = apply;
44
44
  const commands = __importStar(require("./commands"));
45
- const admin = __importStar(require("./commands/admin"));
46
- const subscribe = __importStar(require("./commands/subscribe"));
47
45
  const database = __importStar(require("./database"));
48
46
  const zh_CN_1 = __importDefault(require("./locales/zh-CN"));
49
47
  const notifier_1 = require("./services/notifier");
50
48
  const formatter_1 = require("./services/formatter");
51
49
  exports.name = 'githubsth';
52
50
  exports.inject = {
53
- required: ['database', 'github'],
51
+ required: ['database'],
52
+ optional: ['github'],
54
53
  };
55
54
  __exportStar(require("./config"), exports);
56
55
  function apply(ctx, config) {
56
+ const logger = ctx.logger('githubsth');
57
+ logger.info('Plugin loading...');
57
58
  // 本地化
58
59
  ctx.i18n.define('zh-CN', zh_CN_1.default);
59
60
  // 数据库
60
61
  ctx.plugin(database);
61
62
  // 注册服务
63
+ logger.info('Registering Formatter...');
62
64
  ctx.plugin(formatter_1.Formatter);
65
+ logger.info('Registering Notifier...');
63
66
  ctx.plugin(notifier_1.Notifier, config);
67
+ // Debug listener for raw events
68
+ ctx.on('github/issues', (payload) => {
69
+ logger.info('[DEBUG] Global listener caught github/issues');
70
+ });
71
+ ctx.on('github/opened', (payload) => {
72
+ logger.info('[DEBUG] Global listener caught github/opened');
73
+ });
74
+ // Comprehensive debug listeners
75
+ ctx.on('github/webhook', (payload) => {
76
+ logger.info('[DEBUG] Global listener caught github/webhook');
77
+ });
78
+ // Middleware to log all sessions
79
+ ctx.middleware((session, next) => {
80
+ // Log any session event from github
81
+ if (session.platform === 'github') {
82
+ logger.info(`[DEBUG] Middleware saw session.type: ${session.type}, subtype: ${session.subtype}`);
83
+ }
84
+ return next();
85
+ });
64
86
  // 注册命令
65
- ctx.plugin(commands, config);
66
- ctx.plugin(admin);
67
- ctx.plugin(subscribe);
68
- // 加载成功日志
69
- console.log('githubsth plugin loaded');
87
+ // admin and subscribe are already loaded in commands/index.ts, remove duplicate loading here
88
+ try {
89
+ ctx.plugin(commands, config);
90
+ logger.info('Plugin loaded successfully');
91
+ }
92
+ catch (e) {
93
+ logger.error('Plugin failed to load:', e);
94
+ }
70
95
  }
@@ -1,7 +1,7 @@
1
1
  import { Context, Service, h } from 'koishi';
2
2
  declare module 'koishi' {
3
3
  interface Context {
4
- formatter: Formatter;
4
+ githubsthFormatter: Formatter;
5
5
  }
6
6
  }
7
7
  export declare class Formatter extends Service {
@@ -4,7 +4,8 @@ exports.Formatter = void 0;
4
4
  const koishi_1 = require("koishi");
5
5
  class Formatter extends koishi_1.Service {
6
6
  constructor(ctx) {
7
- super(ctx, 'formatter');
7
+ super(ctx, 'githubsthFormatter');
8
+ ctx.logger('githubsth').info('Formatter service initialized');
8
9
  }
9
10
  formatPush(payload) {
10
11
  const { repository, pusher, commits, compare } = payload;
@@ -2,7 +2,7 @@ import { Context, Service } from 'koishi';
2
2
  import { Config } from '../config';
3
3
  declare module 'koishi' {
4
4
  interface Context {
5
- notifier: Notifier;
5
+ githubsthNotifier: Notifier;
6
6
  }
7
7
  }
8
8
  export declare class Notifier extends Service {
@@ -5,29 +5,100 @@ const koishi_1 = require("koishi");
5
5
  class Notifier extends koishi_1.Service {
6
6
  // @ts-ignore
7
7
  constructor(ctx, config) {
8
- super(ctx, 'notifier', true);
8
+ super(ctx, 'githubsthNotifier', true);
9
9
  this.config = config;
10
+ this.ctx.logger('githubsth').info('Notifier service initialized');
10
11
  this.registerListeners();
11
12
  }
12
13
  registerListeners() {
13
14
  this.ctx.on('github/push', (payload) => this.handleEvent('push', payload));
14
15
  this.ctx.on('github/issues', (payload) => this.handleEvent('issues', payload));
15
16
  this.ctx.on('github/pull_request', (payload) => this.handleEvent('pull_request', payload));
17
+ this.ctx.on('github/pull-request', (payload) => this.handleEvent('pull_request', payload));
16
18
  this.ctx.on('github/star', (payload) => this.handleEvent('star', payload));
17
19
  this.ctx.on('github/fork', (payload) => this.handleEvent('fork', payload));
18
20
  this.ctx.on('github/release', (payload) => this.handleEvent('release', payload));
19
21
  this.ctx.on('github/discussion', (payload) => this.handleEvent('discussion', payload));
20
22
  this.ctx.on('github/workflow_run', (payload) => this.handleEvent('workflow_run', payload));
23
+ this.ctx.on('github/workflow-run', (payload) => this.handleEvent('workflow_run', payload));
21
24
  this.ctx.on('github/issue_comment', (payload) => this.handleEvent('issue_comment', payload));
22
- this.ctx.on('github/pull_request_review', (payload) => this.handleEvent('pull_request_review', payload));
25
+ this.ctx.on('github/issue-comment', (payload) => this.handleEvent('issue_comment', payload));
26
+ this.ctx.on('github/pull-request-review', (payload) => this.handleEvent('pull_request_review', payload));
27
+ // Fallback: Listen to message-created for adapters that map webhooks to messages
28
+ this.ctx.on('message-created', (session) => {
29
+ if (session.platform !== 'github')
30
+ return;
31
+ this.ctx.logger('githubsth').info(`[Debug] Message session keys: ${Object.keys(session).join(', ')}`);
32
+ this.ctx.logger('githubsth').info(`[Debug] Message session content: ${session.content}`);
33
+ // Try to find payload
34
+ const possiblePayload = session.payload || session.extra || session.data;
35
+ if (possiblePayload) {
36
+ this.ctx.logger('githubsth').info(`[Debug] Found payload in property: ${!!session.payload ? 'payload' : !!session.extra ? 'extra' : 'data'}`);
37
+ }
38
+ else {
39
+ this.ctx.logger('githubsth').warn('[Debug] No payload found in session');
40
+ }
41
+ // If we can't find the payload easily, we might need to rely on the adapter emitting proper events.
42
+ // But since we are here, let's try to see if 'payload' or 'extra' exists.
43
+ const payload = possiblePayload;
44
+ if (payload) {
45
+ this.ctx.logger('githubsth').info('Found payload in session, attempting to handle');
46
+ // Infer event type
47
+ let eventType = 'unknown';
48
+ if (payload.issue && payload.comment)
49
+ eventType = 'issue_comment';
50
+ else if (payload.issue)
51
+ eventType = 'issues';
52
+ else if (payload.pull_request && payload.review)
53
+ eventType = 'pull_request_review';
54
+ else if (payload.pull_request)
55
+ eventType = 'pull_request';
56
+ else if (payload.commits)
57
+ eventType = 'push';
58
+ else if (payload.starred_at !== undefined || (payload.action === 'started'))
59
+ eventType = 'star'; // star event usually has action 'created' but check payload structure
60
+ else if (payload.forkee)
61
+ eventType = 'fork';
62
+ else if (payload.release)
63
+ eventType = 'release';
64
+ else if (payload.discussion)
65
+ eventType = 'discussion';
66
+ else if (payload.workflow_run)
67
+ eventType = 'workflow_run';
68
+ if (eventType !== 'unknown') {
69
+ this.handleEvent(eventType, payload);
70
+ }
71
+ }
72
+ });
23
73
  }
24
74
  async handleEvent(event, payload) {
25
- const repoName = payload.repository?.full_name;
26
- if (!repoName)
75
+ // FORCE LOG for debugging
76
+ this.ctx.logger('githubsth').info(`Received event: ${event}`);
77
+ // Check if payload is nested in an 'event' object (common in some adapter versions)
78
+ // or if the event data is directly in payload
79
+ const realPayload = payload.payload || payload;
80
+ let repoName = realPayload.repository?.full_name;
81
+ // Try to fallback if repoName is missing
82
+ if (!repoName && realPayload.issue?.repository_url) {
83
+ const parts = realPayload.issue.repository_url.split('/');
84
+ if (parts.length >= 2) {
85
+ repoName = `${parts[parts.length - 2]}/${parts[parts.length - 1]}`;
86
+ }
87
+ }
88
+ if (!repoName && realPayload.pull_request?.base?.repo?.full_name) {
89
+ repoName = realPayload.pull_request.base.repo.full_name;
90
+ }
91
+ if (!repoName) {
92
+ this.ctx.logger('githubsth').warn(`Missing repo info for event: ${event}`);
93
+ if (this.config.debug) {
94
+ this.ctx.logger('notifier').warn(`Event ${event} missing repository info. Keys: ${Object.keys(realPayload).join(', ')}`);
95
+ }
27
96
  return;
97
+ }
98
+ this.ctx.logger('githubsth').info(`Processing event ${event} for ${repoName}`);
28
99
  if (this.config.debug) {
29
100
  this.ctx.logger('notifier').info(`Received event ${event} for ${repoName}`);
30
- this.ctx.logger('notifier').debug(JSON.stringify(payload, null, 2));
101
+ this.ctx.logger('notifier').debug(JSON.stringify(realPayload, null, 2));
31
102
  }
32
103
  // Get rules from database
33
104
  const dbRules = await this.ctx.database.get('github_subscription', {
@@ -45,49 +116,65 @@ class Notifier extends koishi_1.Service {
45
116
  return false;
46
117
  return true;
47
118
  });
48
- if (matchedRules.length === 0)
119
+ if (matchedRules.length === 0) {
120
+ this.ctx.logger('githubsth').info(`No matching rules for ${repoName} (event: ${event})`);
121
+ if (this.config.debug) {
122
+ this.ctx.logger('notifier').debug(`No matching rules for ${repoName} (event: ${event})`);
123
+ }
49
124
  return;
125
+ }
126
+ this.ctx.logger('githubsth').info(`Found ${matchedRules.length} matching rules for ${repoName}`);
127
+ if (this.config.debug) {
128
+ this.ctx.logger('notifier').debug(`Found ${matchedRules.length} matching rules for ${repoName}`);
129
+ }
50
130
  let message = null;
51
131
  // Ensure formatter is loaded
52
- if (!this.ctx.formatter) {
132
+ if (!this.ctx.githubsthFormatter) {
53
133
  this.ctx.logger('notifier').warn('Formatter service not available');
54
134
  return;
55
135
  }
56
136
  switch (event) {
57
137
  case 'push':
58
- message = this.ctx.formatter.formatPush(payload);
138
+ message = this.ctx.githubsthFormatter.formatPush(realPayload);
59
139
  break;
60
140
  case 'issues':
61
- message = this.ctx.formatter.formatIssue(payload);
141
+ message = this.ctx.githubsthFormatter.formatIssue(realPayload);
62
142
  break;
63
143
  case 'pull_request':
64
- message = this.ctx.formatter.formatPullRequest(payload);
144
+ message = this.ctx.githubsthFormatter.formatPullRequest(realPayload);
65
145
  break;
66
146
  case 'star':
67
- message = this.ctx.formatter.formatStar(payload);
147
+ message = this.ctx.githubsthFormatter.formatStar(realPayload);
68
148
  break;
69
149
  case 'fork':
70
- message = this.ctx.formatter.formatFork(payload);
150
+ message = this.ctx.githubsthFormatter.formatFork(realPayload);
71
151
  break;
72
152
  case 'release':
73
- message = this.ctx.formatter.formatRelease(payload);
153
+ message = this.ctx.githubsthFormatter.formatRelease(realPayload);
74
154
  break;
75
155
  case 'discussion':
76
- message = this.ctx.formatter.formatDiscussion(payload);
156
+ message = this.ctx.githubsthFormatter.formatDiscussion(realPayload);
77
157
  break;
78
158
  case 'workflow_run':
79
- message = this.ctx.formatter.formatWorkflowRun(payload);
159
+ message = this.ctx.githubsthFormatter.formatWorkflowRun(realPayload);
80
160
  break;
81
161
  case 'issue_comment':
82
- message = this.ctx.formatter.formatIssueComment(payload);
162
+ message = this.ctx.githubsthFormatter.formatIssueComment(realPayload);
83
163
  break;
84
164
  case 'pull_request_review':
85
- message = this.ctx.formatter.formatPullRequestReview(payload);
165
+ message = this.ctx.githubsthFormatter.formatPullRequestReview(realPayload);
86
166
  break;
87
167
  }
88
- if (!message)
168
+ if (!message) {
169
+ if (this.config.debug) {
170
+ this.ctx.logger('notifier').debug(`Formatter returned null for event ${event}`);
171
+ }
89
172
  return;
173
+ }
90
174
  for (const rule of matchedRules) {
175
+ if (this.config.debug) {
176
+ this.ctx.logger('notifier').debug(`Sending message to channel ${rule.channelId} (platform: ${rule.platform || 'any'})`);
177
+ }
91
178
  await this.sendMessage(rule, message);
92
179
  }
93
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-githubsth",
3
- "version": "1.0.1-beta",
3
+ "version": "1.0.1-test10",
4
4
  "description": "Github Subscriptions Notifications, push notifications for GitHub subscriptions For koishi",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
@@ -39,10 +39,11 @@
39
39
  },
40
40
  "service": {
41
41
  "required": [
42
- "database",
43
- "github"
42
+ "database"
44
43
  ],
45
- "optional": []
44
+ "optional": [
45
+ "github"
46
+ ]
46
47
  }
47
48
  }
48
49
  }