@centrali-io/centrali-sdk 9.5.2 → 9.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,16 +2,21 @@
2
2
  // Triggers Manager
3
3
  // =====================================================
4
4
 
5
- import type { Method } from 'axios';
5
+ import crypto from 'crypto';
6
+ import type { AxiosRequestConfig, Method } from 'axios';
6
7
  import type { ApiResponse } from '../types/common';
7
8
  import type {
8
9
  FunctionTrigger,
9
10
  InvokeTriggerOptions,
10
11
  InvokeEndpointOptions,
12
+ InvokeHttpTriggerOptions,
13
+ HttpTriggerInvokeResponse,
11
14
  CreateTriggerInput,
12
15
  UpdateTriggerInput,
13
16
  ListAllTriggersOptions,
14
17
  TriggerWithHealth,
18
+ TriggerHealthList,
19
+ TriggerHealthTrend,
15
20
  } from '../types/triggers';
16
21
  import type { TriggerInvokeResponse } from '../types/records';
17
22
  import {
@@ -20,16 +25,15 @@ import {
20
25
  getFunctionTriggerPauseApiPath,
21
26
  getFunctionTriggerResumeApiPath,
22
27
  getEndpointApiPath,
28
+ getHttpTriggerApiPath,
23
29
  } from '../internal/paths';
24
30
 
25
31
  // =====================================================
26
32
 
27
33
  /**
28
- * TriggersManager provides methods for working with on-demand function triggers.
29
- * Access via `client.triggers`.
30
- *
31
- * Note: This manager only works with on-demand triggers. Scheduled, event-driven,
32
- * and webhook triggers are managed through other mechanisms.
34
+ * TriggersManager provides trigger management, invocation, and health reads.
35
+ * Access via `client.triggers`. Health reads cover every trigger type; HTTP
36
+ * request metrics apply only to traffic reaching the HTTP trigger controller.
33
37
  *
34
38
  * Usage:
35
39
  * ```ts
@@ -49,17 +53,31 @@ import {
49
53
  * ```
50
54
  */
51
55
  export class TriggersManager {
52
- private requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>;
56
+ private requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>, config?: AxiosRequestConfig) => Promise<ApiResponse<T>>;
53
57
  private workspaceId: string;
54
58
 
55
59
  constructor(
56
60
  workspaceId: string,
57
- requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>
61
+ requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>, config?: AxiosRequestConfig) => Promise<ApiResponse<T>>,
62
+ private readonly requestBody?: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<T>
58
63
  ) {
59
64
  this.workspaceId = workspaceId;
60
65
  this.requestFn = requestFn;
61
66
  }
62
67
 
68
+ /** Request acceptance and execution success are independent metrics. */
69
+ public async health(period: 7 | 30 = 30): Promise<ApiResponse<TriggerHealthList>> {
70
+ if (!this.requestBody) throw new Error('Health reads require CentraliSDK.triggers');
71
+ const body = await this.requestBody<TriggerHealthList>('GET', `data/workspace/${this.workspaceId}/api/v1/triggers/health`, undefined, { period });
72
+ return { data: body };
73
+ }
74
+
75
+ public async healthTrend(triggerId: string, period: 7 | 30 = 30): Promise<ApiResponse<TriggerHealthTrend>> {
76
+ if (!this.requestBody) throw new Error('Health reads require CentraliSDK.triggers');
77
+ const body = await this.requestBody<TriggerHealthTrend>('GET', `data/workspace/${this.workspaceId}/api/v1/triggers/${encodeURIComponent(triggerId)}/health/trend`, undefined, { period });
78
+ return { data: body };
79
+ }
80
+
63
81
  /**
64
82
  * Invoke an on-demand trigger by ID.
65
83
  *
@@ -346,4 +364,118 @@ export class TriggersManager {
346
364
  const queryParams = options?.query;
347
365
  return this.requestFn<T>(method, path, data, queryParams);
348
366
  }
367
+
368
+ /**
369
+ * Invoke an asynchronous HTTP trigger by its stable path.
370
+ *
371
+ * The JSON body is serialized before signing so the bytes transmitted by
372
+ * Axios are exactly the bytes used to compute the HMAC. Signature options
373
+ * mirror the server validator's trigger metadata. Omit `signingSecret` for
374
+ * an unsigned trigger.
375
+ */
376
+ public invokeHttpTrigger(
377
+ triggerPath: string,
378
+ payload: unknown,
379
+ options: InvokeHttpTriggerOptions = {}
380
+ ): Promise<ApiResponse<HttpTriggerInvokeResponse>> {
381
+ const normalizedPath = triggerPath
382
+ .replace(/^\/+|\/+$/g, '')
383
+ .replace(/\/+/g, '-');
384
+ if (!normalizedPath) {
385
+ throw new Error('HTTP trigger path must not be empty');
386
+ }
387
+
388
+ const path = getHttpTriggerApiPath(this.workspaceId, normalizedPath);
389
+ const rawBody = JSON.stringify(payload ?? {});
390
+ const headers: Record<string, string> = {
391
+ 'Content-Type': 'application/json',
392
+ ...options.headers,
393
+ };
394
+
395
+ if (options.signingSecret !== undefined) {
396
+ Object.assign(headers, createHttpTriggerSignatureHeaders(rawBody, options));
397
+ }
398
+
399
+ return this.requestFn<HttpTriggerInvokeResponse>('POST', path, rawBody, undefined, { headers });
400
+ }
401
+ }
402
+
403
+ function createHttpTriggerSignatureHeaders(
404
+ rawBody: string,
405
+ options: InvokeHttpTriggerOptions
406
+ ): Record<string, string> {
407
+ const {
408
+ signingSecret,
409
+ signatureHeaderName,
410
+ signatureIdHeaderName,
411
+ timestampHeaderName,
412
+ timestampExtractionPattern,
413
+ signatureHeaderTemplate = '{sig}',
414
+ hmacAlgorithm = 'sha256',
415
+ hmacEncoding = 'base64',
416
+ encoding = 'base64',
417
+ secretEncoding = 'raw',
418
+ payloadFormat = 'default',
419
+ } = options;
420
+
421
+ if (!signingSecret) {
422
+ throw new Error('Signing secret must not be empty when signing an HTTP trigger request');
423
+ }
424
+ if (!signatureHeaderName) {
425
+ throw new Error('signatureHeaderName is required when signing an HTTP trigger request');
426
+ }
427
+
428
+ const hasTimestamp = Boolean(timestampHeaderName || timestampExtractionPattern);
429
+ const timestamp = hasTimestamp
430
+ ? String(options.timestamp ?? Math.floor(Date.now() / 1000))
431
+ : undefined;
432
+ const sigId = signatureIdHeaderName
433
+ ? (options.sigId ?? `msg_${crypto.randomBytes(12).toString('hex')}`)
434
+ : undefined;
435
+
436
+ let signedPayload = rawBody;
437
+ if (payloadFormat === 'slack') {
438
+ if (!timestamp) {
439
+ throw new Error('Slack signatures require timestamp metadata');
440
+ }
441
+ signedPayload = `v0:${timestamp}:${rawBody}`;
442
+ } else {
443
+ if (timestamp) signedPayload = `${timestamp}.${signedPayload}`;
444
+ if (sigId) signedPayload = `${sigId}.${signedPayload}`;
445
+ }
446
+
447
+ let secret: Buffer;
448
+ if (secretEncoding === 'prefixed-base64') {
449
+ const separator = signingSecret.indexOf('_');
450
+ const encodedSecret = separator < 0 ? '' : signingSecret.slice(separator + 1);
451
+ if (!encodedSecret) {
452
+ throw new Error('Signing secret is malformed for prefixed-base64 encoding');
453
+ }
454
+ secret = Buffer.from(encodedSecret, encoding);
455
+ } else {
456
+ secret = Buffer.from(signingSecret, 'utf8');
457
+ }
458
+
459
+ if (secret.length === 0) {
460
+ throw new Error('Signing secret is malformed: decoded key must not be empty');
461
+ }
462
+
463
+ const digest = crypto
464
+ .createHmac(hmacAlgorithm, secret)
465
+ .update(signedPayload)
466
+ .digest(hmacEncoding);
467
+ const signatureValue = signatureHeaderTemplate
468
+ .replace('{sig}', digest)
469
+ .replace('{ts}', timestamp ?? '');
470
+
471
+ const headers: Record<string, string> = {
472
+ [signatureHeaderName]: signatureValue,
473
+ };
474
+ if (timestampHeaderName && timestamp && timestampHeaderName.toLowerCase() !== signatureHeaderName.toLowerCase()) {
475
+ headers[timestampHeaderName] = timestamp;
476
+ }
477
+ if (signatureIdHeaderName && sigId) {
478
+ headers[signatureIdHeaderName] = sigId;
479
+ }
480
+ return headers;
349
481
  }
@@ -14,6 +14,7 @@ import type {
14
14
  AcceptSuggestionResult,
15
15
  BulkOperationResult,
16
16
  ValidationSummary,
17
+ ValidationPendingCount,
17
18
  } from '../types/validation';
18
19
  import {
19
20
  getValidationScanApiPath,
@@ -31,6 +32,15 @@ import {
31
32
  // Validation Manager (Data Quality)
32
33
  // =====================================================
33
34
 
35
+ // Optional list/summary filters preserve empty-string compatibility, but reject
36
+ // non-string JavaScript inputs before query serialization can erase the filter.
37
+ function optionalCollectionSlug(value: unknown, name = 'recordSlug'): string | undefined {
38
+ if (value !== undefined && typeof value !== 'string') {
39
+ throw new TypeError(`${name} must be a string`);
40
+ }
41
+ return value === '' ? undefined : value;
42
+ }
43
+
34
44
  /**
35
45
  * ValidationManager provides methods for AI-powered data quality validation.
36
46
  * Access via `client.validation`.
@@ -76,7 +86,7 @@ export class ValidationManager {
76
86
  /**
77
87
  * Trigger a batch validation scan on a structure.
78
88
  *
79
- * @param structureSlug - The structure's slug to scan
89
+ * @param recordSlug - The collection slug to scan
80
90
  * @param options - Optional scan configuration
81
91
  * @returns The batch scan result with batchId for tracking
82
92
  *
@@ -87,14 +97,17 @@ export class ValidationManager {
87
97
  * console.log('Records to scan:', batch.data.total);
88
98
  * ```
89
99
  */
90
- public triggerScan(
91
- structureSlug: string,
100
+ public async triggerScan(
101
+ recordSlug: string,
92
102
  options?: TriggerScanOptions
93
103
  ): Promise<ApiResponse<BatchScanResult>> {
104
+ const slug = optionalCollectionSlug(recordSlug);
105
+ if (slug === undefined) throw new TypeError('recordSlug is required');
94
106
  const path = getValidationScanApiPath(this.workspaceId);
95
107
  // Note: workspaceSlug is in URL path, not body
96
108
  return this.requestFn<BatchScanResult>('POST', path, {
97
- structureSlug,
109
+ recordSlug: slug,
110
+ structureSlug: slug,
98
111
  validationTypes: options?.validationTypes,
99
112
  });
100
113
  }
@@ -179,11 +192,23 @@ export class ValidationManager {
179
192
  * });
180
193
  * ```
181
194
  */
182
- public listSuggestions(
195
+ public async listSuggestions(
183
196
  options?: ListValidationSuggestionsOptions
184
197
  ): Promise<ApiResponse<ValidationSuggestion[]>> {
185
198
  const path = getValidationSuggestionsApiPath(this.workspaceId);
186
- return this.requestFn<ValidationSuggestion[]>('GET', path, null, options);
199
+ if (!options) return this.requestFn<ValidationSuggestion[]>('GET', path, null, options);
200
+ const { recordSlug, structureSlug, ...query } = options;
201
+ const canonical = optionalCollectionSlug(recordSlug);
202
+ const legacy = optionalCollectionSlug(structureSlug, 'structureSlug');
203
+ if (canonical !== undefined && legacy !== undefined && canonical !== legacy) {
204
+ throw new Error('recordSlug and structureSlug must match');
205
+ }
206
+ const slug = canonical ?? legacy;
207
+ // Keep filtering safe when this SDK is used against an older server.
208
+ const params: ListValidationSuggestionsOptions = { ...query };
209
+ if (canonical !== undefined) params.recordSlug = canonical;
210
+ if (slug !== undefined) params.structureSlug = slug;
211
+ return this.requestFn<ValidationSuggestion[]>('GET', path, null, params);
187
212
  }
188
213
 
189
214
  /**
@@ -274,7 +299,7 @@ export class ValidationManager {
274
299
  /**
275
300
  * Get validation summary statistics.
276
301
  *
277
- * @param structureId - Optional structure ID to filter summary
302
+ * @param recordSlug - Optional collection slug to filter summary
278
303
  * @returns Summary of suggestions by status and type
279
304
  *
280
305
  * @example
@@ -284,20 +309,21 @@ export class ValidationManager {
284
309
  * console.log('By type:', summary.data.byIssueType);
285
310
  * ```
286
311
  */
287
- public getSummary(structureSlug?: string): Promise<ApiResponse<ValidationSummary>> {
312
+ public async getSummary(recordSlug?: string): Promise<ApiResponse<ValidationSummary>> {
313
+ const slug = optionalCollectionSlug(recordSlug);
288
314
  const path = getValidationSummaryApiPath(this.workspaceId);
289
- const params = structureSlug ? { structureSlug } : undefined;
315
+ const params = slug !== undefined ? { recordSlug: slug, structureSlug: slug } : undefined;
290
316
  return this.requestFn<ValidationSummary>('GET', path, null, params);
291
317
  }
292
318
 
293
319
  /**
294
320
  * Get the count of pending suggestions for a structure.
295
321
  *
296
- * @param structureSlug - The structure slug (recordSlug)
322
+ * @param recordSlug - The collection slug
297
323
  * @returns Object with pending count
298
324
  */
299
- public getPendingCount(structureSlug: string): Promise<ApiResponse<{ structureSlug: string; pendingCount: number }>> {
300
- const path = getValidationPendingCountApiPath(this.workspaceId, structureSlug);
301
- return this.requestFn<{ structureSlug: string; pendingCount: number }>('GET', path);
325
+ public getPendingCount(recordSlug: string): Promise<ApiResponse<ValidationPendingCount>> {
326
+ const path = getValidationPendingCountApiPath(this.workspaceId, recordSlug);
327
+ return this.requestFn<ValidationPendingCount>('GET', path);
302
328
  }
303
329
  }
@@ -48,6 +48,48 @@ export interface InvokeEndpointOptions {
48
48
  query?: Record<string, string>;
49
49
  }
50
50
 
51
+ /**
52
+ * Options for invoking an asynchronous HTTP trigger.
53
+ *
54
+ * Signature options mirror the HTTP trigger's signature metadata. When
55
+ * `signingSecret` is omitted, the request is sent unsigned.
56
+ */
57
+ export interface InvokeHttpTriggerOptions {
58
+ /** Additional request headers. Signature-related headers generated by the SDK take precedence. */
59
+ headers?: Record<string, string>;
60
+ /** HMAC signing secret. Omit for a trigger with signature validation disabled. */
61
+ signingSecret?: string;
62
+ /** Header that receives the generated signature. Required when signing. */
63
+ signatureHeaderName?: string;
64
+ /** Optional header carrying the signature/message ID. */
65
+ signatureIdHeaderName?: string;
66
+ /** Optional header carrying the Unix timestamp. */
67
+ timestampHeaderName?: string;
68
+ /** Indicates that the timestamp is embedded in the signature header (for example, Stripe). */
69
+ timestampExtractionPattern?: string;
70
+ /** Template for the signature header value. Supports `{sig}` and `{ts}` placeholders. */
71
+ signatureHeaderTemplate?: string;
72
+ /** HMAC algorithm (default: `sha256`). */
73
+ hmacAlgorithm?: string;
74
+ /** Digest encoding (default: `base64`). */
75
+ hmacEncoding?: 'base64' | 'base64url' | 'hex';
76
+ /** Encoding used to decode a prefixed secret (default: `base64`). */
77
+ encoding?: 'base64' | 'base64url' | 'hex';
78
+ /** Secret handling used by the server validator (default: `raw`). */
79
+ secretEncoding?: 'raw' | 'prefixed-base64';
80
+ /** Payload canonicalization used by the server validator (default: `default`). */
81
+ payloadFormat?: 'default' | 'slack';
82
+ /** Unix timestamp override. Intended for deterministic tests; defaults to the current time. */
83
+ timestamp?: number;
84
+ /** Signature/message ID override; otherwise one is generated when required. */
85
+ sigId?: string;
86
+ }
87
+
88
+ /** Response returned after an HTTP trigger request is accepted for async execution. */
89
+ export interface HttpTriggerInvokeResponse {
90
+ status: 'queued';
91
+ }
92
+
51
93
  /**
52
94
  * Response from a synchronous compute endpoint invocation.
53
95
  */
@@ -120,3 +162,45 @@ export interface TriggerWithHealth extends FunctionTrigger {
120
162
  health: TriggerHealthMetrics;
121
163
  healthStatus: TriggerHealthStatus;
122
164
  }
165
+
166
+ /** HTTP request health recorded since tracking rollout; no historical backfill. */
167
+ export interface TriggerRequestHealth {
168
+ receivedCount: number;
169
+ acceptedCount: number;
170
+ rejectedCount: number;
171
+ requestAcceptanceRate: number | null;
172
+ rejectionReasonBreakdown: Record<string, number>;
173
+ }
174
+
175
+ export interface TriggerHealthSummary extends TriggerRequestHealth {
176
+ triggerId: string;
177
+ triggerName: string;
178
+ executionType: string;
179
+ enabled: boolean;
180
+ totalRuns: number;
181
+ successCount: number;
182
+ failureCount: number;
183
+ executionSuccessRate: number;
184
+ /** @deprecated Use executionSuccessRate. Retained through at least 2027-04-27. */
185
+ successRate: number;
186
+ failureRate: number;
187
+ avgDurationMs: number;
188
+ lastRunAt: string | null;
189
+ attentionNeeded: boolean;
190
+ trendDirection: 'increasing' | 'decreasing' | 'stable';
191
+ }
192
+
193
+ export interface TriggerHealthList {
194
+ data: TriggerHealthSummary[];
195
+ meta: { period: number; totalTriggers: number; attentionCount: number; unattributedRequests: TriggerRequestHealth };
196
+ }
197
+
198
+ export interface TriggerHealthTrend {
199
+ trigger: { id: string; name: string; executionType: string };
200
+ data: Array<TriggerRequestHealth & {
201
+ date: string; successCount: number; failureCount: number; totalRuns: number;
202
+ failureRate: number; avgDurationMs: number;
203
+ }>;
204
+ summary: TriggerRequestHealth & Pick<TriggerHealthSummary,
205
+ 'totalRuns' | 'executionSuccessRate' | 'successRate' | 'failureRate' | 'avgDurationMs' | 'attentionNeeded' | 'trendDirection'>;
206
+ }
@@ -61,7 +61,9 @@ export interface ValidationSuggestion {
61
61
  * Options for listing validation suggestions.
62
62
  */
63
63
  export interface ListValidationSuggestionsOptions {
64
- /** Filter by structure slug (recordSlug) */
64
+ /** Filter by collection slug. Empty aliases are omitted; nonempty aliases must match. */
65
+ recordSlug?: string;
66
+ /** Legacy alias for recordSlug. */
65
67
  structureSlug?: string;
66
68
  /** Filter by record ID */
67
69
  recordId?: string;
@@ -165,3 +167,12 @@ export interface BulkOperationResult {
165
167
  /** Status message */
166
168
  message: string;
167
169
  }
170
+
171
+ /** Pending validation suggestions for a collection. */
172
+ export interface ValidationPendingCount {
173
+ /** Collection slug. Absent on older servers. */
174
+ recordSlug?: string;
175
+ /** Legacy alias for the collection slug. */
176
+ structureSlug: string;
177
+ pendingCount: number;
178
+ }