@lucern/sdk 0.2.0-alpha.5 → 0.2.0-alpha.7
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/.turbo/turbo-build.log +7 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/CHANGELOG.md +13 -0
- package/examples/README.md +69 -0
- package/examples/contradiction.ts +94 -0
- package/examples/investigation-context.ts +118 -0
- package/examples/questions-and-tasks.ts +55 -0
- package/examples/quickstart.ts +97 -0
- package/examples/shared.ts +318 -0
- package/examples/strict-public-types.ts +143 -0
- package/examples/worktree-lifecycle.ts +79 -0
- package/package.json +16 -59
- package/src/README.md +6 -0
- package/src/adminClient.ts +789 -0
- package/{dist/lib/platform/sdk/answersClient.d.ts → src/answersClient.ts} +17 -4
- package/src/audiencesClient.ts +209 -0
- package/src/auditClient.ts +50 -0
- package/src/beliefsClient.ts +319 -0
- package/src/client.ts +2647 -0
- package/src/contextClient.ts +130 -0
- package/src/contextFacade.ts +15 -0
- package/src/contextPackCompiler.ts +828 -0
- package/src/contextPackSchema.ts +251 -0
- package/src/contextTypes.ts +153 -0
- package/src/contracts/api-enums.contract.ts +202 -0
- package/src/contracts/auth-session.contract.ts +109 -0
- package/src/contracts/context-pack.contract.ts +700 -0
- package/src/contracts/contextPack.ts +1 -0
- package/src/contracts/index.ts +10 -0
- package/src/contracts/lens-filter.contract.ts +183 -0
- package/src/contracts/lens-workflow.contract.ts +162 -0
- package/src/contracts/lensFilter.ts +1 -0
- package/src/contracts/lensWorkflow.ts +1 -0
- package/src/contracts/mcp-tools.contract.ts +3636 -0
- package/src/contracts/mcpTools.ts +1 -0
- package/src/contracts/prompt.contract.ts +50 -0
- package/src/contracts/prompt.ts +1 -0
- package/src/contracts/sdk-tools.contract.ts +1457 -0
- package/src/contracts/sdkTools.ts +1 -0
- package/src/contracts/workflow-runtime.contract.ts +440 -0
- package/src/contracts/workflowRuntime.ts +1 -0
- package/src/controlObjectOwnership.ts +286 -0
- package/src/coreClient.ts +570 -0
- package/src/customTools.ts +398 -0
- package/src/decisionsClient.ts +286 -0
- package/src/domainContext.ts +15 -0
- package/src/events.ts +531 -0
- package/src/eventsCore.ts +168 -0
- package/src/facade/beliefs.ts +83 -0
- package/src/facade/context.ts +110 -0
- package/src/facade/contradictions.ts +29 -0
- package/src/facade/edges.ts +30 -0
- package/src/facade/events.ts +23 -0
- package/src/facade/evidence.ts +41 -0
- package/src/facade/graph.ts +38 -0
- package/src/facade/identity.ts +16 -0
- package/src/facade/ontologies.ts +34 -0
- package/src/facade/questions.ts +59 -0
- package/src/facade/search.ts +16 -0
- package/src/facade/tasks.ts +37 -0
- package/src/facade/topics.ts +42 -0
- package/src/facade/webhooks.ts +58 -0
- package/src/facade/worktrees.ts +51 -0
- package/src/gatewayFacades.ts +1666 -0
- package/src/graphClient.ts +529 -0
- package/src/harnessClient.ts +585 -0
- package/src/identityClient.ts +278 -0
- package/{dist/lib/platform/sdk/index.d.ts → src/index.ts} +3 -0
- package/src/learningClient.ts +95 -0
- package/src/mcpParityClient.ts +240 -0
- package/src/mcpParitySurface.ts +70 -0
- package/src/ontologyClient.ts +275 -0
- package/src/packRuntime.ts +3 -0
- package/src/packsClient.ts +260 -0
- package/src/policyClient.ts +572 -0
- package/src/promptCatalog.ts +1 -0
- package/src/realtime/index.ts +51 -0
- package/src/realtime/refs.ts +17 -0
- package/src/reportsClient.ts +99 -0
- package/src/schemaClient.ts +129 -0
- package/src/sdkSurface.ts +190 -0
- package/src/topicsClient.ts +243 -0
- package/src/types.ts +807 -0
- package/src/workflowClient.ts +826 -0
- package/tsconfig.json +9 -0
- package/dist/.generated +0 -2
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -3
- package/dist/lib/platform/auth/credentials.d.ts +0 -5
- package/dist/lib/platform/auth/credentials.js +0 -40
- package/dist/lib/platform/sdk/adminClient.d.ts +0 -404
- package/dist/lib/platform/sdk/adminClient.js +0 -384
- package/dist/lib/platform/sdk/answersClient.js +0 -21
- package/dist/lib/platform/sdk/audiencesClient.d.ts +0 -93
- package/dist/lib/platform/sdk/audiencesClient.js +0 -111
- package/dist/lib/platform/sdk/auditClient.d.ts +0 -24
- package/dist/lib/platform/sdk/auditClient.js +0 -21
- package/dist/lib/platform/sdk/beliefsClient.d.ts +0 -157
- package/dist/lib/platform/sdk/beliefsClient.js +0 -124
- package/dist/lib/platform/sdk/client.d.ts +0 -2369
- package/dist/lib/platform/sdk/client.js +0 -1831
- package/dist/lib/platform/sdk/contextClient.d.ts +0 -21
- package/dist/lib/platform/sdk/contextClient.js +0 -86
- package/dist/lib/platform/sdk/contextPackCompiler.d.ts +0 -100
- package/dist/lib/platform/sdk/contextPackCompiler.js +0 -534
- package/dist/lib/platform/sdk/contextTypes.d.ts +0 -133
- package/dist/lib/platform/sdk/contextTypes.js +0 -1
- package/dist/lib/platform/sdk/controlObjectOwnership.d.ts +0 -308
- package/dist/lib/platform/sdk/controlObjectOwnership.js +0 -220
- package/dist/lib/platform/sdk/coreClient.d.ts +0 -139
- package/dist/lib/platform/sdk/coreClient.js +0 -366
- package/dist/lib/platform/sdk/customTools.d.ts +0 -83
- package/dist/lib/platform/sdk/customTools.js +0 -247
- package/dist/lib/platform/sdk/decisionsClient.d.ts +0 -106
- package/dist/lib/platform/sdk/decisionsClient.js +0 -129
- package/dist/lib/platform/sdk/domainContext.d.ts +0 -1
- package/dist/lib/platform/sdk/domainContext.js +0 -1
- package/dist/lib/platform/sdk/events.d.ts +0 -176
- package/dist/lib/platform/sdk/events.js +0 -261
- package/dist/lib/platform/sdk/gatewayFacades.d.ts +0 -586
- package/dist/lib/platform/sdk/gatewayFacades.js +0 -845
- package/dist/lib/platform/sdk/graphClient.d.ts +0 -266
- package/dist/lib/platform/sdk/graphClient.js +0 -235
- package/dist/lib/platform/sdk/harnessClient.d.ts +0 -309
- package/dist/lib/platform/sdk/harnessClient.js +0 -219
- package/dist/lib/platform/sdk/identityClient.d.ts +0 -134
- package/dist/lib/platform/sdk/identityClient.js +0 -131
- package/dist/lib/platform/sdk/index.js +0 -46
- package/dist/lib/platform/sdk/learningClient.d.ts +0 -40
- package/dist/lib/platform/sdk/learningClient.js +0 -53
- package/dist/lib/platform/sdk/mcpParityClient.d.ts +0 -69
- package/dist/lib/platform/sdk/mcpParityClient.js +0 -196
- package/dist/lib/platform/sdk/mcpParitySurface.d.ts +0 -10
- package/dist/lib/platform/sdk/mcpParitySurface.js +0 -57
- package/dist/lib/platform/sdk/ontologyClient.d.ts +0 -131
- package/dist/lib/platform/sdk/ontologyClient.js +0 -161
- package/dist/lib/platform/sdk/packRuntime.d.ts +0 -1
- package/dist/lib/platform/sdk/packRuntime.js +0 -1
- package/dist/lib/platform/sdk/packsClient.d.ts +0 -126
- package/dist/lib/platform/sdk/packsClient.js +0 -157
- package/dist/lib/platform/sdk/policyClient.d.ts +0 -293
- package/dist/lib/platform/sdk/policyClient.js +0 -277
- package/dist/lib/platform/sdk/promptCatalog.d.ts +0 -1
- package/dist/lib/platform/sdk/promptCatalog.js +0 -1
- package/dist/lib/platform/sdk/reportsClient.d.ts +0 -34
- package/dist/lib/platform/sdk/reportsClient.js +0 -64
- package/dist/lib/platform/sdk/schemaClient.d.ts +0 -59
- package/dist/lib/platform/sdk/schemaClient.js +0 -71
- package/dist/lib/platform/sdk/sdkSurface.d.ts +0 -56
- package/dist/lib/platform/sdk/sdkSurface.js +0 -140
- package/dist/lib/platform/sdk/topicsClient.d.ts +0 -78
- package/dist/lib/platform/sdk/topicsClient.js +0 -118
- package/dist/lib/platform/sdk/types.d.ts +0 -692
- package/dist/lib/platform/sdk/types.js +0 -1
- package/dist/lib/platform/sdk/version.d.ts +0 -2
- package/dist/lib/platform/sdk/workflowClient.d.ts +0 -313
- package/dist/lib/platform/sdk/workflowClient.js +0 -366
- package/dist/lucern/contracts/src/api-enums.contract.d.ts +0 -58
- package/dist/lucern/contracts/src/api-enums.contract.js +0 -147
- package/dist/lucern/contracts/src/lens-filter.contract.d.ts +0 -70
- package/dist/lucern/contracts/src/lens-filter.contract.js +0 -95
- package/dist/lucern/contracts/src/lens-workflow.contract.d.ts +0 -84
- package/dist/lucern/contracts/src/lens-workflow.contract.js +0 -54
- package/dist/lucern/contracts/src/mcp-tools.contract.d.ts +0 -151
- package/dist/lucern/contracts/src/mcp-tools.contract.js +0 -3281
- /package/{dist/lib/platform/sdk/version.js → src/version.ts} +0 -0
package/src/events.ts
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
export const DOMAIN_EVENT_VERSION = "1.0" as const;
|
|
2
|
+
export const EVENT_RETENTION_DEFAULT_DAYS = 30;
|
|
3
|
+
export const WEBHOOK_MAX_ATTEMPTS = 5;
|
|
4
|
+
export const WEBHOOK_RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 300_000] as const;
|
|
5
|
+
|
|
6
|
+
export const DOMAIN_EVENT_TYPES = [
|
|
7
|
+
"belief.created",
|
|
8
|
+
"belief.forked",
|
|
9
|
+
"belief.confidence_updated",
|
|
10
|
+
"belief.archived",
|
|
11
|
+
"belief.refined",
|
|
12
|
+
"belief.contract_created",
|
|
13
|
+
"belief.contract_evaluated",
|
|
14
|
+
"belief.lineage_queried",
|
|
15
|
+
"evidence.created",
|
|
16
|
+
"evidence.linked",
|
|
17
|
+
"evidence.search_executed",
|
|
18
|
+
"question.created",
|
|
19
|
+
"question.answered",
|
|
20
|
+
"question.refined",
|
|
21
|
+
"question.status_updated",
|
|
22
|
+
"question.archived",
|
|
23
|
+
"edge.created",
|
|
24
|
+
"contradiction.flagged",
|
|
25
|
+
"worktree.created",
|
|
26
|
+
"worktree.activated",
|
|
27
|
+
"worktree.merged",
|
|
28
|
+
"worktree.targets_updated",
|
|
29
|
+
"worktree.metadata_updated",
|
|
30
|
+
"topic.created",
|
|
31
|
+
"topic.updated",
|
|
32
|
+
"topic.archived",
|
|
33
|
+
"task.created",
|
|
34
|
+
"task.completed",
|
|
35
|
+
"task.updated",
|
|
36
|
+
"ontology.bound",
|
|
37
|
+
"context.compiled",
|
|
38
|
+
"identity.key_created",
|
|
39
|
+
"identity.key_rotated",
|
|
40
|
+
"identity.key_revoked",
|
|
41
|
+
"webhook.test",
|
|
42
|
+
] as const;
|
|
43
|
+
|
|
44
|
+
export type DomainEventType = (typeof DOMAIN_EVENT_TYPES)[number];
|
|
45
|
+
|
|
46
|
+
export type DomainResourceType =
|
|
47
|
+
| "belief"
|
|
48
|
+
| "evidence"
|
|
49
|
+
| "question"
|
|
50
|
+
| "edge"
|
|
51
|
+
| "contradiction"
|
|
52
|
+
| "worktree"
|
|
53
|
+
| "topic"
|
|
54
|
+
| "task"
|
|
55
|
+
| "ontology"
|
|
56
|
+
| "context"
|
|
57
|
+
| "identity"
|
|
58
|
+
| "webhook";
|
|
59
|
+
|
|
60
|
+
export type DomainActorType = "human" | "agent" | "service";
|
|
61
|
+
export type DomainEventData = Record<string, unknown>;
|
|
62
|
+
|
|
63
|
+
export type DomainEvent = {
|
|
64
|
+
eventId: string;
|
|
65
|
+
type: DomainEventType | string;
|
|
66
|
+
version: typeof DOMAIN_EVENT_VERSION;
|
|
67
|
+
timestamp: number;
|
|
68
|
+
tenantId?: string;
|
|
69
|
+
workspaceId?: string;
|
|
70
|
+
topicId: string;
|
|
71
|
+
resourceId: string;
|
|
72
|
+
resourceType: DomainResourceType | string;
|
|
73
|
+
actorId: string;
|
|
74
|
+
actorType: DomainActorType;
|
|
75
|
+
data: DomainEventData;
|
|
76
|
+
correlationId?: string;
|
|
77
|
+
expiresAt: number;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export type CreateDomainEventInput = {
|
|
81
|
+
eventId?: string;
|
|
82
|
+
timestamp?: number;
|
|
83
|
+
tenantId?: string;
|
|
84
|
+
workspaceId?: string;
|
|
85
|
+
topicId: string;
|
|
86
|
+
type: DomainEventType | string;
|
|
87
|
+
resourceId: string;
|
|
88
|
+
resourceType: DomainResourceType | string;
|
|
89
|
+
actorId: string;
|
|
90
|
+
actorType: DomainActorType;
|
|
91
|
+
data?: DomainEventData;
|
|
92
|
+
correlationId?: string;
|
|
93
|
+
retentionDays?: number;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
export type EventCursor = {
|
|
97
|
+
timestamp: number;
|
|
98
|
+
eventId: string;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export type EventListQuery = {
|
|
102
|
+
topicId?: string;
|
|
103
|
+
after?: string;
|
|
104
|
+
types?: string[];
|
|
105
|
+
startTime?: number;
|
|
106
|
+
endTime?: number;
|
|
107
|
+
limit?: number;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export type EventListResult = {
|
|
111
|
+
events: DomainEvent[];
|
|
112
|
+
nextCursor: string | null;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type WebhookSecretMode = "configured";
|
|
116
|
+
|
|
117
|
+
export type WebhookRecord = {
|
|
118
|
+
id: string;
|
|
119
|
+
webhookId: string;
|
|
120
|
+
tenantId?: string;
|
|
121
|
+
workspaceId?: string;
|
|
122
|
+
topicId?: string;
|
|
123
|
+
url: string;
|
|
124
|
+
events: string[];
|
|
125
|
+
active: boolean;
|
|
126
|
+
secretConfigured: boolean;
|
|
127
|
+
createdAt: number;
|
|
128
|
+
updatedAt: number;
|
|
129
|
+
createdBy: string;
|
|
130
|
+
updatedBy: string;
|
|
131
|
+
lastDeliveryAt?: number;
|
|
132
|
+
lastSuccessfulDeliveryAt?: number;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export type WebhookCreateInput = {
|
|
136
|
+
url: string;
|
|
137
|
+
events: string[];
|
|
138
|
+
secret: string;
|
|
139
|
+
topicId?: string;
|
|
140
|
+
active?: boolean;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export type WebhookUpdateInput = {
|
|
144
|
+
url?: string;
|
|
145
|
+
events?: string[];
|
|
146
|
+
secret?: string;
|
|
147
|
+
topicId?: string | null;
|
|
148
|
+
active?: boolean;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export type WebhookDeliveryStatus =
|
|
152
|
+
| "pending"
|
|
153
|
+
| "delivering"
|
|
154
|
+
| "succeeded"
|
|
155
|
+
| "failed"
|
|
156
|
+
| "dead_letter";
|
|
157
|
+
|
|
158
|
+
export type WebhookDeliveryRecord = {
|
|
159
|
+
id: string;
|
|
160
|
+
deliveryId: string;
|
|
161
|
+
webhookId: string;
|
|
162
|
+
eventId: string;
|
|
163
|
+
eventType: string;
|
|
164
|
+
topicId: string;
|
|
165
|
+
status: WebhookDeliveryStatus;
|
|
166
|
+
attemptCount: number;
|
|
167
|
+
maxAttempts: number;
|
|
168
|
+
nextAttemptAt?: number;
|
|
169
|
+
lastAttemptAt?: number;
|
|
170
|
+
lastStatusCode?: number;
|
|
171
|
+
lastError?: string;
|
|
172
|
+
deliveredAt?: number;
|
|
173
|
+
createdAt: number;
|
|
174
|
+
updatedAt: number;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export type WebhookDeliveryAttemptRecord = {
|
|
178
|
+
id: string;
|
|
179
|
+
attemptId: string;
|
|
180
|
+
deliveryId: string;
|
|
181
|
+
webhookId: string;
|
|
182
|
+
eventId: string;
|
|
183
|
+
eventType: string;
|
|
184
|
+
attemptNumber: number;
|
|
185
|
+
status: "succeeded" | "failed";
|
|
186
|
+
statusCode?: number;
|
|
187
|
+
error?: string;
|
|
188
|
+
responseBody?: string;
|
|
189
|
+
durationMs?: number;
|
|
190
|
+
createdAt: number;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
export type WebhookDeliveriesResult = {
|
|
194
|
+
deliveries: Array<
|
|
195
|
+
WebhookDeliveryRecord & {
|
|
196
|
+
attempts?: WebhookDeliveryAttemptRecord[];
|
|
197
|
+
}
|
|
198
|
+
>;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export type WebhookHealthResult = {
|
|
202
|
+
webhookId: string;
|
|
203
|
+
totalAttempts: number;
|
|
204
|
+
successfulAttempts: number;
|
|
205
|
+
failedAttempts: number;
|
|
206
|
+
successRate: number;
|
|
207
|
+
pendingDeliveries: number;
|
|
208
|
+
deadLetterDeliveries: number;
|
|
209
|
+
lastDeliveryAt?: number;
|
|
210
|
+
lastSuccessfulDeliveryAt?: number;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export type WebhookTestResult = {
|
|
214
|
+
webhookId: string;
|
|
215
|
+
deliveryId: string;
|
|
216
|
+
status: WebhookDeliveryStatus;
|
|
217
|
+
attempts: number;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
export type ReplayEventsInput = EventListQuery & {
|
|
221
|
+
webhookId?: string;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
export type ReplayEventsResult = EventListResult & {
|
|
225
|
+
replayedDeliveries?: number;
|
|
226
|
+
replayedWebhookId?: string;
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
function escapeRegex(value: string): string {
|
|
230
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function eventPatternToRegExp(pattern: string): RegExp {
|
|
234
|
+
const normalized = pattern.trim();
|
|
235
|
+
if (!normalized) {
|
|
236
|
+
return /^$/;
|
|
237
|
+
}
|
|
238
|
+
if (normalized === "*") {
|
|
239
|
+
return /^.*$/;
|
|
240
|
+
}
|
|
241
|
+
const source = escapeRegex(normalized).replace(/\\\*/g, ".*");
|
|
242
|
+
return new RegExp(`^${source}$`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function matchesEventPattern(
|
|
246
|
+
eventType: string,
|
|
247
|
+
pattern: string
|
|
248
|
+
): boolean {
|
|
249
|
+
return eventPatternToRegExp(pattern).test(eventType.trim());
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function matchesAnyEventPattern(
|
|
253
|
+
eventType: string,
|
|
254
|
+
patterns: readonly string[]
|
|
255
|
+
): boolean {
|
|
256
|
+
if (patterns.length === 0) {
|
|
257
|
+
return true;
|
|
258
|
+
}
|
|
259
|
+
return patterns.some((pattern) => matchesEventPattern(eventType, pattern));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function toBase64(value: string): string {
|
|
263
|
+
if (typeof Buffer !== "undefined") {
|
|
264
|
+
return Buffer.from(value, "utf8").toString("base64url");
|
|
265
|
+
}
|
|
266
|
+
return btoa(unescape(encodeURIComponent(value)))
|
|
267
|
+
.replace(/\+/g, "-")
|
|
268
|
+
.replace(/\//g, "_")
|
|
269
|
+
.replace(/=+$/g, "");
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function fromBase64(value: string): string {
|
|
273
|
+
if (typeof Buffer !== "undefined") {
|
|
274
|
+
return Buffer.from(value, "base64url").toString("utf8");
|
|
275
|
+
}
|
|
276
|
+
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
277
|
+
return decodeURIComponent(escape(atob(normalized)));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function createEventId(): string {
|
|
281
|
+
const random =
|
|
282
|
+
typeof globalThis.crypto?.randomUUID === "function"
|
|
283
|
+
? globalThis.crypto.randomUUID().replace(/-/g, "")
|
|
284
|
+
: Array.from(
|
|
285
|
+
typeof globalThis.crypto?.getRandomValues === "function"
|
|
286
|
+
? globalThis.crypto.getRandomValues(new Uint8Array(16))
|
|
287
|
+
: Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)),
|
|
288
|
+
(value) => value.toString(16).padStart(2, "0")
|
|
289
|
+
).join("");
|
|
290
|
+
return `evt_${random}`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function normalizeRetentionDays(value: number | undefined): number {
|
|
294
|
+
if (!Number.isFinite(value) || typeof value !== "number" || value <= 0) {
|
|
295
|
+
return EVENT_RETENTION_DEFAULT_DAYS;
|
|
296
|
+
}
|
|
297
|
+
return Math.max(1, Math.trunc(value));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function buildDomainEvent(input: CreateDomainEventInput): DomainEvent {
|
|
301
|
+
const timestamp = input.timestamp ?? Date.now();
|
|
302
|
+
const retentionDays = normalizeRetentionDays(input.retentionDays);
|
|
303
|
+
return {
|
|
304
|
+
eventId: input.eventId?.trim() || createEventId(),
|
|
305
|
+
type: input.type.trim(),
|
|
306
|
+
version: DOMAIN_EVENT_VERSION,
|
|
307
|
+
timestamp,
|
|
308
|
+
tenantId: input.tenantId?.trim() || undefined,
|
|
309
|
+
workspaceId: input.workspaceId?.trim() || undefined,
|
|
310
|
+
topicId: input.topicId.trim(),
|
|
311
|
+
resourceId: input.resourceId.trim(),
|
|
312
|
+
resourceType: input.resourceType.trim(),
|
|
313
|
+
actorId: input.actorId.trim(),
|
|
314
|
+
actorType: input.actorType,
|
|
315
|
+
data: input.data ?? {},
|
|
316
|
+
correlationId: input.correlationId?.trim() || undefined,
|
|
317
|
+
expiresAt: timestamp + retentionDays * 24 * 60 * 60 * 1000,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function compareEventCursor(left: EventCursor, right: EventCursor): number {
|
|
322
|
+
if (left.timestamp !== right.timestamp) {
|
|
323
|
+
return left.timestamp - right.timestamp;
|
|
324
|
+
}
|
|
325
|
+
return left.eventId.localeCompare(right.eventId);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function encodeEventCursor(cursor: EventCursor): string {
|
|
329
|
+
return toBase64(JSON.stringify(cursor));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function decodeEventCursor(cursor: string | undefined): EventCursor | null {
|
|
333
|
+
if (!cursor || cursor.trim().length === 0) {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
const parsed = JSON.parse(fromBase64(cursor.trim())) as Partial<EventCursor>;
|
|
338
|
+
if (
|
|
339
|
+
typeof parsed.timestamp !== "number" ||
|
|
340
|
+
!Number.isFinite(parsed.timestamp) ||
|
|
341
|
+
typeof parsed.eventId !== "string" ||
|
|
342
|
+
parsed.eventId.trim().length === 0
|
|
343
|
+
) {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
return {
|
|
347
|
+
timestamp: parsed.timestamp,
|
|
348
|
+
eventId: parsed.eventId.trim(),
|
|
349
|
+
};
|
|
350
|
+
} catch {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function isAfterCursor(
|
|
356
|
+
event: Pick<DomainEvent, "timestamp" | "eventId">,
|
|
357
|
+
cursor: EventCursor | null
|
|
358
|
+
): boolean {
|
|
359
|
+
if (!cursor) {
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
362
|
+
return compareEventCursor(event, cursor) > 0;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export function sortEventsByCursor<T extends Pick<DomainEvent, "timestamp" | "eventId">>(
|
|
366
|
+
events: readonly T[]
|
|
367
|
+
): T[] {
|
|
368
|
+
return [...events].sort((left, right) => compareEventCursor(left, right));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function inferActorType(args: {
|
|
372
|
+
sessionType?: "agent" | "user";
|
|
373
|
+
authMode?: string;
|
|
374
|
+
principalType?: string;
|
|
375
|
+
}): DomainActorType {
|
|
376
|
+
if (args.sessionType === "agent") {
|
|
377
|
+
return "agent";
|
|
378
|
+
}
|
|
379
|
+
if (
|
|
380
|
+
args.authMode === "service_principal" ||
|
|
381
|
+
args.authMode === "tenant_api_key" ||
|
|
382
|
+
args.principalType === "service"
|
|
383
|
+
) {
|
|
384
|
+
return "service";
|
|
385
|
+
}
|
|
386
|
+
return "human";
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export async function emitDomainEvent(
|
|
390
|
+
invokeMutation: (reference: any, args: CreateDomainEventInput) => Promise<unknown>,
|
|
391
|
+
input: CreateDomainEventInput
|
|
392
|
+
): Promise<unknown> {
|
|
393
|
+
return await invokeMutation("events:recordEvent" as any, input);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const LOCALHOST_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
|
397
|
+
|
|
398
|
+
function normalizeUrl(url: string): URL {
|
|
399
|
+
try {
|
|
400
|
+
return new URL(url.trim());
|
|
401
|
+
} catch {
|
|
402
|
+
throw new Error("Webhook URL must be a valid absolute URL.");
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function assertValidWebhookUrl(url: string): string {
|
|
407
|
+
const parsed = normalizeUrl(url);
|
|
408
|
+
const hostname = parsed.hostname.trim().toLowerCase();
|
|
409
|
+
const nodeEnv =
|
|
410
|
+
typeof process !== "undefined" ? process.env?.NODE_ENV : undefined;
|
|
411
|
+
const allowLocalHttp =
|
|
412
|
+
nodeEnv === "test" || LOCALHOST_HOSTS.has(hostname);
|
|
413
|
+
|
|
414
|
+
if (parsed.protocol !== "https:" && !(allowLocalHttp && parsed.protocol === "http:")) {
|
|
415
|
+
throw new Error("Webhook URL must use HTTPS.");
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
return parsed.toString();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export function normalizeWebhookPatterns(patterns: readonly string[]): string[] {
|
|
422
|
+
const normalized = Array.from(
|
|
423
|
+
new Set(
|
|
424
|
+
patterns
|
|
425
|
+
.map((pattern) => pattern.trim())
|
|
426
|
+
.filter((pattern) => pattern.length > 0)
|
|
427
|
+
)
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
if (normalized.length === 0) {
|
|
431
|
+
throw new Error("At least one webhook event pattern is required.");
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
return normalized;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function assertValidWebhookSecret(secret: string): string {
|
|
438
|
+
const normalized = secret.trim();
|
|
439
|
+
if (normalized.length < 8) {
|
|
440
|
+
throw new Error("Webhook secret must be at least 8 characters.");
|
|
441
|
+
}
|
|
442
|
+
return normalized;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export async function computeWebhookSignature(
|
|
446
|
+
payload: string,
|
|
447
|
+
secret: string
|
|
448
|
+
): Promise<string> {
|
|
449
|
+
const encoder = new TextEncoder();
|
|
450
|
+
const key = await crypto.subtle.importKey(
|
|
451
|
+
"raw",
|
|
452
|
+
encoder.encode(secret),
|
|
453
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
454
|
+
false,
|
|
455
|
+
["sign"]
|
|
456
|
+
);
|
|
457
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
|
|
458
|
+
return Array.from(new Uint8Array(signature))
|
|
459
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
460
|
+
.join("");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export function nextDeliveryAttemptAt(
|
|
464
|
+
currentAttemptCount: number,
|
|
465
|
+
now = Date.now()
|
|
466
|
+
): number | undefined {
|
|
467
|
+
if (currentAttemptCount >= WEBHOOK_MAX_ATTEMPTS) {
|
|
468
|
+
return undefined;
|
|
469
|
+
}
|
|
470
|
+
const retryIndex = currentAttemptCount - 1;
|
|
471
|
+
const delay = WEBHOOK_RETRY_DELAYS_MS[retryIndex];
|
|
472
|
+
return typeof delay === "number" ? now + delay : undefined;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export function resolveDeliveryFailureStatus(
|
|
476
|
+
attemptCount: number
|
|
477
|
+
): WebhookDeliveryStatus {
|
|
478
|
+
return attemptCount >= WEBHOOK_MAX_ATTEMPTS ? "dead_letter" : "failed";
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export function sanitizeWebhookRecord(
|
|
482
|
+
value: Record<string, unknown>
|
|
483
|
+
): WebhookRecord {
|
|
484
|
+
return {
|
|
485
|
+
id: String(value.id ?? value.webhookId ?? value._id ?? ""),
|
|
486
|
+
webhookId: String(value.webhookId ?? value.id ?? value._id ?? ""),
|
|
487
|
+
tenantId:
|
|
488
|
+
typeof value.tenantId === "string" && value.tenantId.trim().length > 0
|
|
489
|
+
? value.tenantId
|
|
490
|
+
: undefined,
|
|
491
|
+
workspaceId:
|
|
492
|
+
typeof value.workspaceId === "string" && value.workspaceId.trim().length > 0
|
|
493
|
+
? value.workspaceId
|
|
494
|
+
: undefined,
|
|
495
|
+
topicId:
|
|
496
|
+
typeof value.topicId === "string" && value.topicId.trim().length > 0
|
|
497
|
+
? value.topicId
|
|
498
|
+
: undefined,
|
|
499
|
+
url: String(value.url ?? ""),
|
|
500
|
+
events: Array.isArray(value.events)
|
|
501
|
+
? value.events
|
|
502
|
+
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
|
503
|
+
.filter(Boolean)
|
|
504
|
+
: [],
|
|
505
|
+
active: value.active !== false,
|
|
506
|
+
secretConfigured: true,
|
|
507
|
+
createdAt: Number(value.createdAt ?? Date.now()),
|
|
508
|
+
updatedAt: Number(value.updatedAt ?? value.createdAt ?? Date.now()),
|
|
509
|
+
createdBy: String(value.createdBy ?? ""),
|
|
510
|
+
updatedBy: String(value.updatedBy ?? value.createdBy ?? ""),
|
|
511
|
+
lastDeliveryAt:
|
|
512
|
+
typeof value.lastDeliveryAt === "number" ? value.lastDeliveryAt : undefined,
|
|
513
|
+
lastSuccessfulDeliveryAt:
|
|
514
|
+
typeof value.lastSuccessfulDeliveryAt === "number"
|
|
515
|
+
? value.lastSuccessfulDeliveryAt
|
|
516
|
+
: undefined,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
export function truncateWebhookResponseBody(
|
|
521
|
+
responseBody: string | undefined,
|
|
522
|
+
maxLength = 2_000
|
|
523
|
+
): string | undefined {
|
|
524
|
+
if (!responseBody) {
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
if (responseBody.length <= maxLength) {
|
|
528
|
+
return responseBody;
|
|
529
|
+
}
|
|
530
|
+
return `${responseBody.slice(0, maxLength - 3)}...`;
|
|
531
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createGatewayRequestClient,
|
|
3
|
+
randomIdempotencyKey,
|
|
4
|
+
toQueryString,
|
|
5
|
+
type GatewayClientConfig,
|
|
6
|
+
type PlatformGatewaySuccess,
|
|
7
|
+
} from "./coreClient";
|
|
8
|
+
import type {
|
|
9
|
+
EventListQuery,
|
|
10
|
+
EventListResult,
|
|
11
|
+
ReplayEventsInput,
|
|
12
|
+
ReplayEventsResult,
|
|
13
|
+
WebhookCreateInput,
|
|
14
|
+
WebhookDeliveriesResult,
|
|
15
|
+
WebhookHealthResult,
|
|
16
|
+
WebhookRecord,
|
|
17
|
+
WebhookTestResult,
|
|
18
|
+
WebhookUpdateInput,
|
|
19
|
+
} from "./events";
|
|
20
|
+
import type { JsonObject } from "./types";
|
|
21
|
+
|
|
22
|
+
export type EventsClientCoreConfig = GatewayClientConfig;
|
|
23
|
+
export type EventsListResponse = PlatformGatewaySuccess<EventListResult>;
|
|
24
|
+
export type EventsReplayResponse = PlatformGatewaySuccess<ReplayEventsResult>;
|
|
25
|
+
|
|
26
|
+
export type WebhooksClientCoreConfig = GatewayClientConfig;
|
|
27
|
+
export type WebhookListQuery = {
|
|
28
|
+
topicId?: string;
|
|
29
|
+
};
|
|
30
|
+
export type WebhookDeliveriesQuery = {
|
|
31
|
+
limit?: number;
|
|
32
|
+
};
|
|
33
|
+
export type WebhookDeleteResult = {
|
|
34
|
+
webhookId: string;
|
|
35
|
+
deleted: boolean;
|
|
36
|
+
};
|
|
37
|
+
export type WebhooksCreateResponse = PlatformGatewaySuccess<WebhookRecord>;
|
|
38
|
+
export type WebhooksListResponse = PlatformGatewaySuccess<{ webhooks: WebhookRecord[] }>;
|
|
39
|
+
export type WebhooksGetResponse = PlatformGatewaySuccess<WebhookRecord>;
|
|
40
|
+
export type WebhooksUpdateResponse = PlatformGatewaySuccess<WebhookRecord>;
|
|
41
|
+
export type WebhooksDeleteResponse = PlatformGatewaySuccess<WebhookDeleteResult>;
|
|
42
|
+
export type WebhooksTestResponse = PlatformGatewaySuccess<WebhookTestResult>;
|
|
43
|
+
export type WebhooksDeliveriesResponse =
|
|
44
|
+
PlatformGatewaySuccess<WebhookDeliveriesResult>;
|
|
45
|
+
export type WebhooksHealthResponse = PlatformGatewaySuccess<WebhookHealthResult>;
|
|
46
|
+
|
|
47
|
+
function serializeTypes(types: string[] | undefined) {
|
|
48
|
+
return Array.isArray(types) && types.length > 0 ? types.join(",") : undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createEventsClientCore(config: EventsClientCoreConfig = {}) {
|
|
52
|
+
const gateway = createGatewayRequestClient(config);
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
async list(query: EventListQuery = {}): Promise<EventsListResponse> {
|
|
56
|
+
return gateway.request<EventListResult>({
|
|
57
|
+
path: `/v1/events${toQueryString({
|
|
58
|
+
topicId: query.topicId,
|
|
59
|
+
after: query.after,
|
|
60
|
+
types: serializeTypes(query.types),
|
|
61
|
+
startTime: query.startTime,
|
|
62
|
+
endTime: query.endTime,
|
|
63
|
+
limit: query.limit,
|
|
64
|
+
})}`,
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
async replay(
|
|
69
|
+
input: ReplayEventsInput,
|
|
70
|
+
idempotencyKey = randomIdempotencyKey()
|
|
71
|
+
): Promise<EventsReplayResponse> {
|
|
72
|
+
return gateway.request<ReplayEventsResult>({
|
|
73
|
+
path: "/v1/events/replay",
|
|
74
|
+
method: "POST",
|
|
75
|
+
body: input as JsonObject,
|
|
76
|
+
idempotencyKey,
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createWebhooksClientCore(
|
|
83
|
+
config: WebhooksClientCoreConfig = {}
|
|
84
|
+
) {
|
|
85
|
+
const gateway = createGatewayRequestClient(config);
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
async create(
|
|
89
|
+
input: WebhookCreateInput,
|
|
90
|
+
idempotencyKey = randomIdempotencyKey()
|
|
91
|
+
): Promise<WebhooksCreateResponse> {
|
|
92
|
+
return gateway.request<WebhookRecord>({
|
|
93
|
+
path: "/v1/webhooks",
|
|
94
|
+
method: "POST",
|
|
95
|
+
body: input as JsonObject,
|
|
96
|
+
idempotencyKey,
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
async list(query: WebhookListQuery = {}): Promise<WebhooksListResponse> {
|
|
101
|
+
return gateway.request<{ webhooks: WebhookRecord[] }>({
|
|
102
|
+
path: `/v1/webhooks${toQueryString({
|
|
103
|
+
topicId: query.topicId,
|
|
104
|
+
})}`,
|
|
105
|
+
});
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async get(id: string): Promise<WebhooksGetResponse> {
|
|
109
|
+
return gateway.request<WebhookRecord>({
|
|
110
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}`,
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
async update(
|
|
115
|
+
id: string,
|
|
116
|
+
input: WebhookUpdateInput,
|
|
117
|
+
idempotencyKey = randomIdempotencyKey()
|
|
118
|
+
): Promise<WebhooksUpdateResponse> {
|
|
119
|
+
return gateway.request<WebhookRecord>({
|
|
120
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}`,
|
|
121
|
+
method: "PATCH",
|
|
122
|
+
body: input as JsonObject,
|
|
123
|
+
idempotencyKey,
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
async delete(
|
|
128
|
+
id: string,
|
|
129
|
+
idempotencyKey = randomIdempotencyKey()
|
|
130
|
+
): Promise<WebhooksDeleteResponse> {
|
|
131
|
+
return gateway.request<WebhookDeleteResult>({
|
|
132
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}`,
|
|
133
|
+
method: "DELETE",
|
|
134
|
+
idempotencyKey,
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
async test(
|
|
139
|
+
id: string,
|
|
140
|
+
input: { topicId?: string } = {},
|
|
141
|
+
idempotencyKey = randomIdempotencyKey()
|
|
142
|
+
): Promise<WebhooksTestResponse> {
|
|
143
|
+
return gateway.request<WebhookTestResult>({
|
|
144
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}/test`,
|
|
145
|
+
method: "POST",
|
|
146
|
+
body: input as JsonObject,
|
|
147
|
+
idempotencyKey,
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
async deliveries(
|
|
152
|
+
id: string,
|
|
153
|
+
query: WebhookDeliveriesQuery = {}
|
|
154
|
+
): Promise<WebhooksDeliveriesResponse> {
|
|
155
|
+
return gateway.request<WebhookDeliveriesResult>({
|
|
156
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries${toQueryString({
|
|
157
|
+
limit: query.limit,
|
|
158
|
+
})}`,
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
async health(id: string): Promise<WebhooksHealthResponse> {
|
|
163
|
+
return gateway.request<WebhookHealthResult>({
|
|
164
|
+
path: `/v1/webhooks/${encodeURIComponent(id)}/health`,
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|