alemonjs 2.1.76 → 2.1.78

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.
@@ -112,18 +112,18 @@ const onProcessor = (name, event, data) => {
112
112
  const masterId = value?.master_id;
113
113
  const masterKey = value?.master_key;
114
114
  if (event['UserId'] && matchIn(masterId, event['UserId'])) {
115
- event['isMaster'] = true;
115
+ event['IsMaster'] = true;
116
116
  }
117
117
  else if (event['UserKey'] && matchIn(masterKey, event['UserKey'])) {
118
- event['isMaster'] = true;
118
+ event['IsMaster'] = true;
119
119
  }
120
120
  const botId = value?.bot_id;
121
121
  const botKey = value?.bot_key;
122
122
  if (event['UserId'] && matchIn(botId, event['UserId'])) {
123
- event['isBot'] = true;
123
+ event['IsBot'] = true;
124
124
  }
125
125
  else if (event['UserKey'] && matchIn(botKey, event['UserKey'])) {
126
- event['isBot'] = true;
126
+ event['IsBot'] = true;
127
127
  }
128
128
  const Now = Date.now();
129
129
  const EVENT_INTERVAL = value?.processor?.repeated_event_time ?? processorRepeatedEventTime;
@@ -1,3 +1,4 @@
1
+ import { Result } from '../core';
1
2
  import { EventKeys, Events } from '../types';
2
3
  export type EventTraceReason = 'filtered' | 'completed' | 'consumed' | 'error';
3
4
  export declare const withEventContext: <T extends EventKeys, R>(event: Events[T], next: (...args: boolean[]) => void, runner: () => R) => R;
@@ -5,3 +6,7 @@ export declare const withProcessorTrace: <T extends EventKeys, R>(select: T, eve
5
6
  export declare const getCurrentEvent: <T extends EventKeys>() => Events[T] | undefined;
6
7
  export declare const getCurrentNext: () => ((...args: boolean[]) => void) | undefined;
7
8
  export declare const finishCurrentTrace: (reason: EventTraceReason) => void;
9
+ export declare const markEventSendAttempt: <T extends EventKeys>(event?: Events[T]) => void;
10
+ export declare const markEventSendSuccess: <T extends EventKeys>(event?: Events[T]) => void;
11
+ export declare const markEventSendFailure: <T extends EventKeys>(error: unknown, event?: Events[T]) => void;
12
+ export declare const recordEventSendResults: <T extends EventKeys>(results: Result[], event?: Events[T]) => void;
@@ -93,5 +93,43 @@ const getCurrentNext = () => {
93
93
  const finishCurrentTrace = (reason) => {
94
94
  eventStore.getStore()?.trace?.finish(reason);
95
95
  };
96
+ const getTargetEvent = (event) => {
97
+ return event ?? eventStore.getStore()?.event;
98
+ };
99
+ const markEventSendAttempt = (event) => {
100
+ const target = getTargetEvent(event);
101
+ if (!target) {
102
+ return;
103
+ }
104
+ target._has_send_attempt = true;
105
+ };
106
+ const markEventSendSuccess = (event) => {
107
+ const target = getTargetEvent(event);
108
+ if (!target) {
109
+ return;
110
+ }
111
+ target._has_send_attempt = true;
112
+ target._has_send_success = true;
113
+ target._last_send_error = null;
114
+ };
115
+ const markEventSendFailure = (error, event) => {
116
+ const target = getTargetEvent(event);
117
+ if (!target) {
118
+ return;
119
+ }
120
+ target._has_send_attempt = true;
121
+ target._last_send_error = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Unknown send error';
122
+ };
123
+ const recordEventSendResults = (results, event) => {
124
+ markEventSendAttempt(event);
125
+ if (Array.isArray(results) && results.some(item => item?.code === ResultCode.Ok)) {
126
+ markEventSendSuccess(event);
127
+ return;
128
+ }
129
+ const firstError = Array.isArray(results) ? results.find(item => item?.code !== ResultCode.Ok)?.message : null;
130
+ if (firstError) {
131
+ markEventSendFailure(firstError, event);
132
+ }
133
+ };
96
134
 
97
- export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace };
135
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, markEventSendAttempt, markEventSendFailure, markEventSendSuccess, recordEventSendResults, withEventContext, withProcessorTrace };
@@ -5,9 +5,9 @@ import { createResult, Result } from '../../core/utils';
5
5
  import { sendAction } from '../../cbp/processor/actions';
6
6
  import { sendAPI } from '../../cbp/processor/api';
7
7
  import { Format } from '../message-format';
8
- import { getCurrentEvent, getCurrentNext } from '../hook-event-context';
8
+ import { getCurrentEvent, getCurrentNext, recordEventSendResults, markEventSendAttempt, markEventSendFailure } from '../hook-event-context';
9
9
  export type { DataEnums, EventKeys, Events, User, GuildInfo, ChannelInfo, MemberInfo, RoleInfo, PaginationParams, PaginatedResult, Result };
10
- export { ResultCode, ChildrenApp, createResult, sendAction, sendAPI, Format, getCurrentEvent, getCurrentNext };
10
+ export { ResultCode, ChildrenApp, createResult, sendAction, sendAPI, Format, getCurrentEvent, getCurrentNext, recordEventSendResults, markEventSendAttempt, markEventSendFailure };
11
11
  export type Options = {
12
12
  UserId?: string;
13
13
  UserKey?: string;
@@ -5,7 +5,7 @@ export { sendAction } from '../../cbp/processor/actions.js';
5
5
  export { sendAPI } from '../../cbp/processor/api.js';
6
6
  export { Format } from '../message-format.js';
7
7
  import { getCurrentEvent } from '../hook-event-context.js';
8
- export { getCurrentNext } from '../hook-event-context.js';
8
+ export { getCurrentNext, markEventSendAttempt, markEventSendFailure, recordEventSendResults } from '../hook-event-context.js';
9
9
 
10
10
  const getEventOrThrow = (event) => {
11
11
  const currentEvent = event ?? getCurrentEvent();
@@ -3,6 +3,7 @@ import { createResult } from '../../core/utils.js';
3
3
  import { ResultCode } from '../../core/variable.js';
4
4
  import { sendAction } from '../../cbp/processor/actions.js';
5
5
  import { Format } from '../message-format.js';
6
+ import { markEventSendAttempt, recordEventSendResults, markEventSendFailure } from '../hook-event-context.js';
6
7
 
7
8
  const useMessage = (event) => {
8
9
  const valueEvent = getEventOrThrow(event);
@@ -16,17 +17,26 @@ const useMessage = (event) => {
16
17
  if (!val || val.length === 0) {
17
18
  return [createResult(ResultCode.FailParams, 'Invalid val: val must be a non-empty array', null)];
18
19
  }
19
- const result = await sendAction({
20
- action: 'message.send',
21
- payload: {
22
- event: valueEvent,
23
- params: {
24
- format: val,
25
- replyId
20
+ markEventSendAttempt(valueEvent);
21
+ try {
22
+ const result = await sendAction({
23
+ action: 'message.send',
24
+ payload: {
25
+ event: valueEvent,
26
+ params: {
27
+ format: val,
28
+ replyId
29
+ }
26
30
  }
27
- }
28
- });
29
- return Array.isArray(result) ? result : [result];
31
+ });
32
+ const results = Array.isArray(result) ? result : [result];
33
+ recordEventSendResults(results, valueEvent);
34
+ return results;
35
+ }
36
+ catch (error) {
37
+ markEventSendFailure(error, valueEvent);
38
+ throw error;
39
+ }
30
40
  };
31
41
  const lightweight = {
32
42
  send(params) {
package/lib/app/index.js CHANGED
@@ -34,7 +34,7 @@ export { useUser } from './hook-use/user.js';
34
34
  export { useObserver, useSubscribe } from './hook-use/subscribe.js';
35
35
  export { createEvent, useEvent } from './hook-use/event.js';
36
36
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './api/schedule.js';
37
- export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace } from './hook-event-context.js';
37
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, markEventSendAttempt, markEventSendFailure, markEventSendSuccess, recordEventSendResults, withEventContext, withProcessorTrace } from './hook-event-context.js';
38
38
  export { registerAppDir, scheduleCancel, scheduleCancelAll, scheduleCancelByApp, scheduleCron, scheduleInterval, scheduleList, schedulePause, scheduleResume, scheduleTimeout, unregisterAppDir } from './schedule-store.js';
39
39
  export { createEventValue, createSelects, onSelects, onState, unChildren, unState, useState } from './event-utils.js';
40
40
  export { MessageDirect, createDataFormat, format, getMessageIntent, sendToChannel, sendToUser } from './message-api.js';
@@ -4,6 +4,7 @@ import 'fs';
4
4
  import 'path';
5
5
  import 'yaml';
6
6
  import { createResult } from '../core/utils.js';
7
+ import { markEventSendAttempt, recordEventSendResults, markEventSendFailure } from './hook-event-context.js';
7
8
 
8
9
  const format = (...data) => {
9
10
  if (!data || data.length === 0) {
@@ -31,16 +32,25 @@ class MessageDirect {
31
32
  });
32
33
  throw new Error('Invalid SpaceId: SpaceId must be a string');
33
34
  }
34
- return await sendAction({
35
- action: 'message.send.channel',
36
- payload: {
37
- ChannelId: params.SpaceId,
38
- params: {
39
- format: Array.isArray(params.format) ? params.format : params.format.value,
40
- replyId: params?.replyId
35
+ markEventSendAttempt();
36
+ try {
37
+ const results = await sendAction({
38
+ action: 'message.send.channel',
39
+ payload: {
40
+ ChannelId: params.SpaceId,
41
+ params: {
42
+ format: Array.isArray(params.format) ? params.format : params.format.value,
43
+ replyId: params?.replyId
44
+ }
41
45
  }
42
- }
43
- });
46
+ });
47
+ recordEventSendResults(results, undefined);
48
+ return results;
49
+ }
50
+ catch (error) {
51
+ markEventSendFailure(error);
52
+ throw error;
53
+ }
44
54
  }
45
55
  async sendToUser(params) {
46
56
  if (!params.OpenID || typeof params.OpenID !== 'string') {
@@ -51,15 +61,24 @@ class MessageDirect {
51
61
  });
52
62
  throw new Error('Invalid OpenID: OpenID must be a string');
53
63
  }
54
- return await sendAction({
55
- action: 'message.send.user',
56
- payload: {
57
- UserId: params.OpenID,
58
- params: {
59
- format: Array.isArray(params.format) ? params.format : params.format.value
64
+ markEventSendAttempt();
65
+ try {
66
+ const results = await sendAction({
67
+ action: 'message.send.user',
68
+ payload: {
69
+ UserId: params.OpenID,
70
+ params: {
71
+ format: Array.isArray(params.format) ? params.format : params.format.value
72
+ }
60
73
  }
61
- }
62
- });
74
+ });
75
+ recordEventSendResults(results, undefined);
76
+ return results;
77
+ }
78
+ catch (error) {
79
+ markEventSendFailure(error);
80
+ throw error;
81
+ }
63
82
  }
64
83
  }
65
84
  const sendToChannel = (SpaceId, data) => {
@@ -72,6 +72,13 @@ function getImporterLabel(importer, index) {
72
72
  function formatRouteDescription(description) {
73
73
  return typeof description === 'string' && description.trim() ? description.trim() : undefined;
74
74
  }
75
+ function formatArgReference(arg, displayIndex) {
76
+ const name = typeof arg.name === 'string' ? arg.name.trim() : '';
77
+ if (name) {
78
+ return `参数「${name}」`;
79
+ }
80
+ return `第${displayIndex}个参数`;
81
+ }
75
82
  function formatArgRuleHint(arg, displayIndex) {
76
83
  const rules = arg.rules ?? [];
77
84
  const parts = [];
@@ -105,7 +112,7 @@ function formatArgRuleHint(arg, displayIndex) {
105
112
  parts.push(`最大 ${typeRule.max}`);
106
113
  }
107
114
  const suffix = arg.description ? `,${arg.description}` : '';
108
- return `参数${displayIndex} \`${arg.name}\`:${parts.join(',')}${suffix}`;
115
+ return `${formatArgReference(arg, displayIndex)}:${parts.join(',')}${suffix}`;
109
116
  }
110
117
  function buildSchemaHints(schema) {
111
118
  const args = schema?.args ?? [];
@@ -21,11 +21,15 @@ function levenshteinDistance(a, b) {
21
21
  function normalizeForCompare(text) {
22
22
  return text.replace(/^([!!/##])\s*/, '').trim();
23
23
  }
24
+ function escapeRegExp(text) {
25
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+ }
24
27
  function shouldCheckCandidate(messageText, candidate) {
25
28
  if (!messageText || !candidate) {
26
29
  return false;
27
30
  }
28
- return messageText.startsWith(candidate);
31
+ const candidatePattern = new RegExp(`^${escapeRegExp(candidate)}(?:\\s|$)`);
32
+ return candidatePattern.test(messageText);
29
33
  }
30
34
  function getAdaptiveMaxDistance(input) {
31
35
  if (input.length <= 2) {
@@ -20,6 +20,24 @@ function getMaxArgs(schema) {
20
20
  }
21
21
  return args.length > 0 ? args.length : undefined;
22
22
  }
23
+ function getMissingRequiredArg(rawArgs, schema) {
24
+ const args = schema?.args ?? [];
25
+ for (let index = 0; index < args.length; index += 1) {
26
+ const arg = args[index];
27
+ const requiredRule = getRequiredRule(arg);
28
+ if (!requiredRule) {
29
+ continue;
30
+ }
31
+ const rawValue = arg.rules?.some(rule => rule.type === 'rest') ? rawArgs.slice(index).join(' ').trim() : rawArgs[index];
32
+ if (rawValue === undefined || rawValue === '') {
33
+ return {
34
+ arg,
35
+ displayIndex: index + 1
36
+ };
37
+ }
38
+ }
39
+ return null;
40
+ }
23
41
  function parseRange(rawValue, rule) {
24
42
  const separators = rule.separators ?? ['-', '-'];
25
43
  const separator = separators.find(item => rawValue.includes(item));
@@ -34,8 +52,15 @@ function parseRange(rawValue, rule) {
34
52
  }
35
53
  return { start, end };
36
54
  }
55
+ function formatArgReference(argName, displayIndex) {
56
+ const name = String(argName ?? '').trim();
57
+ if (name) {
58
+ return `参数「${name}」`;
59
+ }
60
+ return `第${displayIndex}个参数`;
61
+ }
37
62
  function validateTypedRule(rawValue, rule, context, usage) {
38
- const messagePrefix = `参数${context.displayIndex}`;
63
+ const messagePrefix = formatArgReference(context.argName, context.displayIndex);
39
64
  const normalizedValue = rule.normalizeMap?.[rawValue] ?? rawValue;
40
65
  if (rule.pattern) {
41
66
  rule.pattern.lastIndex = 0;
@@ -226,9 +251,11 @@ function validateRouteArgsForCommand(commandPath, rawArgs, schema) {
226
251
  const maxArgs = getMaxArgs(schema);
227
252
  const usage = schema?.usage;
228
253
  if (rawArgs.length < minArgs) {
254
+ const missingRequiredArg = getMissingRequiredArg(rawArgs, schema);
229
255
  return {
230
256
  valid: false,
231
- error: schema?.messages?.tooFewArgs ?? `至少需要 ${minArgs} 个参数`,
257
+ error: schema?.messages?.tooFewArgs ??
258
+ (missingRequiredArg ? `${formatArgReference(missingRequiredArg.arg.name, missingRequiredArg.displayIndex)}是必填的` : `至少需要 ${minArgs} 个参数`),
232
259
  usage
233
260
  };
234
261
  }
@@ -252,7 +279,7 @@ function validateRouteArgsForCommand(commandPath, rawArgs, schema) {
252
279
  if (requiredRule) {
253
280
  return {
254
281
  valid: false,
255
- error: requiredRule.message ?? `参数${displayIndex}是必填的`,
282
+ error: requiredRule.message ?? `${formatArgReference(arg.name, displayIndex)}是必填的`,
256
283
  usage
257
284
  };
258
285
  }
@@ -282,7 +309,7 @@ function validateRouteArgsForCommand(commandPath, rawArgs, schema) {
282
309
  if (requiredRule) {
283
310
  return {
284
311
  valid: false,
285
- error: requiredRule.message ?? `参数${displayIndex}是必填的`,
312
+ error: requiredRule.message ?? `${formatArgReference(arg.name, displayIndex)}是必填的`,
286
313
  usage
287
314
  };
288
315
  }
package/lib/index.js CHANGED
@@ -41,7 +41,7 @@ export { useUser } from './app/hook-use/user.js';
41
41
  export { useObserver, useSubscribe } from './app/hook-use/subscribe.js';
42
42
  export { createEvent, useEvent } from './app/hook-use/event.js';
43
43
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './app/api/schedule.js';
44
- export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace } from './app/hook-event-context.js';
44
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, markEventSendAttempt, markEventSendFailure, markEventSendSuccess, recordEventSendResults, withEventContext, withProcessorTrace } from './app/hook-event-context.js';
45
45
  export { registerAppDir, scheduleCancel, scheduleCancelAll, scheduleCancelByApp, scheduleCron, scheduleInterval, scheduleList, schedulePause, scheduleResume, scheduleTimeout, unregisterAppDir } from './app/schedule-store.js';
46
46
  export { createEventValue, createSelects, onSelects, onState, unChildren, unState, useState } from './app/event-utils.js';
47
47
  export { MessageDirect, createDataFormat, format, getMessageIntent, sendToChannel, sendToUser } from './app/message-api.js';
@@ -1,3 +1,6 @@
1
1
  export type Expansion = {
2
+ _has_send_attempt?: boolean;
3
+ _has_send_success?: boolean;
4
+ _last_send_error?: string | null;
2
5
  [key: string]: any;
3
6
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alemonjs",
3
- "version": "2.1.76",
3
+ "version": "2.1.78",
4
4
  "description": "bot script",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",