@lark-apaas/nestjs-trigger 0.0.1-alpha.2 → 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Lark Technologies Pte. Ltd. and/or its affiliates
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8
+ IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
9
+ INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
10
+ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
11
+ CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
12
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
13
+ ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -4,29 +4,13 @@
4
4
 
5
5
  基于 TriggerClient 实现,提供 `@Automation`/`@BindTrigger` 装饰器、自动发现机制、REST 触发接口,以及与 trigger-server 的完整集成。
6
6
 
7
- ## 目录
8
-
9
- - [功能特性](#功能特性)
10
- - [安装](#安装)
11
- - [快速开始](#快速开始)
12
- - [核心概念](#核心概念)
13
- - [装饰器使用](#装饰器使用)
14
- - [核心组件](#核心组件)
15
- - [配置选项](#配置选项)
16
- - [TriggerClient 接口](#triggerclient-接口)
17
- - [与 trigger-server 集成](#与-trigger-server-集成)
18
- - [开发与测试](#开发与测试)
19
- - [许可证](#许可证)
20
-
21
7
  ## 功能特性
22
8
 
23
9
  - 🎯 **声明式 API** - 使用 `@Automation` 和 `@BindTrigger` 装饰器定义自动化任务
24
10
  - 🔍 **自动发现** - 应用启动时自动扫描并注册所有自动化任务
25
11
  - 📝 **强类型** - 完整的 TypeScript 类型定义与类型推断
26
- - ⚡ **执行模式** - 支持同步和异步执行
27
- - 🔒 **1:1 绑定** - 强制每个 triggerID 只能绑定一个方法,避免冲突
12
+ - 🔒 **1:1 绑定** - 强制每个 triggerName 只能绑定一个方法,避免冲突
28
13
  - 📡 **日志上报** - 集成观测系统,自动上报执行状态
29
- - ⏱️ **超时控制** - 内置超时管理机制
30
14
  - 📊 **日志跟踪** - 完整的执行生命周期日志记录
31
15
 
32
16
  ## 安装
@@ -58,12 +42,11 @@ export class AppModule {}
58
42
  使用 `@Automation()` 和 `@BindTrigger()` 装饰器定义任务:
59
43
 
60
44
  ```typescript
61
- import { Injectable } from '@nestjs/common';
45
+ // xxx.automation.ts
62
46
  import { Automation, BindTrigger } from '@lark-apaas/nestjs-trigger';
63
47
 
64
48
  @Automation()
65
- @Injectable()
66
- export class MyAutomationController {
49
+ export class MyAutomationService {
67
50
  /**
68
51
  * 简单的问候任务
69
52
  */
@@ -75,24 +58,12 @@ export class MyAutomationController {
75
58
  return `Hello, ${name}!`;
76
59
  }
77
60
 
78
- /**
79
- * 发送邮件通知任务
80
- */
81
- @BindTrigger('task-send-email', {
82
- actionName: 'SendEmail',
83
- actionDesc: 'Send notification email',
84
- })
85
- async sendEmail(to: string, subject: string, body: string) {
86
- // 邮件发送逻辑
87
- return { success: true, sentAt: new Date() };
88
- }
89
-
90
61
  /**
91
62
  * 定时任务示例 - 每周五15:00执行
92
63
  */
93
64
  @BindTrigger('cron1[0 15 * * Fri]', {
94
- actionName: 'SendWelcomeEmail',
95
- actionDesc: '每周五15:00发送欢迎邮件'
65
+ actionName: 'SendWeeklyEmail',
66
+ actionDesc: '每周五15:00发送邮件'
96
67
  })
97
68
  async sendWeeklyEmail() {
98
69
  // 每周五发送邮件逻辑
@@ -101,74 +72,30 @@ export class MyAutomationController {
101
72
  }
102
73
  ```
103
74
 
104
- ### 3. 执行任务
75
+ ### 3. 导入
105
76
 
106
- 注入 `AutomationService` 来执行任务:
77
+ 在 `XXXModule` 中导入 `MyAutomationService`:
107
78
 
108
79
  ```typescript
109
- import { Injectable } from '@nestjs/common';
110
- import { AutomationService } from '@lark-apaas/nestjs-trigger';
111
-
112
- @Injectable()
113
- export class SomeService {
114
- constructor(private readonly automation: AutomationService) {}
115
-
116
- /**
117
- * 同步执行任务并等待结果
118
- */
119
- async greet() {
120
- const result = await this.automation.executeAction('task-hello', { name: 'world' });
121
- console.log(result.result); // "Hello, world!"
122
- return result;
123
- }
124
-
125
- /**
126
- * 查询所有已注册的任务
127
- */
128
- getAllTasks() {
129
- return this.automation.getAllActions();
130
- }
80
+ import { Module } from '@nestjs/common';
81
+ import { XController } from './x.controller';
82
+ import { MyAutomationService } from './my.automation';
131
83
 
132
- /**
133
- * 获取指定任务的详细信息
134
- */
135
- getTaskInfo(taskId: string) {
136
- return this.automation.getActionInfo(taskId);
137
- }
138
- }
84
+ @Module({
85
+ controllers: [XController],
86
+ providers: [MyAutomationService],
87
+ })
88
+ export class XModule {}
139
89
  ```
140
90
 
141
- ## 核心概念
142
-
143
- ### 任务模型
144
-
145
- 本模块采用以下任务模型:
146
-
147
- - **Trigger** - 任务的唯一标识符,用于触发和执行任务
148
- - **Action** - 具体的任务执行逻辑,由方法实现
149
- - **Metadata** - 任务的元数据,包括名称、描述等信息
150
- - **Context** - 任务执行的上下文,包含参数、租户ID等信息
151
91
 
152
- ### 核心组件
153
92
 
154
- | 组件 | 类型 | 说明 |
155
- |------|------|------|
156
- | `AutomationModule` | 模块 | 主模块,提供自动化功能 |
157
- | `AutomationService` | 服务 | 提供任务执行、查询等API |
158
- | `AutomationDiscoveryService` | 服务 | 自动发现并注册任务 |
159
- | `AutomationController` | 控制器 | 提供REST触发接口 |
160
- | `TriggerClient` | 客户端 | 与trigger-server通信的客户端 |
161
- | `@Automation()` | 装饰器 | 标记自动化任务类 |
162
- | `@BindTrigger()` | 装饰器 | 绑定任务方法到triggerID |
163
-
164
- ## 装饰器使用
93
+ ## 核心概念
165
94
 
166
95
  ### @Automation()
167
96
 
168
97
  类装饰器,标记一个类为自动化任务控制器。
169
98
 
170
- **使用示例:**
171
-
172
99
  ```typescript
173
100
  @Automation()
174
101
  @Injectable()
@@ -194,7 +121,6 @@ export class EmailAutomation {
194
121
 
195
122
  ```typescript
196
123
  @Automation()
197
- @Injectable()
198
124
  export class NotificationAutomation {
199
125
  @BindTrigger('cron1[0 15 * * Fri]', {
200
126
  actionName: 'SendWelcomeEmail',
@@ -222,100 +148,7 @@ export class NotificationAutomation {
222
148
  - **自动注册**:应用启动时自动扫描并注册所有绑定的任务
223
149
  - **类型安全**:支持完整的 TypeScript 类型推断
224
150
 
225
- ## 核心组件
226
-
227
- ### AutomationService
228
-
229
- 提供任务执行和查询的核心API。
230
-
231
- **主要方法:**
232
-
233
- ```typescript
234
- @Injectable()
235
- export class MyService {
236
- constructor(private readonly automation: AutomationService) {}
237
-
238
- async executeTask() {
239
- // 1. 执行任务
240
- const result = await this.automation.executeAction(
241
- 'task-hello',
242
- { name: 'world' }
243
- );
244
-
245
- // 2. 检查任务是否存在
246
- const exists = this.automation.hasAction('task-hello');
247
-
248
- // 3. 获取任务信息
249
- const info = this.automation.getActionInfo('task-hello');
250
-
251
- // 4. 获取所有任务
252
- const allTasks = this.automation.getAllActions();
253
-
254
- // 5. 获取单个任务
255
- const task = this.automation.getAction('task-hello');
256
- }
257
- }
258
- ```
259
-
260
- **返回类型:**
261
-
262
- ```typescript
263
- interface ActionExecutionResult {
264
- trigger: string;
265
- success: boolean;
266
- result?: any;
267
- error?: string;
268
- startTime: Date;
269
- endTime: Date;
270
- duration: number;
271
- }
272
- ```
273
-
274
- ### AutomationDiscoveryService
275
-
276
- 自动发现并注册所有自动化任务。
277
-
278
- **工作原理:**
279
-
280
- 1. **模块初始化**:在 `onModuleInit()` 阶段启动扫描
281
- 2. **类扫描**:查找所有带有 `@Automation()` 装饰器的类
282
- 3. **方法扫描**:扫描类中带有 `@BindTrigger()` 装饰器的方法
283
- 4. **自动注册**:将方法注册到 TriggerClient
284
- 5. **冲突检测**:检查 triggerID 是否重复,确保 1:1 绑定
285
-
286
- **生命周期:**
287
-
288
- ```
289
- Module Init → AutomationDiscoveryService.onModuleInit()
290
- ↓
291
- 扫描所有 @Automation() 类
292
- ↓
293
- 扫描 @BindTrigger() 方法
294
- ↓
295
- 注册到 TriggerClient
296
- ↓
297
- 任务可通过 AutomationService 执行
298
- ```
299
-
300
- **高级用法:**
301
-
302
- ```typescript
303
- @Injectable()
304
- export class TaskManagementService {
305
- constructor(private readonly discovery: AutomationDiscoveryService) {}
306
-
307
- // 获取所有已注册的任务 ID
308
- getAllRegisteredTasks(): string[] {
309
- return this.discovery.getAllRegisteredTasks();
310
- }
311
-
312
- // 获取任务的元数据
313
- getTaskMetadata(taskId: string) {
314
- return this.discovery.getTaskMetadata(taskId);
315
- // 返回: { name: string, path: string, desc?: string }
316
- }
317
- }
318
- ```
151
+ ## API 参考
319
152
 
320
153
  ### AutomationController
321
154
 
@@ -327,23 +160,16 @@ export class TaskManagementService {
327
160
  POST /innerapi/automation/invoke
328
161
  ```
329
162
 
330
- **请求头:**
331
-
332
- ```
333
- trigger-start-time: 1732567890123 # 触发开始时间戳(毫秒)
334
- x-tenant-id: tenant_123 # 租户ID
335
- ```
336
-
337
163
  **请求体:**
338
164
 
339
- ```json
340
- {
341
- "appid": "app_123",
342
- "triggerID": "task-hello",
343
- "instanceID": "inst_20251125_100023",
344
- "params": {
345
- "name": "world"
346
- }
165
+ ```typescript
166
+ export interface TriggerExecutionDto {
167
+ trigger?: string;
168
+ triggerID?: string;
169
+ triggerType?: string; // cron
170
+ instanceID?: string;
171
+ startAt?: number;
172
+ parameter?: string;
347
173
  }
348
174
  ```
349
175
 
@@ -363,82 +189,6 @@ x-tenant-id: tenant_123 # 租户ID
363
189
  - `404`: triggerID 未注册
364
190
  - `500`: 内部错误
365
191
 
366
- ## 配置选项
367
-
368
- 通过 `AutomationModule.forRoot(options)` 传入配置:
369
-
370
- ```typescript
371
- AutomationModule.forRoot({
372
- timeout: 10_000, // 10秒超时
373
- logEndpoint: 'https://observability.example.com', // 观测系统端点
374
- imports: [ConfigModule], // 额外导入的模块
375
- });
376
- ```
377
-
378
- ### 配置项说明
379
-
380
- | 选项 | 类型 | 默认值 | 说明 |
381
- |------|------|--------|------|
382
- | `timeout` | `number` | `undefined` | 执行超时时间(毫秒) |
383
- | `logEndpoint` | `string` | `undefined` | 观测系统日志上报端点 |
384
- | `imports` | `Array<Type<any>\|DynamicModule\|Promise<DynamicModule>\|ForwardReference>` | `[]` | 额外导入的模块 |
385
-
386
- ### 异步配置
387
-
388
- 如果需要从 `ConfigService` 获取配置:
389
-
390
- ```typescript
391
- import { ConfigModule, ConfigService } from '@nestjs/config';
392
-
393
- @Module({
394
- imports: [
395
- ConfigModule.forRoot(),
396
- AutomationModule.forRootAsync({
397
- imports: [ConfigModule],
398
- inject: [ConfigService],
399
- useFactory: async (configService: ConfigService) => ({
400
- timeout: configService.get('AUTOMATION_TIMEOUT', 10_000),
401
- logEndpoint: configService.get('OBSERVABILITY_ENDPOINT'),
402
- }),
403
- }),
404
- ],
405
- })
406
- export class AppModule {}
407
- ```
408
-
409
- ## TriggerClient 接口
410
-
411
- `TriggerClient` 是与 trigger-server 通信的核心客户端。
412
-
413
- ### 主要功能
414
-
415
- 1. **任务注册**:注册任务到客户端
416
- 2. **任务执行**:执行指定任务
417
- 3. **日志上报**:上报执行状态和日志到观测系统
418
- 4. **超时管理**:管理任务执行超时
419
-
420
- ### 日志上报
421
-
422
- 自动上报以下信息到观测系统:
423
-
424
- - **执行状态**:RECEIVED、SUCCEEDED、FAILED
425
- - **执行信息**:任务ID、成功状态、结果、错误、耗时等
426
- - **时间信息**:触发延迟、执行时长(秒级精确)
427
-
428
- **上报数据格式:**
429
-
430
- ```typescript
431
- interface ReportData {
432
- triggerID: string;
433
- success: boolean;
434
- result?: any;
435
- error?: string;
436
- startTime: Date;
437
- endTime: Date;
438
- duration: number;
439
- }
440
- ```
441
-
442
192
  ## 与 trigger-server 集成
443
193
 
444
194
  ### 集成架构
@@ -457,25 +207,6 @@ Trigger Server → HTTP POST /innerapi/automation/invoke
457
207
  TriggerClient.report() → 观测系统
458
208
  ```
459
209
 
460
- ### 配置 logEndpoint
461
-
462
- 在 `AutomationModule.forRoot()` 中配置 `logEndpoint`:
463
-
464
- ```typescript
465
- AutomationModule.forRoot({
466
- logEndpoint: process.env.OBSERVABILITY_ENDPOINT,
467
- timeout: 30_000,
468
- });
469
- ```
470
-
471
- ### 执行流程
472
-
473
- 1. **触发**:Trigger Server 发送 HTTP 请求到 `/innerapi/automation/invoke`
474
- 2. **接收**:`AutomationController` 接收请求并验证参数
475
- 3. **执行**:`AutomationService` 调用 `TriggerClient.executeAction()`
476
- 4. **上报**:执行完成后,`TriggerClient` 自动上报日志到观测系统
477
- 5. **响应**:返回 200 状态码,表示接收成功(异步执行)
478
-
479
210
  ## 开发与测试
480
211
 
481
212
  ### 本地开发
@@ -487,90 +218,18 @@ yarn install
487
218
  # 构建
488
219
  yarn build
489
220
 
490
- # 类型检查
491
- yarn typecheck
492
-
493
- # 运行测试
494
- yarn test
495
-
496
- # 监听模式
497
- yarn test:watch
498
221
  ```
499
222
 
500
- ### 编写单元测试
223
+ ### 本地调试接口
501
224
 
502
- ```typescript
503
- import { Test, TestingModule } from '@nestjs/testing';
504
- import { AutomationModule } from '@lark-apaas/nestjs-trigger';
505
- import { MyAutomation } from './my-automation';
506
-
507
- describe('MyAutomation', () => {
508
- let automation: MyAutomation;
509
- let automationService: AutomationService;
510
-
511
- beforeEach(async () => {
512
- const module: TestingModule = await Test.createTestingModule({
513
- imports: [AutomationModule.forRoot()],
514
- providers: [MyAutomation],
515
- }).compile();
516
-
517
- automation = module.get<MyAutomation>(MyAutomation);
518
- automationService = module.get<AutomationService>(AutomationService);
519
- });
520
-
521
- it('should execute task', async () => {
522
- const result = await automationService.executeAction('task-hello', { name: 'test' });
523
- expect(result.success).toBe(true);
524
- expect(result.result).toBe('Hello, test!');
525
- });
526
- });
527
- ```
528
-
529
- ### 集成测试
530
-
531
- ```typescript
532
- import * as request from 'supertest';
533
- import { Test } from '@nestjs/testing';
534
- import { INestApplication } from '@nestjs/common';
535
- import { AutomationModule } from '@lark-apaas/nestjs-trigger';
225
+ ```bash
226
+ # 获取调试列表
227
+ curl -X GET /dev/logs/trace/trigger/list?trigger=xx&triggerID=xx
536
228
 
537
- describe('AutomationController (e2e)', () => {
538
- let app: INestApplication;
539
-
540
- beforeAll(async () => {
541
- const moduleRef = await Test.createTestingModule({
542
- imports: [AutomationModule.forRoot()],
543
- }).compile();
544
-
545
- app = moduleRef.createNestApplication();
546
- await app.init();
547
- });
548
-
549
- it('/innerapi/automation/invoke (POST)', () => {
550
- return request(app.getHttpServer())
551
- .post('/innerapi/automation/invoke')
552
- .set('trigger-start-time', Date.now().toString())
553
- .set('x-tenant-id', 'test-tenant')
554
- .send({
555
- appid: 'test-app',
556
- triggerID: 'task-hello',
557
- instanceID: 'test-instance',
558
- params: { name: 'world' },
559
- })
560
- .expect(200);
561
- });
562
-
563
- afterAll(async () => {
564
- await app.close();
565
- });
566
- });
229
+ # 获取调试详情
230
+ curl -X GET /dev/logs/trace/trigger/:instanceID
567
231
  ```
568
232
 
569
233
  ## 许可证
570
234
 
571
- MIT
572
-
573
- ## 相关链接
574
-
575
- - [NestJS 文档](https://docs.nestjs.com/)
576
- - [示例项目](../../examples/node-demo)
235
+ MIT
@@ -119,7 +119,7 @@ var TriggerClient = class {
119
119
  * @param context - 执行上下文
120
120
  * @returns 执行报告数据
121
121
  */
122
- async executeAction(trigger, instanceID, context) {
122
+ executeAction(trigger, instanceID, context) {
123
123
  let input;
124
124
  try {
125
125
  input = JSON.parse(context.content || "{}");
@@ -301,7 +301,7 @@ var TriggerClient = class {
301
301
  ...signature
302
302
  });
303
303
  } else {
304
- this._logger.info(msg, {
304
+ this._logger.log(msg, {
305
305
  ...extra,
306
306
  ...signature
307
307
  });
@@ -322,14 +322,12 @@ var TriggerClient = class {
322
322
  input = void 0;
323
323
  }
324
324
  try {
325
- Object.assign(context, {
325
+ const actionStartAt = Date.now();
326
+ const output = await Promise.resolve(handler({
326
327
  attributes: {
327
328
  ...context.attributes,
328
- startAt: Date.now()
329
- }
330
- });
331
- const output = await Promise.resolve(handler({
332
- ...context,
329
+ startAt: actionStartAt
330
+ },
333
331
  content: {
334
332
  input
335
333
  }
@@ -338,6 +336,7 @@ var TriggerClient = class {
338
336
  ...context,
339
337
  attributes: {
340
338
  ...context.attributes,
339
+ startAt: actionStartAt,
341
340
  phase: ENUM_PHASE.Action,
342
341
  status: ENUM_STATUS.SUCCEEDED,
343
342
  endAt: Date.now()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/index.ts","../../src/client/types.ts","../../src/client/utils.ts","../../src/client/trigger-client.ts"],"sourcesContent":["export * from './types';\nexport * from './trigger-client';\nexport * from './utils';\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Action handler function type\n */\nexport interface ActionHandler {\n (...args: any[]): any | Promise<any>;\n}\n\n/**\n * Action definition\n */\nexport interface Action extends ActionMetadata {\n handler: ActionHandler;\n}\n\nexport enum ENUM_STATUS {\n SUCCEEDED = 'succeed',\n FAILED = 'failed',\n}\n\nexport enum ENUM_PHASE {\n Trigger = 'trigger',\n Action = 'action',\n}\n\nexport enum ENUM_ENV {\n DEV = 'development',\n PROD = 'production',\n}\n\nexport interface ActionContext {\n attributes: {\n trigger: string;\n triggerID?: string;\n triggerType?: string;\n instanceID: string;\n status?: ENUM_STATUS;\n phase?: ENUM_PHASE;\n startAt?: number;\n endAt?: number;\n };\n content?: string; // '{ input: {}, output: {} }'\n}\n\n\nexport type TLogContent = string; // stringified { input, output }\nexport interface ILogAttributes {\n trigger?: string;\n trigger_id?: string;\n trigger_type?: string;\n instance_id?: string;\n status?: ENUM_STATUS;\n phase?: ENUM_PHASE;\n start_at?: number;\n end_at?: number;\n}\n\n// const logger = { level: 'INFO', attributes: {}, ...attributes };\n\n// logger.info(JSON.stringify({ input, output }), {\n// ...attributes,\n// })\n\n/**\n * Action metadata (without handler)\n */\nexport interface ActionMetadata {\n name?: string;\n path?: string;\n desc?: string;\n}\n\n/**\n * Logger interface for client SDK\n */\nexport interface Logger {\n debug(message: string, extra?: any): void;\n info(message: string, extra?: any): void;\n warn(message: string, extra?: any): void;\n error(message: string, extra?: any): void;\n}\n\n/**\n * TriggerClient configuration options\n */\nexport interface TriggerClientOptions {\n /**\n * Timeout for action execution (ms)\n */\n timeout?: number;\n imports?: any[];\n}\n\nexport enum ENUM_ERROR {\n NOT_EXIST = 'NOT_EXIST',\n TIMEOUT = 'TIMEOUT',\n PARAM_INVALID = 'PARAM_INVALID',\n TRY_CATCH = 'TRY_CATCH',\n}","import { ActionContext, ILogAttributes, TLogContent } from './types';\n\nexport const convertActionContextToReportData = (actionCtx: ActionContext): [TLogContent, ILogAttributes] => {\n const { attributes, content } = actionCtx;\n return [\n content || '',\n {\n trigger: attributes?.trigger,\n trigger_id: attributes?.triggerID,\n trigger_type: attributes?.triggerType,\n instance_id: attributes?.instanceID,\n status: attributes?.status,\n phase: attributes?.phase,\n start_at: attributes?.startAt,\n end_at: attributes?.endAt,\n },\n ];\n};","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n ENUM_STATUS,\n ENUM_PHASE,\n type Action,\n type ActionHandler,\n type ActionMetadata,\n type Logger,\n ENUM_ERROR,\n ActionContext,\n TLogContent,\n ILogAttributes,\n} from './types';\nimport { convertActionContextToReportData } from './utils';\n\nconst INTERNAL = 'AUTOMATION_INTERNAL';\n\n/**\n * TriggerClient\n *\n * 自动化触发器管理客户端核心类\n *\n * 负责管理触发器注册、执行和生命周期事件\n * 提供中间件支持和与 trigger-server 的回调集成\n */\nexport class TriggerClient {\n private _triggerActionMap: Map<string, Action> = new Map();\n private _logger: Logger;\n\n /**\n * 创建 TriggerClient 实例\n *\n * @param logger - 日志记录器\n */\n public constructor(logger: Logger) {\n this._logger = logger;\n }\n\n /**\n * 为指定的 trigger 注册动作\n *\n * @param trigger - 触发器标识\n * @param action - 动作配置\n */\n public registerAction(trigger: string, action: Action): void {\n this._logger.debug(\n `[${INTERNAL}] Registering action for trigger: ${trigger}`,\n {\n actionName: action.name,\n path: action.path,\n desc: action.desc,\n }\n );\n\n if (this._triggerActionMap.has(trigger)) {\n this._logger.debug(\n `[${INTERNAL}] Trigger ${trigger} already registered, overwriting`\n );\n }\n\n const wrappedHandler = this._wrapHandler(action.handler);\n const wrappedAction: Action = {\n ...action,\n handler: wrappedHandler,\n };\n\n this._triggerActionMap.set(trigger, wrappedAction);\n this._logger.debug(\n `[${INTERNAL}] Action registered successfully for trigger: ${trigger}`\n );\n }\n\n /**\n * 执行指定的 trigger 动作\n *\n * @param trigger - 触发器标识\n * @param instanceID - 实例ID\n * @param context - 执行上下文\n * @returns 执行报告数据\n */\n public async executeAction(\n trigger: string,\n instanceID: string,\n context: ActionContext,\n ): Promise<ActionContext> {\n let input;\n\n // 解析输入参数\n try {\n input = JSON.parse(context.content || '{}');\n } catch (error) {\n input = undefined;\n const content = JSON.stringify({\n input,\n output: {\n error: ENUM_ERROR.PARAM_INVALID,\n message: `参数解析失败(trigger: ${trigger}, instanceID: ${instanceID})`,\n },\n });\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now()\n },\n content,\n };\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n\n try {\n // 获取动作处理器\n const action = this.getAction(trigger);\n\n // 如果动作不存在,返回错误\n if (!action) {\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now()\n },\n content: JSON.stringify({\n input,\n output: {\n error: ENUM_ERROR.NOT_EXIST,\n message: `执行动作不存在: ${trigger}`,\n },\n })\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n\n // 直接执行 _wrapHandler(handler),不会等待执行结束\n action.handler(context);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.SUCCEEDED,\n endAt: Date.now(),\n },\n content: JSON.stringify({ input, output: null }),\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output: { error: ENUM_ERROR.TRY_CATCH, message: errorMessage },\n }),\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n }\n }\n\n /**\n * 根据 trigger 获取对应的动作\n *\n * @param trigger - 触发器标识\n * @returns 动作实例,如果不存在返回 undefined\n */\n public getAction(trigger: string): Action | undefined {\n const action = this._triggerActionMap.get(trigger);\n\n if (!action) {\n this._logger.debug(`No action found for trigger: ${trigger}`);\n return undefined;\n }\n\n this._logger.debug(`Retrieved action for trigger: ${trigger}`, {\n actionName: action.name,\n path: action.path,\n });\n\n return action;\n }\n\n /**\n * 获取所有已注册的动作\n *\n * @returns 动作映射表\n */\n public getAllActions(): Map<string, Action> {\n return this._triggerActionMap;\n }\n\n /**\n * 根据 trigger 获取动作的元数据\n *\n * @param trigger - 触发器标识\n * @returns 动作元数据,如果不存在返回 undefined\n */\n public getActionMetadata(trigger: string): ActionMetadata | undefined {\n const action = this.getAction(trigger);\n\n if (!action) {\n return undefined;\n }\n\n return {\n name: action.name,\n path: action.path,\n desc: action.desc,\n };\n }\n\n /**\n * 获取所有已注册的 trigger 标识\n *\n * @returns trigger 标识数组\n */\n public getAllTriggers(): string[] {\n const triggers = Array.from(this._triggerActionMap.keys());\n this._logger.debug(`Retrieved all triggers`, {\n count: triggers.length,\n });\n return triggers;\n }\n\n /**\n * 根据 trigger 移除对应的动作\n *\n * @param trigger - 触发器标识\n * @returns 如果成功移除返回 true,如果不存在返回 false\n */\n public removeAction(trigger: string): boolean {\n const existed = this._triggerActionMap.has(trigger);\n\n if (existed) {\n this._triggerActionMap.delete(trigger);\n this._logger.debug(`Removed action for trigger: ${trigger}`);\n } else {\n this._logger.debug(\n `Attempted to remove non-existent trigger: ${trigger}`\n );\n }\n\n return existed;\n }\n\n /**\n * 清空所有已注册的动作\n */\n public clearAllActions(): void {\n const count = this._triggerActionMap.size;\n this._triggerActionMap.clear();\n this._logger.debug(`Cleared all actions`, { count });\n }\n\n /**\n * 上报执行数据,用于日志记录和调试\n */\n public report(msg: TLogContent, extra: ILogAttributes): void {\n const { status } = extra;\n\n // for 观测\n const signature = { module: 'trigger', sourceType: 'platform' };\n // msg\n if (status === ENUM_STATUS.FAILED) {\n this._logger.error(msg, { ...extra, ...signature });\n } else {\n this._logger.info(msg, { ...extra, ...signature });\n }\n }\n\n /**\n * 包装处理器,添加日志记录和计时功能\n *\n * @param handler - 原始处理器\n * @returns 包装后的处理器\n */\n private _wrapHandler(handler: Action['handler']): ActionHandler {\n return async (context: ActionContext): Promise<ActionContext> => {\n let input;\n\n // 解析输入参数\n try {\n input = JSON.parse(context.content || '{}').input;\n } catch (error) {\n input = undefined;\n }\n\n try {\n // 执行处理器(暂时不支持超时)\n // if (this._options.timeout) {\n // result = await this._withTimeout(\n // handler(context),\n // this._options.timeout\n // );\n // } else {\n Object.assign(context, {\n attributes: {\n ...context.attributes,\n startAt: Date.now(),\n }\n })\n const output = await Promise.resolve(\n handler({\n ...context,\n content: {\n input,\n },\n })\n );\n // }\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Action,\n status: ENUM_STATUS.SUCCEEDED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output,\n }),\n };\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Action,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output: { error: ENUM_ERROR.TRY_CATCH, message: errorMessage },\n }),\n };\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n };\n }\n\n /**\n * @desc 暂时不支持超时\n * Execute action with timeout\n */\n // private async _withTimeout<T>(\n // promise: Promise<T>,\n // timeout: number\n // ): Promise<T> {\n // return Promise.race([\n // promise,\n // new Promise<T>((_, reject) =>\n // setTimeout(\n // () => reject(new Error(`Action timeout after ${timeout}ms`)),\n // timeout\n // )\n // ),\n // ]);\n // }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACgBO,IAAKA,cAAAA,0BAAAA,cAAAA;;;SAAAA;;AAKL,IAAKC,aAAAA,0BAAAA,aAAAA;;;SAAAA;;AAKL,IAAKC,WAAAA,0BAAAA,WAAAA;;;SAAAA;;AAoEL,IAAKC,aAAAA,0BAAAA,aAAAA;;;;;SAAAA;;;;AC5FL,IAAMC,mCAAmC,wBAACC,cAAAA;AAC/C,QAAM,EAAEC,YAAYC,QAAO,IAAKF;AAChC,SAAO;IACLE,WAAW;IACX;MACEC,SAASF,YAAYE;MACrBC,YAAYH,YAAYI;MACxBC,cAAcL,YAAYM;MAC1BC,aAAaP,YAAYQ;MACzBC,QAAQT,YAAYS;MACpBC,OAAOV,YAAYU;MACnBC,UAAUX,YAAYY;MACtBC,QAAQb,YAAYc;IACtB;;AAEJ,GAfgD;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oBF;","names":["ENUM_STATUS","ENUM_PHASE","ENUM_ENV","ENUM_ERROR","convertActionContextToReportData","actionCtx","attributes","content","trigger","trigger_id","triggerID","trigger_type","triggerType","instance_id","instanceID","status","phase","start_at","startAt","end_at","endAt","INTERNAL","TriggerClient","_triggerActionMap","Map","_logger","logger","registerAction","trigger","action","debug","actionName","name","path","desc","has","wrappedHandler","_wrapHandler","handler","wrappedAction","set","executeAction","instanceID","context","input","JSON","parse","content","error","undefined","stringify","output","ENUM_ERROR","PARAM_INVALID","message","actionCtx","attributes","phase","ENUM_PHASE","Trigger","status","ENUM_STATUS","FAILED","endAt","Date","now","report","convertActionContextToReportData","getAction","NOT_EXIST","SUCCEEDED","errorMessage","Error","String","TRY_CATCH","get","getAllActions","getActionMetadata","getAllTriggers","triggers","Array","from","keys","count","length","removeAction","existed","delete","clearAllActions","size","clear","msg","extra","signature","module","sourceType","info","Object","assign","startAt","Promise","resolve","Action"]}
1
+ {"version":3,"sources":["../../src/client/index.ts","../../src/client/types.ts","../../src/client/utils.ts","../../src/client/trigger-client.ts"],"sourcesContent":["export * from './types';\nexport * from './trigger-client';\nexport * from './utils';\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Action handler function type\n */\nexport interface ActionHandler {\n (...args: any[]): any | Promise<any>;\n}\n\n/**\n * Action definition\n */\nexport interface Action extends ActionMetadata {\n handler: ActionHandler;\n}\n\nexport enum ENUM_STATUS {\n SUCCEEDED = 'succeed',\n FAILED = 'failed',\n}\n\nexport enum ENUM_PHASE {\n Trigger = 'trigger',\n Action = 'action',\n}\n\nexport enum ENUM_ENV {\n DEV = 'development',\n PROD = 'production',\n}\n\nexport interface ActionContext {\n attributes: {\n trigger: string;\n triggerID?: string;\n triggerType?: string;\n instanceID: string;\n status?: ENUM_STATUS;\n phase?: ENUM_PHASE;\n startAt?: number;\n endAt?: number;\n };\n content?: string; // '{ input: {}, output: {} }'\n}\n\n\nexport type TLogContent = string; // stringified { input, output }\nexport interface ILogAttributes {\n trigger?: string;\n trigger_id?: string;\n trigger_type?: string;\n instance_id?: string;\n status?: ENUM_STATUS;\n phase?: ENUM_PHASE;\n start_at?: number;\n end_at?: number;\n}\n\n/**\n * Action metadata (without handler)\n */\nexport interface ActionMetadata {\n name?: string;\n path?: string;\n desc?: string;\n}\n\n/**\n * Logger interface for client SDK\n */\nexport interface Logger {\n debug(message: string, extra?: any): void;\n info(message: string, extra?: any): void;\n warn(message: string, extra?: any): void;\n error(message: string, extra?: any): void;\n}\n\n/**\n * TriggerClient configuration options\n */\nexport interface TriggerClientOptions {\n /**\n * Timeout for action execution (ms)\n */\n timeout?: number;\n imports?: any[];\n}\n\nexport enum ENUM_ERROR {\n NOT_EXIST = 'NOT_EXIST',\n TIMEOUT = 'TIMEOUT',\n PARAM_INVALID = 'PARAM_INVALID',\n TRY_CATCH = 'TRY_CATCH',\n}","import { ActionContext, ILogAttributes, TLogContent } from './types';\n\nexport const convertActionContextToReportData = (actionCtx: ActionContext): [TLogContent, ILogAttributes] => {\n const { attributes, content } = actionCtx;\n return [\n content || '',\n {\n trigger: attributes?.trigger,\n trigger_id: attributes?.triggerID,\n trigger_type: attributes?.triggerType,\n instance_id: attributes?.instanceID,\n status: attributes?.status,\n phase: attributes?.phase,\n start_at: attributes?.startAt,\n end_at: attributes?.endAt,\n },\n ];\n};","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Logger } from '@nestjs/common';\nimport {\n ENUM_STATUS,\n ENUM_PHASE,\n type Action,\n type ActionHandler,\n type ActionMetadata,\n ENUM_ERROR,\n ActionContext,\n TLogContent,\n ILogAttributes,\n} from './types';\nimport { convertActionContextToReportData } from './utils';\n\nconst INTERNAL = 'AUTOMATION_INTERNAL';\n\n/**\n * TriggerClient\n *\n * 自动化触发器管理客户端核心类\n *\n * 负责管理触发器注册、执行和生命周期事件\n * 提供中间件支持和与 trigger-server 的回调集成\n */\nexport class TriggerClient {\n private _triggerActionMap: Map<string, Action> = new Map();\n private _logger: Logger;\n\n /**\n * 创建 TriggerClient 实例\n *\n * @param logger - 日志记录器\n */\n public constructor(logger: Logger) {\n this._logger = logger;\n }\n\n /**\n * 为指定的 trigger 注册动作\n *\n * @param trigger - 触发器标识\n * @param action - 动作配置\n */\n public registerAction(trigger: string, action: Action): void {\n this._logger.debug(\n `[${INTERNAL}] Registering action for trigger: ${trigger}`,\n {\n actionName: action.name,\n path: action.path,\n desc: action.desc,\n }\n );\n\n if (this._triggerActionMap.has(trigger)) {\n this._logger.debug(\n `[${INTERNAL}] Trigger ${trigger} already registered, overwriting`\n );\n }\n\n const wrappedHandler = this._wrapHandler(action.handler);\n const wrappedAction: Action = {\n ...action,\n handler: wrappedHandler,\n };\n\n this._triggerActionMap.set(trigger, wrappedAction);\n this._logger.debug(\n `[${INTERNAL}] Action registered successfully for trigger: ${trigger}`\n );\n }\n\n /**\n * 执行指定的 trigger 动作\n *\n * @param trigger - 触发器标识\n * @param instanceID - 实例ID\n * @param context - 执行上下文\n * @returns 执行报告数据\n */\n public executeAction(\n trigger: string,\n instanceID: string,\n context: ActionContext,\n ): ActionContext {\n let input;\n\n // 解析输入参数\n try {\n input = JSON.parse(context.content || '{}');\n } catch (error) {\n input = undefined;\n const content = JSON.stringify({\n input,\n output: {\n error: ENUM_ERROR.PARAM_INVALID,\n message: `参数解析失败(trigger: ${trigger}, instanceID: ${instanceID})`,\n },\n });\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now()\n },\n content,\n };\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n\n try {\n // 获取动作处理器\n const action = this.getAction(trigger);\n\n // 如果动作不存在,返回错误\n if (!action) {\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now()\n },\n content: JSON.stringify({\n input,\n output: {\n error: ENUM_ERROR.NOT_EXIST,\n message: `执行动作不存在: ${trigger}`,\n },\n })\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n\n // 直接执行 _wrapHandler(handler),不会等待执行结束\n action.handler(context);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.SUCCEEDED,\n endAt: Date.now(),\n },\n content: JSON.stringify({ input, output: null }),\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Trigger,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output: { error: ENUM_ERROR.TRY_CATCH, message: errorMessage },\n }),\n };\n // 上报 trigger 结果{成功/失败}\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n }\n }\n\n /**\n * 根据 trigger 获取对应的动作\n *\n * @param trigger - 触发器标识\n * @returns 动作实例,如果不存在返回 undefined\n */\n public getAction(trigger: string): Action | undefined {\n const action = this._triggerActionMap.get(trigger);\n\n if (!action) {\n this._logger.debug(`No action found for trigger: ${trigger}`);\n return undefined;\n }\n\n this._logger.debug(`Retrieved action for trigger: ${trigger}`, {\n actionName: action.name,\n path: action.path,\n });\n\n return action;\n }\n\n /**\n * 获取所有已注册的动作\n *\n * @returns 动作映射表\n */\n public getAllActions(): Map<string, Action> {\n return this._triggerActionMap;\n }\n\n /**\n * 根据 trigger 获取动作的元数据\n *\n * @param trigger - 触发器标识\n * @returns 动作元数据,如果不存在返回 undefined\n */\n public getActionMetadata(trigger: string): ActionMetadata | undefined {\n const action = this.getAction(trigger);\n\n if (!action) {\n return undefined;\n }\n\n return {\n name: action.name,\n path: action.path,\n desc: action.desc,\n };\n }\n\n /**\n * 获取所有已注册的 trigger 标识\n *\n * @returns trigger 标识数组\n */\n public getAllTriggers(): string[] {\n const triggers = Array.from(this._triggerActionMap.keys());\n this._logger.debug(`Retrieved all triggers`, {\n count: triggers.length,\n });\n return triggers;\n }\n\n /**\n * 根据 trigger 移除对应的动作\n *\n * @param trigger - 触发器标识\n * @returns 如果成功移除返回 true,如果不存在返回 false\n */\n public removeAction(trigger: string): boolean {\n const existed = this._triggerActionMap.has(trigger);\n\n if (existed) {\n this._triggerActionMap.delete(trigger);\n this._logger.debug(`Removed action for trigger: ${trigger}`);\n } else {\n this._logger.debug(\n `Attempted to remove non-existent trigger: ${trigger}`\n );\n }\n\n return existed;\n }\n\n /**\n * 清空所有已注册的动作\n */\n public clearAllActions(): void {\n const count = this._triggerActionMap.size;\n this._triggerActionMap.clear();\n this._logger.debug(`Cleared all actions`, { count });\n }\n\n /**\n * 上报执行数据,用于日志记录和调试\n */\n public report(msg: TLogContent, extra: ILogAttributes): void {\n const { status } = extra;\n\n // for 观测\n const signature = { module: 'trigger', sourceType: 'platform' };\n // msg\n if (status === ENUM_STATUS.FAILED) {\n this._logger.error(msg, { ...extra, ...signature });\n } else {\n this._logger.log(msg, { ...extra, ...signature });\n }\n }\n\n /**\n * 包装处理器,添加日志记录和计时功能\n *\n * @param handler - 原始处理器\n * @returns 包装后的处理器\n */\n private _wrapHandler(handler: Action['handler']): ActionHandler {\n return async (context: ActionContext): Promise<ActionContext> => {\n let input;\n\n // 解析输入参数\n try {\n input = JSON.parse(context.content || '{}').input;\n } catch (error) {\n input = undefined;\n }\n\n try {\n const actionStartAt = Date.now();\n const output = await Promise.resolve(\n handler({\n attributes: {\n ...context.attributes,\n startAt: actionStartAt\n },\n content: {\n input,\n },\n })\n );\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n startAt: actionStartAt,\n phase: ENUM_PHASE.Action,\n status: ENUM_STATUS.SUCCEEDED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output,\n }),\n };\n this.report(...convertActionContextToReportData(actionCtx));\n\n return actionCtx;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n const actionCtx: ActionContext = {\n ...context,\n attributes: {\n ...context.attributes,\n phase: ENUM_PHASE.Action,\n status: ENUM_STATUS.FAILED,\n endAt: Date.now(),\n },\n content: JSON.stringify({\n input,\n output: { error: ENUM_ERROR.TRY_CATCH, message: errorMessage },\n }),\n };\n this.report(...convertActionContextToReportData(actionCtx));\n return actionCtx;\n }\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACgBO,IAAKA,cAAAA,0BAAAA,cAAAA;;;SAAAA;;AAKL,IAAKC,aAAAA,0BAAAA,aAAAA;;;SAAAA;;AAKL,IAAKC,WAAAA,0BAAAA,WAAAA;;;SAAAA;;AA8DL,IAAKC,aAAAA,0BAAAA,aAAAA;;;;;SAAAA;;;;ACtFL,IAAMC,mCAAmC,wBAACC,cAAAA;AAC/C,QAAM,EAAEC,YAAYC,QAAO,IAAKF;AAChC,SAAO;IACLE,WAAW;IACX;MACEC,SAASF,YAAYE;MACrBC,YAAYH,YAAYI;MACxBC,cAAcL,YAAYM;MAC1BC,aAAaP,YAAYQ;MACzBC,QAAQT,YAAYS;MACpBC,OAAOV,YAAYU;MACnBC,UAAUX,YAAYY;MACtBC,QAAQb,YAAYc;IACtB;;AAEJ,GAfgD;;;ACahD,IAAMC,WAAW;AAUV,IAAMC,gBAAN,MAAMA;EAzBb,OAyBaA;;;EACHC,oBAAyC,oBAAIC,IAAAA;EAC7CC;;;;;;EAOR,YAAmBC,QAAgB;AACjC,SAAKD,UAAUC;EACjB;;;;;;;EAQOC,eAAeC,SAAiBC,QAAsB;AAC3D,SAAKJ,QAAQK,MACX,IAAIT,QAAAA,qCAA6CO,OAAAA,IACjD;MACEG,YAAYF,OAAOG;MACnBC,MAAMJ,OAAOI;MACbC,MAAML,OAAOK;IACf,CAAA;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D,gBAAgBjC,KAAKC,IAAG;AAC9B,cAAMd,SAAS,MAAM+C,QAAQC,QAC3B7D,QAAQ;UACNkB,YAAY;YACV,GAAGb,QAAQa;YACX4C,SAASH;UACX;UACAlD,SAAS;YACPH;UACF;QACF,CAAA,CAAA;AAGF,cAAMW,YAA2B;UAC/B,GAAGZ;UACHa,YAAY;YACV,GAAGb,QAAQa;YACX4C,SAASH;YACTxC,OAAOC,WAAW2C;YAClBzC,QAAQC,YAAYS;YACpBP,OAAOC,KAAKC,IAAG;UACjB;UACAlB,SAASF,KAAKK,UAAU;YACtBN;YACAO;UACF,CAAA;QACF;AACA,aAAKe,OAAM,GAAIC,iCAAiCZ,SAAAA,CAAAA;AAEhD,eAAOA;MACT,SAASP,OAAO;AACd,cAAMuB,eACJvB,iBAAiBwB,QAAQxB,MAAMM,UAAUmB,OAAOzB,KAAAA;AAElD,cAAMO,YAA2B;UAC/B,GAAGZ;UACHa,YAAY;YACV,GAAGb,QAAQa;YACXC,OAAOC,WAAW2C;YAClBzC,QAAQC,YAAYC;YACpBC,OAAOC,KAAKC,IAAG;UACjB;UACAlB,SAASF,KAAKK,UAAU;YACtBN;YACAO,QAAQ;cAAEH,OAAOI,WAAWsB;cAAWpB,SAASiB;YAAa;UAC/D,CAAA;QACF;AACA,aAAKL,OAAM,GAAIC,iCAAiCZ,SAAAA,CAAAA;AAChD,eAAOA;MACT;IACF;EACF;AACF;","names":["ENUM_STATUS","ENUM_PHASE","ENUM_ENV","ENUM_ERROR","convertActionContextToReportData","actionCtx","attributes","content","trigger","trigger_id","triggerID","trigger_type","triggerType","instance_id","instanceID","status","phase","start_at","startAt","end_at","endAt","INTERNAL","TriggerClient","_triggerActionMap","Map","_logger","logger","registerAction","trigger","action","debug","actionName","name","path","desc","has","wrappedHandler","_wrapHandler","handler","wrappedAction","set","executeAction","instanceID","context","input","JSON","parse","content","error","undefined","stringify","output","ENUM_ERROR","PARAM_INVALID","message","actionCtx","attributes","phase","ENUM_PHASE","Trigger","status","ENUM_STATUS","FAILED","endAt","Date","now","report","convertActionContextToReportData","getAction","NOT_EXIST","SUCCEEDED","errorMessage","Error","String","TRY_CATCH","get","getAllActions","getActionMetadata","getAllTriggers","triggers","Array","from","keys","count","length","removeAction","existed","delete","clearAllActions","size","clear","msg","extra","signature","module","sourceType","log","actionStartAt","Promise","resolve","startAt","Action"]}
@@ -1,3 +1,5 @@
1
+ import { Logger as Logger$1 } from '@nestjs/common';
2
+
1
3
  /**
2
4
  * Action handler function type
3
5
  */
@@ -96,7 +98,7 @@ declare class TriggerClient {
96
98
  *
97
99
  * @param logger - 日志记录器
98
100
  */
99
- constructor(logger: Logger);
101
+ constructor(logger: Logger$1);
100
102
  /**
101
103
  * 为指定的 trigger 注册动作
102
104
  *
@@ -112,7 +114,7 @@ declare class TriggerClient {
112
114
  * @param context - 执行上下文
113
115
  * @returns 执行报告数据
114
116
  */
115
- executeAction(trigger: string, instanceID: string, context: ActionContext): Promise<ActionContext>;
117
+ executeAction(trigger: string, instanceID: string, context: ActionContext): ActionContext;
116
118
  /**
117
119
  * 根据 trigger 获取对应的动作
118
120
  *