@cloudwerk/trigger 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.
@@ -0,0 +1,966 @@
1
+ import { T as TriggerSource, a as TriggerConfig, b as TriggerDefinition, W as WebhookVerifier, c as TriggerContext } from './types-w3ZeMXZ9.js';
2
+ export { A as Awaitable, B as BatchConfig, D as D1Event, d as D1EventType, e as D1TriggerSource, E as EmailEvent, f as EmailTriggerSource, I as InferEventType, Q as QueueBatchEvent, g as QueueMessage, h as QueueTriggerSource, R as R2Event, i as R2EventType, j as R2TriggerSource, k as RetryConfig, S as ScannedTrigger, l as ScheduledEvent, m as ScheduledTriggerSource, n as TailEvent, o as TailLogEntry, p as TailTriggerSource, q as TriggerEntry, r as TriggerErrorCode, s as TriggerErrorHandler, t as TriggerHandler, u as TriggerManifest, v as TriggerScanResult, w as TriggerValidationError, x as TriggerValidationWarning, y as TriggerWarningCode, z as WebhookEvent, C as WebhookTriggerSource, F as WebhookVerificationResult } from './types-w3ZeMXZ9.js';
3
+
4
+ /**
5
+ * @cloudwerk/trigger - Error Classes
6
+ *
7
+ * Custom error classes for trigger processing.
8
+ */
9
+ /**
10
+ * Base error class for trigger-related errors.
11
+ */
12
+ declare class TriggerError extends Error {
13
+ /** Error code for programmatic handling */
14
+ readonly code: string;
15
+ constructor(code: string, message: string, options?: ErrorOptions);
16
+ }
17
+ /**
18
+ * Error thrown when trigger configuration is invalid.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * throw new TriggerConfigError('timeout must be a positive number', 'timeout')
23
+ * ```
24
+ */
25
+ declare class TriggerConfigError extends TriggerError {
26
+ /** The configuration field that is invalid */
27
+ readonly field?: string;
28
+ constructor(message: string, field?: string);
29
+ }
30
+ /**
31
+ * Error thrown when no handler function is defined.
32
+ */
33
+ declare class TriggerNoHandlerError extends TriggerError {
34
+ constructor(triggerName: string);
35
+ }
36
+ /**
37
+ * Error thrown when the trigger source configuration is invalid.
38
+ */
39
+ declare class TriggerInvalidSourceError extends TriggerError {
40
+ /** The source type that is invalid */
41
+ readonly sourceType?: string;
42
+ constructor(message: string, sourceType?: string);
43
+ }
44
+ /**
45
+ * Error thrown when a cron expression is invalid.
46
+ */
47
+ declare class TriggerInvalidCronError extends TriggerError {
48
+ /** The invalid cron expression */
49
+ readonly cron: string;
50
+ constructor(cron: string, reason?: string);
51
+ }
52
+ /**
53
+ * Error thrown when a webhook path is invalid.
54
+ */
55
+ declare class TriggerInvalidWebhookPathError extends TriggerError {
56
+ /** The invalid path */
57
+ readonly path: string;
58
+ constructor(path: string, reason?: string);
59
+ }
60
+ /**
61
+ * Error thrown when accessing a trigger outside of execution context.
62
+ */
63
+ declare class TriggerContextError extends TriggerError {
64
+ constructor();
65
+ }
66
+ /**
67
+ * Error thrown when a trigger binding is not found.
68
+ */
69
+ declare class TriggerNotFoundError extends TriggerError {
70
+ /** The trigger name that was not found */
71
+ readonly triggerName: string;
72
+ /** Available trigger names */
73
+ readonly availableTriggers: string[];
74
+ constructor(triggerName: string, availableTriggers: string[]);
75
+ }
76
+ /**
77
+ * Error thrown when trigger processing fails.
78
+ */
79
+ declare class TriggerProcessingError extends TriggerError {
80
+ /** The trigger name that failed */
81
+ readonly triggerName: string;
82
+ /** Number of execution attempts */
83
+ readonly attempts: number;
84
+ /** The event that was being processed (if available) */
85
+ readonly event?: unknown;
86
+ constructor(message: string, triggerName: string, attempts: number, options?: ErrorOptions & {
87
+ event?: unknown;
88
+ });
89
+ }
90
+ /**
91
+ * Error thrown when a trigger execution times out.
92
+ */
93
+ declare class TriggerTimeoutError extends TriggerError {
94
+ /** The trigger name that timed out */
95
+ readonly triggerName: string;
96
+ /** Configured timeout in milliseconds */
97
+ readonly timeoutMs: number;
98
+ constructor(triggerName: string, timeoutMs: number);
99
+ }
100
+ /**
101
+ * Error thrown when max retries are exceeded.
102
+ */
103
+ declare class TriggerMaxRetriesError extends TriggerError {
104
+ /** The trigger name that exceeded retries */
105
+ readonly triggerName: string;
106
+ /** Maximum retries configured */
107
+ readonly maxRetries: number;
108
+ /** The original error that caused the failure */
109
+ readonly originalError?: Error;
110
+ constructor(triggerName: string, maxRetries: number, originalError?: Error);
111
+ }
112
+ /**
113
+ * Error thrown when webhook signature verification fails.
114
+ */
115
+ declare class TriggerWebhookVerificationError extends TriggerError {
116
+ /** The trigger name */
117
+ readonly triggerName: string;
118
+ /** The verification error message */
119
+ readonly verificationError?: string;
120
+ constructor(triggerName: string, verificationError?: string);
121
+ }
122
+
123
+ /**
124
+ * @cloudwerk/trigger - defineTrigger()
125
+ *
126
+ * Factory function for creating trigger definitions.
127
+ */
128
+
129
+ /**
130
+ * Parse a duration string into seconds.
131
+ *
132
+ * Supports formats like:
133
+ * - '30s' - 30 seconds
134
+ * - '5m' - 5 minutes
135
+ * - '1h' - 1 hour
136
+ * - 60 - number of seconds
137
+ *
138
+ * @param duration - Duration string or number
139
+ * @returns Duration in seconds
140
+ */
141
+ declare function parseDuration(duration: string | number): number;
142
+ /**
143
+ * Define a trigger consumer.
144
+ *
145
+ * This function creates a trigger definition that will be automatically
146
+ * discovered and registered by Cloudwerk during build.
147
+ *
148
+ * @typeParam TSource - The trigger source type
149
+ * @param config - Trigger configuration
150
+ * @returns Trigger definition
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * // app/triggers/daily-cleanup.ts
155
+ * import { defineTrigger } from '@cloudwerk/trigger'
156
+ *
157
+ * export default defineTrigger({
158
+ * source: { type: 'scheduled', cron: '0 0 * * *' },
159
+ * async handle(event, ctx) {
160
+ * console.log(`[${ctx.traceId}] Running cleanup at ${event.scheduledTime}`)
161
+ * await cleanupOldRecords()
162
+ * }
163
+ * })
164
+ * ```
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * // app/triggers/process-uploads.ts
169
+ * import { defineTrigger } from '@cloudwerk/trigger'
170
+ *
171
+ * export default defineTrigger({
172
+ * source: {
173
+ * type: 'r2',
174
+ * bucket: 'uploads',
175
+ * events: ['object-create'],
176
+ * prefix: 'images/',
177
+ * },
178
+ * retry: { maxAttempts: 5, delay: '30s' },
179
+ * async handle(event, ctx) {
180
+ * console.log(`New file: ${event.key}`)
181
+ * await processImage(event.key)
182
+ * },
183
+ * async onError(error, event, ctx) {
184
+ * await reportError(error, { key: event.key, traceId: ctx.traceId })
185
+ * }
186
+ * })
187
+ * ```
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * // app/triggers/stripe-webhook.ts
192
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
193
+ *
194
+ * export default defineTrigger({
195
+ * source: {
196
+ * type: 'webhook',
197
+ * path: '/webhooks/stripe',
198
+ * verify: verifiers.stripe(STRIPE_WEBHOOK_SECRET),
199
+ * },
200
+ * async handle(event, ctx) {
201
+ * switch (event.payload.type) {
202
+ * case 'checkout.session.completed':
203
+ * await handleCheckoutComplete(event.payload)
204
+ * break
205
+ * }
206
+ * }
207
+ * })
208
+ * ```
209
+ */
210
+ declare function defineTrigger<TSource extends TriggerSource>(config: TriggerConfig<TSource>): TriggerDefinition<TSource>;
211
+ /**
212
+ * Check if a value is a trigger definition created by defineTrigger().
213
+ *
214
+ * @param value - Value to check
215
+ * @returns true if value is a TriggerDefinition
216
+ */
217
+ declare function isTriggerDefinition(value: unknown): value is TriggerDefinition;
218
+ /**
219
+ * Get the source type from a trigger definition.
220
+ *
221
+ * @param definition - Trigger definition
222
+ * @returns The source type string
223
+ */
224
+ declare function getTriggerSourceType(definition: TriggerDefinition): TriggerSource['type'];
225
+
226
+ /**
227
+ * Custom webhook signature verifier factory.
228
+ *
229
+ * Create verifiers for any webhook provider using common patterns.
230
+ */
231
+
232
+ /**
233
+ * Signature encoding format.
234
+ */
235
+ type SignatureEncoding = 'hex' | 'base64';
236
+ /**
237
+ * Hash algorithm for HMAC computation.
238
+ */
239
+ type HashAlgorithm = 'SHA-256' | 'SHA-1' | 'SHA-512';
240
+ interface CustomVerifierOptions {
241
+ /**
242
+ * Name of the header containing the signature.
243
+ * @example 'x-webhook-signature'
244
+ */
245
+ header: string;
246
+ /**
247
+ * Hash algorithm to use.
248
+ * @default 'SHA-256'
249
+ */
250
+ algorithm?: HashAlgorithm;
251
+ /**
252
+ * Encoding of the signature in the header.
253
+ * @default 'hex'
254
+ */
255
+ encoding?: SignatureEncoding;
256
+ /**
257
+ * Prefix before the signature (e.g., 'sha256=').
258
+ * Will be stripped before comparison.
259
+ */
260
+ prefix?: string;
261
+ /**
262
+ * Optional timestamp header for replay attack prevention.
263
+ */
264
+ timestampHeader?: string;
265
+ /**
266
+ * Tolerance for timestamp validation in seconds.
267
+ * Only used if timestampHeader is set.
268
+ * @default 300
269
+ */
270
+ timestampTolerance?: number;
271
+ /**
272
+ * Function to build the signature base string.
273
+ * By default, just uses the raw body.
274
+ *
275
+ * @param body - Raw request body as string
276
+ * @param timestamp - Timestamp value if timestampHeader is set
277
+ * @returns String to compute signature over
278
+ */
279
+ buildSignatureBase?: (body: string, timestamp?: string) => string;
280
+ }
281
+ /**
282
+ * Create a custom webhook signature verifier.
283
+ *
284
+ * @param secret - Webhook signing secret
285
+ * @param options - Verifier configuration
286
+ * @returns WebhookVerifier function
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * // Simple HMAC-SHA256 with hex encoding
291
+ * verifiers.custom(secret, {
292
+ * header: 'x-webhook-signature',
293
+ * algorithm: 'SHA-256',
294
+ * encoding: 'hex',
295
+ * })
296
+ *
297
+ * // With timestamp validation (like Stripe)
298
+ * verifiers.custom(secret, {
299
+ * header: 'x-signature',
300
+ * timestampHeader: 'x-timestamp',
301
+ * timestampTolerance: 300,
302
+ * buildSignatureBase: (body, timestamp) => `${timestamp}.${body}`,
303
+ * })
304
+ *
305
+ * // With prefix (like GitHub)
306
+ * verifiers.custom(secret, {
307
+ * header: 'x-hub-signature-256',
308
+ * prefix: 'sha256=',
309
+ * })
310
+ * ```
311
+ */
312
+ declare function customVerifier(secret: string, options: CustomVerifierOptions): WebhookVerifier;
313
+ /**
314
+ * Alias for customVerifier.
315
+ */
316
+ declare const custom: typeof customVerifier;
317
+
318
+ /**
319
+ * Linear webhook signature verifier.
320
+ *
321
+ * @see https://developers.linear.app/docs/graphql/webhooks#webhook-security
322
+ */
323
+
324
+ /**
325
+ * Create a Linear webhook signature verifier.
326
+ *
327
+ * @param secret - Linear webhook signing secret
328
+ * @returns WebhookVerifier function
329
+ *
330
+ * @example
331
+ * ```typescript
332
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
333
+ *
334
+ * export default defineTrigger({
335
+ * source: {
336
+ * type: 'webhook',
337
+ * path: '/webhooks/linear',
338
+ * verify: verifiers.linear(process.env.LINEAR_WEBHOOK_SECRET),
339
+ * },
340
+ * async handle(event) {
341
+ * const { action, type, data } = event.payload
342
+ * switch (type) {
343
+ * case 'Issue':
344
+ * if (action === 'create') {
345
+ * // Handle new issue
346
+ * }
347
+ * break
348
+ * }
349
+ * }
350
+ * })
351
+ * ```
352
+ */
353
+ declare function linearVerifier(secret: string): WebhookVerifier;
354
+ /**
355
+ * Alias for linearVerifier.
356
+ */
357
+ declare const linear: typeof linearVerifier;
358
+
359
+ /**
360
+ * Shopify webhook signature verifier.
361
+ *
362
+ * @see https://shopify.dev/docs/apps/webhooks/configuration/https#step-5-verify-the-webhook
363
+ */
364
+
365
+ /**
366
+ * Create a Shopify webhook signature verifier.
367
+ *
368
+ * @param secret - Shopify webhook signing secret (from Partner Dashboard)
369
+ * @returns WebhookVerifier function
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
374
+ *
375
+ * export default defineTrigger({
376
+ * source: {
377
+ * type: 'webhook',
378
+ * path: '/webhooks/shopify',
379
+ * verify: verifiers.shopify(process.env.SHOPIFY_WEBHOOK_SECRET),
380
+ * },
381
+ * async handle(event) {
382
+ * const topic = event.headers.get('x-shopify-topic')
383
+ * switch (topic) {
384
+ * case 'orders/create':
385
+ * // Handle new order
386
+ * break
387
+ * case 'products/update':
388
+ * // Handle product update
389
+ * break
390
+ * }
391
+ * }
392
+ * })
393
+ * ```
394
+ */
395
+ declare function shopifyVerifier(secret: string): WebhookVerifier;
396
+ /**
397
+ * Alias for shopifyVerifier.
398
+ */
399
+ declare const shopify: typeof shopifyVerifier;
400
+
401
+ /**
402
+ * Twilio webhook signature verifier.
403
+ *
404
+ * @see https://www.twilio.com/docs/usage/security#validating-requests
405
+ */
406
+
407
+ interface TwilioVerifierOptions {
408
+ /**
409
+ * The full URL of your webhook endpoint.
410
+ * Required for signature validation.
411
+ */
412
+ url: string;
413
+ }
414
+ /**
415
+ * Create a Twilio webhook signature verifier.
416
+ *
417
+ * @param authToken - Twilio Auth Token
418
+ * @param options - Verifier options including the webhook URL
419
+ * @returns WebhookVerifier function
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
424
+ *
425
+ * export default defineTrigger({
426
+ * source: {
427
+ * type: 'webhook',
428
+ * path: '/webhooks/twilio',
429
+ * verify: verifiers.twilio(process.env.TWILIO_AUTH_TOKEN, {
430
+ * url: 'https://your-app.com/webhooks/twilio',
431
+ * }),
432
+ * },
433
+ * async handle(event) {
434
+ * const { From, Body } = event.payload
435
+ * // Handle SMS or voice webhook
436
+ * }
437
+ * })
438
+ * ```
439
+ */
440
+ declare function twilioVerifier(authToken: string, options: TwilioVerifierOptions): WebhookVerifier;
441
+ /**
442
+ * Alias for twilioVerifier.
443
+ */
444
+ declare const twilio: typeof twilioVerifier;
445
+
446
+ /**
447
+ * Slack webhook signature verifier.
448
+ *
449
+ * @see https://api.slack.com/authentication/verifying-requests-from-slack
450
+ */
451
+
452
+ interface SlackVerifierOptions {
453
+ /**
454
+ * Tolerance for timestamp validation in seconds.
455
+ * @default 300 (5 minutes)
456
+ */
457
+ tolerance?: number;
458
+ }
459
+ /**
460
+ * Create a Slack webhook signature verifier.
461
+ *
462
+ * @param signingSecret - Slack signing secret
463
+ * @param options - Verifier options
464
+ * @returns WebhookVerifier function
465
+ *
466
+ * @example
467
+ * ```typescript
468
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
469
+ *
470
+ * export default defineTrigger({
471
+ * source: {
472
+ * type: 'webhook',
473
+ * path: '/webhooks/slack',
474
+ * verify: verifiers.slack(process.env.SLACK_SIGNING_SECRET),
475
+ * },
476
+ * async handle(event) {
477
+ * const payload = event.payload
478
+ * // Handle Slack event
479
+ * }
480
+ * })
481
+ * ```
482
+ */
483
+ declare function slackVerifier(signingSecret: string, options?: SlackVerifierOptions): WebhookVerifier;
484
+ /**
485
+ * Alias for slackVerifier.
486
+ */
487
+ declare const slack: typeof slackVerifier;
488
+
489
+ /**
490
+ * GitHub webhook signature verifier.
491
+ *
492
+ * @see https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries
493
+ */
494
+
495
+ /**
496
+ * Create a GitHub webhook signature verifier.
497
+ *
498
+ * @param secret - GitHub webhook secret
499
+ * @returns WebhookVerifier function
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
504
+ *
505
+ * export default defineTrigger({
506
+ * source: {
507
+ * type: 'webhook',
508
+ * path: '/webhooks/github',
509
+ * verify: verifiers.github(process.env.GITHUB_WEBHOOK_SECRET),
510
+ * },
511
+ * async handle(event) {
512
+ * const githubEvent = event.headers.get('x-github-event')
513
+ * switch (githubEvent) {
514
+ * case 'push':
515
+ * // Handle push event
516
+ * break
517
+ * case 'pull_request':
518
+ * // Handle PR event
519
+ * break
520
+ * }
521
+ * }
522
+ * })
523
+ * ```
524
+ */
525
+ declare function githubVerifier(secret: string): WebhookVerifier;
526
+ /**
527
+ * Alias for githubVerifier.
528
+ */
529
+ declare const github: typeof githubVerifier;
530
+
531
+ /**
532
+ * Stripe webhook signature verifier.
533
+ *
534
+ * @see https://stripe.com/docs/webhooks/signatures
535
+ */
536
+
537
+ interface StripeVerifierOptions {
538
+ /**
539
+ * Tolerance for timestamp validation in seconds.
540
+ * @default 300 (5 minutes)
541
+ */
542
+ tolerance?: number;
543
+ }
544
+ /**
545
+ * Create a Stripe webhook signature verifier.
546
+ *
547
+ * @param secret - Stripe webhook signing secret (whsec_...)
548
+ * @param options - Verifier options
549
+ * @returns WebhookVerifier function
550
+ *
551
+ * @example
552
+ * ```typescript
553
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
554
+ *
555
+ * export default defineTrigger({
556
+ * source: {
557
+ * type: 'webhook',
558
+ * path: '/webhooks/stripe',
559
+ * verify: verifiers.stripe(process.env.STRIPE_WEBHOOK_SECRET),
560
+ * },
561
+ * async handle(event) {
562
+ * const stripeEvent = event.payload
563
+ * switch (stripeEvent.type) {
564
+ * case 'checkout.session.completed':
565
+ * // Handle checkout completion
566
+ * break
567
+ * }
568
+ * }
569
+ * })
570
+ * ```
571
+ */
572
+ declare function stripeVerifier(secret: string, options?: StripeVerifierOptions): WebhookVerifier;
573
+ /**
574
+ * Alias for stripeVerifier.
575
+ */
576
+ declare const stripe: typeof stripeVerifier;
577
+
578
+ /**
579
+ * Collection of all built-in webhook verifiers.
580
+ *
581
+ * @example
582
+ * ```typescript
583
+ * import { defineTrigger, verifiers } from '@cloudwerk/trigger'
584
+ *
585
+ * export default defineTrigger({
586
+ * source: {
587
+ * type: 'webhook',
588
+ * path: '/webhooks/stripe',
589
+ * verify: verifiers.stripe(STRIPE_WEBHOOK_SECRET),
590
+ * },
591
+ * async handle(event) {
592
+ * // Handle verified webhook
593
+ * }
594
+ * })
595
+ * ```
596
+ */
597
+ declare const verifiers: {
598
+ readonly stripe: typeof stripeVerifier;
599
+ readonly github: typeof githubVerifier;
600
+ readonly slack: typeof slackVerifier;
601
+ readonly twilio: typeof twilioVerifier;
602
+ readonly shopify: typeof shopifyVerifier;
603
+ readonly linear: typeof linearVerifier;
604
+ readonly custom: typeof customVerifier;
605
+ };
606
+
607
+ /**
608
+ * @cloudwerk/trigger - Trigger Chaining via emit()
609
+ *
610
+ * Allows triggers to invoke other triggers with automatic
611
+ * trace ID propagation for observability.
612
+ */
613
+
614
+ /**
615
+ * Options for emitting to a trigger.
616
+ */
617
+ interface EmitOptions {
618
+ /**
619
+ * Delay before the trigger executes (in milliseconds).
620
+ * @default 0
621
+ */
622
+ delay?: number;
623
+ /**
624
+ * Custom trace ID (defaults to current context's traceId).
625
+ */
626
+ traceId?: string;
627
+ }
628
+ /**
629
+ * Result of an emit operation.
630
+ */
631
+ interface EmitResult {
632
+ /** Whether the emit was successful */
633
+ success: boolean;
634
+ /** The trace ID used for this emission */
635
+ traceId: string;
636
+ /** Target trigger name */
637
+ trigger: string;
638
+ /** Timestamp when emit was called */
639
+ emittedAt: Date;
640
+ }
641
+ /**
642
+ * Pending emission that was queued during execution.
643
+ */
644
+ interface PendingEmission {
645
+ trigger: string;
646
+ payload: unknown;
647
+ options: EmitOptions;
648
+ traceId: string;
649
+ emittedAt: Date;
650
+ }
651
+ /**
652
+ * Emitter interface for different execution modes.
653
+ */
654
+ interface TriggerEmitter {
655
+ /**
656
+ * Emit to a trigger.
657
+ */
658
+ emit(trigger: string, payload: unknown, options?: EmitOptions): Promise<EmitResult>;
659
+ /**
660
+ * Get all pending emissions (for testing/debugging).
661
+ */
662
+ getPendingEmissions(): PendingEmission[];
663
+ /**
664
+ * Clear pending emissions.
665
+ */
666
+ clearPendingEmissions(): void;
667
+ }
668
+ /**
669
+ * Run a function within a trigger context.
670
+ *
671
+ * @param context - Trigger context
672
+ * @param fn - Function to execute
673
+ * @returns Function result
674
+ */
675
+ declare function runWithTriggerContext<T>(context: TriggerContext, fn: () => T): T;
676
+ /**
677
+ * Get the current trigger context.
678
+ *
679
+ * @returns Current context or undefined if not in a trigger
680
+ */
681
+ declare function getTriggerContext(): TriggerContext | undefined;
682
+ /**
683
+ * Get pending emissions from the current context.
684
+ */
685
+ declare function getPendingEmissions(): PendingEmission[];
686
+ /**
687
+ * Generate a new trace ID.
688
+ *
689
+ * @param prefix - Optional prefix (default: 'tr')
690
+ * @returns Trace ID string
691
+ */
692
+ declare function generateTraceId(prefix?: string): string;
693
+ /**
694
+ * Create a child trace ID from a parent.
695
+ *
696
+ * @param parentTraceId - Parent trace ID
697
+ * @returns Child trace ID
698
+ */
699
+ declare function createChildTraceId(parentTraceId: string): string;
700
+ /**
701
+ * Emit an event to another trigger.
702
+ *
703
+ * This function queues an event to be processed by another trigger,
704
+ * with automatic trace ID propagation for distributed tracing.
705
+ *
706
+ * @param trigger - Name of the trigger to invoke
707
+ * @param payload - Data to pass to the trigger
708
+ * @param options - Emit options
709
+ * @returns EmitResult
710
+ *
711
+ * @example
712
+ * ```typescript
713
+ * import { defineTrigger, emit } from '@cloudwerk/trigger'
714
+ *
715
+ * export default defineTrigger({
716
+ * source: { type: 'r2', bucket: 'uploads', events: ['object-create'] },
717
+ * async handle(event, ctx) {
718
+ * // Process the upload
719
+ * const metadata = await processFile(event.key)
720
+ *
721
+ * // Chain to other triggers
722
+ * await emit('index-for-search', { key: event.key, metadata })
723
+ * await emit('generate-thumbnail', { key: event.key })
724
+ *
725
+ * // Trace ID is automatically propagated
726
+ * console.log(ctx.traceId) // Same traceId in chained triggers
727
+ * }
728
+ * })
729
+ * ```
730
+ *
731
+ * @example
732
+ * ```typescript
733
+ * // With delay
734
+ * await emit('send-reminder', { userId }, { delay: 60000 }) // 1 minute delay
735
+ * ```
736
+ */
737
+ declare function emit(trigger: string, payload: unknown, options?: EmitOptions): Promise<EmitResult>;
738
+ /**
739
+ * Emit to multiple triggers in parallel.
740
+ *
741
+ * @param emissions - Array of [trigger, payload] pairs
742
+ * @param options - Shared options for all emissions
743
+ * @returns Array of EmitResults
744
+ *
745
+ * @example
746
+ * ```typescript
747
+ * const results = await emitMany([
748
+ * ['process-image', { key: 'image.jpg' }],
749
+ * ['update-index', { key: 'image.jpg' }],
750
+ * ['notify-user', { userId, message: 'Upload complete' }],
751
+ * ])
752
+ * ```
753
+ */
754
+ declare function emitMany(emissions: [string, unknown][], options?: EmitOptions): Promise<EmitResult[]>;
755
+ /**
756
+ * Default trigger emitter implementation.
757
+ *
758
+ * In production, this would be replaced with an implementation
759
+ * that actually dispatches to other triggers via queues or
760
+ * direct function calls.
761
+ */
762
+ declare const defaultEmitter: TriggerEmitter;
763
+
764
+ /**
765
+ * @cloudwerk/trigger - Observability & Metrics
766
+ *
767
+ * Utilities for tracing, metrics collection, and monitoring trigger executions.
768
+ */
769
+
770
+ /**
771
+ * Trigger execution metrics.
772
+ */
773
+ interface TriggerMetrics {
774
+ /** Trigger name */
775
+ name: string;
776
+ /** Trigger source type */
777
+ sourceType: TriggerSource['type'];
778
+ /** Execution start timestamp */
779
+ startedAt: Date;
780
+ /** Execution end timestamp */
781
+ endedAt?: Date;
782
+ /** Duration in milliseconds */
783
+ durationMs?: number;
784
+ /** Whether execution was successful */
785
+ success: boolean;
786
+ /** Error if execution failed */
787
+ error?: Error;
788
+ /** Number of retries */
789
+ retryCount: number;
790
+ /** Trace ID for distributed tracing */
791
+ traceId: string;
792
+ }
793
+ /**
794
+ * Trigger execution span for tracing.
795
+ */
796
+ interface TriggerSpan {
797
+ /** Span ID */
798
+ spanId: string;
799
+ /** Trace ID */
800
+ traceId: string;
801
+ /** Parent span ID (for nested triggers) */
802
+ parentSpanId?: string;
803
+ /** Trigger name */
804
+ triggerName: string;
805
+ /** Source type */
806
+ sourceType: TriggerSource['type'];
807
+ /** Operation name */
808
+ operationName: string;
809
+ /** Start time (Unix timestamp ms) */
810
+ startTime: number;
811
+ /** End time (Unix timestamp ms) */
812
+ endTime?: number;
813
+ /** Span status */
814
+ status: 'ok' | 'error' | 'unset';
815
+ /** Attributes */
816
+ attributes: Record<string, string | number | boolean>;
817
+ /** Events that occurred during the span */
818
+ events: SpanEvent[];
819
+ }
820
+ /**
821
+ * Event that occurred during a span.
822
+ */
823
+ interface SpanEvent {
824
+ /** Event name */
825
+ name: string;
826
+ /** Timestamp (Unix ms) */
827
+ timestamp: number;
828
+ /** Event attributes */
829
+ attributes?: Record<string, string | number | boolean>;
830
+ }
831
+ /**
832
+ * Metrics reporter interface for pluggable metrics backends.
833
+ */
834
+ interface MetricsReporter {
835
+ /** Report execution metrics */
836
+ reportExecution(metrics: TriggerMetrics): void;
837
+ /** Report a span */
838
+ reportSpan(span: TriggerSpan): void;
839
+ /** Flush pending metrics */
840
+ flush(): Promise<void>;
841
+ }
842
+ /**
843
+ * Generate a span ID.
844
+ */
845
+ declare function generateSpanId(): string;
846
+ /**
847
+ * Create a new trigger span.
848
+ */
849
+ declare function createTriggerSpan(triggerName: string, sourceType: TriggerSource['type'], traceId: string, parentSpanId?: string): TriggerSpan;
850
+ /**
851
+ * End a trigger span.
852
+ */
853
+ declare function endTriggerSpan(span: TriggerSpan, success: boolean, error?: Error): TriggerSpan;
854
+ /**
855
+ * Add an event to a span.
856
+ */
857
+ declare function addSpanEvent(span: TriggerSpan, name: string, attributes?: Record<string, string | number | boolean>): void;
858
+ /**
859
+ * Add attributes to a span.
860
+ */
861
+ declare function setSpanAttributes(span: TriggerSpan, attributes: Record<string, string | number | boolean>): void;
862
+ /**
863
+ * Timer for measuring trigger execution duration.
864
+ */
865
+ declare class ExecutionTimer {
866
+ private startTime;
867
+ private endTime?;
868
+ private marks;
869
+ constructor();
870
+ /**
871
+ * Mark a point in time.
872
+ */
873
+ mark(name: string): void;
874
+ /**
875
+ * Get time since start to a mark.
876
+ */
877
+ getMarkDuration(name: string): number | undefined;
878
+ /**
879
+ * Stop the timer.
880
+ */
881
+ stop(): number;
882
+ /**
883
+ * Get total duration in milliseconds.
884
+ */
885
+ get duration(): number;
886
+ /**
887
+ * Get all marks with their durations.
888
+ */
889
+ getMarks(): Record<string, number>;
890
+ }
891
+ /**
892
+ * Console-based metrics reporter for development.
893
+ */
894
+ declare class ConsoleMetricsReporter implements MetricsReporter {
895
+ private prefix;
896
+ constructor(prefix?: string);
897
+ reportExecution(metrics: TriggerMetrics): void;
898
+ reportSpan(span: TriggerSpan): void;
899
+ flush(): Promise<void>;
900
+ }
901
+ /**
902
+ * No-op metrics reporter that discards all metrics.
903
+ */
904
+ declare class NoOpMetricsReporter implements MetricsReporter {
905
+ reportExecution(_metrics: TriggerMetrics): void;
906
+ reportSpan(_span: TriggerSpan): void;
907
+ flush(): Promise<void>;
908
+ }
909
+ /**
910
+ * Collect and aggregate trigger metrics.
911
+ */
912
+ declare class MetricsCollector {
913
+ private executions;
914
+ private spans;
915
+ private reporter;
916
+ constructor(reporter?: MetricsReporter);
917
+ /**
918
+ * Record a trigger execution.
919
+ */
920
+ recordExecution(metrics: TriggerMetrics): void;
921
+ /**
922
+ * Record a span.
923
+ */
924
+ recordSpan(span: TriggerSpan): void;
925
+ /**
926
+ * Get execution count for a trigger.
927
+ */
928
+ getExecutionCount(triggerName: string): number;
929
+ /**
930
+ * Get success rate for a trigger.
931
+ */
932
+ getSuccessRate(triggerName: string): number;
933
+ /**
934
+ * Get average duration for a trigger.
935
+ */
936
+ getAverageDuration(triggerName: string): number | undefined;
937
+ /**
938
+ * Get percentile duration for a trigger.
939
+ */
940
+ getPercentileDuration(triggerName: string, percentile: number): number | undefined;
941
+ /**
942
+ * Get summary statistics for a trigger.
943
+ */
944
+ getSummary(triggerName: string): {
945
+ count: number;
946
+ successRate: number;
947
+ avgDurationMs?: number;
948
+ p50DurationMs?: number;
949
+ p95DurationMs?: number;
950
+ p99DurationMs?: number;
951
+ };
952
+ /**
953
+ * Flush metrics to the reporter.
954
+ */
955
+ flush(): Promise<void>;
956
+ /**
957
+ * Clear collected metrics.
958
+ */
959
+ clear(): void;
960
+ }
961
+ /**
962
+ * Create trigger metrics from an execution.
963
+ */
964
+ declare function createTriggerMetrics(name: string, sourceType: TriggerSource['type'], ctx: TriggerContext, timer: ExecutionTimer, success: boolean, error?: Error, retryCount?: number): TriggerMetrics;
965
+
966
+ export { ConsoleMetricsReporter, type CustomVerifierOptions, type EmitOptions, type EmitResult, ExecutionTimer, type HashAlgorithm, MetricsCollector, type MetricsReporter, NoOpMetricsReporter, type PendingEmission, type SignatureEncoding, type SlackVerifierOptions, type SpanEvent, type StripeVerifierOptions, TriggerConfig, TriggerConfigError, TriggerContext, TriggerContextError, TriggerDefinition, type TriggerEmitter, TriggerError, TriggerInvalidCronError, TriggerInvalidSourceError, TriggerInvalidWebhookPathError, TriggerMaxRetriesError, type TriggerMetrics, TriggerNoHandlerError, TriggerNotFoundError, TriggerProcessingError, TriggerSource, type TriggerSpan, TriggerTimeoutError, TriggerWebhookVerificationError, type TwilioVerifierOptions, WebhookVerifier, addSpanEvent, createChildTraceId, createTriggerMetrics, createTriggerSpan, custom, customVerifier, defaultEmitter, defineTrigger, emit, emitMany, endTriggerSpan, generateSpanId, generateTraceId, getPendingEmissions, getTriggerContext, getTriggerSourceType, github, githubVerifier, isTriggerDefinition, linear, linearVerifier, parseDuration, runWithTriggerContext, setSpanAttributes, shopify, shopifyVerifier, slack, slackVerifier, stripe, stripeVerifier, twilio, twilioVerifier, verifiers };