@pattern-stack/codegen 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/consumer-skills/integration/change-sources-and-sinks.md +1 -1
- package/dist/{chunk-32DOFN3T.js → chunk-2WDX6I7T.js} +2 -2
- package/dist/{chunk-WWGYCIJX.js → chunk-43SBT72G.js} +2 -2
- package/dist/{chunk-VNBC3VXM.js → chunk-5LXOJGO2.js} +6 -6
- package/dist/{chunk-3NMCDN7L.js → chunk-5TK7MEN4.js} +2 -2
- package/dist/chunk-5TK7MEN4.js.map +1 -0
- package/dist/{chunk-RUYLXR5F.js → chunk-AYC2HEAL.js} +9 -9
- package/dist/{chunk-CEWLVVAH.js → chunk-CRBVI4GE.js} +5 -5
- package/dist/{chunk-DKKFTHHI.js → chunk-CZQUOIDY.js} +4 -4
- package/dist/{chunk-3RWMQC3K.js → chunk-DGYTSCKN.js} +14 -14
- package/dist/{chunk-EBKVKN75.js → chunk-DLG62MQY.js} +7 -7
- package/dist/{chunk-4PFF3ED4.js → chunk-H6FO2ZDJ.js} +4 -4
- package/dist/{chunk-OTR44OH6.js → chunk-IT6FRTEW.js} +10 -10
- package/dist/{chunk-XDIIVIIK.js → chunk-JM3T27ZW.js} +7 -7
- package/dist/{chunk-KSTZIULO.js → chunk-K2I6XIK5.js} +4 -4
- package/dist/{chunk-DRCLNYH7.js → chunk-NXNVTXKG.js} +4 -4
- package/dist/{chunk-BHZP6LOV.js → chunk-QSJ3J4HE.js} +7 -7
- package/dist/{chunk-BK5ICA2F.js → chunk-RUSUZZAF.js} +4 -4
- package/dist/{chunk-BULPAAD3.js → chunk-T4YJRD22.js} +4 -4
- package/dist/{chunk-YLPAPPLW.js → chunk-TIZXQU26.js} +36 -9
- package/dist/chunk-TIZXQU26.js.map +1 -0
- package/dist/{chunk-EJBK7I4F.js → chunk-TKVTEUBD.js} +2 -2
- package/dist/runtime/shared/openapi/index.js +3 -3
- package/dist/runtime/subsystems/analytics/analytics.module.js +2 -2
- package/dist/runtime/subsystems/analytics/index.js +4 -4
- package/dist/runtime/subsystems/auth/auth.module.js +1 -1
- package/dist/runtime/subsystems/auth/index.js +6 -6
- package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js +2 -2
- package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js +2 -2
- package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js +6 -6
- package/dist/runtime/subsystems/bridge/bridge.module.js +19 -19
- package/dist/runtime/subsystems/bridge/index.js +21 -21
- package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js +2 -2
- package/dist/runtime/subsystems/events/events.module.js +3 -3
- package/dist/runtime/subsystems/events/index.js +3 -3
- package/dist/runtime/subsystems/index.js +60 -60
- package/dist/runtime/subsystems/integration/build-change-source.js +2 -2
- package/dist/runtime/subsystems/integration/detection-config.schema.d.ts +23 -15
- package/dist/runtime/subsystems/integration/detection-config.schema.js +1 -1
- package/dist/runtime/subsystems/integration/index.js +3 -3
- package/dist/runtime/subsystems/integration/webhook-change-source.d.ts +36 -6
- package/dist/runtime/subsystems/integration/webhook-change-source.js +1 -1
- package/dist/runtime/subsystems/jobs/index.js +43 -43
- package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js +6 -6
- package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js +3 -3
- package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +3 -3
- package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js +3 -3
- package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +3 -3
- package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js +3 -3
- package/dist/runtime/subsystems/jobs/job-worker.js +3 -3
- package/dist/runtime/subsystems/jobs/job-worker.module.js +13 -13
- package/dist/runtime/subsystems/jobs/jobs-domain.module.js +11 -11
- package/dist/runtime/subsystems/storage/index.js +4 -4
- package/dist/runtime/subsystems/storage/storage.module.js +2 -2
- package/dist/src/cli/index.js +4 -4
- package/dist/src/index.d.ts +11 -11
- package/dist/src/index.js +4 -4
- package/package.json +1 -1
- package/runtime/subsystems/integration/detection-config.schema.ts +64 -54
- package/runtime/subsystems/integration/webhook-change-source.ts +187 -133
- package/dist/chunk-3NMCDN7L.js.map +0 -1
- package/dist/chunk-YLPAPPLW.js.map +0 -1
- /package/dist/{chunk-32DOFN3T.js.map → chunk-2WDX6I7T.js.map} +0 -0
- /package/dist/{chunk-WWGYCIJX.js.map → chunk-43SBT72G.js.map} +0 -0
- /package/dist/{chunk-VNBC3VXM.js.map → chunk-5LXOJGO2.js.map} +0 -0
- /package/dist/{chunk-RUYLXR5F.js.map → chunk-AYC2HEAL.js.map} +0 -0
- /package/dist/{chunk-CEWLVVAH.js.map → chunk-CRBVI4GE.js.map} +0 -0
- /package/dist/{chunk-DKKFTHHI.js.map → chunk-CZQUOIDY.js.map} +0 -0
- /package/dist/{chunk-3RWMQC3K.js.map → chunk-DGYTSCKN.js.map} +0 -0
- /package/dist/{chunk-EBKVKN75.js.map → chunk-DLG62MQY.js.map} +0 -0
- /package/dist/{chunk-4PFF3ED4.js.map → chunk-H6FO2ZDJ.js.map} +0 -0
- /package/dist/{chunk-OTR44OH6.js.map → chunk-IT6FRTEW.js.map} +0 -0
- /package/dist/{chunk-XDIIVIIK.js.map → chunk-JM3T27ZW.js.map} +0 -0
- /package/dist/{chunk-KSTZIULO.js.map → chunk-K2I6XIK5.js.map} +0 -0
- /package/dist/{chunk-DRCLNYH7.js.map → chunk-NXNVTXKG.js.map} +0 -0
- /package/dist/{chunk-BHZP6LOV.js.map → chunk-QSJ3J4HE.js.map} +0 -0
- /package/dist/{chunk-BK5ICA2F.js.map → chunk-RUSUZZAF.js.map} +0 -0
- /package/dist/{chunk-BULPAAD3.js.map → chunk-T4YJRD22.js.map} +0 -0
- /package/dist/{chunk-EJBK7I4F.js.map → chunk-TKVTEUBD.js.map} +0 -0
|
@@ -22,10 +22,12 @@
|
|
|
22
22
|
* primitive while emitting `Change<T>.source = 'cdc'`. Long-lived
|
|
23
23
|
* streaming CDC (SFDC Pub-Sub, Debezium) is a separate primitive
|
|
24
24
|
* deferred to #226-8.
|
|
25
|
-
* - `webhook` mode
|
|
26
|
-
*
|
|
25
|
+
* - `webhook` mode's `eventIdField` is optional: `WebhookChangeSource<T>`
|
|
26
|
+
* prefers an `eventId` yielded by the queue iterator and falls back to the
|
|
27
|
+
* `eventIdField` record extraction (precedence: yielded eventId >
|
|
28
|
+
* eventIdField extraction > undefined dedupKey).
|
|
27
29
|
*/
|
|
28
|
-
import { z } from
|
|
30
|
+
import { z } from "zod";
|
|
29
31
|
|
|
30
32
|
// ============================================================================
|
|
31
33
|
// Field mapping — provider field → canonical target
|
|
@@ -37,9 +39,9 @@ import { z } from 'zod';
|
|
|
37
39
|
* etc.); the schema does not enumerate transforms — adapters interpret them.
|
|
38
40
|
*/
|
|
39
41
|
export const FieldMappingSchema = z.object({
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
source: z.string().min(1),
|
|
43
|
+
target: z.string().min(1),
|
|
44
|
+
transform: z.string().min(1).optional(),
|
|
43
45
|
});
|
|
44
46
|
|
|
45
47
|
export type FieldMapping = z.infer<typeof FieldMappingSchema>;
|
|
@@ -54,9 +56,9 @@ export type FieldMapping = z.infer<typeof FieldMappingSchema>;
|
|
|
54
56
|
* adapters interpret per provider.
|
|
55
57
|
*/
|
|
56
58
|
export const ResolvedFilterSchema = z.object({
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
59
|
+
field: z.string().min(1),
|
|
60
|
+
op: z.enum(["eq", "neq", "in", "nin", "gt", "gte", "lt", "lte"]),
|
|
61
|
+
value: z.unknown(),
|
|
60
62
|
});
|
|
61
63
|
|
|
62
64
|
export type ResolvedFilter = z.infer<typeof ResolvedFilterSchema>;
|
|
@@ -66,23 +68,23 @@ export type ResolvedFilter = z.infer<typeof ResolvedFilterSchema>;
|
|
|
66
68
|
// ============================================================================
|
|
67
69
|
|
|
68
70
|
const SystemModstampCursorSchema = z.object({
|
|
69
|
-
|
|
70
|
-
|
|
71
|
+
kind: z.literal("systemModstamp"),
|
|
72
|
+
field: z.string().min(1),
|
|
71
73
|
});
|
|
72
74
|
|
|
73
75
|
const ReplayIdCursorSchema = z.object({
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
kind: z.literal("replayId"),
|
|
77
|
+
field: z.string().min(1),
|
|
76
78
|
});
|
|
77
79
|
|
|
78
80
|
const TimestampCursorSchema = z.object({
|
|
79
|
-
|
|
80
|
-
|
|
81
|
+
kind: z.literal("timestamp"),
|
|
82
|
+
field: z.string().min(1),
|
|
81
83
|
});
|
|
82
84
|
|
|
83
85
|
const EventIdCursorSchema = z.object({
|
|
84
|
-
|
|
85
|
-
|
|
86
|
+
kind: z.literal("eventId"),
|
|
87
|
+
field: z.string().min(1),
|
|
86
88
|
});
|
|
87
89
|
|
|
88
90
|
/**
|
|
@@ -91,8 +93,8 @@ const EventIdCursorSchema = z.object({
|
|
|
91
93
|
* `field` is metadata for codegen/adapters (the response key the token lives on).
|
|
92
94
|
*/
|
|
93
95
|
const HistoryIdCursorSchema = z.object({
|
|
94
|
-
|
|
95
|
-
|
|
96
|
+
kind: z.literal("historyId"),
|
|
97
|
+
field: z.string().min(1),
|
|
96
98
|
});
|
|
97
99
|
|
|
98
100
|
/**
|
|
@@ -100,17 +102,17 @@ const HistoryIdCursorSchema = z.object({
|
|
|
100
102
|
* same divisibility profile as `historyId`.
|
|
101
103
|
*/
|
|
102
104
|
const SyncTokenCursorSchema = z.object({
|
|
103
|
-
|
|
104
|
-
|
|
105
|
+
kind: z.literal("syncToken"),
|
|
106
|
+
field: z.string().min(1),
|
|
105
107
|
});
|
|
106
108
|
|
|
107
|
-
export const CursorStrategySchema = z.discriminatedUnion(
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
109
|
+
export const CursorStrategySchema = z.discriminatedUnion("kind", [
|
|
110
|
+
SystemModstampCursorSchema,
|
|
111
|
+
ReplayIdCursorSchema,
|
|
112
|
+
TimestampCursorSchema,
|
|
113
|
+
EventIdCursorSchema,
|
|
114
|
+
HistoryIdCursorSchema,
|
|
115
|
+
SyncTokenCursorSchema,
|
|
114
116
|
]);
|
|
115
117
|
|
|
116
118
|
export type CursorStrategy = z.infer<typeof CursorStrategySchema>;
|
|
@@ -135,18 +137,20 @@ export type CursorStrategy = z.infer<typeof CursorStrategySchema>;
|
|
|
135
137
|
* `eventId` is classified atomic conservatively: a generic opaque id is treated
|
|
136
138
|
* all-or-nothing unless a concrete strategy proves it monotonically resumable.
|
|
137
139
|
*/
|
|
138
|
-
export const CURSOR_DIVISIBILITY: Readonly<
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
140
|
+
export const CURSOR_DIVISIBILITY: Readonly<
|
|
141
|
+
Record<CursorStrategy["kind"], boolean>
|
|
142
|
+
> = {
|
|
143
|
+
systemModstamp: true,
|
|
144
|
+
timestamp: true,
|
|
145
|
+
replayId: true,
|
|
146
|
+
eventId: false,
|
|
147
|
+
historyId: false,
|
|
148
|
+
syncToken: false,
|
|
145
149
|
};
|
|
146
150
|
|
|
147
151
|
/** Predicate form of {@link CURSOR_DIVISIBILITY}. */
|
|
148
|
-
export function isDivisibleCursor(kind: CursorStrategy[
|
|
149
|
-
|
|
152
|
+
export function isDivisibleCursor(kind: CursorStrategy["kind"]): boolean {
|
|
153
|
+
return CURSOR_DIVISIBILITY[kind];
|
|
150
154
|
}
|
|
151
155
|
|
|
152
156
|
// ============================================================================
|
|
@@ -159,19 +163,25 @@ export function isDivisibleCursor(kind: CursorStrategy['kind']): boolean {
|
|
|
159
163
|
* `field` — used for Stripe-style event endpoints. Defaults to `'poll'`.
|
|
160
164
|
*/
|
|
161
165
|
export const PollDetectionSchema = z.object({
|
|
162
|
-
|
|
163
|
-
|
|
166
|
+
cursor: CursorStrategySchema,
|
|
167
|
+
provenance: z.enum(["poll", "cdc"]).optional(),
|
|
164
168
|
});
|
|
165
169
|
|
|
166
170
|
export type PollDetection = z.infer<typeof PollDetectionSchema>;
|
|
167
171
|
|
|
168
172
|
/**
|
|
169
|
-
* Webhook-mode block. `eventIdField
|
|
170
|
-
*
|
|
171
|
-
* `Change<T>.dedupKey
|
|
173
|
+
* Webhook-mode block. `eventIdField`, when present, names the field on the
|
|
174
|
+
* emitted canonical record that `WebhookChangeSource<T>` reads to set
|
|
175
|
+
* `Change<T>.dedupKey` — used only as the fallback when the queue iterator
|
|
176
|
+
* does NOT yield an `eventId` alongside the record.
|
|
177
|
+
*
|
|
178
|
+
* `eventIdField` is **optional**: a queue iterator that always yields an
|
|
179
|
+
* `eventId` (vendor delivery metadata, the preferred channel) need not declare
|
|
180
|
+
* a record field for it. dedupKey precedence is: yielded `eventId` >
|
|
181
|
+
* `eventIdField` record extraction > undefined.
|
|
172
182
|
*/
|
|
173
183
|
export const WebhookDetectionSchema = z.object({
|
|
174
|
-
|
|
184
|
+
eventIdField: z.string().min(1).optional(),
|
|
175
185
|
});
|
|
176
186
|
|
|
177
187
|
export type WebhookDetection = z.infer<typeof WebhookDetectionSchema>;
|
|
@@ -181,17 +191,17 @@ export type WebhookDetection = z.infer<typeof WebhookDetectionSchema>;
|
|
|
181
191
|
// ============================================================================
|
|
182
192
|
|
|
183
193
|
const PollModeSchema = z.object({
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
194
|
+
mode: z.literal("poll"),
|
|
195
|
+
poll: PollDetectionSchema,
|
|
196
|
+
mapping: z.array(FieldMappingSchema).min(1),
|
|
197
|
+
filters: z.array(ResolvedFilterSchema).default([]),
|
|
188
198
|
});
|
|
189
199
|
|
|
190
200
|
const WebhookModeSchema = z.object({
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
201
|
+
mode: z.literal("webhook"),
|
|
202
|
+
webhook: WebhookDetectionSchema,
|
|
203
|
+
mapping: z.array(FieldMappingSchema).min(1),
|
|
204
|
+
filters: z.array(ResolvedFilterSchema).default([]),
|
|
195
205
|
});
|
|
196
206
|
|
|
197
207
|
/**
|
|
@@ -201,9 +211,9 @@ const WebhookModeSchema = z.object({
|
|
|
201
211
|
* (Stripe-style event endpoints) is expressed via `mode: 'poll'` with
|
|
202
212
|
* `poll.provenance: 'cdc'`.
|
|
203
213
|
*/
|
|
204
|
-
export const DetectionConfigSchema = z.discriminatedUnion(
|
|
205
|
-
|
|
206
|
-
|
|
214
|
+
export const DetectionConfigSchema = z.discriminatedUnion("mode", [
|
|
215
|
+
PollModeSchema,
|
|
216
|
+
WebhookModeSchema,
|
|
207
217
|
]);
|
|
208
218
|
|
|
209
219
|
export type DetectionConfig = z.infer<typeof DetectionConfigSchema>;
|
|
@@ -7,8 +7,11 @@
|
|
|
7
7
|
* queue. The primitive owns:
|
|
8
8
|
*
|
|
9
9
|
* - canonical `Change<T>.source = 'webhook'` stamping;
|
|
10
|
-
* - `dedupKey` derivation
|
|
11
|
-
* the
|
|
10
|
+
* - `dedupKey` derivation, preferring the `eventId` yielded alongside the
|
|
11
|
+
* record by the queue iterator, and falling back to the configured
|
|
12
|
+
* `webhook.eventIdField` on the emitted record when no `eventId` is yielded
|
|
13
|
+
* (precedence: yielded `eventId` > `eventIdField` record extraction >
|
|
14
|
+
* undefined `dedupKey`);
|
|
12
15
|
* - `externalId` derivation: the mapping entry whose `target === 'external_id'`
|
|
13
16
|
* names — via its `source` — the field on the emitted record that carries
|
|
14
17
|
* the canonical external id (mirrors `PollChangeSource`);
|
|
@@ -37,16 +40,16 @@
|
|
|
37
40
|
* into either this primitive or the poll primitive.
|
|
38
41
|
*/
|
|
39
42
|
|
|
40
|
-
import type { DetectionConfig } from
|
|
43
|
+
import type { DetectionConfig } from "./detection-config.schema";
|
|
41
44
|
import type {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
} from
|
|
45
|
+
Change,
|
|
46
|
+
IChangeSource,
|
|
47
|
+
IntegrationSubscriptionView,
|
|
48
|
+
} from "./integration-change-source.protocol";
|
|
46
49
|
import type {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
} from
|
|
50
|
+
ChangeIterator,
|
|
51
|
+
ChangeMiddleware,
|
|
52
|
+
} from "./integration-middleware.protocol";
|
|
50
53
|
|
|
51
54
|
// ============================================================================
|
|
52
55
|
// Cursor + queue callback shapes
|
|
@@ -66,16 +69,28 @@ export type WebhookCursor = unknown;
|
|
|
66
69
|
* `userId` / `tenantId`.
|
|
67
70
|
*/
|
|
68
71
|
export interface WebhookFetchContext {
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
readonly subscription: IntegrationSubscriptionView;
|
|
73
|
+
readonly cursor: WebhookCursor | null;
|
|
71
74
|
}
|
|
72
75
|
|
|
73
76
|
/**
|
|
74
77
|
* Consumer-supplied queue iterator. Returns an async iterable of
|
|
75
|
-
* `{ record }`
|
|
76
|
-
* emits already-mapped canonical records `T`. The primitive
|
|
77
|
-
* `source: 'webhook'` and `dedupKey`
|
|
78
|
-
*
|
|
78
|
+
* `{ record, eventId?, cursor? }` tuples — the consumer drains the inbound
|
|
79
|
+
* staging queue and emits already-mapped canonical records `T`. The primitive
|
|
80
|
+
* stamps `source: 'webhook'` and derives `dedupKey` with this precedence:
|
|
81
|
+
*
|
|
82
|
+
* 1. the yielded `eventId` (vendor delivery metadata — the queue is the
|
|
83
|
+
* right channel for it: a vendor's event id should never need a field
|
|
84
|
+
* on the vendor-neutral canonical record);
|
|
85
|
+
* 2. else the record field named by `webhook.eventIdField`, when configured;
|
|
86
|
+
* 3. else `undefined`.
|
|
87
|
+
*
|
|
88
|
+
* Yielding `eventId` is the safe channel when one canonical record identity
|
|
89
|
+
* (the `external_id`) can recur across distinct vendor events in a single
|
|
90
|
+
* drain batch — e.g. a message create and its later edit share an
|
|
91
|
+
* `external_id` but are different events. Reading dedup identity off the
|
|
92
|
+
* record (`eventIdField`) collapses those into one `dedupKey`; the yielded
|
|
93
|
+
* `eventId` keeps them distinct. The consumer is the one who decided when a
|
|
79
94
|
* staging row is "ready" to drain.
|
|
80
95
|
*
|
|
81
96
|
* Webhook mode has no per-record cursor advance — the staging-row drain
|
|
@@ -84,33 +99,33 @@ export interface WebhookFetchContext {
|
|
|
84
99
|
* is whatever the consumer chooses to surface, if anything.
|
|
85
100
|
*/
|
|
86
101
|
export type WebhookFetchCallback<T> = (
|
|
87
|
-
|
|
88
|
-
) => AsyncIterable<{ record: T; cursor?: WebhookCursor }>;
|
|
102
|
+
ctx: WebhookFetchContext,
|
|
103
|
+
) => AsyncIterable<{ record: T; eventId?: string; cursor?: WebhookCursor }>;
|
|
89
104
|
|
|
90
105
|
// ============================================================================
|
|
91
106
|
// Constructor options
|
|
92
107
|
// ============================================================================
|
|
93
108
|
|
|
94
109
|
export interface WebhookChangeSourceOptions<T> {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
110
|
+
/** Consumer-supplied inbound queue iterator. */
|
|
111
|
+
readonly queue: WebhookFetchCallback<T>;
|
|
112
|
+
/**
|
|
113
|
+
* Parsed detection config. MUST be `mode: 'webhook'`; the constructor
|
|
114
|
+
* throws if a poll config is supplied. Codegen-emitted factories call
|
|
115
|
+
* `DetectionConfigSchema.parse(...)` upstream so this is a safety net,
|
|
116
|
+
* not the primary validation point.
|
|
117
|
+
*/
|
|
118
|
+
readonly config: DetectionConfig;
|
|
119
|
+
/**
|
|
120
|
+
* Optional middleware chain. Same shape and composition rules as
|
|
121
|
+
* `PollChangeSource` — first element is the outermost layer.
|
|
122
|
+
*/
|
|
123
|
+
readonly middlewares?: ReadonlyArray<ChangeMiddleware<T>>;
|
|
124
|
+
/**
|
|
125
|
+
* Optional human label for run logs (e.g. `'stripe-webhook-charge'`).
|
|
126
|
+
* Defaults to a derived label based on the mapping at construction.
|
|
127
|
+
*/
|
|
128
|
+
readonly label?: string;
|
|
114
129
|
}
|
|
115
130
|
|
|
116
131
|
// ============================================================================
|
|
@@ -118,100 +133,139 @@ export interface WebhookChangeSourceOptions<T> {
|
|
|
118
133
|
// ============================================================================
|
|
119
134
|
|
|
120
135
|
export class WebhookChangeSource<T> implements IChangeSource<T> {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
136
|
+
public readonly label: string;
|
|
137
|
+
|
|
138
|
+
private readonly queue: WebhookFetchCallback<T>;
|
|
139
|
+
private readonly externalIdSourceField: string;
|
|
140
|
+
/**
|
|
141
|
+
* Record field carrying the event id, when `webhook.eventIdField` is
|
|
142
|
+
* configured. Used only as the fallback when the queue iterator does NOT
|
|
143
|
+
* yield an `eventId` — see {@link WebhookFetchCallback} for the precedence.
|
|
144
|
+
*/
|
|
145
|
+
private readonly eventIdSourceField: string | undefined;
|
|
146
|
+
private readonly composed: ChangeIterator<T>;
|
|
147
|
+
|
|
148
|
+
constructor(opts: WebhookChangeSourceOptions<T>) {
|
|
149
|
+
if (opts.config.mode !== "webhook") {
|
|
150
|
+
throw new Error(
|
|
151
|
+
`WebhookChangeSource requires DetectionConfig.mode === 'webhook'; got '${(opts.config as { mode: string }).mode}'`,
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
const config = opts.config;
|
|
155
|
+
|
|
156
|
+
// Field mapping: locate the entry whose canonical `target` is `external_id`
|
|
157
|
+
// — mirrors the poll primitive's contract. Adapters emit records
|
|
158
|
+
// already-mapped; the primitive needs to know which key on T carries the
|
|
159
|
+
// external id so it can stamp `Change.externalId`. That key is the
|
|
160
|
+
// mapping's `source` (the field on the emitted record), NOT its `target`
|
|
161
|
+
// (the canonical column) — they differ whenever the canonical record is
|
|
162
|
+
// vendor-neutral camelCase (e.g. `source: 'externalId'` → `target: 'external_id'`).
|
|
163
|
+
const externalIdMapping = config.mapping.find(
|
|
164
|
+
(m) => m.target === "external_id",
|
|
165
|
+
);
|
|
166
|
+
if (!externalIdMapping) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
"WebhookChangeSource: DetectionConfig.mapping must include an entry with target 'external_id' so emitted Change<T>.externalId can be populated",
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
this.externalIdSourceField = externalIdMapping.source;
|
|
172
|
+
this.eventIdSourceField = config.webhook.eventIdField;
|
|
173
|
+
// `eventIdField` is optional (a callback that always yields `eventId` need
|
|
174
|
+
// not declare one); `undefined` here just disables the fallback extraction.
|
|
175
|
+
|
|
176
|
+
this.queue = opts.queue;
|
|
177
|
+
|
|
178
|
+
this.label =
|
|
179
|
+
opts.label ?? `webhook-change-source:${externalIdMapping.source}`;
|
|
180
|
+
|
|
181
|
+
// Compose middleware chain — same shape as PollChangeSource.
|
|
182
|
+
const inner: ChangeIterator<T> = (sub, cur) => this.fetch(sub, cur);
|
|
183
|
+
const middlewares = opts.middlewares ?? [];
|
|
184
|
+
this.composed = middlewares.reduceRight<ChangeIterator<T>>(
|
|
185
|
+
(next, mw) => mw(next),
|
|
186
|
+
inner,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
listChanges(
|
|
191
|
+
subscription: IntegrationSubscriptionView,
|
|
192
|
+
cursor: unknown | null,
|
|
193
|
+
): AsyncIterable<Change<T>> {
|
|
194
|
+
return this.composed(subscription, cursor);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private async *fetch(
|
|
198
|
+
subscription: IntegrationSubscriptionView,
|
|
199
|
+
cursor: unknown | null,
|
|
200
|
+
): AsyncIterable<Change<T>> {
|
|
201
|
+
const ctx: WebhookFetchContext = {
|
|
202
|
+
subscription,
|
|
203
|
+
cursor: cursor as WebhookCursor | null,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
for await (const {
|
|
207
|
+
record,
|
|
208
|
+
eventId: yieldedEventId,
|
|
209
|
+
cursor: nextCursor,
|
|
210
|
+
} of this.queue(ctx)) {
|
|
211
|
+
const externalIdRaw = (record as Record<string, unknown>)[
|
|
212
|
+
this.externalIdSourceField
|
|
213
|
+
];
|
|
214
|
+
if (typeof externalIdRaw !== "string" || externalIdRaw.length === 0) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`WebhookChangeSource: record missing string '${this.externalIdSourceField}' — emitted records MUST carry the canonical external id keyed by the mapping source`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// dedupKey precedence: yielded `eventId` > `eventIdField` record
|
|
221
|
+
// extraction > undefined. The yielded id is vendor delivery metadata
|
|
222
|
+
// (the right channel for it), and keeps distinct vendor events for the
|
|
223
|
+
// same `external_id` (e.g. a message and its edit) from collapsing to
|
|
224
|
+
// one dedupKey — which a record-field extraction would do.
|
|
225
|
+
const dedupKey = this.deriveDedupKey(yieldedEventId, record);
|
|
226
|
+
|
|
227
|
+
const change: Change<T> = {
|
|
228
|
+
externalId: externalIdRaw,
|
|
229
|
+
// Webhook mode cannot distinguish create vs. update vs. delete on
|
|
230
|
+
// its own — the orchestrator's diff stage handles classification.
|
|
231
|
+
// Tombstone / soft-delete detection is consumer-driven (same as
|
|
232
|
+
// poll mode — see ADR-033).
|
|
233
|
+
operation: "updated",
|
|
234
|
+
record,
|
|
235
|
+
cursor: nextCursor ?? null,
|
|
236
|
+
source: "webhook",
|
|
237
|
+
dedupKey,
|
|
238
|
+
};
|
|
239
|
+
yield change;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Resolve `Change<T>.dedupKey` with the precedence: yielded `eventId` >
|
|
245
|
+
* `webhook.eventIdField` record extraction > `undefined`. A non-empty
|
|
246
|
+
* yielded `eventId` always wins; otherwise the configured field is read off
|
|
247
|
+
* the record (and must be a non-empty string when the field is configured);
|
|
248
|
+
* with neither, `dedupKey` is `undefined` (the orchestrator then has no
|
|
249
|
+
* delivery-level dedup signal for this change).
|
|
250
|
+
*/
|
|
251
|
+
private deriveDedupKey(
|
|
252
|
+
yieldedEventId: string | undefined,
|
|
253
|
+
record: T,
|
|
254
|
+
): string | undefined {
|
|
255
|
+
if (yieldedEventId !== undefined && yieldedEventId.length > 0) {
|
|
256
|
+
return yieldedEventId;
|
|
257
|
+
}
|
|
258
|
+
if (this.eventIdSourceField === undefined) {
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
const eventIdRaw = (record as Record<string, unknown>)[
|
|
262
|
+
this.eventIdSourceField
|
|
263
|
+
];
|
|
264
|
+
if (typeof eventIdRaw !== "string" || eventIdRaw.length === 0) {
|
|
265
|
+
throw new Error(
|
|
266
|
+
`WebhookChangeSource: record missing string '${this.eventIdSourceField}' — a webhook record MUST carry the event id (DetectionConfig.webhook.eventIdField) so Change<T>.dedupKey can be populated, unless the queue iterator yields an 'eventId' alongside the record`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
return eventIdRaw;
|
|
270
|
+
}
|
|
217
271
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../runtime/subsystems/integration/detection-config.schema.ts"],"sourcesContent":["/**\n * Integration subsystem — DetectionConfig schema (#226-1)\n *\n * Canonical Zod schema for per-entity integration detection config. The schema is\n * the single source of truth for filter/mapping shape and is consumed by:\n *\n * 1. Runtime primitives — `PollChangeSource<T>`, `WebhookChangeSource<T>`\n * (#226-3, #226-4) accept a parsed `DetectionConfig` at construction.\n * 2. Codegen — `src/schema/entity-definition.schema.ts` (#226-6) imports\n * this schema so per-entity YAML `detection:` blocks validate against\n * the same shape the runtime enforces.\n *\n * Locked decisions (see ADR-033 + decision memo Q1–Q6):\n * - Filter vocabulary is flat AND of `{ field, op, value }` triples; richer\n * boolean expressions (OR / NOT / nested) are deferred per epic open Q3.\n * - Cursor strategy is a tagged union over the four shapes the three modes\n * need (`systemModstamp`, `replayId`, `timestamp`, `eventId`). Each\n * strategy types its cursor internally; the orchestrator persists what\n * the iterator last yielded (integration skill rule 2).\n * - `mode: 'poll'` may opt into `provenance: 'cdc'` so Stripe-style event\n * endpoints (mechanically a poll, semantically CDC) reuse the poll\n * primitive while emitting `Change<T>.source = 'cdc'`. Long-lived\n * streaming CDC (SFDC Pub-Sub, Debezium) is a separate primitive\n * deferred to #226-8.\n * - `webhook` mode requires `eventIdField` so `WebhookChangeSource<T>`\n * can populate `Change<T>.dedupKey` from the inbound staging row.\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// Field mapping — provider field → canonical target\n// ============================================================================\n\n/**\n * Maps a single provider field onto the canonical record. `transform` is an\n * opt-in tag the adapter callback may inspect (`date-iso`, `decimal-string`,\n * etc.); the schema does not enumerate transforms — adapters interpret them.\n */\nexport const FieldMappingSchema = z.object({\n source: z.string().min(1),\n target: z.string().min(1),\n transform: z.string().min(1).optional(),\n});\n\nexport type FieldMapping = z.infer<typeof FieldMappingSchema>;\n\n// ============================================================================\n// Resolved filter — flat-AND triple\n// ============================================================================\n\n/**\n * A single resolved filter clause applied at fetch time. `value` is `unknown`\n * to admit primitives, arrays (for `in` / `nin`), and dates as ISO strings —\n * adapters interpret per provider.\n */\nexport const ResolvedFilterSchema = z.object({\n field: z.string().min(1),\n op: z.enum(['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte']),\n value: z.unknown(),\n});\n\nexport type ResolvedFilter = z.infer<typeof ResolvedFilterSchema>;\n\n// ============================================================================\n// Cursor strategy — tagged union over the four shapes the modes need\n// ============================================================================\n\nconst SystemModstampCursorSchema = z.object({\n kind: z.literal('systemModstamp'),\n field: z.string().min(1),\n});\n\nconst ReplayIdCursorSchema = z.object({\n kind: z.literal('replayId'),\n field: z.string().min(1),\n});\n\nconst TimestampCursorSchema = z.object({\n kind: z.literal('timestamp'),\n field: z.string().min(1),\n});\n\nconst EventIdCursorSchema = z.object({\n kind: z.literal('eventId'),\n field: z.string().min(1),\n});\n\n/**\n * Gmail `historyId` (RFC-0003 §3) — an opaque, atomic vendor token. The next\n * watermark only exists at end-of-walk; there is no resumable mid-walk value.\n * `field` is metadata for codegen/adapters (the response key the token lives on).\n */\nconst HistoryIdCursorSchema = z.object({\n kind: z.literal('historyId'),\n field: z.string().min(1),\n});\n\n/**\n * Google Calendar `syncToken` (RFC-0003 §3) — an opaque, atomic sync token,\n * same divisibility profile as `historyId`.\n */\nconst SyncTokenCursorSchema = z.object({\n kind: z.literal('syncToken'),\n field: z.string().min(1),\n});\n\nexport const CursorStrategySchema = z.discriminatedUnion('kind', [\n SystemModstampCursorSchema,\n ReplayIdCursorSchema,\n TimestampCursorSchema,\n EventIdCursorSchema,\n HistoryIdCursorSchema,\n SyncTokenCursorSchema,\n]);\n\nexport type CursorStrategy = z.infer<typeof CursorStrategySchema>;\n\n// ============================================================================\n// Cursor divisibility (RFC-0003 §3)\n// ============================================================================\n\n/**\n * Whether a cursor strategy is *divisible* — a property of the strategy, not\n * the read primitive. Divisible cursors are sortable/monotonic watermarks whose\n * value is meaningful AS OF any single record (HubSpot `systemModstamp`, a\n * `timestamp` field, a Salesforce CDC `replayId`); the read primitive may\n * checkpoint per-ref mid-walk, so a crash resumes from the last delivered ref.\n *\n * Atomic cursors are opaque vendor tokens (Gmail `historyId`, Calendar\n * `syncToken`, a generic `eventId`) whose next value only exists at end-of-walk.\n * The primitive must withhold per-ref cursors and emit the token only at a safe\n * boundary, so an interrupted run never persists an unresumable mid-walk token\n * (it resumes all-or-nothing from the prior token — see `IncrementalReadBase`).\n *\n * `eventId` is classified atomic conservatively: a generic opaque id is treated\n * all-or-nothing unless a concrete strategy proves it monotonically resumable.\n */\nexport const CURSOR_DIVISIBILITY: Readonly<Record<CursorStrategy['kind'], boolean>> = {\n systemModstamp: true,\n timestamp: true,\n replayId: true,\n eventId: false,\n historyId: false,\n syncToken: false,\n};\n\n/** Predicate form of {@link CURSOR_DIVISIBILITY}. */\nexport function isDivisibleCursor(kind: CursorStrategy['kind']): boolean {\n return CURSOR_DIVISIBILITY[kind];\n}\n\n// ============================================================================\n// Mode-specific blocks\n// ============================================================================\n\n/**\n * Poll-mode block. `provenance: 'cdc'` opts the poll primitive into stamping\n * `Change<T>.source = 'cdc'` and populating `dedupKey` from the cursor's\n * `field` — used for Stripe-style event endpoints. Defaults to `'poll'`.\n */\nexport const PollDetectionSchema = z.object({\n cursor: CursorStrategySchema,\n provenance: z.enum(['poll', 'cdc']).optional(),\n});\n\nexport type PollDetection = z.infer<typeof PollDetectionSchema>;\n\n/**\n * Webhook-mode block. `eventIdField` names the column in the consumer-owned\n * inbound staging row that `WebhookChangeSource<T>` reads to set\n * `Change<T>.dedupKey`.\n */\nexport const WebhookDetectionSchema = z.object({\n eventIdField: z.string().min(1),\n});\n\nexport type WebhookDetection = z.infer<typeof WebhookDetectionSchema>;\n\n// ============================================================================\n// DetectionConfig — top-level discriminated union over `mode`\n// ============================================================================\n\nconst PollModeSchema = z.object({\n mode: z.literal('poll'),\n poll: PollDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\nconst WebhookModeSchema = z.object({\n mode: z.literal('webhook'),\n webhook: WebhookDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\n/**\n * Top-level detection config. Discriminated on `mode` so the relevant\n * mode-block (poll/webhook) is structurally required for that mode. CDC as a\n * long-lived streaming primitive is deferred (#226-8); CDC-as-provenance\n * (Stripe-style event endpoints) is expressed via `mode: 'poll'` with\n * `poll.provenance: 'cdc'`.\n */\nexport const DetectionConfigSchema = z.discriminatedUnion('mode', [\n PollModeSchema,\n WebhookModeSchema,\n]);\n\nexport type DetectionConfig = z.infer<typeof DetectionConfigSchema>;\n"],"mappings":";AA2BA,SAAS,SAAS;AAWX,IAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxB,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AACxC,CAAC;AAaM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,IAAI,EAAE,KAAK,CAAC,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,KAAK,CAAC;AAAA,EAC/D,OAAO,EAAE,QAAQ;AACnB,CAAC;AAQD,IAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,QAAQ,gBAAgB;AAAA,EAChC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAED,IAAM,uBAAuB,EAAE,OAAO;AAAA,EACpC,MAAM,EAAE,QAAQ,UAAU;AAAA,EAC1B,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAED,IAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,MAAM,EAAE,QAAQ,WAAW;AAAA,EAC3B,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAED,IAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,MAAM,EAAE,QAAQ,SAAS;AAAA,EACzB,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAOD,IAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,MAAM,EAAE,QAAQ,WAAW;AAAA,EAC3B,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAMD,IAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,MAAM,EAAE,QAAQ,WAAW;AAAA,EAC3B,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AACzB,CAAC;AAEM,IAAM,uBAAuB,EAAE,mBAAmB,QAAQ;AAAA,EAC/D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAwBM,IAAM,sBAAyE;AAAA,EACpF,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW;AAAA,EACX,WAAW;AACb;AAGO,SAAS,kBAAkB,MAAuC;AACvE,SAAO,oBAAoB,IAAI;AACjC;AAWO,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,QAAQ;AAAA,EACR,YAAY,EAAE,KAAK,CAAC,QAAQ,KAAK,CAAC,EAAE,SAAS;AAC/C,CAAC;AASM,IAAM,yBAAyB,EAAE,OAAO;AAAA,EAC7C,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAChC,CAAC;AAQD,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,MAAM,EAAE,QAAQ,MAAM;AAAA,EACtB,MAAM;AAAA,EACN,SAAS,EAAE,MAAM,kBAAkB,EAAE,IAAI,CAAC;AAAA,EAC1C,SAAS,EAAE,MAAM,oBAAoB,EAAE,QAAQ,CAAC,CAAC;AACnD,CAAC;AAED,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,MAAM,EAAE,QAAQ,SAAS;AAAA,EACzB,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,kBAAkB,EAAE,IAAI,CAAC;AAAA,EAC1C,SAAS,EAAE,MAAM,oBAAoB,EAAE,QAAQ,CAAC,CAAC;AACnD,CAAC;AASM,IAAM,wBAAwB,EAAE,mBAAmB,QAAQ;AAAA,EAChE;AAAA,EACA;AACF,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../runtime/subsystems/integration/webhook-change-source.ts"],"sourcesContent":["/**\n * Integration subsystem — `WebhookChangeSource<T>` primitive (#226-4, ADR-033).\n *\n * Generic webhook-mode `IChangeSource<T>` implementation parameterized by a\n * parsed `DetectionConfig` (webhook mode) and a consumer-supplied\n * `WebhookFetchCallback<T>` that iterates a consumer-owned inbound staging\n * queue. The primitive owns:\n *\n * - canonical `Change<T>.source = 'webhook'` stamping;\n * - `dedupKey` derivation from the configured `webhook.eventIdField` on\n * the emitted record;\n * - `externalId` derivation: the mapping entry whose `target === 'external_id'`\n * names — via its `source` — the field on the emitted record that carries\n * the canonical external id (mirrors `PollChangeSource`);\n * - middleware-chain composition via the locked `ChangeMiddleware<T>` shape\n * (#226-1) — same composition seam as the poll primitive.\n *\n * The primitive is **passive**: it iterates whatever the consumer-owned\n * queue yields. It does NOT synchronously drive the orchestrator, does NOT\n * own a transport, and does NOT manage acks. The inbound staging table\n * schema is consumer-owned and deferred per ADR-0002 §Phase 4 — the\n * `WebhookFetchCallback<T>` is the queue contract the consumer injects.\n *\n * Shape locks (decision memo Q5, mirrored from poll primitive):\n * - `WebhookFetchContext = { subscription, cursor }` — explicitly NO\n * `userId` / `tenantId`. Run-scope identity is closed over by the\n * consumer at queue construction or resolved inside the callback via\n * consumer services. There are no `filters` on the webhook context —\n * filtering is done at registration / on the staging row, not at the\n * port seam (the queue is already filtered by the time the primitive\n * iterates).\n *\n * Long-lived streaming CDC primitives (SFDC Pub-Sub gRPC, Debezium/Kafka,\n * Postgres logical replication) are deferred to `#226-8` — they need a\n * fundamentally different lifecycle (`subscribe(onChange, onError)`,\n * server-paced backpressure, ack-on-yield) and shouldn't be retrofitted\n * into either this primitive or the poll primitive.\n */\n\nimport type { DetectionConfig } from './detection-config.schema';\nimport type {\n Change,\n IChangeSource,\n IntegrationSubscriptionView,\n} from './integration-change-source.protocol';\nimport type {\n ChangeIterator,\n ChangeMiddleware,\n} from './integration-middleware.protocol';\n\n// ============================================================================\n// Cursor + queue callback shapes\n// ============================================================================\n\n/**\n * Opaque webhook cursor shape. Webhook mode typically has a cursor of\n * `{ ts: ISO-string }` (last drained staging-row timestamp) but the\n * primitive treats it as opaque. Consumer-owned queue iterators interpret\n * it however the staging schema needs.\n */\nexport type WebhookCursor = unknown;\n\n/**\n * Context the primitive forwards to the queue iterator. Locked to exactly\n * two fields per the same Q5 reasoning that locks `PollFetchContext` — no\n * `userId` / `tenantId`.\n */\nexport interface WebhookFetchContext {\n readonly subscription: IntegrationSubscriptionView;\n readonly cursor: WebhookCursor | null;\n}\n\n/**\n * Consumer-supplied queue iterator. Returns an async iterable of\n * `{ record }` pairs — the consumer drains the inbound staging queue and\n * emits already-mapped canonical records `T`. The primitive stamps\n * `source: 'webhook'` and `dedupKey` from the record's configured\n * `webhook.eventIdField`; the consumer is the one who decided when a\n * staging row is \"ready\" to drain.\n *\n * Webhook mode has no per-record cursor advance — the staging-row drain\n * order is consumer policy (FIFO by ingestion timestamp, by event id, etc.)\n * and is opaque to the primitive. The orchestrator's last-yielded cursor\n * is whatever the consumer chooses to surface, if anything.\n */\nexport type WebhookFetchCallback<T> = (\n ctx: WebhookFetchContext,\n) => AsyncIterable<{ record: T; cursor?: WebhookCursor }>;\n\n// ============================================================================\n// Constructor options\n// ============================================================================\n\nexport interface WebhookChangeSourceOptions<T> {\n /** Consumer-supplied inbound queue iterator. */\n readonly queue: WebhookFetchCallback<T>;\n /**\n * Parsed detection config. MUST be `mode: 'webhook'`; the constructor\n * throws if a poll config is supplied. Codegen-emitted factories call\n * `DetectionConfigSchema.parse(...)` upstream so this is a safety net,\n * not the primary validation point.\n */\n readonly config: DetectionConfig;\n /**\n * Optional middleware chain. Same shape and composition rules as\n * `PollChangeSource` — first element is the outermost layer.\n */\n readonly middlewares?: ReadonlyArray<ChangeMiddleware<T>>;\n /**\n * Optional human label for run logs (e.g. `'stripe-webhook-charge'`).\n * Defaults to a derived label based on the mapping at construction.\n */\n readonly label?: string;\n}\n\n// ============================================================================\n// WebhookChangeSource<T>\n// ============================================================================\n\nexport class WebhookChangeSource<T> implements IChangeSource<T> {\n public readonly label: string;\n\n private readonly queue: WebhookFetchCallback<T>;\n private readonly externalIdSourceField: string;\n private readonly eventIdSourceField: string;\n private readonly composed: ChangeIterator<T>;\n\n constructor(opts: WebhookChangeSourceOptions<T>) {\n if (opts.config.mode !== 'webhook') {\n throw new Error(\n `WebhookChangeSource requires DetectionConfig.mode === 'webhook'; got '${(opts.config as { mode: string }).mode}'`,\n );\n }\n const config = opts.config;\n\n // Field mapping: locate the entry whose canonical `target` is `external_id`\n // — mirrors the poll primitive's contract. Adapters emit records\n // already-mapped; the primitive needs to know which key on T carries the\n // external id so it can stamp `Change.externalId`. That key is the\n // mapping's `source` (the field on the emitted record), NOT its `target`\n // (the canonical column) — they differ whenever the canonical record is\n // vendor-neutral camelCase (e.g. `source: 'externalId'` → `target: 'external_id'`).\n const externalIdMapping = config.mapping.find(\n (m) => m.target === 'external_id',\n );\n if (!externalIdMapping) {\n throw new Error(\n \"WebhookChangeSource: DetectionConfig.mapping must include an entry with target 'external_id' so emitted Change<T>.externalId can be populated\",\n );\n }\n this.externalIdSourceField = externalIdMapping.source;\n this.eventIdSourceField = config.webhook.eventIdField;\n\n this.queue = opts.queue;\n\n this.label =\n opts.label ?? `webhook-change-source:${externalIdMapping.source}`;\n\n // Compose middleware chain — same shape as PollChangeSource.\n const inner: ChangeIterator<T> = (sub, cur) => this.fetch(sub, cur);\n const middlewares = opts.middlewares ?? [];\n this.composed = middlewares.reduceRight<ChangeIterator<T>>(\n (next, mw) => mw(next),\n inner,\n );\n }\n\n listChanges(\n subscription: IntegrationSubscriptionView,\n cursor: unknown | null,\n ): AsyncIterable<Change<T>> {\n return this.composed(subscription, cursor);\n }\n\n private async *fetch(\n subscription: IntegrationSubscriptionView,\n cursor: unknown | null,\n ): AsyncIterable<Change<T>> {\n const ctx: WebhookFetchContext = {\n subscription,\n cursor: cursor as WebhookCursor | null,\n };\n\n for await (const { record, cursor: nextCursor } of this.queue(ctx)) {\n const externalIdRaw = (record as Record<string, unknown>)[\n this.externalIdSourceField\n ];\n if (typeof externalIdRaw !== 'string' || externalIdRaw.length === 0) {\n throw new Error(\n `WebhookChangeSource: record missing string '${this.externalIdSourceField}' — emitted records MUST carry the canonical external id keyed by the mapping source`,\n );\n }\n const eventIdRaw = (record as Record<string, unknown>)[\n this.eventIdSourceField\n ];\n if (typeof eventIdRaw !== 'string' || eventIdRaw.length === 0) {\n throw new Error(\n `WebhookChangeSource: record missing string '${this.eventIdSourceField}' — webhook records MUST carry the event id (DetectionConfig.webhook.eventIdField) so Change<T>.dedupKey can be populated`,\n );\n }\n\n const change: Change<T> = {\n externalId: externalIdRaw,\n // Webhook mode cannot distinguish create vs. update vs. delete on\n // its own — the orchestrator's diff stage handles classification.\n // Tombstone / soft-delete detection is consumer-driven (same as\n // poll mode — see ADR-033).\n operation: 'updated',\n record,\n cursor: nextCursor ?? null,\n source: 'webhook',\n dedupKey: eventIdRaw,\n };\n yield change;\n }\n }\n}\n"],"mappings":";AAuHO,IAAM,sBAAN,MAAyD;AAAA,EAC9C;AAAA,EAEC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,MAAqC;AAC/C,QAAI,KAAK,OAAO,SAAS,WAAW;AAClC,YAAM,IAAI;AAAA,QACR,yEAA0E,KAAK,OAA4B,IAAI;AAAA,MACjH;AAAA,IACF;AACA,UAAM,SAAS,KAAK;AASpB,UAAM,oBAAoB,OAAO,QAAQ;AAAA,MACvC,CAAC,MAAM,EAAE,WAAW;AAAA,IACtB;AACA,QAAI,CAAC,mBAAmB;AACtB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,SAAK,wBAAwB,kBAAkB;AAC/C,SAAK,qBAAqB,OAAO,QAAQ;AAEzC,SAAK,QAAQ,KAAK;AAElB,SAAK,QACH,KAAK,SAAS,yBAAyB,kBAAkB,MAAM;AAGjE,UAAM,QAA2B,CAAC,KAAK,QAAQ,KAAK,MAAM,KAAK,GAAG;AAClE,UAAM,cAAc,KAAK,eAAe,CAAC;AACzC,SAAK,WAAW,YAAY;AAAA,MAC1B,CAAC,MAAM,OAAO,GAAG,IAAI;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YACE,cACA,QAC0B;AAC1B,WAAO,KAAK,SAAS,cAAc,MAAM;AAAA,EAC3C;AAAA,EAEA,OAAe,MACb,cACA,QAC0B;AAC1B,UAAM,MAA2B;AAAA,MAC/B;AAAA,MACA;AAAA,IACF;AAEA,qBAAiB,EAAE,QAAQ,QAAQ,WAAW,KAAK,KAAK,MAAM,GAAG,GAAG;AAClE,YAAM,gBAAiB,OACrB,KAAK,qBACP;AACA,UAAI,OAAO,kBAAkB,YAAY,cAAc,WAAW,GAAG;AACnE,cAAM,IAAI;AAAA,UACR,+CAA+C,KAAK,qBAAqB;AAAA,QAC3E;AAAA,MACF;AACA,YAAM,aAAc,OAClB,KAAK,kBACP;AACA,UAAI,OAAO,eAAe,YAAY,WAAW,WAAW,GAAG;AAC7D,cAAM,IAAI;AAAA,UACR,+CAA+C,KAAK,kBAAkB;AAAA,QACxE;AAAA,MACF;AAEA,YAAM,SAAoB;AAAA,QACxB,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,QAKZ,WAAW;AAAA,QACX;AAAA,QACA,QAAQ,cAAc;AAAA,QACtB,QAAQ;AAAA,QACR,UAAU;AAAA,MACZ;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|