@superdurable/connector-hubspot 0.1.0 → 0.2.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 +22 -3
- package/dex-connector.json +269 -6
- package/dist/{chunk-SUNBKTMW.js → chunk-HHRHOJKC.js} +8 -3
- package/dist/{connection-B7L88dB2.d.ts → connection-pqfXajbM.d.ts} +3 -0
- package/dist/index.d.ts +159 -8
- package/dist/index.js +436 -24
- package/dist/mock.d.ts +1 -1
- package/dist/mock.js +1 -1
- package/package.json +8 -6
package/README.md
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
# HubSpot TypeScript connector
|
|
2
2
|
|
|
3
|
-
`@superdurable/connector-hubspot` provides Dex Steps for `searchObjects`, `getObject`, `upsertObject`, and `updateObject
|
|
3
|
+
`@superdurable/connector-hubspot` provides Dex Steps for `searchObjects`, `getObject`, `upsertObject`, and `updateObject`, and, from 0.2.0, the `crmObjectChanged` poll Trigger at parity with the Go connector. It requires `@superdurable/connectors-sdk` 0.12.0 and `@superdurable/dex` 1.45.4 or newer. It supports HubSpot private app tokens and HubSpot OAuth. The connection resolves credentials at dispatch, refreshes OAuth tokens through the generated manifest driver, and retries one request after a rejected OAuth access token. The two writes are repeat-safe: upsert uses a unique HubSpot property and update replaces named property values.
|
|
4
4
|
|
|
5
5
|
The [search deals example](examples/search-deals/README.md) is a runnable Flow with a Worker entrypoint and static `hubspot-crm` connection name. Create that connection in Dex Web **Connections**. For private apps, open [HubSpot](https://app.hubspot.com/), choose **Development > Legacy apps > Create legacy app > Private**, grant the CRM read and write scopes listed in `connector.yaml`, and copy the access token from the app's **Auth** tab. For OAuth, choose a public legacy app or project app, register the redirect URI shown in Dex Web on the app's **Auth** tab, add the manifest scopes, enter the client ID and secret, and complete consent. Dex Web holds the credentials; they never enter Flow input or output.
|
|
6
6
|
|
|
7
|
-
From this directory, run `npm ci`, `npm run check`, and `npm run example:
|
|
7
|
+
From this directory, run `npm ci`, `npm run check`, `npm run example:search`, and `npm run example:changes`. To submit the sample input, run `npm run example:search:start -- examples/search-deals/input.example.json` in another terminal. Set `DEX_FLOW_SERVICE_ADDRESS` when Dex uses a nondefault port. `npm run test:integration` runs the same Flow through a real Dex Worker and Client against a local provider stand-in.
|
|
8
8
|
|
|
9
|
-
The package exports generated Config, Credentials, operation models, definitions, Step factories, and mock cases. Use `newProjectConnection(project, ConnectionName)` to bind the project connection, or `newConnection(new HubSpotClient(config, credentialSource), reference)` when constructing a client directly. The provider endpoint defaults to HubSpot's public API; `maxResponseBytes` defaults to one MiB.
|
|
9
|
+
The package exports generated Config, Credentials, operation models, definitions, Step factories, and mock cases. Use `newProjectConnection(project, ConnectionName)` to bind the project connection, or `newConnection(new HubSpotClient(config, credentialSource), reference)` when constructing a client directly. The provider endpoint defaults to HubSpot's public API; `maxResponseBytes` defaults to one MiB; `pollIntervalMs` defaults to 30 seconds and must be at least 5 seconds. A project connection reads the saved `pollInterval` as Go `time.Duration` nanoseconds.
|
|
10
|
+
|
|
11
|
+
## crmObjectChanged Trigger
|
|
12
|
+
|
|
13
|
+
`crmObjectChanged` polls one object type, `contacts`, `companies`, or `deals`, through HubSpot CRM search and delivers one `CRMObjectChangedEvent` per created or changed record: `objectType`, `changeKind` (`created` or `updated`), `modifiedAt`, and the `object` as search returned it. It is built on the `@superdurable/connectors-sdk/pollingtrigger` kit and follows the Go connector exactly: the first poll records the newest last-modified date as a baseline and delivers no existing record; later polls search ascending on `lastmodifieddate` (contacts) or `hs_lastmodifieddate`, 100 records per page, re-read a two-minute lag window for late-indexed records, and skip versions already delivered. A 429 or 423 pauses every binding of the connection for `Retry-After` or `X-HubSpot-RateLimit-Interval-Milliseconds`, an exhausted daily limit backs off up to 15 minutes, and a rejected paging offset or unusable cursor records a new baseline with a WARN record. The [connector README](../README.md#crmobjectchanged-trigger) describes the behavior in full.
|
|
14
|
+
|
|
15
|
+
The cursor document is the Go connector's JSON byte for byte, and the event ID is the same hash of object type, record ID, and last-modified millisecond, so Go and TypeScript replicas can share one binding's cursor and inbox. A test replays a scenario recorded from the Go fetcher (`test/fixtures/go-crm-object-change-cursors.json`) and compares every cursor token and event ID.
|
|
16
|
+
|
|
17
|
+
`newProjectCRMObjectTriggerRunner(project, connectionName, { crmObjectChangedRoutes }, options)` is the durable path: it loads each binding's saved object type, records every change in the binding's project Trigger inbox, and commits the search position in its project poll cursor only after that. From [`examples/crm-object-changed/app.ts`](examples/crm-object-changed/app.ts):
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const runner = newProjectCRMObjectTriggerRunner(project, ConnectionName, { crmObjectChangedRoutes: [{
|
|
21
|
+
bindingName: CRMObjectChangedTriggerBinding, properties: DeliveredProperties,
|
|
22
|
+
target: newDexFlowTriggerTarget(client, flow, acceptEveryCRMObjectChange, resolveFlowId, mapToFlowInput, { logger: options.logger }),
|
|
23
|
+
}] }, hubspotOptions);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Run it with `runner.run(newTriggerContext(signal))`; `runner.wakePoller(bindingName)` polls a binding at once. `newCRMObjectTriggerRunner` takes targets and cursor stores directly, and `newCRMObjectChangedTrigger` builds one binding for `newTrigger`; both keep the cursor in memory unless given a store, so a restart records a new baseline. `defineCRMObjectChangedTriggerBinding` declares a Flow's static binding with the `objectTypePicker` unit (`UIUnitObjectTypePicker`, port `objectType`). The `logger` client option receives seed, reseed, failure, pause, and inbox records, which never contain record properties or credentials.
|
|
27
|
+
|
|
28
|
+
The [crm-object-changed example](examples/crm-object-changed/README.md) starts one Flow per change. `npm run test:integration` runs it on a real Dex Worker and Client against a local HubSpot search stand-in, covering the baseline, one Flow per change, changes made while the process was stopped, and a 429 pause. Live HubSpot search has not been verified.
|
package/dex-connector.json
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"connectorId": "hubspot",
|
|
3
|
-
"releaseTag": "connectors/hubspot/go/v0.
|
|
3
|
+
"releaseTag": "connectors/hubspot/go/v0.25.0",
|
|
4
4
|
"package": {
|
|
5
5
|
"ecosystem": "npm",
|
|
6
6
|
"name": "@superdurable/connector-hubspot",
|
|
7
|
-
"version": "0.
|
|
7
|
+
"version": "0.2.0"
|
|
8
8
|
},
|
|
9
9
|
"factories": [
|
|
10
10
|
{
|
|
11
11
|
"name": "newSearchObjectsStep",
|
|
12
12
|
"kind": "query",
|
|
13
13
|
"operationId": "searchObjects",
|
|
14
|
+
"inputType": "SearchObjectsInput",
|
|
15
|
+
"description": "Search one bounded page of HubSpot contacts, companies, or deals with typed property filters, one sort, and an after cursor.",
|
|
14
16
|
"fields": {
|
|
15
17
|
"stepType": "stepType",
|
|
16
18
|
"annotations": "annotations",
|
|
@@ -38,12 +40,157 @@
|
|
|
38
40
|
"field": "defect",
|
|
39
41
|
"optional": true
|
|
40
42
|
}
|
|
41
|
-
]
|
|
43
|
+
],
|
|
44
|
+
"inputSchema": {
|
|
45
|
+
"$defs": {
|
|
46
|
+
"SearchFilter": {
|
|
47
|
+
"additionalProperties": false,
|
|
48
|
+
"description": "SearchFilter is one typed CRM search condition.",
|
|
49
|
+
"properties": {
|
|
50
|
+
"highValue": {
|
|
51
|
+
"description": "HighValue is the inclusive upper bound for BETWEEN.",
|
|
52
|
+
"type": "string"
|
|
53
|
+
},
|
|
54
|
+
"operator": {
|
|
55
|
+
"description": "Operator selects the comparison.",
|
|
56
|
+
"enum": [
|
|
57
|
+
"BETWEEN",
|
|
58
|
+
"CONTAINS_TOKEN",
|
|
59
|
+
"EQ",
|
|
60
|
+
"GT",
|
|
61
|
+
"GTE",
|
|
62
|
+
"HAS_PROPERTY",
|
|
63
|
+
"IN",
|
|
64
|
+
"LT",
|
|
65
|
+
"LTE",
|
|
66
|
+
"NEQ",
|
|
67
|
+
"NOT_CONTAINS_TOKEN",
|
|
68
|
+
"NOT_HAS_PROPERTY",
|
|
69
|
+
"NOT_IN"
|
|
70
|
+
],
|
|
71
|
+
"type": "string"
|
|
72
|
+
},
|
|
73
|
+
"propertyName": {
|
|
74
|
+
"description": "PropertyName is an internal property name such as email, or an association pseudo-property such as associations.contact.",
|
|
75
|
+
"type": "string"
|
|
76
|
+
},
|
|
77
|
+
"value": {
|
|
78
|
+
"description": "Value is the comparison value for EQ, NEQ, LT, LTE, GT, GTE, BETWEEN, CONTAINS_TOKEN, and NOT_CONTAINS_TOKEN. Dates are Unix milliseconds.",
|
|
79
|
+
"type": "string"
|
|
80
|
+
},
|
|
81
|
+
"values": {
|
|
82
|
+
"description": "Values lists the candidates for IN and NOT_IN. HubSpot requires lowercase values when the property is a string property.",
|
|
83
|
+
"items": {
|
|
84
|
+
"type": "string"
|
|
85
|
+
},
|
|
86
|
+
"type": "array"
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"required": [
|
|
90
|
+
"operator",
|
|
91
|
+
"propertyName"
|
|
92
|
+
],
|
|
93
|
+
"type": "object"
|
|
94
|
+
},
|
|
95
|
+
"SearchFilterGroup": {
|
|
96
|
+
"additionalProperties": false,
|
|
97
|
+
"description": "SearchFilterGroup AND-s its filters. A search OR-s its groups.",
|
|
98
|
+
"properties": {
|
|
99
|
+
"filters": {
|
|
100
|
+
"description": "Filters are the conditions that must all match.",
|
|
101
|
+
"items": {
|
|
102
|
+
"$ref": "#/$defs/SearchFilter"
|
|
103
|
+
},
|
|
104
|
+
"type": [
|
|
105
|
+
"array",
|
|
106
|
+
"null"
|
|
107
|
+
]
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
"required": [
|
|
111
|
+
"filters"
|
|
112
|
+
],
|
|
113
|
+
"type": "object"
|
|
114
|
+
},
|
|
115
|
+
"SearchSort": {
|
|
116
|
+
"additionalProperties": false,
|
|
117
|
+
"description": "SearchSort orders search results by one property.",
|
|
118
|
+
"properties": {
|
|
119
|
+
"direction": {
|
|
120
|
+
"description": "Direction is ascending or descending.",
|
|
121
|
+
"enum": [
|
|
122
|
+
"ASCENDING",
|
|
123
|
+
"DESCENDING"
|
|
124
|
+
],
|
|
125
|
+
"type": "string"
|
|
126
|
+
},
|
|
127
|
+
"propertyName": {
|
|
128
|
+
"description": "PropertyName is the internal property name to sort by.",
|
|
129
|
+
"type": "string"
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
"required": [
|
|
133
|
+
"direction",
|
|
134
|
+
"propertyName"
|
|
135
|
+
],
|
|
136
|
+
"type": "object"
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
"additionalProperties": false,
|
|
140
|
+
"description": "SearchObjectsInput selects one bounded page of matching records.",
|
|
141
|
+
"properties": {
|
|
142
|
+
"after": {
|
|
143
|
+
"description": "After is the NextAfter cursor of the previous page; empty starts at the first result. Paging cannot pass HubSpot's 10,000th result.",
|
|
144
|
+
"type": "string"
|
|
145
|
+
},
|
|
146
|
+
"filterGroups": {
|
|
147
|
+
"description": "FilterGroups are OR-ed; empty matches every record. HubSpot allows five groups, six filters per group, and eighteen filters in total.",
|
|
148
|
+
"items": {
|
|
149
|
+
"$ref": "#/$defs/SearchFilterGroup"
|
|
150
|
+
},
|
|
151
|
+
"type": "array"
|
|
152
|
+
},
|
|
153
|
+
"limit": {
|
|
154
|
+
"description": "Limit is the page size from 1 through 200; zero uses 10.",
|
|
155
|
+
"type": "integer"
|
|
156
|
+
},
|
|
157
|
+
"objectType": {
|
|
158
|
+
"description": "ObjectType is the object type to search.",
|
|
159
|
+
"enum": [
|
|
160
|
+
"companies",
|
|
161
|
+
"contacts",
|
|
162
|
+
"deals"
|
|
163
|
+
],
|
|
164
|
+
"type": "string"
|
|
165
|
+
},
|
|
166
|
+
"properties": {
|
|
167
|
+
"description": "Properties lists the property values to return; empty returns HubSpot's default properties for the object type.",
|
|
168
|
+
"items": {
|
|
169
|
+
"type": "string"
|
|
170
|
+
},
|
|
171
|
+
"type": "array"
|
|
172
|
+
},
|
|
173
|
+
"query": {
|
|
174
|
+
"description": "Query optionally searches the object's default text properties.",
|
|
175
|
+
"type": "string"
|
|
176
|
+
},
|
|
177
|
+
"sort": {
|
|
178
|
+
"$ref": "#/$defs/SearchSort",
|
|
179
|
+
"description": "Sort optionally orders results; without it HubSpot returns oldest records first."
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
"required": [
|
|
183
|
+
"objectType"
|
|
184
|
+
],
|
|
185
|
+
"type": "object"
|
|
186
|
+
}
|
|
42
187
|
},
|
|
43
188
|
{
|
|
44
189
|
"name": "newGetObjectStep",
|
|
45
190
|
"kind": "query",
|
|
46
191
|
"operationId": "getObject",
|
|
192
|
+
"inputType": "GetObjectInput",
|
|
193
|
+
"description": "Read one HubSpot contact, company, or deal by record ID with the requested properties.",
|
|
47
194
|
"fields": {
|
|
48
195
|
"stepType": "stepType",
|
|
49
196
|
"annotations": "annotations",
|
|
@@ -76,12 +223,45 @@
|
|
|
76
223
|
"field": "defect",
|
|
77
224
|
"optional": true
|
|
78
225
|
}
|
|
79
|
-
]
|
|
226
|
+
],
|
|
227
|
+
"inputSchema": {
|
|
228
|
+
"additionalProperties": false,
|
|
229
|
+
"description": "GetObjectInput identifies one record.",
|
|
230
|
+
"properties": {
|
|
231
|
+
"objectId": {
|
|
232
|
+
"description": "ObjectID is HubSpot's decimal record ID.",
|
|
233
|
+
"type": "string"
|
|
234
|
+
},
|
|
235
|
+
"objectType": {
|
|
236
|
+
"description": "ObjectType is the record's object type.",
|
|
237
|
+
"enum": [
|
|
238
|
+
"companies",
|
|
239
|
+
"contacts",
|
|
240
|
+
"deals"
|
|
241
|
+
],
|
|
242
|
+
"type": "string"
|
|
243
|
+
},
|
|
244
|
+
"properties": {
|
|
245
|
+
"description": "Properties lists the property values to return; empty returns HubSpot's default properties for the object type.",
|
|
246
|
+
"items": {
|
|
247
|
+
"type": "string"
|
|
248
|
+
},
|
|
249
|
+
"type": "array"
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
"required": [
|
|
253
|
+
"objectId",
|
|
254
|
+
"objectType"
|
|
255
|
+
],
|
|
256
|
+
"type": "object"
|
|
257
|
+
}
|
|
80
258
|
},
|
|
81
259
|
{
|
|
82
260
|
"name": "newUpsertObjectStep",
|
|
83
261
|
"kind": "mutation",
|
|
84
262
|
"operationId": "upsertObject",
|
|
263
|
+
"inputType": "UpsertObjectInput",
|
|
264
|
+
"description": "Create or update one HubSpot contact, company, or deal identified by a unique property, such as email for contacts.",
|
|
85
265
|
"fields": {
|
|
86
266
|
"stepType": "stepType",
|
|
87
267
|
"annotations": "annotations",
|
|
@@ -114,12 +294,50 @@
|
|
|
114
294
|
"field": "defect",
|
|
115
295
|
"optional": true
|
|
116
296
|
}
|
|
117
|
-
]
|
|
297
|
+
],
|
|
298
|
+
"inputSchema": {
|
|
299
|
+
"additionalProperties": false,
|
|
300
|
+
"description": "UpsertObjectInput creates or updates one record identified by a unique property value.",
|
|
301
|
+
"properties": {
|
|
302
|
+
"idProperty": {
|
|
303
|
+
"description": "IDProperty is a unique identifier property: email for contacts, or a custom property created with unique values for any object type.",
|
|
304
|
+
"type": "string"
|
|
305
|
+
},
|
|
306
|
+
"idValue": {
|
|
307
|
+
"description": "IDValue is the unique value that identifies the record, such as the email address.",
|
|
308
|
+
"type": "string"
|
|
309
|
+
},
|
|
310
|
+
"objectType": {
|
|
311
|
+
"description": "ObjectType is the record's object type.",
|
|
312
|
+
"enum": [
|
|
313
|
+
"companies",
|
|
314
|
+
"contacts",
|
|
315
|
+
"deals"
|
|
316
|
+
],
|
|
317
|
+
"type": "string"
|
|
318
|
+
},
|
|
319
|
+
"properties": {
|
|
320
|
+
"additionalProperties": {
|
|
321
|
+
"type": "string"
|
|
322
|
+
},
|
|
323
|
+
"description": "Properties are the values to set, keyed by internal property name. An empty string clears a value.",
|
|
324
|
+
"type": "object"
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
"required": [
|
|
328
|
+
"idProperty",
|
|
329
|
+
"idValue",
|
|
330
|
+
"objectType"
|
|
331
|
+
],
|
|
332
|
+
"type": "object"
|
|
333
|
+
}
|
|
118
334
|
},
|
|
119
335
|
{
|
|
120
336
|
"name": "newUpdateObjectStep",
|
|
121
337
|
"kind": "mutation",
|
|
122
338
|
"operationId": "updateObject",
|
|
339
|
+
"inputType": "UpdateObjectInput",
|
|
340
|
+
"description": "Update properties of one HubSpot contact, company, or deal by record ID.",
|
|
123
341
|
"fields": {
|
|
124
342
|
"stepType": "stepType",
|
|
125
343
|
"annotations": "annotations",
|
|
@@ -157,7 +375,52 @@
|
|
|
157
375
|
"field": "defect",
|
|
158
376
|
"optional": true
|
|
159
377
|
}
|
|
160
|
-
]
|
|
378
|
+
],
|
|
379
|
+
"inputSchema": {
|
|
380
|
+
"additionalProperties": false,
|
|
381
|
+
"description": "UpdateObjectInput replaces property values on one record.",
|
|
382
|
+
"properties": {
|
|
383
|
+
"objectId": {
|
|
384
|
+
"description": "ObjectID is HubSpot's decimal record ID.",
|
|
385
|
+
"type": "string"
|
|
386
|
+
},
|
|
387
|
+
"objectType": {
|
|
388
|
+
"description": "ObjectType is the record's object type.",
|
|
389
|
+
"enum": [
|
|
390
|
+
"companies",
|
|
391
|
+
"contacts",
|
|
392
|
+
"deals"
|
|
393
|
+
],
|
|
394
|
+
"type": "string"
|
|
395
|
+
},
|
|
396
|
+
"properties": {
|
|
397
|
+
"additionalProperties": {
|
|
398
|
+
"type": "string"
|
|
399
|
+
},
|
|
400
|
+
"description": "Properties are the values to set, keyed by internal property name. At least one is required, and an empty string clears a value.",
|
|
401
|
+
"type": [
|
|
402
|
+
"object",
|
|
403
|
+
"null"
|
|
404
|
+
]
|
|
405
|
+
}
|
|
406
|
+
},
|
|
407
|
+
"required": [
|
|
408
|
+
"objectId",
|
|
409
|
+
"objectType",
|
|
410
|
+
"properties"
|
|
411
|
+
],
|
|
412
|
+
"type": "object"
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
{
|
|
416
|
+
"name": "defineCRMObjectChangedTriggerBinding",
|
|
417
|
+
"kind": "trigger",
|
|
418
|
+
"triggerName": "crmObjectChanged",
|
|
419
|
+
"fields": {
|
|
420
|
+
"connectionName": "connectionName",
|
|
421
|
+
"bindingName": "bindingName",
|
|
422
|
+
"configurationUI": "configurationUI"
|
|
423
|
+
}
|
|
161
424
|
}
|
|
162
425
|
]
|
|
163
426
|
}
|
|
@@ -26,7 +26,8 @@ function canonicalGoTimeJSON(value) {
|
|
|
26
26
|
var GoTimeJSONSchema = z.string().refine(isGoTimeJSON, "invalid Go time.Time JSON timestamp").transform(canonicalGoTimeJSON);
|
|
27
27
|
var ConfigSchema = z.object({
|
|
28
28
|
"endpoint": z.string().optional(),
|
|
29
|
-
"maxResponseBytes": z.number().int().optional()
|
|
29
|
+
"maxResponseBytes": z.number().int().optional(),
|
|
30
|
+
"pollIntervalMs": z.number().int().optional()
|
|
30
31
|
});
|
|
31
32
|
function decodeCredentials(value) {
|
|
32
33
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
|
|
@@ -214,7 +215,9 @@ var UpsertObjectDefinition = {
|
|
|
214
215
|
{ id: "invalidResponse", description: "HubSpot applied or rejected the upsert but returned an invalid or oversized response.", optional: true },
|
|
215
216
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
216
217
|
],
|
|
217
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
|
|
218
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" },
|
|
219
|
+
repeatOnUnknown: "limited",
|
|
220
|
+
maxSends: 3
|
|
218
221
|
};
|
|
219
222
|
var UpsertObjectMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
|
|
220
223
|
var UpdateObjectBranch = {
|
|
@@ -241,7 +244,9 @@ var UpdateObjectDefinition = {
|
|
|
241
244
|
{ id: "invalidResponse", description: "HubSpot applied or rejected the update but returned an invalid or oversized response.", optional: true },
|
|
242
245
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
243
246
|
],
|
|
244
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
|
|
247
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" },
|
|
248
|
+
repeatOnUnknown: "limited",
|
|
249
|
+
maxSends: 3
|
|
245
250
|
};
|
|
246
251
|
var UpdateObjectMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
|
|
247
252
|
|
|
@@ -7,11 +7,14 @@ interface Config {
|
|
|
7
7
|
endpoint?: string;
|
|
8
8
|
/** Maximum complete HubSpot API response in bytes; enter a positive integer only to change the safety limit. Oversized responses select invalidResponse. */
|
|
9
9
|
maxResponseBytes?: number;
|
|
10
|
+
/** Delay between crmObjectChanged Trigger polls of HubSpot CRM search, as a Go duration of at least 5s such as 15s or 2m; leave it blank for the default interval. Shorter intervals deliver changes sooner and use more of the account's search limit of five requests per second and its daily API limit. Runtime value in milliseconds. */
|
|
11
|
+
pollIntervalMs?: number;
|
|
10
12
|
}
|
|
11
13
|
/** Runtime schema for manifest configuration. */
|
|
12
14
|
declare const ConfigSchema: z.ZodObject<{
|
|
13
15
|
endpoint: z.ZodOptional<z.ZodString>;
|
|
14
16
|
maxResponseBytes: z.ZodOptional<z.ZodNumber>;
|
|
17
|
+
pollIntervalMs: z.ZodOptional<z.ZodNumber>;
|
|
15
18
|
}, z.core.$strip>;
|
|
16
19
|
/** Private connector credentials resolved by the host. */
|
|
17
20
|
interface Credentials {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { G as GetObjectInput, C as CRMObject, a as Connection, S as SearchObjectsInput, O as ObjectPage, U as UpdateObjectInput, b as UpsertObjectInput, c as UpsertedObject, d as Config, e as CredentialSource, f as Operations } from './connection-
|
|
2
|
-
export { g as CRMObjectSchema, h as ConfigSchema, i as Credentials, j as GetObjectInputSchema, k as ObjectPageSchema, l as SearchFilter, m as SearchFilterGroup, n as SearchFilterGroupSchema, o as SearchFilterSchema, p as SearchObjectsInputSchema, q as SearchSort, r as SearchSortSchema, s as UpdateObjectInputSchema, t as UpsertObjectInputSchema, u as UpsertedObjectSchema, v as decodeCredentials, w as decodeSharedCredentials, x as newConnection, y as newConnectionWithOperations } from './connection-
|
|
1
|
+
import { G as GetObjectInput, C as CRMObject, a as Connection, S as SearchObjectsInput, O as ObjectPage, U as UpdateObjectInput, b as UpsertObjectInput, c as UpsertedObject, d as Config, e as CredentialSource, f as Operations } from './connection-pqfXajbM.js';
|
|
2
|
+
export { g as CRMObjectSchema, h as ConfigSchema, i as Credentials, j as GetObjectInputSchema, k as ObjectPageSchema, l as SearchFilter, m as SearchFilterGroup, n as SearchFilterGroupSchema, o as SearchFilterSchema, p as SearchObjectsInputSchema, q as SearchSort, r as SearchSortSchema, s as UpdateObjectInputSchema, t as UpsertObjectInputSchema, u as UpsertedObjectSchema, v as decodeCredentials, w as decodeSharedCredentials, x as newConnection, y as newConnectionWithOperations } from './connection-pqfXajbM.js';
|
|
3
3
|
import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
|
|
4
|
-
import { QueryDefinition, MutationDefinition, QueryStepConfig, Query, QueryResult, MutationStepConfig, Mutation, MutationResult, QueryStep, MutationStep, Call, QueryAttempt, MutationAttempt, ReceiptDraft, Failure } from '@superdurable/connectors-sdk';
|
|
4
|
+
import { QueryDefinition, MutationDefinition, QueryStepConfig, Query, QueryResult, MutationStepConfig, Mutation, MutationResult, QueryStep, MutationStep, Call, QueryAttempt, MutationAttempt, TriggerLogger, ReceiptDraft, Failure, ConnectorConfigurationUI, TriggerDefinition, TriggerBindingDefinition, TriggerTarget, TriggerRunner } from '@superdurable/connectors-sdk';
|
|
5
5
|
import { StepTarget } from '@superdurable/dex';
|
|
6
6
|
import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
|
|
7
7
|
import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
|
|
8
|
-
import 'zod';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { CursorStore, Runner } from '@superdurable/connectors-sdk/pollingtrigger';
|
|
9
10
|
|
|
10
11
|
/** Stable connector identity. */
|
|
11
12
|
declare const ConnectorID = "hubspot";
|
|
@@ -201,6 +202,7 @@ interface UpdateObjectStepConfig<StepInput, OperationInput = UpdateObjectInput,
|
|
|
201
202
|
/** Build the updateObject Step from a named connection. */
|
|
202
203
|
declare function newUpdateObjectStep<StepInput, OperationInput = UpdateObjectInput, OperationOutput = CRMObject>(configuration: UpdateObjectStepConfig<StepInput, OperationInput, OperationOutput>): MutationStep<StepInput, OperationInput, OperationOutput>;
|
|
203
204
|
|
|
205
|
+
/** A supported CRM object type. */ type ObjectType = SearchObjectsInput['objectType'];
|
|
204
206
|
/** Search one bounded CRM page. */
|
|
205
207
|
declare class SearchObjectsOperation implements Query<SearchObjectsInput, ObjectPage> {
|
|
206
208
|
private readonly client;
|
|
@@ -221,7 +223,7 @@ declare class GetObjectOperation implements Query<GetObjectInput, CRMObject> {
|
|
|
221
223
|
declare class UpsertObjectOperation implements Mutation<UpsertObjectInput, UpsertedObject> {
|
|
222
224
|
private readonly client;
|
|
223
225
|
/** Bind a client. */ constructor(client: HubSpotClient);
|
|
224
|
-
/** Return the manifest definition. */ definition(): _superdurable_connectors_sdk.
|
|
226
|
+
/** Return the manifest definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
|
|
225
227
|
/** Reuse the stable Call ID for a repeat-safe upsert. */ idempotencyKey(callId: string): string;
|
|
226
228
|
/** Validate and dispatch, repeating one conflicting upsert. */
|
|
227
229
|
invoke(call: Call, input: UpsertObjectInput): Promise<MutationAttempt<UpsertedObject>>;
|
|
@@ -230,7 +232,7 @@ declare class UpsertObjectOperation implements Mutation<UpsertObjectInput, Upser
|
|
|
230
232
|
declare class UpdateObjectOperation implements Mutation<UpdateObjectInput, CRMObject> {
|
|
231
233
|
private readonly client;
|
|
232
234
|
/** Bind a client. */ constructor(client: HubSpotClient);
|
|
233
|
-
/** Return the manifest definition. */ definition(): _superdurable_connectors_sdk.
|
|
235
|
+
/** Return the manifest definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
|
|
234
236
|
/** Reuse the stable Call ID for an absolute update. */ idempotencyKey(callId: string): string;
|
|
235
237
|
/** Validate, send, and decode one update. */
|
|
236
238
|
invoke(call: Call, input: UpdateObjectInput): Promise<MutationAttempt<CRMObject>>;
|
|
@@ -242,6 +244,12 @@ interface HubSpotClientOptions {
|
|
|
242
244
|
send?: (request: ProviderRequest) => Promise<ProviderResponse>;
|
|
243
245
|
/** Clock used for retry dates and receipts. */
|
|
244
246
|
now?: () => Date;
|
|
247
|
+
/**
|
|
248
|
+
* Receives the crmObjectChanged Trigger runner's records: seeds, reseeds after an unusable cursor, failed polls,
|
|
249
|
+
* rate-limit pauses, and the durable inboxes newProjectCRMObjectTriggerRunner opens. Records carry binding
|
|
250
|
+
* identity and never record properties or credentials. Omitted uses defaultTriggerLogger. Operation Steps do not log.
|
|
251
|
+
*/
|
|
252
|
+
logger?: TriggerLogger;
|
|
245
253
|
}
|
|
246
254
|
/** Classified unsuccessful exchange. */
|
|
247
255
|
interface ExchangeFailure {
|
|
@@ -267,8 +275,14 @@ declare class HubSpotClient {
|
|
|
267
275
|
private readonly maxResponseBytes;
|
|
268
276
|
private readonly send;
|
|
269
277
|
private readonly now;
|
|
278
|
+
/** Delay between crmObjectChanged polls in milliseconds. */ readonly pollIntervalMs: number;
|
|
279
|
+
/** Trigger record destination. */ readonly triggerLogger: TriggerLogger;
|
|
270
280
|
private readonly refreshDriver;
|
|
271
|
-
/**
|
|
281
|
+
/**
|
|
282
|
+
* Validate settings and bind a credential source without contacting HubSpot. A blank endpoint uses
|
|
283
|
+
* https://api.hubapi.com, a zero maxResponseBytes uses one MiB, and a zero pollIntervalMs uses 30 seconds;
|
|
284
|
+
* pollIntervalMs must be at least 5 seconds.
|
|
285
|
+
*/
|
|
272
286
|
constructor(config: Config, credentials: CredentialSource, options?: HubSpotClientOptions);
|
|
273
287
|
/** Bind the search query. */ searchObjects(): SearchObjectsOperation;
|
|
274
288
|
/** Bind the record query. */ getObject(): GetObjectOperation;
|
|
@@ -289,4 +303,141 @@ declare class HubSpotClient {
|
|
|
289
303
|
/** Open a named HubSpot project connection with generated OAuth credential wiring. */
|
|
290
304
|
declare function newProjectConnection(project: LoadedProject, connectionName: string, options?: HubSpotClientOptions): Connection<Operations>;
|
|
291
305
|
|
|
292
|
-
|
|
306
|
+
/** HubSpot object type picker UI unit, which stores HubSpot's object name. */ declare const UIUnitObjectTypePicker = "objectTypePicker";
|
|
307
|
+
/** Object type picker output port. */ declare const UIObjectTypePickerPortObjectType = "objectType";
|
|
308
|
+
/**
|
|
309
|
+
* Bounds CRMObjectChangedTriggerConfiguration.properties; the Trigger always requests the record's creation and
|
|
310
|
+
* last-modified dates beside them.
|
|
311
|
+
*/
|
|
312
|
+
declare const MaximumTriggerProperties: number;
|
|
313
|
+
/**
|
|
314
|
+
* A record HubSpot created after the newest change an earlier poll of the binding observed, so no earlier
|
|
315
|
+
* delivery or baseline included it.
|
|
316
|
+
*/
|
|
317
|
+
declare const CRMObjectChangeCreated = "created";
|
|
318
|
+
/** Any other change to a record's properties, including a record that appeared in search only after HubSpot's indexing delay. */
|
|
319
|
+
declare const CRMObjectChangeUpdated = "updated";
|
|
320
|
+
/** The derived kind of one crmObjectChanged delivery. */
|
|
321
|
+
type CRMObjectChangeKind = typeof CRMObjectChangeCreated | typeof CRMObjectChangeUpdated;
|
|
322
|
+
/**
|
|
323
|
+
* The crmObjectChanged binding configuration that the object type picker saves in Dex Web. Changing the object
|
|
324
|
+
* type of a binding that already polled makes its next poll record a new baseline for the new object type.
|
|
325
|
+
*/
|
|
326
|
+
interface CRMObjectChangedTriggerConfiguration {
|
|
327
|
+
/** The watched object type, contacts, companies, or deals, saved by the object type picker. It is required. */
|
|
328
|
+
objectType: ObjectType;
|
|
329
|
+
/**
|
|
330
|
+
* Internal property names, such as email or dealstage, to return on each delivered record, at most
|
|
331
|
+
* MaximumTriggerProperties. Empty returns HubSpot's default search properties. The Dex Web picker does not
|
|
332
|
+
* set it; an application sets it in code.
|
|
333
|
+
*/
|
|
334
|
+
properties?: string[] | null | undefined;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Decodes a saved crmObjectChanged configuration strictly; unknown fields are rejected. It does not validate
|
|
338
|
+
* values; validateCRMObjectChangedTriggerConfiguration does, as every runner and Trigger factory does.
|
|
339
|
+
*/
|
|
340
|
+
declare const CRMObjectChangedTriggerConfigurationSchema: z.ZodType<CRMObjectChangedTriggerConfiguration>;
|
|
341
|
+
/**
|
|
342
|
+
* Reject a missing or unsupported object type, invalid property names, and a property list whose search request
|
|
343
|
+
* would exceed HubSpot's request body limit, as the Go connector's Validate does.
|
|
344
|
+
*/
|
|
345
|
+
declare function validateCRMObjectChangedTriggerConfiguration(configuration: CRMObjectChangedTriggerConfiguration): void;
|
|
346
|
+
/**
|
|
347
|
+
* One created or changed HubSpot CRM record read through CRM search. Several edits made between two polls
|
|
348
|
+
* arrive as one change carrying the record's latest values. Deleted, archived, and merged-away records are not
|
|
349
|
+
* reported, because CRM search does not return them. Field names match the Go connector.
|
|
350
|
+
*/
|
|
351
|
+
interface CRMObjectChangedEvent {
|
|
352
|
+
/** The watched object type. */ objectType: ObjectType;
|
|
353
|
+
/** The derived change kind; see CRMObjectChangeKind. */ changeKind: CRMObjectChangeKind;
|
|
354
|
+
/**
|
|
355
|
+
* The record's last-modified date, lastmodifieddate for contacts and hs_lastmodifieddate otherwise, in UTC with
|
|
356
|
+
* millisecond precision, as Go encodes a time.Time.
|
|
357
|
+
*/
|
|
358
|
+
modifiedAt: string;
|
|
359
|
+
/** The record as CRM search returned it, with the configured properties. */ object: CRMObject;
|
|
360
|
+
}
|
|
361
|
+
/** Decodes a crmObjectChanged payload that this package or the Go connector recorded. */
|
|
362
|
+
declare const CRMObjectChangedEventSchema: z.ZodType<CRMObjectChangedEvent>;
|
|
363
|
+
/** Manifest definition of crmObjectChanged. */
|
|
364
|
+
declare const CRMObjectChangedTriggerDefinition: TriggerDefinition;
|
|
365
|
+
/** One static application binding of crmObjectChanged. */
|
|
366
|
+
interface CRMObjectChangedTriggerBindingConfig {
|
|
367
|
+
/** Static connection name. */ connectionName: string;
|
|
368
|
+
/** Static binding name. */ bindingName: string;
|
|
369
|
+
/** Connector Studio configuration units for the binding, such as the objectTypePicker unit. */ configurationUI: ConnectorConfigurationUI;
|
|
370
|
+
}
|
|
371
|
+
/** Declare a static crmObjectChanged binding for Flow Definition tooling and Dex Web. */
|
|
372
|
+
declare function defineCRMObjectChangedTriggerBinding(config: CRMObjectChangedTriggerBindingConfig): TriggerBindingDefinition;
|
|
373
|
+
|
|
374
|
+
/** One unsuccessful search exchange; its message carries no record data. */
|
|
375
|
+
declare class CRMObjectChangeSearchError extends Error {
|
|
376
|
+
readonly failure: Failure;
|
|
377
|
+
/** Wrap the classified failure of one search. */
|
|
378
|
+
constructor(failure: Failure);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Binds one crmObjectChanged configuration to its application target and cursor. */
|
|
382
|
+
interface CRMObjectChangedTriggerRoute {
|
|
383
|
+
/** The stable application binding name, unique within the runner. */ bindingName: string;
|
|
384
|
+
/** Selects the watched object type and the returned properties. */ configuration: CRMObjectChangedTriggerConfiguration;
|
|
385
|
+
/**
|
|
386
|
+
* Routes each change into the application. A target that prepares deliveries, such as newDurableTriggerTarget,
|
|
387
|
+
* records each change before the cursor commits past it; any other target consumes it first.
|
|
388
|
+
*/
|
|
389
|
+
target: TriggerTarget<CRMObjectChangedEvent>;
|
|
390
|
+
/**
|
|
391
|
+
* Stores the binding's search position, such as LoadedProject.pollCursorStore. Omitted keeps it in memory, so
|
|
392
|
+
* every process start records a new baseline and changes made while stopped are lost.
|
|
393
|
+
*/
|
|
394
|
+
cursor?: CursorStore | undefined;
|
|
395
|
+
}
|
|
396
|
+
/** Configures every HubSpot Trigger binding polled through one connection. */
|
|
397
|
+
interface CRMObjectTriggerRunnerConfig {
|
|
398
|
+
/** A connection from newProjectConnection or newConnection with a HubSpotClient. */ connection: Connection;
|
|
399
|
+
/** The crmObjectChanged bindings; at least one is required. */ crmObjectChangedRoutes: readonly CRMObjectChangedTriggerRoute[];
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Create one poll runner for the configured crmObjectChanged bindings. run replays each durable target, records a
|
|
403
|
+
* baseline for a binding without a cursor, then polls every binding each pollInterval with jitter, in
|
|
404
|
+
* configuration order, one search request at a time. A 429 or 423 pauses every binding of the connection for
|
|
405
|
+
* Retry-After or X-HubSpot-RateLimit-Interval-Milliseconds, and an exhausted daily limit backs off exponentially up
|
|
406
|
+
* to 15 minutes; other failures back off per binding. A paging offset HubSpot rejects records a new baseline and
|
|
407
|
+
* logs a WARN record. Delivery is at least once, and each record version keeps one Trigger event ID across
|
|
408
|
+
* refetches. Throws for invalid wiring or configuration.
|
|
409
|
+
*/
|
|
410
|
+
declare function newCRMObjectTriggerRunner(config: CRMObjectTriggerRunnerConfig): Runner;
|
|
411
|
+
/** Selects one crmObjectChanged binding saved in the project configuration. */
|
|
412
|
+
interface ProjectCRMObjectChangedTriggerRoute {
|
|
413
|
+
/** Names the saved binding. */ bindingName: string;
|
|
414
|
+
/** Property names to return on each delivered record, as the configuration's properties; applies when the saved binding names none. */ properties?: string[] | undefined;
|
|
415
|
+
/** Routes each change into the application, usually newDexFlowTriggerTarget. */ target: TriggerTarget<CRMObjectChangedEvent>;
|
|
416
|
+
}
|
|
417
|
+
/** Selects HubSpot Trigger bindings saved in the project configuration. */
|
|
418
|
+
interface ProjectCRMObjectTriggerRunnerConfig {
|
|
419
|
+
/** The crmObjectChanged bindings; at least one is required. */ crmObjectChangedRoutes: readonly ProjectCRMObjectChangedTriggerRoute[];
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Open connectionName from the loaded project, load each binding's saved object type, and create a durable runner:
|
|
423
|
+
* each route records changes in its binding's project Trigger inbox before its search position commits in the
|
|
424
|
+
* binding's project poll cursor, so a restarted or replaced replica neither misses nor repeats a change. A binding
|
|
425
|
+
* without a saved object type throws. The options' logger also applies to those inboxes.
|
|
426
|
+
*/
|
|
427
|
+
declare function newProjectCRMObjectTriggerRunner(project: LoadedProject, connectionName: string, config: ProjectCRMObjectTriggerRunnerConfig, options?: HubSpotClientOptions): Runner;
|
|
428
|
+
/** Configuration of one crmObjectChanged Trigger built by hand. */
|
|
429
|
+
interface CRMObjectChangedTriggerConfig {
|
|
430
|
+
/** A connection from newProjectConnection or newConnection with a HubSpotClient. */ connection: Connection;
|
|
431
|
+
/** Static connection name; must equal the connection's name. */ connectionName: string;
|
|
432
|
+
/** Static binding name. */ bindingName: string;
|
|
433
|
+
/** The watched object type and returned properties. */ configuration: CRMObjectChangedTriggerConfiguration;
|
|
434
|
+
/** Routes each change into the application. */ target: TriggerTarget<CRMObjectChangedEvent>;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Create one crmObjectChanged Trigger polled every pollInterval. It has no project storage, so it keeps the cursor
|
|
438
|
+
* in memory and records a new baseline on every start; use newProjectCRMObjectTriggerRunner for durable polling.
|
|
439
|
+
* Throws for an invalid configuration or a connection name that differs from the connection's.
|
|
440
|
+
*/
|
|
441
|
+
declare function newCRMObjectChangedTrigger(config: CRMObjectChangedTriggerConfig): TriggerRunner;
|
|
442
|
+
|
|
443
|
+
export { CRMObject, CRMObjectChangeCreated, type CRMObjectChangeKind, CRMObjectChangeSearchError, CRMObjectChangeUpdated, type CRMObjectChangedEvent, CRMObjectChangedEventSchema, type CRMObjectChangedTriggerBindingConfig, type CRMObjectChangedTriggerConfig, type CRMObjectChangedTriggerConfiguration, CRMObjectChangedTriggerConfigurationSchema, CRMObjectChangedTriggerDefinition, type CRMObjectChangedTriggerRoute, type CRMObjectTriggerRunnerConfig, Config, Connection, ConnectorID, CredentialSource, GetObjectBranch, GetObjectBranchDefect, GetObjectBranchFound, GetObjectBranchInvalidResponse, GetObjectBranchNotFound, GetObjectBranchProviderRejected, GetObjectDefinition, GetObjectInput, GetObjectMetadata, GetObjectOperation, type GetObjectStepConfig, HubSpotClient, type HubSpotClientOptions, MaximumTriggerProperties, ObjectPage, type ProjectCRMObjectChangedTriggerRoute, type ProjectCRMObjectTriggerRunnerConfig, ProviderID, SearchObjectsBranch, SearchObjectsBranchDefect, SearchObjectsBranchInvalidResponse, SearchObjectsBranchProviderRejected, SearchObjectsBranchSearched, SearchObjectsDefinition, SearchObjectsInput, SearchObjectsMetadata, SearchObjectsOperation, type SearchObjectsStepConfig, UIObjectTypePickerPortObjectType, UIUnitObjectTypePicker, UpdateObjectBranch, UpdateObjectBranchConflict, UpdateObjectBranchDefect, UpdateObjectBranchInvalidResponse, UpdateObjectBranchNotFound, UpdateObjectBranchProviderRejected, UpdateObjectBranchUpdated, UpdateObjectDefinition, UpdateObjectInput, UpdateObjectMetadata, UpdateObjectOperation, type UpdateObjectStepConfig, UpsertObjectBranch, UpsertObjectBranchConflict, UpsertObjectBranchDefect, UpsertObjectBranchInvalidResponse, UpsertObjectBranchProviderRejected, UpsertObjectBranchUpserted, UpsertObjectDefinition, UpsertObjectInput, UpsertObjectMetadata, UpsertObjectOperation, type UpsertObjectStepConfig, UpsertedObject, defineCRMObjectChangedTriggerBinding, newCRMObjectChangedTrigger, newCRMObjectTriggerRunner, newGetObjectStep, newProjectCRMObjectTriggerRunner, newProjectConnection, newSearchObjectsStep, newUpdateObjectStep, newUpsertObjectStep, validateCRMObjectChangedTriggerConfiguration };
|
package/dist/index.js
CHANGED
|
@@ -51,7 +51,7 @@ import {
|
|
|
51
51
|
newConnectionWithOperations,
|
|
52
52
|
newProjectConnection,
|
|
53
53
|
newProjectCredentialProvider
|
|
54
|
-
} from "./chunk-
|
|
54
|
+
} from "./chunk-HHRHOJKC.js";
|
|
55
55
|
|
|
56
56
|
// src/generated/steps.ts
|
|
57
57
|
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
@@ -101,7 +101,7 @@ function newUpdateObjectStep(configuration) {
|
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
// src/client.ts
|
|
104
|
-
import { ReauthorizationRequiredError, RetryError, resolveCredential, resolveCredentialAfterRejection, SecretString } from "@superdurable/connectors-sdk";
|
|
104
|
+
import { ReauthorizationRequiredError, RetryError, defaultTriggerLogger, resolveCredential, resolveCredentialAfterRejection, SecretString } from "@superdurable/connectors-sdk";
|
|
105
105
|
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
106
106
|
import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
107
107
|
|
|
@@ -174,7 +174,8 @@ var Authorization = {
|
|
|
174
174
|
"invalid_grant",
|
|
175
175
|
"invalid_client",
|
|
176
176
|
"unauthorized_client"
|
|
177
|
-
]
|
|
177
|
+
],
|
|
178
|
+
"tokenExchangeTimeout": "25s"
|
|
178
179
|
},
|
|
179
180
|
"scopes": [
|
|
180
181
|
"oauth",
|
|
@@ -231,24 +232,7 @@ var SearchObjectsOperation = class {
|
|
|
231
232
|
if ("outcome" in result) return queryOutcome(result.outcome, zeroPage, "providerRejected");
|
|
232
233
|
const receipt = this.client.receipt(call, result.response);
|
|
233
234
|
try {
|
|
234
|
-
|
|
235
|
-
const total = integerField(decoded, "total");
|
|
236
|
-
if (total < 0) throw new TypeError("HubSpot returned a malformed response");
|
|
237
|
-
const results = decoded.results;
|
|
238
|
-
if (results !== void 0 && results !== null && !Array.isArray(results)) throw new TypeError("HubSpot returned a malformed response");
|
|
239
|
-
const objects = (results ?? []).map((item) => decodeCRMObject(input.objectType, item));
|
|
240
|
-
const page = { objectType: input.objectType, total, objects };
|
|
241
|
-
if (decoded.paging !== void 0 && decoded.paging !== null) {
|
|
242
|
-
const paging = requireObject(decoded.paging);
|
|
243
|
-
if (paging.next !== void 0 && paging.next !== null) {
|
|
244
|
-
const after = stringField(requireObject(paging.next), "after");
|
|
245
|
-
if (after) {
|
|
246
|
-
if (!cursor.test(after)) throw new TypeError("HubSpot returned an invalid search cursor");
|
|
247
|
-
page.nextAfter = after;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
return newQueryBranch("searched", page, receipt);
|
|
235
|
+
return newQueryBranch("searched", decodeObjectPage(input.objectType, result.response.body), receipt);
|
|
252
236
|
} catch (error) {
|
|
253
237
|
return queryFailure("searchObjects", "invalidResponse", "PROTOCOL", zeroPage, receipt, error);
|
|
254
238
|
}
|
|
@@ -476,6 +460,26 @@ function requireObject(value) {
|
|
|
476
460
|
function jsonObject(body) {
|
|
477
461
|
return requireObject(JSON.parse(Buffer.from(body).toString()));
|
|
478
462
|
}
|
|
463
|
+
function decodeObjectPage(objectType, body) {
|
|
464
|
+
const decoded = jsonObject(body);
|
|
465
|
+
const total = integerField(decoded, "total");
|
|
466
|
+
if (total < 0) throw new TypeError("HubSpot returned a malformed response");
|
|
467
|
+
const results = decoded.results;
|
|
468
|
+
if (results !== void 0 && results !== null && !Array.isArray(results)) throw new TypeError("HubSpot returned a malformed response");
|
|
469
|
+
const objects = (results ?? []).map((item) => decodeCRMObject(objectType, item));
|
|
470
|
+
const page = { objectType, total, objects };
|
|
471
|
+
if (decoded.paging !== void 0 && decoded.paging !== null) {
|
|
472
|
+
const paging = requireObject(decoded.paging);
|
|
473
|
+
if (paging.next !== void 0 && paging.next !== null) {
|
|
474
|
+
const after = stringField(requireObject(paging.next), "after");
|
|
475
|
+
if (after) {
|
|
476
|
+
if (!cursor.test(after)) throw new TypeError("HubSpot returned an invalid search cursor");
|
|
477
|
+
page.nextAfter = after;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return page;
|
|
482
|
+
}
|
|
479
483
|
function stringField(value, field) {
|
|
480
484
|
const candidate = value[field];
|
|
481
485
|
if (candidate === null || candidate === void 0) return "";
|
|
@@ -539,15 +543,24 @@ function appURL(value) {
|
|
|
539
543
|
|
|
540
544
|
// src/client.ts
|
|
541
545
|
var defaultEndpoint = "https://api.hubapi.com";
|
|
546
|
+
var defaultPollIntervalMs = 3e4;
|
|
547
|
+
var minimumPollIntervalMs = 5e3;
|
|
542
548
|
var knownCategories = /* @__PURE__ */ new Set(["BAD_REQUEST", "CONFLICT", "EXPIRED_AUTHENTICATION", "INVALID_AUTHENTICATION", "MISSING_SCOPES", "OBJECT_ALREADY_EXISTS", "OBJECT_NOT_FOUND", "RATE_LIMITS", "VALIDATION_ERROR"]);
|
|
543
549
|
var HubSpotClient = class {
|
|
544
|
-
/**
|
|
550
|
+
/**
|
|
551
|
+
* Validate settings and bind a credential source without contacting HubSpot. A blank endpoint uses
|
|
552
|
+
* https://api.hubapi.com, a zero maxResponseBytes uses one MiB, and a zero pollIntervalMs uses 30 seconds;
|
|
553
|
+
* pollIntervalMs must be at least 5 seconds.
|
|
554
|
+
*/
|
|
545
555
|
constructor(config, credentials, options = {}) {
|
|
546
556
|
this.credentials = credentials;
|
|
547
557
|
if (!credentials) throw new TypeError("HubSpot credential provider is required");
|
|
548
558
|
this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
549
559
|
this.maxResponseBytes = config.maxResponseBytes || 1048576;
|
|
550
560
|
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("HubSpot maxResponseBytes must be positive");
|
|
561
|
+
this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
|
|
562
|
+
if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("HubSpot pollInterval must be at least 5s");
|
|
563
|
+
this.triggerLogger = options.logger ?? defaultTriggerLogger;
|
|
551
564
|
this.send = options.send ?? sendProviderRequest;
|
|
552
565
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
553
566
|
}
|
|
@@ -556,6 +569,10 @@ var HubSpotClient = class {
|
|
|
556
569
|
maxResponseBytes;
|
|
557
570
|
send;
|
|
558
571
|
now;
|
|
572
|
+
/** Delay between crmObjectChanged polls in milliseconds. */
|
|
573
|
+
pollIntervalMs;
|
|
574
|
+
/** Trigger record destination. */
|
|
575
|
+
triggerLogger;
|
|
559
576
|
refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "HubSpot", auth: Authorization, credentialFields: CredentialFields });
|
|
560
577
|
/** Bind the search query. */
|
|
561
578
|
searchObjects() {
|
|
@@ -704,11 +721,398 @@ function newProjectConnection2(project, connectionName, options = {}) {
|
|
|
704
721
|
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
705
722
|
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "hubspot" && entry.connectionName === name);
|
|
706
723
|
if (!selected) throw new TypeError("HubSpot project connection is not configured");
|
|
707
|
-
const
|
|
724
|
+
const { pollInterval, ...settings } = selected.configuration ?? {};
|
|
725
|
+
const config = ConfigSchema.parse({ ...settings, ...pollInterval === void 0 || pollInterval === null ? {} : { pollIntervalMs: pollIntervalMilliseconds(pollInterval) } });
|
|
708
726
|
return new HubSpotClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
|
|
709
727
|
});
|
|
710
728
|
}
|
|
729
|
+
function pollIntervalMilliseconds(value) {
|
|
730
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("HubSpot configuration pollInterval must be a whole number of nanoseconds");
|
|
731
|
+
return Math.floor(value / 1e6);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// src/crm_object_changed.ts
|
|
735
|
+
import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
|
|
736
|
+
import { z } from "zod";
|
|
737
|
+
|
|
738
|
+
// src/crm_object_change_search.ts
|
|
739
|
+
var MaximumSearchResults = 1e4;
|
|
740
|
+
var crmObjectChangePageSize = 100;
|
|
741
|
+
var rfc3339Pattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
742
|
+
function lastModifiedProperty(objectType) {
|
|
743
|
+
return objectType === "contacts" ? "lastmodifieddate" : "hs_lastmodifieddate";
|
|
744
|
+
}
|
|
745
|
+
function newCRMObjectChangeSearch(configuration, anchorMilliseconds, after) {
|
|
746
|
+
const modifiedProperty = lastModifiedProperty(configuration.objectType);
|
|
747
|
+
return {
|
|
748
|
+
objectType: configuration.objectType,
|
|
749
|
+
filterGroups: [{ filters: [{ propertyName: modifiedProperty, operator: "GTE", value: String(anchorMilliseconds) }] }],
|
|
750
|
+
sort: { propertyName: modifiedProperty, direction: "ASCENDING" },
|
|
751
|
+
properties: [...configuration.properties ?? [], "createdate", modifiedProperty],
|
|
752
|
+
limit: crmObjectChangePageSize,
|
|
753
|
+
...after ? { after } : {}
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
function parseRFC3339Milliseconds(text) {
|
|
757
|
+
const match = rfc3339Pattern.exec(text);
|
|
758
|
+
if (!match) return void 0;
|
|
759
|
+
const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
|
|
760
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month) || hour > 23 || minute > 59 || second > 59) return void 0;
|
|
761
|
+
let offsetMinutes = 0;
|
|
762
|
+
if (match[8] !== "Z") {
|
|
763
|
+
const offsetHours = Number(match[10]), offsetMinute = Number(match[11]);
|
|
764
|
+
if (offsetHours > 24 || offsetMinute > 60) return void 0;
|
|
765
|
+
offsetMinutes = (match[9] === "-" ? -1 : 1) * (offsetHours * 60 + offsetMinute);
|
|
766
|
+
}
|
|
767
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
768
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
769
|
+
date.setUTCHours(hour, minute, second, 0);
|
|
770
|
+
const fractionMilliseconds = Math.floor(Number((match[7] ?? "").slice(0, 9).padEnd(9, "0") || "0") / 1e6);
|
|
771
|
+
return date.getTime() - offsetMinutes * 6e4 + fractionMilliseconds;
|
|
772
|
+
}
|
|
773
|
+
function formatGoTimeMilliseconds(milliseconds) {
|
|
774
|
+
return new Date(milliseconds).toISOString().replace(/\.(\d*?)0*Z$/, (_whole, digits) => digits ? `.${digits}Z` : "Z");
|
|
775
|
+
}
|
|
776
|
+
function recordModifiedMilliseconds(object) {
|
|
777
|
+
const value = object.properties?.[lastModifiedProperty(object.objectType)];
|
|
778
|
+
if (value !== void 0) {
|
|
779
|
+
const parsed = parseRFC3339Milliseconds(value);
|
|
780
|
+
if (parsed === void 0) throw new Error("HubSpot returned an invalid last-modified date");
|
|
781
|
+
return parsed;
|
|
782
|
+
}
|
|
783
|
+
const updated = object.updatedAt ? parseRFC3339Milliseconds(object.updatedAt) : void 0;
|
|
784
|
+
if (updated === void 0) throw new Error("HubSpot returned a record without a last-modified date");
|
|
785
|
+
return updated;
|
|
786
|
+
}
|
|
787
|
+
function recordCreatedMilliseconds(object) {
|
|
788
|
+
return (object.createdAt ? parseRFC3339Milliseconds(object.createdAt) : void 0) ?? Number.NEGATIVE_INFINITY;
|
|
789
|
+
}
|
|
790
|
+
function daysInMonth(year, month) {
|
|
791
|
+
if (month === 2) return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0 ? 29 : 28;
|
|
792
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// src/crm_object_changed.ts
|
|
796
|
+
var UIUnitObjectTypePicker = "objectTypePicker";
|
|
797
|
+
var UIObjectTypePickerPortObjectType = "objectType";
|
|
798
|
+
var maximumProperties = 100;
|
|
799
|
+
var MaximumTriggerProperties = maximumProperties - 2;
|
|
800
|
+
var CRMObjectChangeCreated = "created";
|
|
801
|
+
var CRMObjectChangeUpdated = "updated";
|
|
802
|
+
var CRMObjectChangedTriggerConfigurationSchema = z.strictObject({
|
|
803
|
+
objectType: z.string().nullable().optional().transform((value) => value ?? ""),
|
|
804
|
+
properties: z.array(z.string()).nullable().optional()
|
|
805
|
+
});
|
|
806
|
+
function validateCRMObjectChangedTriggerConfiguration(configuration) {
|
|
807
|
+
if (!configuration?.objectType) throw new Error("crmObjectChanged objectType is required");
|
|
808
|
+
if (!["contacts", "companies", "deals"].includes(configuration.objectType)) throw new Error("crmObjectChanged object type must be contacts, companies, or deals");
|
|
809
|
+
if ((configuration.properties ?? []).length > MaximumTriggerProperties) throw new Error(`crmObjectChanged allows at most ${MaximumTriggerProperties} properties`);
|
|
810
|
+
try {
|
|
811
|
+
searchBody(newCRMObjectChangeSearch(configuration, 0, String(MaximumSearchResults - crmObjectChangePageSize)));
|
|
812
|
+
} catch (error) {
|
|
813
|
+
throw new Error(`crmObjectChanged search: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
var CRMObjectChangedEventSchema = z.object({
|
|
817
|
+
objectType: z.enum(["contacts", "companies", "deals"]),
|
|
818
|
+
changeKind: z.enum([CRMObjectChangeCreated, CRMObjectChangeUpdated]),
|
|
819
|
+
modifiedAt: z.string().transform((value, context) => {
|
|
820
|
+
const milliseconds = parseRFC3339Milliseconds(value);
|
|
821
|
+
if (milliseconds === void 0) {
|
|
822
|
+
context.addIssue({ code: "custom", message: "modifiedAt must be an RFC 3339 time" });
|
|
823
|
+
return z.NEVER;
|
|
824
|
+
}
|
|
825
|
+
return formatGoTimeMilliseconds(milliseconds);
|
|
826
|
+
}),
|
|
827
|
+
object: CRMObjectSchema
|
|
828
|
+
});
|
|
829
|
+
var CRMObjectChangedTriggerDefinition = {
|
|
830
|
+
trigger: { connectorId: ConnectorID, triggerName: "crmObjectChanged" },
|
|
831
|
+
description: "Receive each HubSpot contact, company, or deal of one object type that is created or changed, read by polling CRM search on the last-modified date; the first run records a baseline and delivers no existing records."
|
|
832
|
+
};
|
|
833
|
+
function defineCRMObjectChangedTriggerBinding(config) {
|
|
834
|
+
return mustTriggerBindingDefinition({ definition: CRMObjectChangedTriggerDefinition, ...config });
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// src/crm_object_change_fetcher.ts
|
|
838
|
+
import { createHash } from "crypto";
|
|
839
|
+
import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
840
|
+
|
|
841
|
+
// src/crm_object_change_cursor.ts
|
|
842
|
+
var searchIndexLagWindowMs = 2 * 60 * 1e3;
|
|
843
|
+
var maximumSeenRecordVersions = 1500;
|
|
844
|
+
function lagWindowStart(position) {
|
|
845
|
+
return Math.max(position.floorMs + 1, position.highWaterMs - searchIndexLagWindowMs, position.droppedThroughMs + 1);
|
|
846
|
+
}
|
|
847
|
+
function pruneSeen(position) {
|
|
848
|
+
const windowStart = lagWindowStart(position);
|
|
849
|
+
const kept = [...position.seen].filter(([, modified]) => modified >= windowStart);
|
|
850
|
+
kept.sort(([leftID, left], [rightID, right]) => left !== right ? right - left : compareDecimalIDs(leftID, rightID));
|
|
851
|
+
if (kept.length > maximumSeenRecordVersions) {
|
|
852
|
+
position.droppedThroughMs = Math.max(position.droppedThroughMs, kept[maximumSeenRecordVersions][1]);
|
|
853
|
+
kept.length = maximumSeenRecordVersions;
|
|
854
|
+
}
|
|
855
|
+
position.seen = new Map(kept);
|
|
856
|
+
}
|
|
857
|
+
function compareDecimalIDs(left, right) {
|
|
858
|
+
if (left.length !== right.length) return left.length - right.length;
|
|
859
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
860
|
+
}
|
|
861
|
+
function encodeCRMObjectChangeCursor(position) {
|
|
862
|
+
let token = `{"objectType":${JSON.stringify(position.objectType)},"floorMs":${position.floorMs},"highWaterMs":${position.highWaterMs},"anchorMs":${position.anchorMs}`;
|
|
863
|
+
if (position.after) token += `,"after":${JSON.stringify(position.after)}`;
|
|
864
|
+
if (position.seen.size > 0) {
|
|
865
|
+
const keys = [...position.seen.keys()].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
|
|
866
|
+
token += `,"seen":{${keys.map((key) => `${JSON.stringify(key)}:${position.seen.get(key)}`).join(",")}}`;
|
|
867
|
+
}
|
|
868
|
+
if (position.droppedThroughMs !== 0) token += `,"droppedThroughMs":${position.droppedThroughMs}`;
|
|
869
|
+
return { token: `${token}}` };
|
|
870
|
+
}
|
|
871
|
+
var fieldNames = ["objectType", "floorMs", "highWaterMs", "anchorMs", "after", "seen", "droppedThroughMs"];
|
|
872
|
+
function decodeCRMObjectChangeCursor(token) {
|
|
873
|
+
const position = { objectType: "", floorMs: 0, highWaterMs: 0, anchorMs: 0, after: "", seen: /* @__PURE__ */ new Map(), droppedThroughMs: 0 };
|
|
874
|
+
try {
|
|
875
|
+
const decoded = JSON.parse(token, markNonIntegerLiterals);
|
|
876
|
+
if (decoded !== null) {
|
|
877
|
+
if (typeof decoded !== "object" || Array.isArray(decoded)) throw new TypeError("not an object");
|
|
878
|
+
for (const [key, value] of Object.entries(decoded)) {
|
|
879
|
+
const field = fieldNames.find((name) => name === key) ?? fieldNames.find((name) => name.toLowerCase() === key.toLowerCase());
|
|
880
|
+
if (!field || value === null) continue;
|
|
881
|
+
if (field === "objectType" || field === "after") position[field] = goString(value);
|
|
882
|
+
else if (field === "seen") position.seen = goSeen(value);
|
|
883
|
+
else position[field] = goInteger(value);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
} catch {
|
|
887
|
+
throw new Error("HubSpot change cursor is not decodable");
|
|
888
|
+
}
|
|
889
|
+
if (!["contacts", "companies", "deals"].includes(position.objectType)) throw new Error("HubSpot change cursor has no valid object type");
|
|
890
|
+
if (position.floorMs < 0 || position.highWaterMs < position.floorMs || position.anchorMs <= position.floorMs || position.droppedThroughMs < 0 || position.droppedThroughMs > position.highWaterMs) {
|
|
891
|
+
throw new Error("HubSpot change cursor times are inconsistent");
|
|
892
|
+
}
|
|
893
|
+
if (position.after && !cursor.test(position.after)) throw new Error("HubSpot change cursor has an invalid paging offset");
|
|
894
|
+
if (position.seen.size > maximumSeenRecordVersions) throw new Error("HubSpot change cursor holds too many record versions");
|
|
895
|
+
for (const objectID of position.seen.keys()) if (!recordId.test(objectID)) throw new Error("HubSpot change cursor has an invalid record ID");
|
|
896
|
+
return position;
|
|
897
|
+
}
|
|
898
|
+
var nonIntegerLiteral = /* @__PURE__ */ Symbol("nonIntegerLiteral");
|
|
899
|
+
var integerLiteral = /^-?(?:0|[1-9][0-9]*)$/;
|
|
900
|
+
function markNonIntegerLiterals(_key, value, context) {
|
|
901
|
+
if (typeof value === "number" && context?.source !== void 0 && !integerLiteral.test(context.source)) return nonIntegerLiteral;
|
|
902
|
+
return value;
|
|
903
|
+
}
|
|
904
|
+
function goString(value) {
|
|
905
|
+
if (typeof value !== "string") throw new TypeError("not a string");
|
|
906
|
+
return value;
|
|
907
|
+
}
|
|
908
|
+
function goInteger(value) {
|
|
909
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("not an integer");
|
|
910
|
+
return value;
|
|
911
|
+
}
|
|
912
|
+
function goSeen(value) {
|
|
913
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("not an object");
|
|
914
|
+
return new Map(Object.entries(value).map(([objectID, modified]) => [objectID, modified === null ? 0 : goInteger(modified)]));
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// src/crm_object_change_fetcher.ts
|
|
918
|
+
var crmObjectChangeOperation = "crmObjectChanged";
|
|
919
|
+
var CRMObjectChangeSearchError = class extends Error {
|
|
920
|
+
/** Wrap the classified failure of one search. */
|
|
921
|
+
constructor(failure) {
|
|
922
|
+
super(`HubSpot change search: ${failure.message}`);
|
|
923
|
+
this.failure = failure;
|
|
924
|
+
this.name = "CRMObjectChangeSearchError";
|
|
925
|
+
}
|
|
926
|
+
failure;
|
|
927
|
+
};
|
|
928
|
+
var CRMObjectChangeFetcher = class {
|
|
929
|
+
/** Bind the client, the connection whose credentials each poll resolves, and the validated configuration. */
|
|
930
|
+
constructor(client, connection, configuration) {
|
|
931
|
+
this.client = client;
|
|
932
|
+
this.connection = connection;
|
|
933
|
+
this.configuration = configuration;
|
|
934
|
+
}
|
|
935
|
+
client;
|
|
936
|
+
connection;
|
|
937
|
+
configuration;
|
|
938
|
+
/**
|
|
939
|
+
* Read the newest last-modified date, so every existing record becomes the baseline. An object type without
|
|
940
|
+
* records seeds at zero, so every later record is delivered.
|
|
941
|
+
*/
|
|
942
|
+
async seedCursor(context) {
|
|
943
|
+
const objectType = this.configuration.objectType;
|
|
944
|
+
const modifiedProperty = lastModifiedProperty(objectType);
|
|
945
|
+
const page = await this.search(context, { objectType, properties: [modifiedProperty], limit: 1, sort: { propertyName: modifiedProperty, direction: "DESCENDING" } });
|
|
946
|
+
const floor = page.objects?.[0] ? recordModifiedMilliseconds(page.objects[0]) : 0;
|
|
947
|
+
return encodeCRMObjectChangeCursor({ objectType, floorMs: floor, highWaterMs: floor, anchorMs: floor + 1, after: "", seen: /* @__PURE__ */ new Map(), droppedThroughMs: 0 });
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Read one search page after cursor. An undecodable cursor, a cursor for another object type, and a paging
|
|
951
|
+
* offset HubSpot rejects are marked invalid, so the kit records a new baseline.
|
|
952
|
+
*/
|
|
953
|
+
async fetchChanges(context, cursor2) {
|
|
954
|
+
let position;
|
|
955
|
+
try {
|
|
956
|
+
position = decodeCRMObjectChangeCursor(cursor2.token);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
throw markCursorInvalid(error);
|
|
959
|
+
}
|
|
960
|
+
if (position.objectType !== this.configuration.objectType) throw markCursorInvalid(new Error("HubSpot change cursor belongs to another object type"));
|
|
961
|
+
let page;
|
|
962
|
+
try {
|
|
963
|
+
page = await this.search(context, newCRMObjectChangeSearch(this.configuration, position.anchorMs, position.after));
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (position.after && error instanceof CRMObjectChangeSearchError && error.failure.kind === "VALIDATION") {
|
|
966
|
+
throw markCursorInvalid(new Error(`HubSpot rejected the change search offset: ${error.message}`, { cause: error }));
|
|
967
|
+
}
|
|
968
|
+
throw error;
|
|
969
|
+
}
|
|
970
|
+
const next = { ...position, seen: new Map(position.seen) };
|
|
971
|
+
const changes = [];
|
|
972
|
+
let pageNewest = position.anchorMs;
|
|
973
|
+
for (const object of page.objects ?? []) {
|
|
974
|
+
const modified = recordModifiedMilliseconds(object);
|
|
975
|
+
pageNewest = Math.max(pageNewest, modified);
|
|
976
|
+
const delivered = next.seen.get(object.id);
|
|
977
|
+
if (delivered !== void 0 && delivered >= modified || modified <= position.floorMs) continue;
|
|
978
|
+
const kind = recordCreatedMilliseconds(object) > position.highWaterMs ? CRMObjectChangeCreated : CRMObjectChangeUpdated;
|
|
979
|
+
const modifiedAt = formatGoTimeMilliseconds(modified);
|
|
980
|
+
changes.push({
|
|
981
|
+
id: crmObjectChangeID(object.objectType, object.id, modified),
|
|
982
|
+
occurredAt: new Date(modified),
|
|
983
|
+
payload: { objectType: this.configuration.objectType, changeKind: kind, modifiedAt, object }
|
|
984
|
+
});
|
|
985
|
+
next.seen.set(object.id, modified);
|
|
986
|
+
next.highWaterMs = Math.max(next.highWaterMs, modified);
|
|
987
|
+
}
|
|
988
|
+
pruneSeen(next);
|
|
989
|
+
let hasMorePages = false;
|
|
990
|
+
if (page.nextAfter && pageNewest > position.anchorMs) {
|
|
991
|
+
next.anchorMs = pageNewest;
|
|
992
|
+
next.after = "";
|
|
993
|
+
hasMorePages = true;
|
|
994
|
+
} else if (page.nextAfter) {
|
|
995
|
+
if (Number(page.nextAfter) + crmObjectChangePageSize > MaximumSearchResults) {
|
|
996
|
+
throw markCursorInvalid(new Error(`more than ${MaximumSearchResults} HubSpot records share one last-modified time`));
|
|
997
|
+
}
|
|
998
|
+
next.after = page.nextAfter;
|
|
999
|
+
hasMorePages = true;
|
|
1000
|
+
} else {
|
|
1001
|
+
next.anchorMs = lagWindowStart(next);
|
|
1002
|
+
next.after = "";
|
|
1003
|
+
}
|
|
1004
|
+
return { changes, next: encodeCRMObjectChangeCursor(next), hasMorePages };
|
|
1005
|
+
}
|
|
1006
|
+
/** Send one CRM search; 429, 423, and the daily limit pause the whole connection. */
|
|
1007
|
+
async search(context, input) {
|
|
1008
|
+
let body;
|
|
1009
|
+
try {
|
|
1010
|
+
body = searchBody(input);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
throw new Error(`hubspot crmObjectChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1013
|
+
}
|
|
1014
|
+
await waitForPollRequest(context);
|
|
1015
|
+
const call = newTriggerCredentialCall(this.connection, CRMObjectChangedTriggerDefinition.trigger, context.signal);
|
|
1016
|
+
const result = await this.client.exchange(call, crmObjectChangeOperation, "", "POST", objectsPath(input.objectType, "search"), void 0, body);
|
|
1017
|
+
if ("outcome" in result) {
|
|
1018
|
+
const failure = new CRMObjectChangeSearchError(result.outcome.failure);
|
|
1019
|
+
if (result.outcome.failure.kind === "RATE_LIMIT") throw markRateLimited(failure, result.outcome.retryAfterMs);
|
|
1020
|
+
if (result.outcome.failure.kind === "QUOTA_EXHAUSTED") throw markRateLimited(failure, 0);
|
|
1021
|
+
throw failure;
|
|
1022
|
+
}
|
|
1023
|
+
let page;
|
|
1024
|
+
try {
|
|
1025
|
+
page = decodeObjectPage(input.objectType, result.response.body);
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
throw new Error(`HubSpot change search returned an invalid page: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1028
|
+
}
|
|
1029
|
+
const limit = input.limit ?? 0;
|
|
1030
|
+
if ((page.objects?.length ?? 0) > limit) throw new Error(`HubSpot change search returned ${page.objects?.length ?? 0} records, more than ${limit}`);
|
|
1031
|
+
return page;
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
function crmObjectChangeID(objectType, objectID, modifiedMilliseconds) {
|
|
1035
|
+
const digest = createHash("sha256").update([objectType, objectID, String(modifiedMilliseconds)].join("\0")).digest();
|
|
1036
|
+
return `hubspot-${digest.subarray(0, 16).toString("hex")}`;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// src/trigger.ts
|
|
1040
|
+
import { newTrigger } from "@superdurable/connectors-sdk";
|
|
1041
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1042
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
1043
|
+
function newCRMObjectTriggerRunner(config) {
|
|
1044
|
+
const client = hubSpotClientOf(config.connection);
|
|
1045
|
+
if (!config.crmObjectChangedRoutes?.length) throw new TypeError("HubSpot crmObjectChanged routes are required");
|
|
1046
|
+
const pollers = config.crmObjectChangedRoutes.map((route) => newCRMObjectChangedPoller(client, config.connection.reference, route));
|
|
1047
|
+
return newRunner({ connection: config.connection.reference, schedule: { intervalMs: client.pollIntervalMs }, pollers, logger: client.triggerLogger });
|
|
1048
|
+
}
|
|
1049
|
+
function newProjectCRMObjectTriggerRunner(project, connectionName, config, options = {}) {
|
|
1050
|
+
const connection = newProjectConnection2(project, connectionName, options);
|
|
1051
|
+
const client = hubSpotClientOf(connection);
|
|
1052
|
+
const triggerName = CRMObjectChangedTriggerDefinition.trigger.triggerName;
|
|
1053
|
+
const routes = (config.crmObjectChangedRoutes ?? []).map((route) => {
|
|
1054
|
+
if (!route.target) throw new TypeError(`HubSpot crmObjectChanged binding "${route.bindingName}" target is required`);
|
|
1055
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
|
|
1056
|
+
let configuration;
|
|
1057
|
+
try {
|
|
1058
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, CRMObjectChangedTriggerConfigurationSchema);
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
if (error instanceof ObjectNotFoundError) throw new Error(`hubspot crmObjectChanged binding "${route.bindingName}" has no saved object type; pick one in Dex Web`);
|
|
1061
|
+
throw new Error(`hubspot crmObjectChanged binding "${route.bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1062
|
+
}
|
|
1063
|
+
if (!configuration.properties?.length && route.properties) configuration = { ...configuration, properties: route.properties };
|
|
1064
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, {
|
|
1065
|
+
logger: client.triggerLogger,
|
|
1066
|
+
decodePayload: (_payloadJSON, payloadBytes) => CRMObjectChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes))
|
|
1067
|
+
});
|
|
1068
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
1069
|
+
});
|
|
1070
|
+
return newCRMObjectTriggerRunner({ connection, crmObjectChangedRoutes: routes });
|
|
1071
|
+
}
|
|
1072
|
+
function newCRMObjectChangedTrigger(config) {
|
|
1073
|
+
const client = hubSpotClientOf(config.connection);
|
|
1074
|
+
const reference = config.connection.reference;
|
|
1075
|
+
if (config.connectionName !== reference.name) throw new TypeError(`hubspot connector trigger connectionName "${config.connectionName}" must equal its connection's name "${reference.name}"`);
|
|
1076
|
+
validateConfiguration(config.configuration);
|
|
1077
|
+
const definition = CRMObjectChangedTriggerDefinition;
|
|
1078
|
+
const source = newBindingTriggerSource({
|
|
1079
|
+
definition,
|
|
1080
|
+
binding: { connection: reference, trigger: definition.trigger, name: definition.trigger.triggerName },
|
|
1081
|
+
cursor: newMemoryCursorStore(),
|
|
1082
|
+
fetcher: new CRMObjectChangeFetcher(client, reference, config.configuration)
|
|
1083
|
+
}, { intervalMs: client.pollIntervalMs }, client.triggerLogger);
|
|
1084
|
+
return newTrigger({ definition, binding: { connection: reference, trigger: definition.trigger, name: config.bindingName }, source, target: config.target, logger: client.triggerLogger });
|
|
1085
|
+
}
|
|
1086
|
+
function newCRMObjectChangedPoller(client, connection, route) {
|
|
1087
|
+
if (!route.bindingName?.trim() || !route.target) throw new TypeError("HubSpot crmObjectChanged binding name and target are required");
|
|
1088
|
+
validateConfiguration(route.configuration);
|
|
1089
|
+
const definition = CRMObjectChangedTriggerDefinition;
|
|
1090
|
+
return newBindingPoller({
|
|
1091
|
+
definition,
|
|
1092
|
+
binding: { connection, trigger: definition.trigger, name: route.bindingName },
|
|
1093
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
1094
|
+
fetcher: new CRMObjectChangeFetcher(client, connection, route.configuration),
|
|
1095
|
+
target: route.target
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
function validateConfiguration(configuration) {
|
|
1099
|
+
try {
|
|
1100
|
+
validateCRMObjectChangedTriggerConfiguration(configuration);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
throw new Error(`hubspot crmObjectChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
function hubSpotClientOf(connection) {
|
|
1106
|
+
if (!(connection?.operations instanceof HubSpotClient)) throw new TypeError("HubSpot Triggers require a connection from newProjectConnection or newConnection with a HubSpotClient");
|
|
1107
|
+
return connection.operations;
|
|
1108
|
+
}
|
|
711
1109
|
export {
|
|
1110
|
+
CRMObjectChangeCreated,
|
|
1111
|
+
CRMObjectChangeSearchError,
|
|
1112
|
+
CRMObjectChangeUpdated,
|
|
1113
|
+
CRMObjectChangedEventSchema,
|
|
1114
|
+
CRMObjectChangedTriggerConfigurationSchema,
|
|
1115
|
+
CRMObjectChangedTriggerDefinition,
|
|
712
1116
|
CRMObjectSchema,
|
|
713
1117
|
ConfigSchema,
|
|
714
1118
|
Connection,
|
|
@@ -724,6 +1128,7 @@ export {
|
|
|
724
1128
|
GetObjectMetadata,
|
|
725
1129
|
GetObjectOperation,
|
|
726
1130
|
HubSpotClient,
|
|
1131
|
+
MaximumTriggerProperties,
|
|
727
1132
|
ObjectPageSchema,
|
|
728
1133
|
ProviderID,
|
|
729
1134
|
SearchFilterGroupSchema,
|
|
@@ -738,6 +1143,8 @@ export {
|
|
|
738
1143
|
SearchObjectsMetadata,
|
|
739
1144
|
SearchObjectsOperation,
|
|
740
1145
|
SearchSortSchema,
|
|
1146
|
+
UIObjectTypePickerPortObjectType,
|
|
1147
|
+
UIUnitObjectTypePicker,
|
|
741
1148
|
UpdateObjectBranch,
|
|
742
1149
|
UpdateObjectBranchConflict,
|
|
743
1150
|
UpdateObjectBranchDefect,
|
|
@@ -762,11 +1169,16 @@ export {
|
|
|
762
1169
|
UpsertedObjectSchema,
|
|
763
1170
|
decodeCredentials,
|
|
764
1171
|
decodeSharedCredentials,
|
|
1172
|
+
defineCRMObjectChangedTriggerBinding,
|
|
1173
|
+
newCRMObjectChangedTrigger,
|
|
1174
|
+
newCRMObjectTriggerRunner,
|
|
765
1175
|
newConnection,
|
|
766
1176
|
newConnectionWithOperations,
|
|
767
1177
|
newGetObjectStep,
|
|
1178
|
+
newProjectCRMObjectTriggerRunner,
|
|
768
1179
|
newProjectConnection2 as newProjectConnection,
|
|
769
1180
|
newSearchObjectsStep,
|
|
770
1181
|
newUpdateObjectStep,
|
|
771
|
-
newUpsertObjectStep
|
|
1182
|
+
newUpsertObjectStep,
|
|
1183
|
+
validateCRMObjectChangedTriggerConfiguration
|
|
772
1184
|
};
|
package/dist/mock.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
|
|
2
2
|
import { Failure } from '@superdurable/connectors-sdk';
|
|
3
|
-
import { f as Operations, a as Connection, S as SearchObjectsInput, O as ObjectPage, G as GetObjectInput, C as CRMObject, b as UpsertObjectInput, c as UpsertedObject, U as UpdateObjectInput, l as SearchFilter, m as SearchFilterGroup, q as SearchSort } from './connection-
|
|
3
|
+
import { f as Operations, a as Connection, S as SearchObjectsInput, O as ObjectPage, G as GetObjectInput, C as CRMObject, b as UpsertObjectInput, c as UpsertedObject, U as UpdateObjectInput, l as SearchFilter, m as SearchFilterGroup, q as SearchSort } from './connection-pqfXajbM.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/** Go zero value for SearchFilter in scripted cases. */
|
package/dist/mock.js
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
UpsertObjectInputSchema,
|
|
17
17
|
UpsertedObjectSchema,
|
|
18
18
|
newConnectionWithOperations
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-HHRHOJKC.js";
|
|
20
20
|
|
|
21
21
|
// src/generated/mock.ts
|
|
22
22
|
import { branchCase, retryCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superdurable/connector-hubspot",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "HubSpot CRM operations for Dex Flows",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "HubSpot CRM operations and record change Triggers for Dex Flows",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/superdurable/dex-connectors-library.git",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"./mock": {
|
|
26
26
|
"types": "./dist/mock.d.ts",
|
|
27
27
|
"import": "./dist/mock.js"
|
|
28
|
-
}
|
|
28
|
+
},
|
|
29
|
+
"./dex-connector.json": "./dex-connector.json"
|
|
29
30
|
},
|
|
30
31
|
"files": [
|
|
31
32
|
"dist",
|
|
@@ -41,11 +42,12 @@
|
|
|
41
42
|
"test:integration": "npm run build && vitest run test/integration/*.integration.test.ts",
|
|
42
43
|
"check": "npm test && npm run typecheck && npm run lint",
|
|
43
44
|
"example:search": "npm run build && tsx examples/search-deals/main.ts",
|
|
44
|
-
"example:search:start": "npm run build && tsx examples/search-deals/start.ts"
|
|
45
|
+
"example:search:start": "npm run build && tsx examples/search-deals/start.ts",
|
|
46
|
+
"example:changes": "npm run build && tsx examples/crm-object-changed/main.ts"
|
|
45
47
|
},
|
|
46
48
|
"dependencies": {
|
|
47
|
-
"@superdurable/connectors-sdk": "0.
|
|
48
|
-
"@superdurable/dex": ">=1.
|
|
49
|
+
"@superdurable/connectors-sdk": "0.12.0",
|
|
50
|
+
"@superdurable/dex": ">=1.45.4",
|
|
49
51
|
"zod": "^4.1.0"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|