@centrali-io/centrali-sdk 6.16.2 → 7.0.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.
package/README.md CHANGED
@@ -99,6 +99,7 @@ const centrali = new CentraliSDK({
99
99
  - ✅ **Records management** - Create, read, update, delete records
100
100
  - ✅ **Query operations** - Powerful data querying with filters and sorting
101
101
  - ✅ **Saved Queries** - Execute reusable, parameterized queries
102
+ - ✅ **Alerts** - Schedule a saved query and notify people when its result meets a condition
102
103
  - ✅ **Full-text search** - Search records across structures with Meilisearch
103
104
  - ✅ **Realtime events** - Subscribe to record changes via SSE
104
105
  - ✅ **Compute functions** - Execute serverless functions
@@ -543,6 +544,60 @@ const results = await centrali.savedQueries.execute('orders', queryId);
543
544
 
544
545
  Saved-query bodies authored against the legacy operator vocabulary (`{ status: { $eq: 'open' } }`) keep working server-side via the legacy translator during the deprecation window. New saved-query definitions should use canonical operators (`{ 'data.status': { eq: 'open' } }`).
545
546
 
547
+ ### Alerts
548
+
549
+ Run a saved query on a schedule and notify people when its result meets a condition — no compute function required. Evaluation happens server-side; recipients get an email and an in-app inbox notification.
550
+
551
+ ```typescript
552
+ // Notify two people each weekday at 9am when no orders are open
553
+ const alert = await centrali.alerts.create({
554
+ savedQueryId: 'query-uuid',
555
+ name: 'No open orders',
556
+ cronExpression: '0 9 * * 1-5',
557
+ timezone: 'Europe/London',
558
+ condition: { kind: 'rowCount', op: 'eq', value: 0 },
559
+ recipients: [
560
+ { type: 'user', id: 'user-uuid-1' },
561
+ { type: 'user', id: 'user-uuid-2' },
562
+ ],
563
+ });
564
+
565
+ // List alerts, optionally scoped to one saved query
566
+ const alerts = await centrali.alerts.list({ savedQueryId: 'query-uuid' });
567
+
568
+ // Pause without losing the definition, then resume
569
+ await centrali.alerts.update(alert.data.id, { enabled: false });
570
+ await centrali.alerts.update(alert.data.id, { enabled: true });
571
+
572
+ await centrali.alerts.delete(alert.data.id);
573
+ ```
574
+
575
+ Two condition kinds ship today:
576
+
577
+ | Kind | Fires when |
578
+ |------|-----------|
579
+ | `{ kind: 'rowCount', op, value }` | The execution's row count compares true against `value` (`eq`, `neq`, `gt`, `gte`, `lt`, `lte`) |
580
+ | `{ kind: 'rowsChanged' }` | The row count differs from the previous evaluation. The first run only seeds the baseline — it never fires |
581
+
582
+ #### Binding parameters
583
+
584
+ If the saved query takes parameters, bind them with `variables`:
585
+
586
+ ```typescript
587
+ await centrali.alerts.create({
588
+ savedQueryId: 'query-uuid',
589
+ name: 'Failed payments spiked',
590
+ cronExpression: '0 * * * *',
591
+ condition: { kind: 'rowCount', op: 'gt', value: 10 },
592
+ recipients: [{ type: 'user', id: 'user-uuid' }],
593
+ variables: { status: 'failed' },
594
+ });
595
+ ```
596
+
597
+ The server validates the binding set on create, and on any update that submits `variables`. The rule is deliberately stricter than the saved query's own execute-time validation: **a declaration the query body references with no `default` must be bound here, whether or not it is marked `required`.**
598
+
599
+ That extra strictness exists because the failure it prevents is invisible. Execute-time validation accepts an unbound optional, substitution leaves the raw `${name}` in the body, and re-validation doesn't object either — a placeholder is a legal `eq` value. The query runs, filters on the literal `"${name}"`, matches nothing, and updates `lastEvaluatedAt` as though all is well. Nobody is watching a cron, so the alert would simply never fire. Declarations the body never references can be omitted.
600
+
546
601
  ### Search
547
602
 
548
603
  Perform full-text search across workspace records using Meilisearch:
package/dist/index.d.ts CHANGED
@@ -133,6 +133,13 @@ declare function getSavedQueryCanonicalCollectionPath(workspaceId: string): stri
133
133
  declare function getSavedQueryCanonicalByIdPath(workspaceId: string, queryId: string): string;
134
134
  declare function getSavedQueryCanonicalExecutePath(workspaceId: string, queryId: string): string;
135
135
  declare function getSavedQueryCanonicalTestPath(workspaceId: string): string;
136
+ /**
137
+ * Saved-query alert definition paths (CEN-1123). Workspace-scoped, not
138
+ * nested under a saved query — an alert references its query by id, and the
139
+ * list endpoint filters on `savedQueryId` as a query param.
140
+ */
141
+ declare function getAlertDefinitionsApiPath(workspaceId: string): string;
142
+ declare function getAlertDefinitionByIdApiPath(workspaceId: string, alertId: string): string;
136
143
  /**
137
144
  * Generate Search API URL PATH.
138
145
  */
@@ -2597,6 +2604,138 @@ interface InsightsSummary {
2597
2604
  byType: Record<string, number>;
2598
2605
  }
2599
2606
 
2607
+ /** Comparison operators available to a `rowCount` condition. */
2608
+ type AlertComparisonOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte';
2609
+ /**
2610
+ * What makes an alert fire. v1 ships two kinds; `aggregate` is deferred
2611
+ * until composable aggregations land on saved-query definitions.
2612
+ *
2613
+ * - `rowCount` — compare the execution's row count against a fixed value.
2614
+ * - `rowsChanged` — fire whenever the row count differs from the previous
2615
+ * evaluation. The first evaluation only seeds the baseline and never
2616
+ * fires, since there is nothing to compare against yet.
2617
+ */
2618
+ type AlertCondition = {
2619
+ kind: 'rowCount';
2620
+ op: AlertComparisonOp;
2621
+ value: number;
2622
+ } | {
2623
+ kind: 'rowsChanged';
2624
+ };
2625
+ /** Who gets notified. Recipients are explicit per-alert, not subscribers. */
2626
+ interface AlertRecipient {
2627
+ type: 'user';
2628
+ /** The recipient's user ID. */
2629
+ id: string;
2630
+ }
2631
+ /**
2632
+ * A stored alert definition.
2633
+ */
2634
+ interface AlertDefinition {
2635
+ /** Unique identifier (UUID) */
2636
+ id: string;
2637
+ /** Workspace slug the alert belongs to */
2638
+ workspaceSlug: string;
2639
+ /** The saved query this alert evaluates */
2640
+ savedQueryId: string;
2641
+ /** Human-readable name, used as the notification subject */
2642
+ name: string;
2643
+ /** Optional description */
2644
+ description: string | null;
2645
+ /**
2646
+ * Values bound to the saved query's `${var}` placeholders on every
2647
+ * scheduled evaluation. See `CreateAlertDefinitionInput.variables` for
2648
+ * why an incomplete map is rejected at authoring time.
2649
+ */
2650
+ variables: Record<string, unknown>;
2651
+ /** Cron expression driving evaluation */
2652
+ cronExpression: string;
2653
+ /** IANA timezone the cron is interpreted in */
2654
+ timezone: string;
2655
+ /** The trigger condition */
2656
+ condition: AlertCondition;
2657
+ /** Explicit notification recipients */
2658
+ recipients: AlertRecipient[];
2659
+ /** Disabled alerts keep their definition but are unscheduled */
2660
+ enabled: boolean;
2661
+ /** Underlying scheduler job ID; null when disabled */
2662
+ schedulerJobId: string | null;
2663
+ /** Row count seen on the last evaluation — the `rowsChanged` baseline */
2664
+ lastRowCount: number | null;
2665
+ /** ISO timestamp of the last evaluation, triggered or not */
2666
+ lastEvaluatedAt: string | null;
2667
+ /** ISO timestamp of the last evaluation that fired */
2668
+ lastTriggeredAt: string | null;
2669
+ /** User ID who created the alert */
2670
+ createdBy: string;
2671
+ /** ISO timestamp of creation */
2672
+ createdAt: string;
2673
+ /** ISO timestamp of last update */
2674
+ updatedAt: string;
2675
+ }
2676
+ /**
2677
+ * Body for `client.alerts.create()`.
2678
+ */
2679
+ interface CreateAlertDefinitionInput {
2680
+ /** The saved query to evaluate. Must live in the same workspace. */
2681
+ savedQueryId: string;
2682
+ /** Display name, max 255 characters */
2683
+ name: string;
2684
+ /** Optional description, max 2000 characters */
2685
+ description?: string | null;
2686
+ /**
2687
+ * Values for the saved query's `${var}` placeholders.
2688
+ *
2689
+ * The server rejects a set that won't bind cleanly, and the rule is
2690
+ * stricter than the saved query's own execute-time validation: a
2691
+ * declaration the query body REFERENCES with no `default` must be
2692
+ * supplied here, whether or not it is marked `required`. An unbound
2693
+ * reference is accepted at execute time and left in the body verbatim,
2694
+ * so the alert would quietly filter on the literal `"${name}"`, match
2695
+ * nothing, and never fire — with no error to notice. Declarations the
2696
+ * body never references may be omitted.
2697
+ */
2698
+ variables?: Record<string, unknown>;
2699
+ /** Cron expression, e.g. `"0 9 * * 1-5"` */
2700
+ cronExpression: string;
2701
+ /** IANA timezone; defaults to `"UTC"` */
2702
+ timezone?: string;
2703
+ /** The trigger condition */
2704
+ condition: AlertCondition;
2705
+ /** At least one recipient is required */
2706
+ recipients: AlertRecipient[];
2707
+ /** Defaults to true — an enabled alert is scheduled immediately */
2708
+ enabled?: boolean;
2709
+ }
2710
+ /**
2711
+ * Body for `client.alerts.update()`. At least one field must be present.
2712
+ * `savedQueryId` is immutable — point an alert at a different query by
2713
+ * creating a new one.
2714
+ */
2715
+ interface UpdateAlertDefinitionInput {
2716
+ name?: string;
2717
+ /** Pass `null` to clear the description; omit to leave it unchanged. */
2718
+ description?: string | null;
2719
+ /**
2720
+ * Replaces the stored bindings wholesale. Validated on submission under
2721
+ * the same rule as create — see `CreateAlertDefinitionInput.variables`.
2722
+ * Omit to leave the existing bindings untouched.
2723
+ */
2724
+ variables?: Record<string, unknown>;
2725
+ /** Changing this (or `timezone`) reschedules the underlying job. */
2726
+ cronExpression?: string;
2727
+ timezone?: string;
2728
+ condition?: AlertCondition;
2729
+ recipients?: AlertRecipient[];
2730
+ /** Toggling this schedules or unschedules the underlying job. */
2731
+ enabled?: boolean;
2732
+ }
2733
+ /** Filters for `client.alerts.list()`. */
2734
+ interface ListAlertDefinitionsOptions {
2735
+ /** Only return alerts attached to this saved query. */
2736
+ savedQueryId?: string;
2737
+ }
2738
+
2600
2739
  /**
2601
2740
  * Validation issue types.
2602
2741
  * - 'type': Schema type mismatch (e.g., string where array expected) - rule-based
@@ -4102,6 +4241,137 @@ declare class AnomalyInsightsManager {
4102
4241
  triggerAnalysis(structureSlug: string): Promise<ApiResponse<AnomalyAnalysisResult>>;
4103
4242
  }
4104
4243
 
4244
+ /**
4245
+ * AlertDefinitionsManager — scheduled alerts on saved queries. Access via
4246
+ * `client.alerts`.
4247
+ *
4248
+ * Each alert runs its saved query on a cron, checks the result against a
4249
+ * condition, and on a match notifies its recipients by email and in-app
4250
+ * inbox. Evaluation happens server-side on the schedule; nothing in this
4251
+ * manager runs a query directly (use `client.savedQueries.execute()` for
4252
+ * that).
4253
+ *
4254
+ * Authorization mirrors the console: managing alerts requires the
4255
+ * `alert-definitions` permissions AND `execute` on the saved query the
4256
+ * alert points at — creating an alert must not become a way to schedule
4257
+ * recurring runs of a query you can't run yourself.
4258
+ *
4259
+ * Usage:
4260
+ * ```ts
4261
+ * // Alert when a saved query stops returning rows, each weekday at 9am
4262
+ * const alert = await client.alerts.create({
4263
+ * savedQueryId: 'query-uuid',
4264
+ * name: 'No open orders',
4265
+ * cronExpression: '0 9 * * 1-5',
4266
+ * timezone: 'Europe/London',
4267
+ * condition: { kind: 'rowCount', op: 'eq', value: 0 },
4268
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
4269
+ * });
4270
+ *
4271
+ * // Alerts attached to one saved query
4272
+ * const alerts = await client.alerts.list({ savedQueryId: 'query-uuid' });
4273
+ *
4274
+ * // Pause it without losing the definition
4275
+ * await client.alerts.update(alert.data.id, { enabled: false });
4276
+ * ```
4277
+ */
4278
+ declare class AlertDefinitionsManager {
4279
+ private requestFn;
4280
+ private workspaceId;
4281
+ constructor(workspaceId: string, requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>);
4282
+ /**
4283
+ * List alert definitions in the workspace.
4284
+ *
4285
+ * Alerts whose saved query the caller can't read are omitted rather
4286
+ * than failing the request — `lastRowCount` and `lastTriggeredAt` are
4287
+ * observations about that query's data, so the list is filtered to the
4288
+ * queries you're allowed to see.
4289
+ *
4290
+ * @param options - Optional filters
4291
+ * @returns The alert definitions
4292
+ *
4293
+ * @example
4294
+ * ```ts
4295
+ * const all = await client.alerts.list();
4296
+ * const forQuery = await client.alerts.list({ savedQueryId: 'query-uuid' });
4297
+ * ```
4298
+ */
4299
+ list(options?: ListAlertDefinitionsOptions): Promise<ApiResponse<AlertDefinition[]>>;
4300
+ /**
4301
+ * Get a single alert definition by ID.
4302
+ *
4303
+ * @param alertId - The alert UUID
4304
+ * @returns The alert definition
4305
+ *
4306
+ * @example
4307
+ * ```ts
4308
+ * const alert = await client.alerts.get('alert-uuid');
4309
+ * console.log('Last fired:', alert.data.lastTriggeredAt);
4310
+ * ```
4311
+ */
4312
+ get(alertId: string): Promise<ApiResponse<AlertDefinition>>;
4313
+ /**
4314
+ * Create an alert definition. Unless `enabled` is false, the alert is
4315
+ * scheduled immediately.
4316
+ *
4317
+ * If the saved query takes parameters, bind them via `variables` — the
4318
+ * server rejects a set that would leave a referenced placeholder
4319
+ * unbound, because such an alert runs clean and never fires. See
4320
+ * `CreateAlertDefinitionInput.variables`.
4321
+ *
4322
+ * @param input - The alert definition
4323
+ * @returns The created alert definition
4324
+ *
4325
+ * @example
4326
+ * ```ts
4327
+ * const alert = await client.alerts.create({
4328
+ * savedQueryId: 'query-uuid',
4329
+ * name: 'Failed payments spiked',
4330
+ * cronExpression: '0 * * * *',
4331
+ * condition: { kind: 'rowCount', op: 'gt', value: 10 },
4332
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
4333
+ * variables: { status: 'failed' },
4334
+ * });
4335
+ * ```
4336
+ */
4337
+ create(input: CreateAlertDefinitionInput): Promise<ApiResponse<AlertDefinition>>;
4338
+ /**
4339
+ * Update an alert definition. Only the fields you pass are changed.
4340
+ *
4341
+ * Toggling `enabled`, or changing `cronExpression` / `timezone`,
4342
+ * reschedules the underlying job. A concurrent update to those fields
4343
+ * fails with 409 — refetch and retry rather than replaying the request.
4344
+ *
4345
+ * @param alertId - The alert UUID
4346
+ * @param input - Fields to change
4347
+ * @returns The updated alert definition
4348
+ *
4349
+ * @example
4350
+ * ```ts
4351
+ * // Pause an alert
4352
+ * await client.alerts.update('alert-uuid', { enabled: false });
4353
+ *
4354
+ * // Move it to hourly
4355
+ * await client.alerts.update('alert-uuid', { cronExpression: '0 * * * *' });
4356
+ * ```
4357
+ */
4358
+ update(alertId: string, input: UpdateAlertDefinitionInput): Promise<ApiResponse<AlertDefinition>>;
4359
+ /**
4360
+ * Delete an alert definition and unschedule its job.
4361
+ *
4362
+ * @param alertId - The alert UUID
4363
+ * @returns Confirmation message
4364
+ *
4365
+ * @example
4366
+ * ```ts
4367
+ * await client.alerts.delete('alert-uuid');
4368
+ * ```
4369
+ */
4370
+ delete(alertId: string): Promise<ApiResponse<{
4371
+ message: string;
4372
+ }>>;
4373
+ }
4374
+
4105
4375
  /**
4106
4376
  * ValidationManager provides methods for AI-powered data quality validation.
4107
4377
  * Access via `client.validation`.
@@ -5497,6 +5767,7 @@ declare class CentraliSDK {
5497
5767
  private _smartQueries;
5498
5768
  private _queryRecordsLegacyWarned;
5499
5769
  private _anomalyInsights;
5770
+ private _alerts;
5500
5771
  private _validation;
5501
5772
  private _orchestrations;
5502
5773
  private _allowedDomains;
@@ -5666,6 +5937,28 @@ declare class CentraliSDK {
5666
5937
  */
5667
5938
  get smartQueries(): SmartQueriesManager;
5668
5939
  private _smartQueriesAlias?;
5940
+ /**
5941
+ * Alerts namespace for scheduled alerts on saved queries.
5942
+ *
5943
+ * Usage:
5944
+ * ```ts
5945
+ * // Alert when a saved query returns nothing, weekdays at 9am
5946
+ * const alert = await client.alerts.create({
5947
+ * savedQueryId: 'query-uuid',
5948
+ * name: 'No open orders',
5949
+ * cronExpression: '0 9 * * 1-5',
5950
+ * condition: { kind: 'rowCount', op: 'eq', value: 0 },
5951
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
5952
+ * });
5953
+ *
5954
+ * // List alerts on one saved query
5955
+ * const alerts = await client.alerts.list({ savedQueryId: 'query-uuid' });
5956
+ *
5957
+ * // Pause without deleting
5958
+ * await client.alerts.update(alert.data.id, { enabled: false });
5959
+ * ```
5960
+ */
5961
+ get alerts(): AlertDefinitionsManager;
5669
5962
  /**
5670
5963
  * Anomaly Insights namespace for querying and managing AI-generated insights.
5671
5964
  *
@@ -6341,4 +6634,4 @@ declare class CentraliSDK {
6341
6634
  checkAuthorization(options: CheckAuthorizationOptions): Promise<ApiResponse<AuthorizationResult>>;
6342
6635
  }
6343
6636
 
6344
- export { type AcceptSuggestionResult, type AddAllowedDomainOptions, type AllowedDomain, type AllowedDomainsListResponse, AllowedDomainsManager, type AnomalyAnalysisResult, type AnomalyDetectionData, type AnomalyEventType, type AnomalyInsight, type AnomalyInsightData, AnomalyInsightsManager, type ApiResponse, type ArrayPropertyDefinition, AuditLogManager, type AuthorizationResult, type BasePropertyDefinition, type BatchScanResult, type BatchScanStatus, type BooleanPropertyDefinition, type BulkOperationResult, CANONICAL_OPERATORS, type CanonicalOperator, CentraliError, CentraliSDK, type CentraliSDKOptions, type CheckAuthorizationOptions, CollectionsManager, type ComputeEventType, type ComputeFunction, ComputeFunctionsManager, type ComputeJobStatus, type ComputeJobStatusResponse, type ConditionOperator, type CreateComputeFunctionInput, type CreateOrchestrationInput, type CreateSmartQueryInput, type CreateStructureInput, type CreateTriggerInput, type CreateWebhookSubscriptionInput, type DateTimePropertyDefinition, type DateWindowOption, type DeleteRecordOptions, type EmbedCapability, EmbedManager, type EndpointResponse, EventLogEmbed, type EventLogSourceTable, type EventLogSubscribeOptions, type ExecuteSavedQueryValues, type ExecuteSmartQueryOptions, type ExpandOptions, type FieldCondition, type FieldConditionMap, type FileMetadata, FilesManager, type FilterOperators, type FilterValue, type FunctionMemoryUsage, type FunctionRun, type FunctionRunError, type FunctionRunExecutionSource, type FunctionRunStatus, FunctionRunsManager, type FunctionTrigger, type GetRecordOptions, type IncludeClause, type InsightSeverity, type InsightStatus, type InsightType, type InsightsSummary, type InvokeEndpointOptions, type InvokeTriggerOptions, type IssueEmbedTokenInput, type IssueEmbedTokenResult, JOINS_MAX_LENGTH, type JoinClause, type JoinType, type LegacyTranslateOptions, type LegacyTranslateResult, type LegacyTranslateWarning, type ListAllTriggersOptions, type ListCollectionsOptions, type ListComputeFunctionsOptions, type ListFunctionRunsOptions, type ListInsightsOptions, type ListOrchestrationRunsOptions, type ListOrchestrationsOptions, type ListSmartQueryOptions, type ListStructuresOptions, type ListValidationSuggestionsOptions, type ListWebhookDeliveriesOptions, type NumberPropertyDefinition, OPERATOR_METADATA, type ObjectPropertyDefinition, type OperatorMeta, type OperatorTypeApplicability, type OperatorValueShape, type Orchestration, type OrchestrationCaseEvaluation, type OrchestrationCondition, type OrchestrationConditionEvaluation, type OrchestrationDecisionCase, type OrchestrationDecisionResult, type OrchestrationDelayConfig, type OrchestrationEventType, type OrchestrationFailureReason, type OrchestrationOnFailure, type OrchestrationOnSuccess, type OrchestrationRetryConfig, type OrchestrationRun, type OrchestrationRunStatus, type OrchestrationRunStep, OrchestrationRunsManager, type OrchestrationScheduleType, type OrchestrationStatus, type OrchestrationStep, type OrchestrationStepError, type OrchestrationStepStatus, type OrchestrationStepType, type OrchestrationTrigger, type OrchestrationTriggerMetadata, type OrchestrationTriggerType, OrchestrationsManager, type PageClause, type PaginatedResponse, type ParsedUrlQuery, type PropertyDefinition, type PropertyType, type QueryDefinition, type QueryError, type QueryErrorCode, type QueryExecutionMode, type QueryHttpError, type QueryHttpErrorCode, QueryManager, type QueryRecordOptions, type QueryResult, type QueryResultMeta, type QueryValidateOptions, type QueryVariableDefinition, RECORDS_PAGE_DEFAULT_LIMIT, RECORDS_PAGE_MAX_LIMIT, type RealtimeAnomalyDetectionEvent, type RealtimeAnomalyInsightEvent, type RealtimeCloseEvent, type RealtimeError, type RealtimeEvent, type RealtimeEventLogEntry, type RealtimeEventType, type RealtimeFunctionRunEvent, RealtimeManager, type RealtimeOrchestrationRunEvent, type RealtimeRecordEvent, type RealtimeSubscribeOptions, type RealtimeSubscription, type RealtimeValidationBatchEvent, type RealtimeValidationSuggestionEvent, type RecordEventType, RecordEvents, type RecordTtlOptions, RecordsManager, type ReferencePropertyDefinition, type ResourceCategory, type RevokeEmbedSessionInput, type RevokeEmbedSessionResult, type SavedQueryDefinition, type SavedQueryScalarBinding, type ScalarValue, type SchemaDiscoveryMode, type SearchHit, type SearchOptions, type SearchResponse, type SelectClause, SmartQueriesManager, type SmartQuery, type SmartQueryDefinition, type SmartQueryExecuteResult, type SmartQueryFieldCondition, type SmartQueryJoin, type SmartQuerySort, type SmartQueryWhereClause, type SortClause, type StepEncryptedParam, type StringPropertyDefinition, type Structure, StructuresManager, type TestComputeFunctionInput, type TestComputeFunctionResult, type TestSmartQueryInput, type TextSearchClause, type TriggerExecutionType, type TriggerHealthMetrics, type TriggerHealthStatus, type TriggerInvokeResponse, type TriggerOrchestrationRunOptions, type TriggerScanOptions, type TriggerWithHealth, TriggersManager, type UpdateComputeFunctionInput, type UpdateOrchestrationInput, type UpdateSmartQueryInput, type UpdateStructureInput, type UpdateTriggerInput, type UpdateWebhookSubscriptionInput, type UrlParserOptions, type ValidateStructureInput, type ValidationBatchData, type ValidationEventType, type ValidationIssueType, ValidationManager, type ValidationResult, type ValidationSuggestion, type ValidationSuggestionData, type ValidationSuggestionStatus, type ValidationSummary, type VariableType, type WaitForScanOptions, type WebhookCancelResponse, type WebhookDeliveriesListMeta, type WebhookDelivery, type WebhookDeliveryStatus, type WebhookDeliverySummary, type WebhookPayloadVersions, type WebhookReplayResponse, type WebhookSubscription, WebhookSubscriptionsManager, type WhereExpression, fetchClientToken, getAllowedDomainsApiPath, getAnomalyAnalysisTriggerApiPath, getAnomalyInsightAcknowledgeApiPath, getAnomalyInsightDismissApiPath, getAnomalyInsightsApiPath, getAnomalyInsightsBulkAcknowledgeApiPath, getAnomalyInsightsSummaryApiPath, getApiUrl, getAuthUrl, getCollectionBySlugApiPath, getCollectionInsightsApiPath, getCollectionValidateApiPath, getCollectionsApiPath, getComputeFunctionTestApiPath, getComputeFunctionsApiPath, getComputeJobStatusApiPath, getEndpointApiPath, getFileUploadApiPath, getFilesCanonicalApiPath, getFunctionRunsApiPath, getFunctionRunsByFunctionApiPath, getFunctionRunsByTriggerApiPath, getFunctionTriggerExecuteApiPath, getFunctionTriggerPauseApiPath, getFunctionTriggerResumeApiPath, getFunctionTriggersApiPath, getOrchestrationRunStepsApiPath, getOrchestrationRunsApiPath, getOrchestrationRunsCanonicalApiPath, getOrchestrationsApiPath, getRealtimeUrl, getRecordApiPath, getSavedQueryCanonicalByIdPath, getSavedQueryCanonicalCollectionPath, getSavedQueryCanonicalExecutePath, getSavedQueryCanonicalTestPath, getSearchApiPath, getSmartQueriesApiPath, getSmartQueriesStructureApiPath, getSmartQueryByNameApiPath, getSmartQueryExecuteApiPath, getSmartQueryTestApiPath, getStructureBySlugApiPath, getStructureInsightsApiPath, getStructureValidateApiPath, getStructuresApiPath, getValidationBulkAcceptApiPath, getValidationBulkRejectApiPath, getValidationPendingCountApiPath, getValidationRecordSuggestionsApiPath, getValidationScanApiPath, getValidationSuggestionAcceptApiPath, getValidationSuggestionRejectApiPath, getValidationSuggestionsApiPath, getValidationSummaryApiPath, getWebhookDeliveryCancelApiPath, getWebhookDeliveryRetryApiPath, getWebhookPayloadVersionsApiPath, getWebhookSubscriptionDeliveriesApiPath, getWebhookSubscriptionRotateSecretApiPath, getWebhookSubscriptionsApiPath, isCentraliError, operatorsForFieldType };
6637
+ export { type AcceptSuggestionResult, type AddAllowedDomainOptions, type AlertComparisonOp, type AlertCondition, type AlertDefinition, AlertDefinitionsManager, type AlertRecipient, type AllowedDomain, type AllowedDomainsListResponse, AllowedDomainsManager, type AnomalyAnalysisResult, type AnomalyDetectionData, type AnomalyEventType, type AnomalyInsight, type AnomalyInsightData, AnomalyInsightsManager, type ApiResponse, type ArrayPropertyDefinition, AuditLogManager, type AuthorizationResult, type BasePropertyDefinition, type BatchScanResult, type BatchScanStatus, type BooleanPropertyDefinition, type BulkOperationResult, CANONICAL_OPERATORS, type CanonicalOperator, CentraliError, CentraliSDK, type CentraliSDKOptions, type CheckAuthorizationOptions, CollectionsManager, type ComputeEventType, type ComputeFunction, ComputeFunctionsManager, type ComputeJobStatus, type ComputeJobStatusResponse, type ConditionOperator, type CreateAlertDefinitionInput, type CreateComputeFunctionInput, type CreateOrchestrationInput, type CreateSmartQueryInput, type CreateStructureInput, type CreateTriggerInput, type CreateWebhookSubscriptionInput, type DateTimePropertyDefinition, type DateWindowOption, type DeleteRecordOptions, type EmbedCapability, EmbedManager, type EndpointResponse, EventLogEmbed, type EventLogSourceTable, type EventLogSubscribeOptions, type ExecuteSavedQueryValues, type ExecuteSmartQueryOptions, type ExpandOptions, type FieldCondition, type FieldConditionMap, type FileMetadata, FilesManager, type FilterOperators, type FilterValue, type FunctionMemoryUsage, type FunctionRun, type FunctionRunError, type FunctionRunExecutionSource, type FunctionRunStatus, FunctionRunsManager, type FunctionTrigger, type GetRecordOptions, type IncludeClause, type InsightSeverity, type InsightStatus, type InsightType, type InsightsSummary, type InvokeEndpointOptions, type InvokeTriggerOptions, type IssueEmbedTokenInput, type IssueEmbedTokenResult, JOINS_MAX_LENGTH, type JoinClause, type JoinType, type LegacyTranslateOptions, type LegacyTranslateResult, type LegacyTranslateWarning, type ListAlertDefinitionsOptions, type ListAllTriggersOptions, type ListCollectionsOptions, type ListComputeFunctionsOptions, type ListFunctionRunsOptions, type ListInsightsOptions, type ListOrchestrationRunsOptions, type ListOrchestrationsOptions, type ListSmartQueryOptions, type ListStructuresOptions, type ListValidationSuggestionsOptions, type ListWebhookDeliveriesOptions, type NumberPropertyDefinition, OPERATOR_METADATA, type ObjectPropertyDefinition, type OperatorMeta, type OperatorTypeApplicability, type OperatorValueShape, type Orchestration, type OrchestrationCaseEvaluation, type OrchestrationCondition, type OrchestrationConditionEvaluation, type OrchestrationDecisionCase, type OrchestrationDecisionResult, type OrchestrationDelayConfig, type OrchestrationEventType, type OrchestrationFailureReason, type OrchestrationOnFailure, type OrchestrationOnSuccess, type OrchestrationRetryConfig, type OrchestrationRun, type OrchestrationRunStatus, type OrchestrationRunStep, OrchestrationRunsManager, type OrchestrationScheduleType, type OrchestrationStatus, type OrchestrationStep, type OrchestrationStepError, type OrchestrationStepStatus, type OrchestrationStepType, type OrchestrationTrigger, type OrchestrationTriggerMetadata, type OrchestrationTriggerType, OrchestrationsManager, type PageClause, type PaginatedResponse, type ParsedUrlQuery, type PropertyDefinition, type PropertyType, type QueryDefinition, type QueryError, type QueryErrorCode, type QueryExecutionMode, type QueryHttpError, type QueryHttpErrorCode, QueryManager, type QueryRecordOptions, type QueryResult, type QueryResultMeta, type QueryValidateOptions, type QueryVariableDefinition, RECORDS_PAGE_DEFAULT_LIMIT, RECORDS_PAGE_MAX_LIMIT, type RealtimeAnomalyDetectionEvent, type RealtimeAnomalyInsightEvent, type RealtimeCloseEvent, type RealtimeError, type RealtimeEvent, type RealtimeEventLogEntry, type RealtimeEventType, type RealtimeFunctionRunEvent, RealtimeManager, type RealtimeOrchestrationRunEvent, type RealtimeRecordEvent, type RealtimeSubscribeOptions, type RealtimeSubscription, type RealtimeValidationBatchEvent, type RealtimeValidationSuggestionEvent, type RecordEventType, RecordEvents, type RecordTtlOptions, RecordsManager, type ReferencePropertyDefinition, type ResourceCategory, type RevokeEmbedSessionInput, type RevokeEmbedSessionResult, type SavedQueryDefinition, type SavedQueryScalarBinding, type ScalarValue, type SchemaDiscoveryMode, type SearchHit, type SearchOptions, type SearchResponse, type SelectClause, SmartQueriesManager, type SmartQuery, type SmartQueryDefinition, type SmartQueryExecuteResult, type SmartQueryFieldCondition, type SmartQueryJoin, type SmartQuerySort, type SmartQueryWhereClause, type SortClause, type StepEncryptedParam, type StringPropertyDefinition, type Structure, StructuresManager, type TestComputeFunctionInput, type TestComputeFunctionResult, type TestSmartQueryInput, type TextSearchClause, type TriggerExecutionType, type TriggerHealthMetrics, type TriggerHealthStatus, type TriggerInvokeResponse, type TriggerOrchestrationRunOptions, type TriggerScanOptions, type TriggerWithHealth, TriggersManager, type UpdateAlertDefinitionInput, type UpdateComputeFunctionInput, type UpdateOrchestrationInput, type UpdateSmartQueryInput, type UpdateStructureInput, type UpdateTriggerInput, type UpdateWebhookSubscriptionInput, type UrlParserOptions, type ValidateStructureInput, type ValidationBatchData, type ValidationEventType, type ValidationIssueType, ValidationManager, type ValidationResult, type ValidationSuggestion, type ValidationSuggestionData, type ValidationSuggestionStatus, type ValidationSummary, type VariableType, type WaitForScanOptions, type WebhookCancelResponse, type WebhookDeliveriesListMeta, type WebhookDelivery, type WebhookDeliveryStatus, type WebhookDeliverySummary, type WebhookPayloadVersions, type WebhookReplayResponse, type WebhookSubscription, WebhookSubscriptionsManager, type WhereExpression, fetchClientToken, getAlertDefinitionByIdApiPath, getAlertDefinitionsApiPath, getAllowedDomainsApiPath, getAnomalyAnalysisTriggerApiPath, getAnomalyInsightAcknowledgeApiPath, getAnomalyInsightDismissApiPath, getAnomalyInsightsApiPath, getAnomalyInsightsBulkAcknowledgeApiPath, getAnomalyInsightsSummaryApiPath, getApiUrl, getAuthUrl, getCollectionBySlugApiPath, getCollectionInsightsApiPath, getCollectionValidateApiPath, getCollectionsApiPath, getComputeFunctionTestApiPath, getComputeFunctionsApiPath, getComputeJobStatusApiPath, getEndpointApiPath, getFileUploadApiPath, getFilesCanonicalApiPath, getFunctionRunsApiPath, getFunctionRunsByFunctionApiPath, getFunctionRunsByTriggerApiPath, getFunctionTriggerExecuteApiPath, getFunctionTriggerPauseApiPath, getFunctionTriggerResumeApiPath, getFunctionTriggersApiPath, getOrchestrationRunStepsApiPath, getOrchestrationRunsApiPath, getOrchestrationRunsCanonicalApiPath, getOrchestrationsApiPath, getRealtimeUrl, getRecordApiPath, getSavedQueryCanonicalByIdPath, getSavedQueryCanonicalCollectionPath, getSavedQueryCanonicalExecutePath, getSavedQueryCanonicalTestPath, getSearchApiPath, getSmartQueriesApiPath, getSmartQueriesStructureApiPath, getSmartQueryByNameApiPath, getSmartQueryExecuteApiPath, getSmartQueryTestApiPath, getStructureBySlugApiPath, getStructureInsightsApiPath, getStructureValidateApiPath, getStructuresApiPath, getValidationBulkAcceptApiPath, getValidationBulkRejectApiPath, getValidationPendingCountApiPath, getValidationRecordSuggestionsApiPath, getValidationScanApiPath, getValidationSuggestionAcceptApiPath, getValidationSuggestionRejectApiPath, getValidationSuggestionsApiPath, getValidationSummaryApiPath, getWebhookDeliveryCancelApiPath, getWebhookDeliveryRetryApiPath, getWebhookPayloadVersionsApiPath, getWebhookSubscriptionDeliveriesApiPath, getWebhookSubscriptionRotateSecretApiPath, getWebhookSubscriptionsApiPath, isCentraliError, operatorsForFieldType };
package/dist/index.js CHANGED
@@ -67,6 +67,7 @@ var __async = (__this, __arguments, generator) => {
67
67
  // index.ts
68
68
  var index_exports = {};
69
69
  __export(index_exports, {
70
+ AlertDefinitionsManager: () => AlertDefinitionsManager,
70
71
  AllowedDomainsManager: () => AllowedDomainsManager,
71
72
  AnomalyInsightsManager: () => AnomalyInsightsManager,
72
73
  AuditLogManager: () => AuditLogManager,
@@ -95,6 +96,8 @@ __export(index_exports, {
95
96
  ValidationManager: () => ValidationManager,
96
97
  WebhookSubscriptionsManager: () => WebhookSubscriptionsManager,
97
98
  fetchClientToken: () => fetchClientToken,
99
+ getAlertDefinitionByIdApiPath: () => getAlertDefinitionByIdApiPath,
100
+ getAlertDefinitionsApiPath: () => getAlertDefinitionsApiPath,
98
101
  getAllowedDomainsApiPath: () => getAllowedDomainsApiPath,
99
102
  getAnomalyAnalysisTriggerApiPath: () => getAnomalyAnalysisTriggerApiPath,
100
103
  getAnomalyInsightAcknowledgeApiPath: () => getAnomalyInsightAcknowledgeApiPath,
@@ -265,6 +268,12 @@ function getSavedQueryCanonicalExecutePath(workspaceId, queryId) {
265
268
  function getSavedQueryCanonicalTestPath(workspaceId) {
266
269
  return `data/workspace/${workspaceId}/api/v1/saved-queries/test`;
267
270
  }
271
+ function getAlertDefinitionsApiPath(workspaceId) {
272
+ return `data/workspace/${workspaceId}/api/v1/alert-definitions`;
273
+ }
274
+ function getAlertDefinitionByIdApiPath(workspaceId, alertId) {
275
+ return `data/workspace/${workspaceId}/api/v1/alert-definitions/${alertId}`;
276
+ }
268
277
  function getSearchApiPath(workspaceId) {
269
278
  return `search/workspace/${workspaceId}/api/v1/records/search`;
270
279
  }
@@ -6942,6 +6951,118 @@ var AnomalyInsightsManager = class {
6942
6951
  }
6943
6952
  };
6944
6953
 
6954
+ // src/managers/alertDefinitions.ts
6955
+ var AlertDefinitionsManager = class {
6956
+ constructor(workspaceId, requestFn) {
6957
+ this.workspaceId = workspaceId;
6958
+ this.requestFn = requestFn;
6959
+ }
6960
+ /**
6961
+ * List alert definitions in the workspace.
6962
+ *
6963
+ * Alerts whose saved query the caller can't read are omitted rather
6964
+ * than failing the request — `lastRowCount` and `lastTriggeredAt` are
6965
+ * observations about that query's data, so the list is filtered to the
6966
+ * queries you're allowed to see.
6967
+ *
6968
+ * @param options - Optional filters
6969
+ * @returns The alert definitions
6970
+ *
6971
+ * @example
6972
+ * ```ts
6973
+ * const all = await client.alerts.list();
6974
+ * const forQuery = await client.alerts.list({ savedQueryId: 'query-uuid' });
6975
+ * ```
6976
+ */
6977
+ list(options) {
6978
+ const path = getAlertDefinitionsApiPath(this.workspaceId);
6979
+ return this.requestFn("GET", path, null, options);
6980
+ }
6981
+ /**
6982
+ * Get a single alert definition by ID.
6983
+ *
6984
+ * @param alertId - The alert UUID
6985
+ * @returns The alert definition
6986
+ *
6987
+ * @example
6988
+ * ```ts
6989
+ * const alert = await client.alerts.get('alert-uuid');
6990
+ * console.log('Last fired:', alert.data.lastTriggeredAt);
6991
+ * ```
6992
+ */
6993
+ get(alertId) {
6994
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
6995
+ return this.requestFn("GET", path);
6996
+ }
6997
+ /**
6998
+ * Create an alert definition. Unless `enabled` is false, the alert is
6999
+ * scheduled immediately.
7000
+ *
7001
+ * If the saved query takes parameters, bind them via `variables` — the
7002
+ * server rejects a set that would leave a referenced placeholder
7003
+ * unbound, because such an alert runs clean and never fires. See
7004
+ * `CreateAlertDefinitionInput.variables`.
7005
+ *
7006
+ * @param input - The alert definition
7007
+ * @returns The created alert definition
7008
+ *
7009
+ * @example
7010
+ * ```ts
7011
+ * const alert = await client.alerts.create({
7012
+ * savedQueryId: 'query-uuid',
7013
+ * name: 'Failed payments spiked',
7014
+ * cronExpression: '0 * * * *',
7015
+ * condition: { kind: 'rowCount', op: 'gt', value: 10 },
7016
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
7017
+ * variables: { status: 'failed' },
7018
+ * });
7019
+ * ```
7020
+ */
7021
+ create(input) {
7022
+ const path = getAlertDefinitionsApiPath(this.workspaceId);
7023
+ return this.requestFn("POST", path, input);
7024
+ }
7025
+ /**
7026
+ * Update an alert definition. Only the fields you pass are changed.
7027
+ *
7028
+ * Toggling `enabled`, or changing `cronExpression` / `timezone`,
7029
+ * reschedules the underlying job. A concurrent update to those fields
7030
+ * fails with 409 — refetch and retry rather than replaying the request.
7031
+ *
7032
+ * @param alertId - The alert UUID
7033
+ * @param input - Fields to change
7034
+ * @returns The updated alert definition
7035
+ *
7036
+ * @example
7037
+ * ```ts
7038
+ * // Pause an alert
7039
+ * await client.alerts.update('alert-uuid', { enabled: false });
7040
+ *
7041
+ * // Move it to hourly
7042
+ * await client.alerts.update('alert-uuid', { cronExpression: '0 * * * *' });
7043
+ * ```
7044
+ */
7045
+ update(alertId, input) {
7046
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
7047
+ return this.requestFn("PATCH", path, input);
7048
+ }
7049
+ /**
7050
+ * Delete an alert definition and unschedule its job.
7051
+ *
7052
+ * @param alertId - The alert UUID
7053
+ * @returns Confirmation message
7054
+ *
7055
+ * @example
7056
+ * ```ts
7057
+ * await client.alerts.delete('alert-uuid');
7058
+ * ```
7059
+ */
7060
+ delete(alertId) {
7061
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
7062
+ return this.requestFn("DELETE", path);
7063
+ }
7064
+ };
7065
+
6945
7066
  // src/managers/validation.ts
6946
7067
  var ValidationManager = class {
6947
7068
  constructor(workspaceId, requestFn) {
@@ -8201,6 +8322,7 @@ var CentraliSDK = class {
8201
8322
  this._smartQueries = null;
8202
8323
  this._queryRecordsLegacyWarned = false;
8203
8324
  this._anomalyInsights = null;
8325
+ this._alerts = null;
8204
8326
  this._validation = null;
8205
8327
  this._orchestrations = null;
8206
8328
  this._allowedDomains = null;
@@ -8534,6 +8656,36 @@ var CentraliSDK = class {
8534
8656
  }
8535
8657
  return this._smartQueriesAlias;
8536
8658
  }
8659
+ /**
8660
+ * Alerts namespace for scheduled alerts on saved queries.
8661
+ *
8662
+ * Usage:
8663
+ * ```ts
8664
+ * // Alert when a saved query returns nothing, weekdays at 9am
8665
+ * const alert = await client.alerts.create({
8666
+ * savedQueryId: 'query-uuid',
8667
+ * name: 'No open orders',
8668
+ * cronExpression: '0 9 * * 1-5',
8669
+ * condition: { kind: 'rowCount', op: 'eq', value: 0 },
8670
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
8671
+ * });
8672
+ *
8673
+ * // List alerts on one saved query
8674
+ * const alerts = await client.alerts.list({ savedQueryId: 'query-uuid' });
8675
+ *
8676
+ * // Pause without deleting
8677
+ * await client.alerts.update(alert.data.id, { enabled: false });
8678
+ * ```
8679
+ */
8680
+ get alerts() {
8681
+ if (!this._alerts) {
8682
+ this._alerts = new AlertDefinitionsManager(
8683
+ this.options.workspaceId,
8684
+ this.request.bind(this)
8685
+ );
8686
+ }
8687
+ return this._alerts;
8688
+ }
8537
8689
  /**
8538
8690
  * Anomaly Insights namespace for querying and managing AI-generated insights.
8539
8691
  *
@@ -9435,6 +9587,7 @@ var CentraliSDK = class {
9435
9587
  };
9436
9588
  // Annotate the CommonJS export names for ESM import in node:
9437
9589
  0 && (module.exports = {
9590
+ AlertDefinitionsManager,
9438
9591
  AllowedDomainsManager,
9439
9592
  AnomalyInsightsManager,
9440
9593
  AuditLogManager,
@@ -9463,6 +9616,8 @@ var CentraliSDK = class {
9463
9616
  ValidationManager,
9464
9617
  WebhookSubscriptionsManager,
9465
9618
  fetchClientToken,
9619
+ getAlertDefinitionByIdApiPath,
9620
+ getAlertDefinitionsApiPath,
9466
9621
  getAllowedDomainsApiPath,
9467
9622
  getAnomalyAnalysisTriggerApiPath,
9468
9623
  getAnomalyInsightAcknowledgeApiPath,
package/index.ts CHANGED
@@ -29,6 +29,7 @@ export * from './src/types/structures';
29
29
  export * from './src/types/compute';
30
30
  export * from './src/types/search';
31
31
  export * from './src/types/insights';
32
+ export * from './src/types/alertDefinitions';
32
33
  export * from './src/types/validation';
33
34
  export * from './src/types/webhooks';
34
35
  export * from './src/types/allowedDomains';
@@ -44,6 +45,7 @@ export { RecordsManager } from './src/managers/records';
44
45
  export { AuditLogManager } from './src/managers/auditLog';
45
46
  export { SmartQueriesManager } from './src/managers/smartQueries';
46
47
  export { AnomalyInsightsManager } from './src/managers/anomalyInsights';
48
+ export { AlertDefinitionsManager } from './src/managers/alertDefinitions';
47
49
  export { ValidationManager } from './src/managers/validation';
48
50
  export { AllowedDomainsManager } from './src/managers/allowedDomains';
49
51
  export { StructuresManager } from './src/managers/structures';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centrali-io/centrali-sdk",
3
- "version": "6.16.2",
3
+ "version": "7.0.0",
4
4
  "description": "Centrali Node SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/client.ts CHANGED
@@ -26,6 +26,7 @@ import { RecordsManager } from './managers/records';
26
26
  import { AuditLogManager } from './managers/auditLog';
27
27
  import { SmartQueriesManager } from './managers/smartQueries';
28
28
  import { AnomalyInsightsManager } from './managers/anomalyInsights';
29
+ import { AlertDefinitionsManager } from './managers/alertDefinitions';
29
30
  import { ValidationManager } from './managers/validation';
30
31
  import { AllowedDomainsManager } from './managers/allowedDomains';
31
32
  import { StructuresManager } from './managers/structures';
@@ -49,6 +50,7 @@ export class CentraliSDK {
49
50
  private _smartQueries: SmartQueriesManager | null = null;
50
51
  private _queryRecordsLegacyWarned: boolean = false;
51
52
  private _anomalyInsights: AnomalyInsightsManager | null = null;
53
+ private _alerts: AlertDefinitionsManager | null = null;
52
54
  private _validation: ValidationManager | null = null;
53
55
  private _orchestrations: OrchestrationsManager | null = null;
54
56
  private _allowedDomains: AllowedDomainsManager | null = null;
@@ -425,6 +427,37 @@ export class CentraliSDK {
425
427
  }
426
428
  private _smartQueriesAlias?: SmartQueriesManager;
427
429
 
430
+ /**
431
+ * Alerts namespace for scheduled alerts on saved queries.
432
+ *
433
+ * Usage:
434
+ * ```ts
435
+ * // Alert when a saved query returns nothing, weekdays at 9am
436
+ * const alert = await client.alerts.create({
437
+ * savedQueryId: 'query-uuid',
438
+ * name: 'No open orders',
439
+ * cronExpression: '0 9 * * 1-5',
440
+ * condition: { kind: 'rowCount', op: 'eq', value: 0 },
441
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
442
+ * });
443
+ *
444
+ * // List alerts on one saved query
445
+ * const alerts = await client.alerts.list({ savedQueryId: 'query-uuid' });
446
+ *
447
+ * // Pause without deleting
448
+ * await client.alerts.update(alert.data.id, { enabled: false });
449
+ * ```
450
+ */
451
+ public get alerts(): AlertDefinitionsManager {
452
+ if (!this._alerts) {
453
+ this._alerts = new AlertDefinitionsManager(
454
+ this.options.workspaceId,
455
+ this.request.bind(this)
456
+ );
457
+ }
458
+ return this._alerts;
459
+ }
460
+
428
461
  /**
429
462
  * Anomaly Insights namespace for querying and managing AI-generated insights.
430
463
  *
@@ -113,6 +113,18 @@ export function getSavedQueryCanonicalTestPath(workspaceId: string): string {
113
113
  return `data/workspace/${workspaceId}/api/v1/saved-queries/test`;
114
114
  }
115
115
 
116
+ /**
117
+ * Saved-query alert definition paths (CEN-1123). Workspace-scoped, not
118
+ * nested under a saved query — an alert references its query by id, and the
119
+ * list endpoint filters on `savedQueryId` as a query param.
120
+ */
121
+ export function getAlertDefinitionsApiPath(workspaceId: string): string {
122
+ return `data/workspace/${workspaceId}/api/v1/alert-definitions`;
123
+ }
124
+ export function getAlertDefinitionByIdApiPath(workspaceId: string, alertId: string): string {
125
+ return `data/workspace/${workspaceId}/api/v1/alert-definitions/${alertId}`;
126
+ }
127
+
116
128
  /**
117
129
  * Generate Search API URL PATH.
118
130
  */
@@ -0,0 +1,172 @@
1
+ // =====================================================
2
+ // Alert Definitions Manager
3
+ // =====================================================
4
+
5
+ import type { Method } from 'axios';
6
+ import type { ApiResponse } from '../types/common';
7
+ import type {
8
+ AlertDefinition,
9
+ CreateAlertDefinitionInput,
10
+ UpdateAlertDefinitionInput,
11
+ ListAlertDefinitionsOptions,
12
+ } from '../types/alertDefinitions';
13
+ import {
14
+ getAlertDefinitionsApiPath,
15
+ getAlertDefinitionByIdApiPath,
16
+ } from '../internal/paths';
17
+
18
+ /**
19
+ * AlertDefinitionsManager — scheduled alerts on saved queries. Access via
20
+ * `client.alerts`.
21
+ *
22
+ * Each alert runs its saved query on a cron, checks the result against a
23
+ * condition, and on a match notifies its recipients by email and in-app
24
+ * inbox. Evaluation happens server-side on the schedule; nothing in this
25
+ * manager runs a query directly (use `client.savedQueries.execute()` for
26
+ * that).
27
+ *
28
+ * Authorization mirrors the console: managing alerts requires the
29
+ * `alert-definitions` permissions AND `execute` on the saved query the
30
+ * alert points at — creating an alert must not become a way to schedule
31
+ * recurring runs of a query you can't run yourself.
32
+ *
33
+ * Usage:
34
+ * ```ts
35
+ * // Alert when a saved query stops returning rows, each weekday at 9am
36
+ * const alert = await client.alerts.create({
37
+ * savedQueryId: 'query-uuid',
38
+ * name: 'No open orders',
39
+ * cronExpression: '0 9 * * 1-5',
40
+ * timezone: 'Europe/London',
41
+ * condition: { kind: 'rowCount', op: 'eq', value: 0 },
42
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
43
+ * });
44
+ *
45
+ * // Alerts attached to one saved query
46
+ * const alerts = await client.alerts.list({ savedQueryId: 'query-uuid' });
47
+ *
48
+ * // Pause it without losing the definition
49
+ * await client.alerts.update(alert.data.id, { enabled: false });
50
+ * ```
51
+ */
52
+ export class AlertDefinitionsManager {
53
+ private requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>;
54
+ private workspaceId: string;
55
+
56
+ constructor(
57
+ workspaceId: string,
58
+ requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>
59
+ ) {
60
+ this.workspaceId = workspaceId;
61
+ this.requestFn = requestFn;
62
+ }
63
+
64
+ /**
65
+ * List alert definitions in the workspace.
66
+ *
67
+ * Alerts whose saved query the caller can't read are omitted rather
68
+ * than failing the request — `lastRowCount` and `lastTriggeredAt` are
69
+ * observations about that query's data, so the list is filtered to the
70
+ * queries you're allowed to see.
71
+ *
72
+ * @param options - Optional filters
73
+ * @returns The alert definitions
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * const all = await client.alerts.list();
78
+ * const forQuery = await client.alerts.list({ savedQueryId: 'query-uuid' });
79
+ * ```
80
+ */
81
+ public list(options?: ListAlertDefinitionsOptions): Promise<ApiResponse<AlertDefinition[]>> {
82
+ const path = getAlertDefinitionsApiPath(this.workspaceId);
83
+ return this.requestFn<AlertDefinition[]>('GET', path, null, options);
84
+ }
85
+
86
+ /**
87
+ * Get a single alert definition by ID.
88
+ *
89
+ * @param alertId - The alert UUID
90
+ * @returns The alert definition
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * const alert = await client.alerts.get('alert-uuid');
95
+ * console.log('Last fired:', alert.data.lastTriggeredAt);
96
+ * ```
97
+ */
98
+ public get(alertId: string): Promise<ApiResponse<AlertDefinition>> {
99
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
100
+ return this.requestFn<AlertDefinition>('GET', path);
101
+ }
102
+
103
+ /**
104
+ * Create an alert definition. Unless `enabled` is false, the alert is
105
+ * scheduled immediately.
106
+ *
107
+ * If the saved query takes parameters, bind them via `variables` — the
108
+ * server rejects a set that would leave a referenced placeholder
109
+ * unbound, because such an alert runs clean and never fires. See
110
+ * `CreateAlertDefinitionInput.variables`.
111
+ *
112
+ * @param input - The alert definition
113
+ * @returns The created alert definition
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const alert = await client.alerts.create({
118
+ * savedQueryId: 'query-uuid',
119
+ * name: 'Failed payments spiked',
120
+ * cronExpression: '0 * * * *',
121
+ * condition: { kind: 'rowCount', op: 'gt', value: 10 },
122
+ * recipients: [{ type: 'user', id: 'user-uuid' }],
123
+ * variables: { status: 'failed' },
124
+ * });
125
+ * ```
126
+ */
127
+ public create(input: CreateAlertDefinitionInput): Promise<ApiResponse<AlertDefinition>> {
128
+ const path = getAlertDefinitionsApiPath(this.workspaceId);
129
+ return this.requestFn<AlertDefinition>('POST', path, input);
130
+ }
131
+
132
+ /**
133
+ * Update an alert definition. Only the fields you pass are changed.
134
+ *
135
+ * Toggling `enabled`, or changing `cronExpression` / `timezone`,
136
+ * reschedules the underlying job. A concurrent update to those fields
137
+ * fails with 409 — refetch and retry rather than replaying the request.
138
+ *
139
+ * @param alertId - The alert UUID
140
+ * @param input - Fields to change
141
+ * @returns The updated alert definition
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * // Pause an alert
146
+ * await client.alerts.update('alert-uuid', { enabled: false });
147
+ *
148
+ * // Move it to hourly
149
+ * await client.alerts.update('alert-uuid', { cronExpression: '0 * * * *' });
150
+ * ```
151
+ */
152
+ public update(alertId: string, input: UpdateAlertDefinitionInput): Promise<ApiResponse<AlertDefinition>> {
153
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
154
+ return this.requestFn<AlertDefinition>('PATCH', path, input);
155
+ }
156
+
157
+ /**
158
+ * Delete an alert definition and unschedule its job.
159
+ *
160
+ * @param alertId - The alert UUID
161
+ * @returns Confirmation message
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * await client.alerts.delete('alert-uuid');
166
+ * ```
167
+ */
168
+ public delete(alertId: string): Promise<ApiResponse<{ message: string }>> {
169
+ const path = getAlertDefinitionByIdApiPath(this.workspaceId, alertId);
170
+ return this.requestFn<{ message: string }>('DELETE', path);
171
+ }
172
+ }
@@ -0,0 +1,143 @@
1
+ // =====================================================
2
+ // Alert Definition Types (`client.alerts`)
3
+ // =====================================================
4
+ //
5
+ // Saved-query alerts (CEN-1123): "notify these people when this saved query
6
+ // returns more than 0 rows at 9am every weekday", without writing compute
7
+ // code. The data service schedules each enabled alert through the Go
8
+ // scheduler, evaluates it on the cron tick, and publishes
9
+ // `alerts.saved-query.triggered` for the notification framework to deliver.
10
+
11
+ /** Comparison operators available to a `rowCount` condition. */
12
+ export type AlertComparisonOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte';
13
+
14
+ /**
15
+ * What makes an alert fire. v1 ships two kinds; `aggregate` is deferred
16
+ * until composable aggregations land on saved-query definitions.
17
+ *
18
+ * - `rowCount` — compare the execution's row count against a fixed value.
19
+ * - `rowsChanged` — fire whenever the row count differs from the previous
20
+ * evaluation. The first evaluation only seeds the baseline and never
21
+ * fires, since there is nothing to compare against yet.
22
+ */
23
+ export type AlertCondition =
24
+ | { kind: 'rowCount'; op: AlertComparisonOp; value: number }
25
+ | { kind: 'rowsChanged' };
26
+
27
+ /** Who gets notified. Recipients are explicit per-alert, not subscribers. */
28
+ export interface AlertRecipient {
29
+ type: 'user';
30
+ /** The recipient's user ID. */
31
+ id: string;
32
+ }
33
+
34
+ /**
35
+ * A stored alert definition.
36
+ */
37
+ export interface AlertDefinition {
38
+ /** Unique identifier (UUID) */
39
+ id: string;
40
+ /** Workspace slug the alert belongs to */
41
+ workspaceSlug: string;
42
+ /** The saved query this alert evaluates */
43
+ savedQueryId: string;
44
+ /** Human-readable name, used as the notification subject */
45
+ name: string;
46
+ /** Optional description */
47
+ description: string | null;
48
+ /**
49
+ * Values bound to the saved query's `${var}` placeholders on every
50
+ * scheduled evaluation. See `CreateAlertDefinitionInput.variables` for
51
+ * why an incomplete map is rejected at authoring time.
52
+ */
53
+ variables: Record<string, unknown>;
54
+ /** Cron expression driving evaluation */
55
+ cronExpression: string;
56
+ /** IANA timezone the cron is interpreted in */
57
+ timezone: string;
58
+ /** The trigger condition */
59
+ condition: AlertCondition;
60
+ /** Explicit notification recipients */
61
+ recipients: AlertRecipient[];
62
+ /** Disabled alerts keep their definition but are unscheduled */
63
+ enabled: boolean;
64
+ /** Underlying scheduler job ID; null when disabled */
65
+ schedulerJobId: string | null;
66
+ /** Row count seen on the last evaluation — the `rowsChanged` baseline */
67
+ lastRowCount: number | null;
68
+ /** ISO timestamp of the last evaluation, triggered or not */
69
+ lastEvaluatedAt: string | null;
70
+ /** ISO timestamp of the last evaluation that fired */
71
+ lastTriggeredAt: string | null;
72
+ /** User ID who created the alert */
73
+ createdBy: string;
74
+ /** ISO timestamp of creation */
75
+ createdAt: string;
76
+ /** ISO timestamp of last update */
77
+ updatedAt: string;
78
+ }
79
+
80
+ /**
81
+ * Body for `client.alerts.create()`.
82
+ */
83
+ export interface CreateAlertDefinitionInput {
84
+ /** The saved query to evaluate. Must live in the same workspace. */
85
+ savedQueryId: string;
86
+ /** Display name, max 255 characters */
87
+ name: string;
88
+ /** Optional description, max 2000 characters */
89
+ description?: string | null;
90
+ /**
91
+ * Values for the saved query's `${var}` placeholders.
92
+ *
93
+ * The server rejects a set that won't bind cleanly, and the rule is
94
+ * stricter than the saved query's own execute-time validation: a
95
+ * declaration the query body REFERENCES with no `default` must be
96
+ * supplied here, whether or not it is marked `required`. An unbound
97
+ * reference is accepted at execute time and left in the body verbatim,
98
+ * so the alert would quietly filter on the literal `"${name}"`, match
99
+ * nothing, and never fire — with no error to notice. Declarations the
100
+ * body never references may be omitted.
101
+ */
102
+ variables?: Record<string, unknown>;
103
+ /** Cron expression, e.g. `"0 9 * * 1-5"` */
104
+ cronExpression: string;
105
+ /** IANA timezone; defaults to `"UTC"` */
106
+ timezone?: string;
107
+ /** The trigger condition */
108
+ condition: AlertCondition;
109
+ /** At least one recipient is required */
110
+ recipients: AlertRecipient[];
111
+ /** Defaults to true — an enabled alert is scheduled immediately */
112
+ enabled?: boolean;
113
+ }
114
+
115
+ /**
116
+ * Body for `client.alerts.update()`. At least one field must be present.
117
+ * `savedQueryId` is immutable — point an alert at a different query by
118
+ * creating a new one.
119
+ */
120
+ export interface UpdateAlertDefinitionInput {
121
+ name?: string;
122
+ /** Pass `null` to clear the description; omit to leave it unchanged. */
123
+ description?: string | null;
124
+ /**
125
+ * Replaces the stored bindings wholesale. Validated on submission under
126
+ * the same rule as create — see `CreateAlertDefinitionInput.variables`.
127
+ * Omit to leave the existing bindings untouched.
128
+ */
129
+ variables?: Record<string, unknown>;
130
+ /** Changing this (or `timezone`) reschedules the underlying job. */
131
+ cronExpression?: string;
132
+ timezone?: string;
133
+ condition?: AlertCondition;
134
+ recipients?: AlertRecipient[];
135
+ /** Toggling this schedules or unschedules the underlying job. */
136
+ enabled?: boolean;
137
+ }
138
+
139
+ /** Filters for `client.alerts.list()`. */
140
+ export interface ListAlertDefinitionsOptions {
141
+ /** Only return alerts attached to this saved query. */
142
+ savedQueryId?: string;
143
+ }