@superdurable/connector-hubspot 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,772 @@
1
+ import {
2
+ CRMObjectSchema,
3
+ ConfigSchema,
4
+ Connection,
5
+ ConnectorID,
6
+ GetObjectBranch,
7
+ GetObjectBranchDefect,
8
+ GetObjectBranchFound,
9
+ GetObjectBranchInvalidResponse,
10
+ GetObjectBranchNotFound,
11
+ GetObjectBranchProviderRejected,
12
+ GetObjectDefinition,
13
+ GetObjectInputSchema,
14
+ GetObjectMetadata,
15
+ ObjectPageSchema,
16
+ ProviderID,
17
+ SearchFilterGroupSchema,
18
+ SearchFilterSchema,
19
+ SearchObjectsBranch,
20
+ SearchObjectsBranchDefect,
21
+ SearchObjectsBranchInvalidResponse,
22
+ SearchObjectsBranchProviderRejected,
23
+ SearchObjectsBranchSearched,
24
+ SearchObjectsDefinition,
25
+ SearchObjectsInputSchema,
26
+ SearchObjectsMetadata,
27
+ SearchSortSchema,
28
+ UpdateObjectBranch,
29
+ UpdateObjectBranchConflict,
30
+ UpdateObjectBranchDefect,
31
+ UpdateObjectBranchInvalidResponse,
32
+ UpdateObjectBranchNotFound,
33
+ UpdateObjectBranchProviderRejected,
34
+ UpdateObjectBranchUpdated,
35
+ UpdateObjectDefinition,
36
+ UpdateObjectInputSchema,
37
+ UpdateObjectMetadata,
38
+ UpsertObjectBranch,
39
+ UpsertObjectBranchConflict,
40
+ UpsertObjectBranchDefect,
41
+ UpsertObjectBranchInvalidResponse,
42
+ UpsertObjectBranchProviderRejected,
43
+ UpsertObjectBranchUpserted,
44
+ UpsertObjectDefinition,
45
+ UpsertObjectInputSchema,
46
+ UpsertObjectMetadata,
47
+ UpsertedObjectSchema,
48
+ decodeCredentials,
49
+ decodeSharedCredentials,
50
+ newConnection,
51
+ newConnectionWithOperations,
52
+ newProjectConnection,
53
+ newProjectCredentialProvider
54
+ } from "./chunk-SUNBKTMW.js";
55
+
56
+ // src/generated/steps.ts
57
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
58
+ function newSearchObjectsStep(configuration) {
59
+ const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
60
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
61
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchObjects(), connection: connection.reference, branches: [
62
+ goToBranch("searched", searched),
63
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
64
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
65
+ ...defect ? [goToBranch("defect", defect)] : []
66
+ ] });
67
+ }
68
+ function newGetObjectStep(configuration) {
69
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
70
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
71
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getObject(), connection: connection.reference, branches: [
72
+ goToBranch("found", found),
73
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
74
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
75
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
76
+ ...defect ? [goToBranch("defect", defect)] : []
77
+ ] });
78
+ }
79
+ function newUpsertObjectStep(configuration) {
80
+ const { connection, connectionName, upserted, conflict, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
81
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
82
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertObject(), connection: connection.reference, branches: [
83
+ goToBranch("upserted", upserted),
84
+ ...conflict ? [goToBranch("conflict", conflict)] : [],
85
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
86
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
87
+ ...defect ? [goToBranch("defect", defect)] : []
88
+ ] });
89
+ }
90
+ function newUpdateObjectStep(configuration) {
91
+ const { connection, connectionName, updated, notFound, conflict, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
92
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
93
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateObject(), connection: connection.reference, branches: [
94
+ goToBranch("updated", updated),
95
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
96
+ ...conflict ? [goToBranch("conflict", conflict)] : [],
97
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
98
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
99
+ ...defect ? [goToBranch("defect", defect)] : []
100
+ ] });
101
+ }
102
+
103
+ // src/client.ts
104
+ import { ReauthorizationRequiredError, RetryError, resolveCredential, resolveCredentialAfterRejection, SecretString } from "@superdurable/connectors-sdk";
105
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
106
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
107
+
108
+ // src/generated/refresh.ts
109
+ var Authorization = {
110
+ "defaultMethod": "private-app-token",
111
+ "methods": [
112
+ {
113
+ "fields": [
114
+ {
115
+ "name": "access_token",
116
+ "required": true,
117
+ "type": "secretString"
118
+ }
119
+ ],
120
+ "id": "private-app-token",
121
+ "type": "apiKey"
122
+ },
123
+ {
124
+ "fields": [
125
+ {
126
+ "name": "oauth_client_id",
127
+ "required": true,
128
+ "type": "string"
129
+ },
130
+ {
131
+ "name": "oauth_client_secret",
132
+ "required": true,
133
+ "type": "secretString"
134
+ },
135
+ {
136
+ "name": "access_token",
137
+ "required": true,
138
+ "type": "secretString"
139
+ },
140
+ {
141
+ "name": "refresh_token",
142
+ "required": true,
143
+ "type": "secretString"
144
+ }
145
+ ],
146
+ "id": "hubspot-oauth",
147
+ "oauth2": {
148
+ "clientIDCredential": "oauth_client_id",
149
+ "clientSecretCredential": "oauth_client_secret",
150
+ "credentialMappings": [
151
+ {
152
+ "credential": "access_token",
153
+ "source": "access_token"
154
+ },
155
+ {
156
+ "credential": "refresh_token",
157
+ "source": "refresh_token"
158
+ }
159
+ ],
160
+ "refresh": {
161
+ "missingExpiry": "reject",
162
+ "requiredScopes": [
163
+ "crm.objects.contacts.read",
164
+ "crm.objects.contacts.write",
165
+ "crm.objects.companies.read",
166
+ "crm.objects.companies.write",
167
+ "crm.objects.deals.read",
168
+ "crm.objects.deals.write",
169
+ "crm.objects.owners.read"
170
+ ],
171
+ "responseScopeField": "scopesArray",
172
+ "storedMissingExpiry": "refresh",
173
+ "terminalErrorCodes": [
174
+ "invalid_grant",
175
+ "invalid_client",
176
+ "unauthorized_client"
177
+ ]
178
+ },
179
+ "scopes": [
180
+ "oauth",
181
+ "crm.objects.contacts.read",
182
+ "crm.objects.contacts.write",
183
+ "crm.objects.companies.read",
184
+ "crm.objects.companies.write",
185
+ "crm.objects.deals.read",
186
+ "crm.objects.deals.write",
187
+ "crm.objects.owners.read"
188
+ ],
189
+ "tokenEndpoint": "https://api.hubapi.com/oauth/2026-09/token"
190
+ },
191
+ "type": "oauth2"
192
+ }
193
+ ],
194
+ "refreshable": true
195
+ };
196
+ var CredentialFields = {
197
+ "access_token": "accessToken",
198
+ "oauth_client_id": "oauthClientId",
199
+ "oauth_client_secret": "oauthClientSecret",
200
+ "refresh_token": "refreshToken"
201
+ };
202
+
203
+ // src/operations.ts
204
+ import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
205
+ var propertyName = /^[A-Za-z0-9][A-Za-z0-9_]{0,99}$/;
206
+ var associationName = /^associations\.[a-z][a-z0-9_]{0,63}$/;
207
+ var recordId = /^[0-9]{1,20}$/;
208
+ var cursor = /^[0-9]{1,5}$/;
209
+ var zeroObject = { objectType: "", id: "", archived: false };
210
+ var zeroPage = { objectType: "", total: 0, objects: [] };
211
+ var zeroUpsert = { object: zeroObject, created: false };
212
+ var SearchObjectsOperation = class {
213
+ /** Bind a client. */
214
+ constructor(client) {
215
+ this.client = client;
216
+ }
217
+ client;
218
+ /** Return the manifest definition. */
219
+ definition() {
220
+ return SearchObjectsDefinition;
221
+ }
222
+ /** Validate, send, and decode a search. */
223
+ async invoke(call, input) {
224
+ let body;
225
+ try {
226
+ body = searchBody(input);
227
+ } catch (error) {
228
+ return queryFailure("searchObjects", "defect", "VALIDATION", zeroPage, {}, error);
229
+ }
230
+ const result = await this.client.exchange(call, "searchObjects", "", "POST", objectsPath(input.objectType, "search"), void 0, body);
231
+ if ("outcome" in result) return queryOutcome(result.outcome, zeroPage, "providerRejected");
232
+ const receipt = this.client.receipt(call, result.response);
233
+ try {
234
+ const decoded = jsonObject(result.response.body);
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);
252
+ } catch (error) {
253
+ return queryFailure("searchObjects", "invalidResponse", "PROTOCOL", zeroPage, receipt, error);
254
+ }
255
+ }
256
+ };
257
+ var GetObjectOperation = class {
258
+ /** Bind a client. */
259
+ constructor(client) {
260
+ this.client = client;
261
+ }
262
+ client;
263
+ /** Return the manifest definition. */
264
+ definition() {
265
+ return GetObjectDefinition;
266
+ }
267
+ /** Validate, send, and decode one record. */
268
+ async invoke(call, input) {
269
+ let query;
270
+ try {
271
+ validateObjectType(input.objectType);
272
+ validateRecordId(input.objectId);
273
+ const properties = uniqueProperties(input.properties ?? []);
274
+ query = `archived=false${properties.length ? `&properties=${goQueryEscape(properties.join(","))}` : ""}`;
275
+ } catch (error) {
276
+ return queryFailure("getObject", "defect", "VALIDATION", zeroObject, {}, error);
277
+ }
278
+ const result = await this.client.exchange(call, "getObject", input.objectId, "GET", objectsPath(input.objectType, input.objectId), query);
279
+ if ("outcome" in result) return queryOutcome(result.outcome, zeroObject, "providerRejected", "notFound");
280
+ const receipt = this.client.receipt(call, result.response, input.objectId);
281
+ try {
282
+ const object = decodeCRMObject(input.objectType, jsonObject(result.response.body));
283
+ if (object.id !== input.objectId) throw new TypeError("HubSpot returned an invalid record");
284
+ return newQueryBranch("found", object, receipt);
285
+ } catch {
286
+ return queryFailure("getObject", "invalidResponse", "PROTOCOL", zeroObject, receipt, new Error("HubSpot returned an invalid record"));
287
+ }
288
+ }
289
+ };
290
+ var UpsertObjectOperation = class {
291
+ /** Bind a client. */
292
+ constructor(client) {
293
+ this.client = client;
294
+ }
295
+ client;
296
+ /** Return the manifest definition. */
297
+ definition() {
298
+ return UpsertObjectDefinition;
299
+ }
300
+ /** Reuse the stable Call ID for a repeat-safe upsert. */
301
+ idempotencyKey(callId) {
302
+ return callId;
303
+ }
304
+ /** Validate and dispatch, repeating one conflicting upsert. */
305
+ async invoke(call, input) {
306
+ let body;
307
+ try {
308
+ validateObjectType(input.objectType);
309
+ if (!propertyName.test(input.idProperty)) throw new Error("upsert ID property name is invalid");
310
+ if (!input.idValue.trim() || [...input.idValue].length > 65536) throw new Error("upsert ID value must be non-empty and within HubSpot's property value limit");
311
+ validateValues(input.properties ?? {}, false);
312
+ body = { inputs: [{ idProperty: input.idProperty, id: input.idValue, properties: input.properties ?? {} }] };
313
+ } catch (error) {
314
+ return mutationFailure("upsertObject", "defect", "VALIDATION", zeroUpsert, {}, error);
315
+ }
316
+ for (let attempt = 0; attempt < 2; attempt++) {
317
+ const result = await this.client.exchange(call, "upsertObject", "", "POST", objectsPath(input.objectType, "batch/upsert"), void 0, body);
318
+ if ("outcome" in result) {
319
+ if (result.outcome.disposition === "conflict" && attempt === 0) continue;
320
+ return mutationOutcome(result.outcome, zeroUpsert, "providerRejected", "providerRejected", "conflict");
321
+ }
322
+ const receipt = this.client.receipt(call, result.response);
323
+ try {
324
+ const decoded = jsonObject(result.response.body);
325
+ const results = arrayField(decoded, "results");
326
+ if (results.length === 0) {
327
+ const errors = arrayField(decoded, "errors");
328
+ if (errors.length) {
329
+ const first = requireObject(errors[0]);
330
+ const statusText = stringField(first, "status");
331
+ let status = /^[+-]?[0-9]+$/.test(statusText) && BigInt(statusText) <= 9223372036854775807n && BigInt(statusText) >= -9223372036854775808n ? Number(statusText) : 400;
332
+ if (!Number.isInteger(status) || status < 400) status = 400;
333
+ const category = stringField(first, "category");
334
+ const syntheticBody = Buffer.from(JSON.stringify({ category }));
335
+ const classified = this.client.classifyBatchError("upsertObject", { status, headers: result.response.headers, body: syntheticBody }, receipt);
336
+ if (classified.disposition === "conflict" && attempt === 0) continue;
337
+ return mutationOutcome(classified, zeroUpsert, "providerRejected", "providerRejected", "conflict");
338
+ }
339
+ throw new TypeError("HubSpot upsert response has no record");
340
+ }
341
+ if (results.length !== 1) throw new TypeError("HubSpot upsert response has more than one record");
342
+ const providerObject = requireObject(results[0]);
343
+ const object = decodeCRMObject(input.objectType, providerObject);
344
+ const created = booleanField(providerObject, "new");
345
+ return newMutationBranch("upserted", { object, created }, { ...receipt, providerObjectId: object.id });
346
+ } catch (error) {
347
+ return mutationFailure("upsertObject", "invalidResponse", "PROTOCOL", zeroUpsert, receipt, error);
348
+ }
349
+ }
350
+ throw new TypeError("unreachable upsert attempt");
351
+ }
352
+ };
353
+ var UpdateObjectOperation = class {
354
+ /** Bind a client. */
355
+ constructor(client) {
356
+ this.client = client;
357
+ }
358
+ client;
359
+ /** Return the manifest definition. */
360
+ definition() {
361
+ return UpdateObjectDefinition;
362
+ }
363
+ /** Reuse the stable Call ID for an absolute update. */
364
+ idempotencyKey(callId) {
365
+ return callId;
366
+ }
367
+ /** Validate, send, and decode one update. */
368
+ async invoke(call, input) {
369
+ try {
370
+ validateObjectType(input.objectType);
371
+ validateRecordId(input.objectId);
372
+ validateValues(input.properties ?? void 0, true);
373
+ } catch (error) {
374
+ return mutationFailure("updateObject", "defect", "VALIDATION", zeroObject, {}, error);
375
+ }
376
+ const result = await this.client.exchange(call, "updateObject", input.objectId, "PATCH", objectsPath(input.objectType, input.objectId), void 0, { properties: input.properties });
377
+ if ("outcome" in result) return mutationOutcome(result.outcome, zeroObject, "providerRejected", "notFound", "conflict");
378
+ const receipt = this.client.receipt(call, result.response, input.objectId);
379
+ try {
380
+ const object = decodeCRMObject(input.objectType, jsonObject(result.response.body));
381
+ if (object.id !== input.objectId) throw new TypeError("HubSpot returned an invalid record");
382
+ return newMutationBranch("updated", object, receipt);
383
+ } catch {
384
+ return mutationFailure("updateObject", "invalidResponse", "PROTOCOL", zeroObject, receipt, new Error("HubSpot returned an invalid record"));
385
+ }
386
+ }
387
+ };
388
+ function queryOutcome(outcome, zero, rejected, notFound = rejected) {
389
+ if (outcome.disposition === "retry") return newQueryRetry(outcome.failure, outcome.retryAfterMs);
390
+ const branch = outcome.disposition === "notFound" ? notFound : outcome.disposition === "conflict" || outcome.disposition === "rejected" ? rejected : outcome.disposition;
391
+ return newQueryBranch(branch, zero, outcome.receipt, outcome.failure);
392
+ }
393
+ function mutationOutcome(outcome, zero, rejected, notFound = rejected, conflict = rejected) {
394
+ if (outcome.disposition === "retry") return newMutationRetry(outcome.failure, outcome.retryAfterMs);
395
+ const branch = outcome.disposition === "notFound" ? notFound : outcome.disposition === "conflict" ? conflict : outcome.disposition === "rejected" ? rejected : outcome.disposition;
396
+ return newMutationBranch(branch, zero, outcome.receipt, outcome.failure);
397
+ }
398
+ function queryFailure(operation, branch, kind, zero, receipt, error) {
399
+ return newQueryBranch(branch, zero, receipt, { kind, provider: "hubspot", operation, message: error instanceof Error ? error.message : "HubSpot returned a malformed response" });
400
+ }
401
+ function mutationFailure(operation, branch, kind, zero, receipt, error) {
402
+ return newMutationBranch(branch, zero, receipt, { kind, provider: "hubspot", operation, message: error instanceof Error ? error.message : "HubSpot returned a malformed response" });
403
+ }
404
+ function validateObjectType(value) {
405
+ if (!["contacts", "companies", "deals"].includes(value)) throw new Error("object type must be contacts, companies, or deals");
406
+ }
407
+ function validateRecordId(value) {
408
+ if (!recordId.test(value)) throw new Error("object ID must be a decimal HubSpot record ID");
409
+ }
410
+ function uniqueProperties(values) {
411
+ if (values.length > 100) throw new Error("at most 100 properties can be requested");
412
+ const unique = [...new Set(values)];
413
+ if (unique.some((value) => !propertyName.test(value))) throw new Error("requested property name is invalid");
414
+ return unique;
415
+ }
416
+ function validateValues(properties, required) {
417
+ if (required && !Object.keys(properties ?? {}).length) throw new Error("at least one property value is required");
418
+ if (Object.keys(properties ?? {}).length > 100) throw new Error("at most 100 property values can be written");
419
+ for (const [name, value] of Object.entries(properties ?? {})) {
420
+ if (!propertyName.test(name)) throw new Error("written property name is invalid");
421
+ if ([...value].length > 65536) throw new Error("property values cannot exceed 65536 characters");
422
+ }
423
+ }
424
+ function objectsPath(objectType, suffix) {
425
+ return `crm/objects/2026-09/${objectType}/${suffix}`;
426
+ }
427
+ function goQueryEscape(value) {
428
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
429
+ }
430
+ function searchBody(input) {
431
+ validateObjectType(input.objectType);
432
+ const groups = input.filterGroups ?? [];
433
+ if (groups.length > 5) throw new Error("search allows at most 5 filter groups");
434
+ let count = 0;
435
+ for (const group of groups) {
436
+ if (!group.filters || group.filters.length < 1 || group.filters.length > 6) throw new Error("each filter group needs 1 to 6 filters");
437
+ count += group.filters.length;
438
+ group.filters.forEach(validateFilter);
439
+ }
440
+ if (count > 18) throw new Error("search allows at most 18 filters in total");
441
+ const properties = uniqueProperties(input.properties ?? []);
442
+ const limit = input.limit || 10;
443
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new Error("search limit must be from 1 through 200");
444
+ if (input.after && !cursor.test(input.after)) throw new Error("search after cursor must be the decimal NextAfter value of a previous page");
445
+ if (Number(input.after || "0") + limit > 1e4) throw new Error("search paging cannot pass HubSpot's 10000-result limit");
446
+ const body = {
447
+ ...groups.length ? { filterGroups: groups.map((group) => ({ filters: group.filters })) } : {},
448
+ ...input.query ? { query: input.query } : {},
449
+ ...input.sort ? { sorts: [input.sort] } : {},
450
+ ...properties.length ? { properties } : {},
451
+ limit,
452
+ ...input.after ? { after: input.after } : {}
453
+ };
454
+ if (input.sort && (!propertyName.test(input.sort.propertyName) || !["ASCENDING", "DESCENDING"].includes(input.sort.direction))) throw new Error("sort property or direction is invalid");
455
+ if (Buffer.byteLength(JSON.stringify(body).replace(/[<>&]/g, (character) => ({ "<": "\\u003c", ">": "\\u003e", "&": "\\u0026" })[character]).replace(/[\u2028\u2029]/g, (character) => character === "\u2028" ? "\\u2028" : "\\u2029")) > 3e3) throw new Error("search request exceeds HubSpot's 3000-character body limit");
456
+ return body;
457
+ }
458
+ function validateFilter(filter) {
459
+ if (!propertyName.test(filter.propertyName) && !associationName.test(filter.propertyName)) throw new Error("filter property name is invalid");
460
+ const hasValue = Boolean(filter.value), hasHigh = Boolean(filter.highValue), hasValues = Boolean(filter.values?.length);
461
+ const operator = filter.operator;
462
+ if (["EQ", "NEQ", "LT", "LTE", "GT", "GTE", "CONTAINS_TOKEN", "NOT_CONTAINS_TOKEN"].includes(operator)) {
463
+ if (!hasValue || hasHigh || hasValues) throw new Error(`filter operator ${operator} needs only a value`);
464
+ } else if (operator === "BETWEEN") {
465
+ if (!hasValue || !hasHigh || hasValues) throw new Error("filter operator BETWEEN needs a value and a highValue");
466
+ } else if (operator === "IN" || operator === "NOT_IN") {
467
+ if (hasValue || hasHigh || !hasValues || (filter.values?.length ?? 0) > 100 || filter.values?.some((value) => !value)) throw new Error(`filter operator ${operator} needs 1 to 100 values`);
468
+ } else if (operator === "HAS_PROPERTY" || operator === "NOT_HAS_PROPERTY") {
469
+ if (hasValue || hasHigh || hasValues) throw new Error(`filter operator ${operator} takes no value`);
470
+ } else throw new Error("filter operator is not supported");
471
+ }
472
+ function requireObject(value) {
473
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("HubSpot returned a malformed response");
474
+ return value;
475
+ }
476
+ function jsonObject(body) {
477
+ return requireObject(JSON.parse(Buffer.from(body).toString()));
478
+ }
479
+ function stringField(value, field) {
480
+ const candidate = value[field];
481
+ if (candidate === null || candidate === void 0) return "";
482
+ if (typeof candidate !== "string") throw new TypeError("HubSpot returned a malformed response");
483
+ return candidate;
484
+ }
485
+ function integerField(value, field) {
486
+ const candidate = value[field];
487
+ if (candidate === null || candidate === void 0) return 0;
488
+ if (!Number.isSafeInteger(candidate)) throw new TypeError("HubSpot returned a malformed response");
489
+ return candidate;
490
+ }
491
+ function booleanField(value, field) {
492
+ const candidate = value[field];
493
+ if (candidate === null || candidate === void 0) return false;
494
+ if (typeof candidate !== "boolean") throw new TypeError("HubSpot returned a malformed response");
495
+ return candidate;
496
+ }
497
+ function arrayField(value, field) {
498
+ const candidate = value[field];
499
+ if (candidate === null || candidate === void 0) return [];
500
+ if (!Array.isArray(candidate)) throw new TypeError("HubSpot returned a malformed response");
501
+ return candidate;
502
+ }
503
+ function decodeCRMObject(objectType, value) {
504
+ const provider = requireObject(value);
505
+ const id = stringField(provider, "id");
506
+ if (!recordId.test(id)) throw new TypeError("HubSpot returned a record without a valid ID");
507
+ const properties = provider.properties === null || provider.properties === void 0 ? void 0 : requireObject(provider.properties);
508
+ const cleaned = {};
509
+ for (const [name, property] of Object.entries(properties ?? {})) {
510
+ if (property === null) continue;
511
+ if (typeof property !== "string") throw new TypeError("HubSpot returned a malformed response");
512
+ cleaned[name] = property;
513
+ }
514
+ const createdAt = stringField(provider, "createdAt");
515
+ const updatedAt = stringField(provider, "updatedAt");
516
+ const result = {
517
+ objectType,
518
+ id,
519
+ ...Object.keys(cleaned).length ? { properties: cleaned } : {},
520
+ ...createdAt ? { createdAt } : {},
521
+ ...updatedAt ? { updatedAt } : {},
522
+ archived: booleanField(provider, "archived")
523
+ };
524
+ const url = appURL(stringField(provider, "url"));
525
+ if (url) result.url = url;
526
+ const parsed = CRMObjectSchema.parse(result);
527
+ if (parsed.createdAt === "0001-01-01T00:00:00Z") delete parsed.createdAt;
528
+ if (parsed.updatedAt === "0001-01-01T00:00:00Z") delete parsed.updatedAt;
529
+ return parsed;
530
+ }
531
+ function appURL(value) {
532
+ try {
533
+ const parsed = new URL(value);
534
+ return parsed.protocol === "https:" && !parsed.username && !parsed.password && parsed.hostname.endsWith(".hubspot.com") ? value : "";
535
+ } catch {
536
+ return "";
537
+ }
538
+ }
539
+
540
+ // src/client.ts
541
+ var defaultEndpoint = "https://api.hubapi.com";
542
+ 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
+ var HubSpotClient = class {
544
+ /** Validate settings and bind a credential source without contacting HubSpot. */
545
+ constructor(config, credentials, options = {}) {
546
+ this.credentials = credentials;
547
+ if (!credentials) throw new TypeError("HubSpot credential provider is required");
548
+ this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
549
+ this.maxResponseBytes = config.maxResponseBytes || 1048576;
550
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("HubSpot maxResponseBytes must be positive");
551
+ this.send = options.send ?? sendProviderRequest;
552
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
553
+ }
554
+ credentials;
555
+ endpoint;
556
+ maxResponseBytes;
557
+ send;
558
+ now;
559
+ refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "HubSpot", auth: Authorization, credentialFields: CredentialFields });
560
+ /** Bind the search query. */
561
+ searchObjects() {
562
+ return new SearchObjectsOperation(this);
563
+ }
564
+ /** Bind the record query. */
565
+ getObject() {
566
+ return new GetObjectOperation(this);
567
+ }
568
+ /** Bind the unique-property upsert. */
569
+ upsertObject() {
570
+ return new UpsertObjectOperation(this);
571
+ }
572
+ /** Bind the absolute update. */
573
+ updateObject() {
574
+ return new UpdateObjectOperation(this);
575
+ }
576
+ /** Return a safe receipt for a completed provider attempt. */
577
+ receipt(call, response, objectId = "") {
578
+ const correlation = response ? header(response, "x-hubspot-correlation-id") : "";
579
+ return {
580
+ callId: call.id,
581
+ provider: "hubspot",
582
+ observedAt: this.now().toISOString(),
583
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
584
+ ...objectId ? { providerObjectId: objectId } : {},
585
+ .../^[A-Za-z0-9-]{1,64}$/.test(correlation) ? { providerRequestId: correlation } : {}
586
+ };
587
+ }
588
+ /** Resolve, send, refresh after one OAuth 401, then classify the response. */
589
+ async exchange(call, operation, objectId, method, path, query, body) {
590
+ let credentials;
591
+ try {
592
+ credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
593
+ this.validateCredentials(credentials);
594
+ } catch (error) {
595
+ if (error instanceof ReauthorizationRequiredError) return { outcome: this.failure("rejected", operation, "AUTHENTICATION", "HubSpot authorization must be renewed") };
596
+ if (error instanceof RetryError) return { outcome: this.failure("retry", operation, "AVAILABILITY", "HubSpot OAuth token refresh is temporarily unavailable") };
597
+ return { outcome: this.failure("defect", operation, "AUTHENTICATION", "HubSpot connection credentials are unavailable") };
598
+ }
599
+ let encoded;
600
+ try {
601
+ if (body !== void 0) encoded = Buffer.from(JSON.stringify(body));
602
+ } catch {
603
+ return { outcome: this.failure("defect", operation, "LOCAL_DEFECT", "HubSpot request could not be built") };
604
+ }
605
+ let response;
606
+ try {
607
+ response = await this.sendRequest(call, credentials, method, path, query, encoded);
608
+ if (response.status === 401 && credentials.authMethodId === "hubspot-oauth" && "resolveAfterRejection" in this.credentials) {
609
+ let replacement;
610
+ try {
611
+ const resolved = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
612
+ this.validateCredentials(resolved);
613
+ replacement = resolved;
614
+ } catch {
615
+ }
616
+ if (replacement) response = await this.sendRequest(call, replacement, method, path, query, encoded);
617
+ }
618
+ } catch (error) {
619
+ const receipt = this.receipt(call, error instanceof BodyTooLargeError && error.headers ? { status: error.status ?? 0, headers: error.headers, body: new Uint8Array() } : void 0, objectId);
620
+ if (error instanceof BodyTooLargeError) return { outcome: this.failure("invalidResponse", operation, "RESPONSE_TOO_LARGE", "HubSpot response exceeds the configured size limit", receipt) };
621
+ return { outcome: this.failure("retry", operation, "TRANSPORT", "HubSpot did not return a complete response", receipt) };
622
+ }
623
+ if (response.status >= 200 && response.status < 300) return { response };
624
+ return { outcome: this.classify(operation, response, this.receipt(call, response, objectId)) };
625
+ }
626
+ validateCredentials(credentials) {
627
+ if (!(credentials.accessToken instanceof SecretString) || !isHeaderSafeCredential(credentials.accessToken.reveal())) throw new TypeError("HubSpot access token is missing or malformed");
628
+ }
629
+ sendRequest(call, credentials, method, path, query, body) {
630
+ return this.send({
631
+ url: `${this.endpoint}/${path}${query ? `?${query}` : ""}`,
632
+ method,
633
+ headers: { Accept: "application/json", Authorization: `Bearer ${credentials.accessToken.reveal()}`, ...body ? { "Content-Type": "application/json" } : {} },
634
+ ...body ? { body } : {},
635
+ maxResponseBytes: this.maxResponseBytes,
636
+ addressPolicy: this.endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS",
637
+ timeoutMs: 25e3,
638
+ signal: call.context.cancellationSignal
639
+ });
640
+ }
641
+ /** Classify a batch upsert error using the same status rules as an HTTP error. */
642
+ classifyBatchError(operation, response, receipt) {
643
+ return this.classify(operation, response, receipt);
644
+ }
645
+ classify(operation, response, receipt) {
646
+ const status = response.status;
647
+ const errorBody = decodeErrorBody(response.body);
648
+ const retryAfter = parseRetryAfter(header(response, "retry-after"), this.now());
649
+ const detail = safeDetail(errorBody);
650
+ if (status === 429 && errorBody.policyName === "DAILY") return this.failure("rejected", operation, "QUOTA_EXHAUSTED", "HubSpot's daily API request limit is exhausted", receipt);
651
+ if (status === 429) return this.failure("retry", operation, "RATE_LIMIT", "HubSpot rate limited the request", receipt, Math.max(retryAfter, rateLimitDelay(header(response, "x-hubspot-ratelimit-interval-milliseconds"))));
652
+ if (status === 423) return this.failure("retry", operation, "RATE_LIMIT", "HubSpot locked the records for a high-volume sync", receipt, Math.max(retryAfter, 2e3));
653
+ if (status === 408 || status === 477 || status >= 500 && status !== 501) return this.failure("retry", operation, "AVAILABILITY", `HubSpot is temporarily unavailable (HTTP ${status})`, receipt, retryAfter);
654
+ if (status === 401) return this.failure("rejected", operation, "AUTHENTICATION", `HubSpot rejected the access token${detail}`, receipt);
655
+ if (status === 403 && errorBody.category === "MISSING_SCOPES") return this.failure("rejected", operation, "AUTHORIZATION", `HubSpot access token lacks a required scope${detail}`, receipt);
656
+ if (status === 403) return this.failure("rejected", operation, "AUTHORIZATION", `HubSpot denied access to the record${detail}`, receipt);
657
+ if (status === 404) return this.failure("notFound", operation, "NOT_FOUND", `HubSpot found no such record${detail}`, receipt);
658
+ if (status === 409) return this.failure("conflict", operation, "CONFLICT", `HubSpot reported a conflict with another record${detail}`, receipt);
659
+ if (status === 400 || status === 422 || errorBody.category === "VALIDATION_ERROR") return this.failure("rejected", operation, "VALIDATION", `HubSpot rejected the request as invalid${detail}`, receipt);
660
+ if (status >= 300 && status < 400) return this.failure("rejected", operation, "PROTOCOL", `HubSpot redirected the request (HTTP ${status})`, receipt);
661
+ return this.failure("rejected", operation, "PROVIDER_REJECTION", `HubSpot rejected the request (HTTP ${status})${detail}`, receipt);
662
+ }
663
+ failure(disposition, operation, kind, message, receipt = {}, retryAfterMs = 0) {
664
+ return { disposition, failure: { kind, provider: "hubspot", operation, message }, receipt, retryAfterMs };
665
+ }
666
+ };
667
+ function header(response, name) {
668
+ const value = response.headers[name];
669
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
670
+ }
671
+ function rateLimitDelay(value) {
672
+ if (!/^[+-]?[0-9]+$/.test(value)) return 0;
673
+ const milliseconds = BigInt(value);
674
+ return milliseconds > 0n && milliseconds <= 9223372036854775807n ? Number(milliseconds > 10000n ? 10000n : milliseconds) : 0;
675
+ }
676
+ function decodeErrorBody(body) {
677
+ if (body.length > 65536) return {};
678
+ try {
679
+ const parsed = JSON.parse(Buffer.from(body).toString());
680
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
681
+ } catch {
682
+ return {};
683
+ }
684
+ }
685
+ function safeDetail(body) {
686
+ const tokens = [];
687
+ if (body.category && knownCategories.has(body.category)) tokens.push(body.category);
688
+ const code = body.errors?.[0]?.code;
689
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(code) && code !== body.category) tokens.push(code);
690
+ return tokens.length ? ` (${tokens.join(", ")})` : "";
691
+ }
692
+
693
+ // src/project.ts
694
+ function encodeCredentials(credentials) {
695
+ return {
696
+ auth_method: credentials.authMethodId ?? "",
697
+ access_token: credentials.accessToken.reveal(),
698
+ oauth_client_id: credentials.oauthClientId ?? "",
699
+ oauth_client_secret: credentials.oauthClientSecret?.reveal() ?? "",
700
+ refresh_token: credentials.refreshToken?.reveal() ?? ""
701
+ };
702
+ }
703
+ function newProjectConnection2(project, connectionName, options = {}) {
704
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
705
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "hubspot" && entry.connectionName === name);
706
+ if (!selected) throw new TypeError("HubSpot project connection is not configured");
707
+ const config = ConfigSchema.parse(selected.configuration);
708
+ return new HubSpotClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
709
+ });
710
+ }
711
+ export {
712
+ CRMObjectSchema,
713
+ ConfigSchema,
714
+ Connection,
715
+ ConnectorID,
716
+ GetObjectBranch,
717
+ GetObjectBranchDefect,
718
+ GetObjectBranchFound,
719
+ GetObjectBranchInvalidResponse,
720
+ GetObjectBranchNotFound,
721
+ GetObjectBranchProviderRejected,
722
+ GetObjectDefinition,
723
+ GetObjectInputSchema,
724
+ GetObjectMetadata,
725
+ GetObjectOperation,
726
+ HubSpotClient,
727
+ ObjectPageSchema,
728
+ ProviderID,
729
+ SearchFilterGroupSchema,
730
+ SearchFilterSchema,
731
+ SearchObjectsBranch,
732
+ SearchObjectsBranchDefect,
733
+ SearchObjectsBranchInvalidResponse,
734
+ SearchObjectsBranchProviderRejected,
735
+ SearchObjectsBranchSearched,
736
+ SearchObjectsDefinition,
737
+ SearchObjectsInputSchema,
738
+ SearchObjectsMetadata,
739
+ SearchObjectsOperation,
740
+ SearchSortSchema,
741
+ UpdateObjectBranch,
742
+ UpdateObjectBranchConflict,
743
+ UpdateObjectBranchDefect,
744
+ UpdateObjectBranchInvalidResponse,
745
+ UpdateObjectBranchNotFound,
746
+ UpdateObjectBranchProviderRejected,
747
+ UpdateObjectBranchUpdated,
748
+ UpdateObjectDefinition,
749
+ UpdateObjectInputSchema,
750
+ UpdateObjectMetadata,
751
+ UpdateObjectOperation,
752
+ UpsertObjectBranch,
753
+ UpsertObjectBranchConflict,
754
+ UpsertObjectBranchDefect,
755
+ UpsertObjectBranchInvalidResponse,
756
+ UpsertObjectBranchProviderRejected,
757
+ UpsertObjectBranchUpserted,
758
+ UpsertObjectDefinition,
759
+ UpsertObjectInputSchema,
760
+ UpsertObjectMetadata,
761
+ UpsertObjectOperation,
762
+ UpsertedObjectSchema,
763
+ decodeCredentials,
764
+ decodeSharedCredentials,
765
+ newConnection,
766
+ newConnectionWithOperations,
767
+ newGetObjectStep,
768
+ newProjectConnection2 as newProjectConnection,
769
+ newSearchObjectsStep,
770
+ newUpdateObjectStep,
771
+ newUpsertObjectStep
772
+ };