@rawdash/connector-hubspot 0.15.0 → 0.16.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,114 +1,84 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
1
3
  # @rawdash/connector-hubspot
2
4
 
3
- Rawdash connector for HubSpot — syncs CRM contacts, companies, and deals, deal stage-change events, and marketing email campaign performance into the six-shape storage model. Covers both the sales (pipeline, win rate) and marketing (email engagement) verticals from a single connector.
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-hubspot)](https://www.npmjs.com/package/@rawdash/connector-hubspot)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-hubspot)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
7
+
8
+ Sync CRM contacts, companies, and deals plus deal stage-change events and marketing email campaign stats from HubSpot.
9
+
10
+ ## Install
4
11
 
5
- ## Auth setup
12
+ ```sh
13
+ npm install @rawdash/connector-hubspot
14
+ ```
6
15
 
7
- The connector authenticates with a **private app access token**.
16
+ ## Authentication
8
17
 
9
- 1. In HubSpot, go to **Settings Integrations Private Apps**.
10
- 2. Click **Create a private app**.
11
- 3. On the **Basic Info** tab, give it a name (e.g. `rawdash`).
12
- 4. On the **Scopes** tab, enable read access for the resources you want to sync:
13
- - `crm.objects.contacts.read`
14
- - `crm.objects.companies.read`
15
- - `crm.objects.deals.read`
16
- - `marketing-email` (only needed for `email_campaigns` / `email_stats`)
17
- 5. Click **Create app**, then **Continue creating** to confirm.
18
- 6. Open the app's **Auth** tab and copy the **Access token** (starts with `pat-`).
18
+ A HubSpot private app access token with read scopes for the resources you sync (contacts, companies, deals, and marketing email).
19
19
 
20
- > **Note:** The token only needs read scopes for the resources you actually sync. Pick the narrowest set that covers your dashboards.
20
+ 1. In HubSpot, go to Settings Integrations Private Apps and create a private app.
21
+ 2. Grant read scopes for the resources you intend to sync (CRM contacts, companies, deals, and marketing email).
22
+ 3. Copy the generated access token (starts with `pat-`).
23
+ 4. Store it as a secret and reference it from the connector config as `accessToken: secret("HUBSPOT_ACCESS_TOKEN")`.
21
24
 
22
25
  ## Configuration
23
26
 
27
+ | Field | Type | Required | Description |
28
+ | ------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
29
+ | `accessToken` | secret | Yes | HubSpot private app access token with read scopes for contacts, companies, deals, and marketing email. Create one at Settings → Integrations → Private Apps. |
30
+ | `resources` | array | No | Which HubSpot resources to sync. Omit to sync all resources. The access token only needs read scopes for the resources listed here. |
31
+
32
+ ## Resources
33
+
34
+ - **`hubspot_contact`** _(entity)_ - CRM contacts with email, lifecycle stage, lead status, owner, and creation time.
35
+ - Endpoint: `POST /crm/v3/objects/contacts/search`
36
+ - **`hubspot_company`** _(entity)_ - CRM companies with name, domain, industry, lifecycle stage, and creation time.
37
+ - Endpoint: `POST /crm/v3/objects/companies/search`
38
+ - **`hubspot_deal`** _(entity)_ - CRM deals with name, stage, pipeline, amount, close date, owner, and creation time.
39
+ - Endpoint: `POST /crm/v3/objects/deals/search`
40
+ - **`hubspot_deal_stage_change`** _(event)_ - Deal stage-change events derived from deal property history, one event per stage transition.
41
+ - Endpoint: `GET /crm/v3/objects/deals?propertiesWithHistory=dealstage`
42
+ - **`hubspot_email_campaign`** _(entity)_ - Marketing email campaigns with name, subject, sender, type, send date, and recipient count.
43
+ - Endpoint: `GET /email/public/v1/campaigns`
44
+ - **`hubspot_email_stats`** _(metric)_ - Per-campaign marketing email engagement stats (sent, delivered, opened, clicked, bounced, unsubscribed) timestamped at the campaign send time.
45
+ - Endpoint: `GET /email/public/v1/campaigns/{id}`
46
+ - Unit: emails
47
+ - Dimensions: `campaignId`, `campaignName`, `delivered`, `opened`, `clicked`, `bounced`, `unsubscribed`
48
+ - One sample per campaign; value is the sent count, and every counter (delivered, opened, clicked, bounced, unsubscribed) is also exposed in attributes.
49
+
50
+ ## Example
51
+
24
52
  ```ts
25
- import { secret } from '@rawdash/core';
53
+ import {
54
+ defineConfig,
55
+ defineDashboard,
56
+ defineMetric,
57
+ secret,
58
+ } from '@rawdash/core';
26
59
 
27
60
  const hubspot = {
28
61
  name: 'hubspot',
29
62
  connectorId: 'hubspot',
30
63
  config: {
31
64
  accessToken: secret('HUBSPOT_ACCESS_TOKEN'),
32
- // resources: ['contacts', 'deals', 'deal_events'], // optional, defaults to all
65
+ resources: ['contacts', 'companies', 'deals'],
33
66
  },
34
67
  };
35
- ```
36
-
37
- Register the connector class when mounting the engine:
38
-
39
- ```ts
40
- import { HubSpotConnector } from '@rawdash/connector-hubspot';
41
- import { mountEngine } from '@rawdash/hono';
42
-
43
- mountEngine(config, { connectorRegistry: { hubspot: HubSpotConnector } });
44
- ```
45
-
46
- ### Choosing resources
47
-
48
- By default the connector syncs every supported resource. To sync only a subset, pass `resources` with any combination of:
49
-
50
- `contacts`, `companies`, `deals`, `deal_events`, `email_campaigns`, `email_stats`
51
-
52
- The access token only needs read scopes for the resources you list, and picking only what you need reduces API calls during full syncs.
53
-
54
- ### Example dashboard
55
-
56
- ```ts
57
- import { defineConfig, defineDashboard, defineMetric } from '@rawdash/core';
58
68
 
59
69
  export default defineConfig({
60
70
  connectors: [hubspot],
61
71
  dashboards: {
62
72
  sales: defineDashboard({
63
73
  widgets: {
64
- open_deal_value: {
65
- kind: 'stat',
66
- title: 'Open deal value',
67
- metric: defineMetric({
68
- connector: hubspot,
69
- shape: 'entity',
70
- entityType: 'hubspot_deal',
71
- field: 'amount',
72
- fn: 'sum',
73
- filter: [{ field: 'dealStage', op: 'neq', value: 'closedlost' }],
74
- }),
75
- },
76
74
  open_deals: {
77
75
  kind: 'stat',
78
- title: 'Open deals',
76
+ title: 'Open Deals',
79
77
  metric: defineMetric({
80
78
  connector: hubspot,
81
79
  shape: 'entity',
82
80
  entityType: 'hubspot_deal',
83
81
  fn: 'count',
84
- filter: [
85
- { field: 'dealstage', op: 'eq', value: 'appointmentscheduled' },
86
- ],
87
- }),
88
- },
89
- contacts_by_lifecycle: {
90
- kind: 'distribution',
91
- title: 'Contacts by lifecycle stage',
92
- metric: defineMetric({
93
- connector: hubspot,
94
- shape: 'entity',
95
- entityType: 'hubspot_contact',
96
- fn: 'count',
97
- groupBy: { field: 'lifecycleStage' },
98
- }),
99
- },
100
- email_opens: {
101
- kind: 'timeseries',
102
- title: 'Email opens per campaign',
103
- window: '90d',
104
- metric: defineMetric({
105
- connector: hubspot,
106
- shape: 'metric',
107
- name: 'hubspot_email_stats',
108
- field: 'opened',
109
- fn: 'sum',
110
- window: '90d',
111
- groupBy: { field: 'ts', granularity: 'day' },
112
82
  }),
113
83
  },
114
84
  },
@@ -117,64 +87,22 @@ export default defineConfig({
117
87
  });
118
88
  ```
119
89
 
120
- ## Data model
121
-
122
- Monetary amounts (deal `amount`) are in the account's currency, as returned by HubSpot. Timestamps stored in attributes are Unix milliseconds.
90
+ ## Rate limits
123
91
 
124
- | Storage shape | Entity/event/metric type | Key attributes |
125
- | ------------- | --------------------------- | --------------------------------------------------------------------------------- |
126
- | entity | `hubspot_contact` | email, lifecycleStage, leadStatus, ownerId, createdAt |
127
- | entity | `hubspot_company` | name, domain, industry, lifecycleStage, createdAt |
128
- | entity | `hubspot_deal` | dealName, dealStage, pipeline, amount, closeDate, ownerId, createdAt |
129
- | event | `hubspot_deal_stage_change` | dealId, stage, sourceType |
130
- | entity | `hubspot_email_campaign` | name, subject, fromName, type, sentDate, numIncluded |
131
- | metric | `hubspot_email_stats` | campaignId, campaignName, sent, delivered, opened, clicked, bounced, unsubscribed |
92
+ HubSpot allows 100 requests / 10s; the Search API caps results at 10,000 per query.
132
93
 
133
- - **`hubspot_deal_stage_change`** events come from the `dealstage` property history on each deal (`propertiesWithHistory=dealstage`). One event per recorded stage value, timestamped at the moment the stage was set.
134
- - **`hubspot_email_stats`** metrics carry one sample per campaign; `value` is the `sent` count and every counter is also exposed in `attributes` so timeseries / distribution widgets can chart any of them.
94
+ ## Limitations
135
95
 
136
- ## Schemas
96
+ - Deal stage-change events are rewritten on every sync because the deal list endpoint has no incremental `since` filter.
97
+ - Marketing email campaign data comes from the legacy email campaigns API and is only available for marketing emails.
98
+ - Very large CRM portfolios may not backfill in full because the Search API caps at 10,000 results per query.
137
99
 
138
- `HubSpotConnector.schemas` declares the Zod schema for each resource's raw API response (the array of records for CRM resources, the deal-history record array, and the campaign-detail object array). Used by the cloud shape-drift pipeline to populate `connector_baselines`, and by the package's property tests.
100
+ ## Links
139
101
 
140
- ## Sync behaviour
141
-
142
- - **Backfill** (`mode: 'full'`): CRM objects are fetched via the Search API (`POST /crm/v3/objects/{object}/search`) sorted by last-modified ascending, paginated with the `after` cursor; deal events and email data are enumerated and rewritten in full.
143
- - **Incremental** (`mode: 'latest'`): CRM searches add a `filterGroups` `GTE` filter on the object's last-modified property so only changed records are fetched. Entity phases upsert (no clear); the event and metric phases rewrite their requested window each run.
144
- - **Resumable**: each phase yields an `after`/offset cursor on abort, so an interrupted sync resumes from the same page.
145
- - **Rate limits**: HubSpot returns `429` when the per-app limit (100 requests / 10s) is exceeded. The shared HTTP client retries automatically with exponential back-off and honors `Retry-After`.
146
-
147
- > **Search API ceiling:** HubSpot's Search API caps results at 10,000 per query. Very large CRM portfolios may not backfill in full in a single window; incremental syncs (which filter on `hs_lastmodifieddate`) stay well under the ceiling.
148
-
149
- ## Aggregates
150
-
151
- | Function | Resource | Upstream call |
152
- | -------- | ----------------- | ------------------------------------------------------------ |
153
- | `count` | `hubspot_contact` | `POST /crm/v3/objects/contacts/search` (`limit=1`, `total`) |
154
- | `count` | `hubspot_company` | `POST /crm/v3/objects/companies/search` (`limit=1`, `total`) |
155
- | `count` | `hubspot_deal` | `POST /crm/v3/objects/deals/search` (`limit=1`, `total`) |
156
-
157
- `count` widgets are served directly from the Search API `total`, so the runner can skip backfilling the underlying entities for that tick. Filter conditions translate to HubSpot search operators (`eq→EQ`, `neq→NEQ`, `gt→GT`, `gte→GTE`, `lt→LT`, `lte→LTE`, `contains→CONTAINS_TOKEN`). `OR` clauses and `latest` aggregates aren't supported and fall back to evaluating against synced storage rows.
158
-
159
- ## Registering in the MCP server
160
-
161
- To make the connector available via the `add_connector` MCP tool, include it in `connectorFactories`:
162
-
163
- ```ts
164
- import { HubSpotConnector, configFields } from '@rawdash/connector-hubspot';
165
-
166
- createMcpServer({
167
- // ...
168
- connectorFactories: [
169
- {
170
- id: 'hubspot',
171
- configFields,
172
- create: HubSpotConnector.create,
173
- },
174
- ],
175
- });
176
- ```
102
+ - [Rawdash docs](https://rawdash.dev/docs/connectors/)
103
+ - [HubSpot API docs](https://developers.hubspot.com/docs/api/overview)
104
+ - [GitHub](https://github.com/rawdash/rawdash)
177
105
 
178
- ## Property tests
106
+ ## License
179
107
 
180
- The CRM entity resources (`contacts`, `companies`, `deals`) have fast-check property tests under `src/property.test.ts` that generate synthetic API payloads from each resource's Zod schema, run them through `connector.sync()` against an `InMemoryStorage`, and assert universal invariants (non-empty ids, finite timestamps, no `undefined` in storage, no thrown errors) plus per-resource entity counts. Deal events, email campaigns, and email stats are covered by example-driven unit tests in `src/hubspot.test.ts`.
108
+ Apache-2.0
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, AggregateRequest, AggregateValue, FilterClause } from '@rawdash/core';
1
+ import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
2
2
  import { z } from 'zod';
3
3
 
4
4
  declare const configFields: z.ZodObject<{
@@ -14,6 +14,7 @@ declare const configFields: z.ZodObject<{
14
14
  email_stats: "email_stats";
15
15
  }>>>;
16
16
  }, z.core.$strip>;
17
+ declare const doc: ConnectorDoc;
17
18
  interface HubSpotSettings {
18
19
  resources?: readonly HubSpotResource[];
19
20
  }
@@ -29,10 +30,128 @@ type HubSpotPhase = (typeof PHASE_ORDER)[number];
29
30
  type HubSpotResource = HubSpotPhase;
30
31
  declare class HubSpotConnector extends BaseConnector<HubSpotSettings, HubSpotCredentials> {
31
32
  static readonly id = "hubspot";
33
+ static readonly resources: {
34
+ readonly hubspot_contact: {
35
+ readonly shape: "entity";
36
+ readonly description: "CRM contacts with email, lifecycle stage, lead status, owner, and creation time.";
37
+ readonly endpoint: "POST /crm/v3/objects/contacts/search";
38
+ readonly responses: {
39
+ readonly contacts: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
40
+ };
41
+ };
42
+ readonly hubspot_company: {
43
+ readonly shape: "entity";
44
+ readonly description: "CRM companies with name, domain, industry, lifecycle stage, and creation time.";
45
+ readonly endpoint: "POST /crm/v3/objects/companies/search";
46
+ readonly responses: {
47
+ readonly companies: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
48
+ };
49
+ };
50
+ readonly hubspot_deal: {
51
+ readonly shape: "entity";
52
+ readonly description: "CRM deals with name, stage, pipeline, amount, close date, owner, and creation time.";
53
+ readonly endpoint: "POST /crm/v3/objects/deals/search";
54
+ readonly responses: {
55
+ readonly deals: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
56
+ };
57
+ };
58
+ readonly hubspot_deal_stage_change: {
59
+ readonly shape: "event";
60
+ readonly description: "Deal stage-change events derived from deal property history, one event per stage transition.";
61
+ readonly endpoint: "GET /crm/v3/objects/deals?propertiesWithHistory=dealstage";
62
+ readonly responses: {
63
+ readonly deal_events: z.ZodArray<z.ZodObject<{
64
+ id: z.ZodString;
65
+ propertiesWithHistory: z.ZodOptional<z.ZodObject<{
66
+ dealstage: z.ZodOptional<z.ZodArray<z.ZodObject<{
67
+ value: z.ZodOptional<z.ZodNullable<z.ZodString>>;
68
+ timestamp: z.ZodOptional<z.ZodNullable<z.ZodString>>;
69
+ sourceType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
+ }, z.core.$strip>>>;
71
+ }, z.core.$strip>>;
72
+ }, z.core.$strip>>;
73
+ };
74
+ };
75
+ readonly hubspot_email_campaign: {
76
+ readonly shape: "entity";
77
+ readonly description: "Marketing email campaigns with name, subject, sender, type, send date, and recipient count.";
78
+ readonly endpoint: "GET /email/public/v1/campaigns";
79
+ readonly responses: {
80
+ readonly email_campaigns: z.ZodArray<z.ZodObject<{
81
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
82
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
83
+ subject: z.ZodOptional<z.ZodNullable<z.ZodString>>;
84
+ fromName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
85
+ type: z.ZodOptional<z.ZodNullable<z.ZodString>>;
86
+ lastProcessingFinishedAt: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
87
+ numIncluded: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
88
+ counters: z.ZodOptional<z.ZodObject<{
89
+ sent: z.ZodOptional<z.ZodNumber>;
90
+ delivered: z.ZodOptional<z.ZodNumber>;
91
+ open: z.ZodOptional<z.ZodNumber>;
92
+ click: z.ZodOptional<z.ZodNumber>;
93
+ bounce: z.ZodOptional<z.ZodNumber>;
94
+ unsubscribed: z.ZodOptional<z.ZodNumber>;
95
+ }, z.core.$strip>>;
96
+ }, z.core.$strip>>;
97
+ };
98
+ };
99
+ readonly hubspot_email_stats: {
100
+ readonly shape: "metric";
101
+ readonly description: "Per-campaign marketing email engagement stats (sent, delivered, opened, clicked, bounced, unsubscribed) timestamped at the campaign send time.";
102
+ readonly endpoint: "GET /email/public/v1/campaigns/{id}";
103
+ readonly unit: "emails";
104
+ readonly notes: "One sample per campaign; value is the sent count, and every counter (delivered, opened, clicked, bounced, unsubscribed) is also exposed in attributes.";
105
+ readonly dimensions: [{
106
+ readonly name: "campaignId";
107
+ readonly description: "HubSpot campaign id.";
108
+ }, {
109
+ readonly name: "campaignName";
110
+ readonly description: "Campaign name.";
111
+ }, {
112
+ readonly name: "delivered";
113
+ readonly description: "Number of emails delivered.";
114
+ }, {
115
+ readonly name: "opened";
116
+ readonly description: "Number of emails opened.";
117
+ }, {
118
+ readonly name: "clicked";
119
+ readonly description: "Number of emails clicked.";
120
+ }, {
121
+ readonly name: "bounced";
122
+ readonly description: "Number of emails bounced.";
123
+ }, {
124
+ readonly name: "unsubscribed";
125
+ readonly description: "Number of recipients who unsubscribed.";
126
+ }];
127
+ readonly responses: {
128
+ readonly email_stats: z.ZodArray<z.ZodObject<{
129
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
130
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
131
+ subject: z.ZodOptional<z.ZodNullable<z.ZodString>>;
132
+ fromName: z.ZodOptional<z.ZodNullable<z.ZodString>>;
133
+ type: z.ZodOptional<z.ZodNullable<z.ZodString>>;
134
+ lastProcessingFinishedAt: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
135
+ numIncluded: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
136
+ counters: z.ZodOptional<z.ZodObject<{
137
+ sent: z.ZodOptional<z.ZodNumber>;
138
+ delivered: z.ZodOptional<z.ZodNumber>;
139
+ open: z.ZodOptional<z.ZodNumber>;
140
+ click: z.ZodOptional<z.ZodNumber>;
141
+ bounce: z.ZodOptional<z.ZodNumber>;
142
+ unsubscribed: z.ZodOptional<z.ZodNumber>;
143
+ }, z.core.$strip>>;
144
+ }, z.core.$strip>>;
145
+ };
146
+ };
147
+ };
32
148
  static readonly schemas: {
33
149
  readonly contacts: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
150
+ } & {
34
151
  readonly companies: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
152
+ } & {
35
153
  readonly deals: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
154
+ } & {
36
155
  readonly deal_events: z.ZodArray<z.ZodObject<{
37
156
  id: z.ZodString;
38
157
  propertiesWithHistory: z.ZodOptional<z.ZodObject<{
@@ -43,6 +162,7 @@ declare class HubSpotConnector extends BaseConnector<HubSpotSettings, HubSpotCre
43
162
  }, z.core.$strip>>>;
44
163
  }, z.core.$strip>>;
45
164
  }, z.core.$strip>>;
165
+ } & {
46
166
  readonly email_campaigns: z.ZodArray<z.ZodObject<{
47
167
  id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
48
168
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -60,6 +180,7 @@ declare class HubSpotConnector extends BaseConnector<HubSpotSettings, HubSpotCre
60
180
  unsubscribed: z.ZodOptional<z.ZodNumber>;
61
181
  }, z.core.$strip>>;
62
182
  }, z.core.$strip>>;
183
+ } & {
63
184
  readonly email_stats: z.ZodArray<z.ZodObject<{
64
185
  id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
65
186
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -77,7 +198,7 @@ declare class HubSpotConnector extends BaseConnector<HubSpotSettings, HubSpotCre
77
198
  unsubscribed: z.ZodOptional<z.ZodNumber>;
78
199
  }, z.core.$strip>>;
79
200
  }, z.core.$strip>>;
80
- };
201
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
81
202
  static create(input: unknown, ctx?: ConnectorContext): HubSpotConnector;
82
203
  readonly id = "hubspot";
83
204
  readonly credentials: {
@@ -101,9 +222,6 @@ declare class HubSpotConnector extends BaseConnector<HubSpotSettings, HubSpotCre
101
222
  private clearScopeOnFirstPage;
102
223
  private writePhase;
103
224
  sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
104
- aggregate(req: AggregateRequest, signal?: AbortSignal): Promise<AggregateValue>;
105
- validateCountFilter(resource: string, filter: FilterClause[]): void;
106
- private translateCountFilter;
107
225
  }
108
226
 
109
- export { HubSpotConnector, type HubSpotResource, type HubSpotSettings, configFields, HubSpotConnector as default };
227
+ export { HubSpotConnector, type HubSpotResource, type HubSpotSettings, configFields, HubSpotConnector as default, doc };
package/dist/index.js CHANGED
@@ -30,8 +30,11 @@ function parseEpoch(value, unit) {
30
30
  import {
31
31
  BaseConnector,
32
32
  defineConfigFields,
33
+ defineConnectorDoc,
34
+ defineResources,
33
35
  makeChunkedCursorGuard,
34
36
  paginateChunked,
37
+ schemasFromResources,
35
38
  selectActivePhases
36
39
  } from "@rawdash/core";
37
40
  import { z } from "zod";
@@ -58,6 +61,32 @@ var configFields = defineConfigFields(
58
61
  })
59
62
  })
60
63
  );
64
+ var doc = defineConnectorDoc({
65
+ displayName: "HubSpot",
66
+ category: "sales",
67
+ brandColor: "#FF7A59",
68
+ tagline: "Sync CRM contacts, companies, and deals plus deal stage-change events and marketing email campaign stats from HubSpot.",
69
+ vendor: {
70
+ name: "HubSpot",
71
+ apiDocs: "https://developers.hubspot.com/docs/api/overview",
72
+ website: "https://www.hubspot.com"
73
+ },
74
+ auth: {
75
+ summary: "A HubSpot private app access token with read scopes for the resources you sync (contacts, companies, deals, and marketing email).",
76
+ setup: [
77
+ "In HubSpot, go to Settings \u2192 Integrations \u2192 Private Apps and create a private app.",
78
+ "Grant read scopes for the resources you intend to sync (CRM contacts, companies, deals, and marketing email).",
79
+ "Copy the generated access token (starts with `pat-`).",
80
+ 'Store it as a secret and reference it from the connector config as `accessToken: secret("HUBSPOT_ACCESS_TOKEN")`.'
81
+ ]
82
+ },
83
+ rateLimit: "HubSpot allows 100 requests / 10s; the Search API caps results at 10,000 per query.",
84
+ limitations: [
85
+ "Deal stage-change events are rewritten on every sync because the deal list endpoint has no incremental `since` filter.",
86
+ "Marketing email campaign data comes from the legacy email campaigns API and is only available for marketing emails.",
87
+ "Very large CRM portfolios may not backfill in full because the Search API caps at 10,000 results per query."
88
+ ]
89
+ });
61
90
  var hubspotCredentials = {
62
91
  accessToken: {
63
92
  description: "HubSpot private app access token",
@@ -117,20 +146,6 @@ var ENTITY_TYPE_BY_PHASE = {
117
146
  };
118
147
  var DEAL_STAGE_EVENT = "hubspot_deal_stage_change";
119
148
  var EMAIL_STATS_METRIC = "hubspot_email_stats";
120
- var COUNT_RESOURCE_TO_OBJECT = {
121
- hubspot_contact: "contacts",
122
- hubspot_company: "companies",
123
- hubspot_deal: "deals"
124
- };
125
- var FILTER_OP_TO_HUBSPOT = {
126
- eq: "EQ",
127
- neq: "NEQ",
128
- gt: "GT",
129
- gte: "GTE",
130
- lt: "LT",
131
- lte: "LTE",
132
- contains: "CONTAINS_TOKEN"
133
- };
134
149
  function finiteNumberOrNull(value) {
135
150
  if (value === null || value === void 0 || value.trim() === "") {
136
151
  return null;
@@ -141,11 +156,6 @@ function finiteNumberOrNull(value) {
141
156
  function counterValue(value) {
142
157
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
143
158
  }
144
- function unsupportedAggregate(req) {
145
- return new Error(
146
- `HubSpot aggregate: unsupported ${req.fn} for resource=${req.resource}`
147
- );
148
- }
149
159
  var idString = z.string().min(1);
150
160
  var contactProperties = z.object({
151
161
  email: z.string().nullish(),
@@ -211,16 +221,67 @@ var campaignDetailSchema = z.object({
211
221
  unsubscribed: z.number().optional()
212
222
  }).optional()
213
223
  });
224
+ var contactsSchema = z.array(crmRecordSchema(contactProperties));
225
+ var companiesSchema = z.array(crmRecordSchema(companyProperties));
226
+ var dealsSchema = z.array(crmRecordSchema(dealProperties));
227
+ var dealEventsSchema = z.array(dealHistoryRecordSchema);
228
+ var campaignsSchema = z.array(campaignDetailSchema);
229
+ var hubspotResources = defineResources({
230
+ hubspot_contact: {
231
+ shape: "entity",
232
+ description: "CRM contacts with email, lifecycle stage, lead status, owner, and creation time.",
233
+ endpoint: "POST /crm/v3/objects/contacts/search",
234
+ responses: { contacts: contactsSchema }
235
+ },
236
+ hubspot_company: {
237
+ shape: "entity",
238
+ description: "CRM companies with name, domain, industry, lifecycle stage, and creation time.",
239
+ endpoint: "POST /crm/v3/objects/companies/search",
240
+ responses: { companies: companiesSchema }
241
+ },
242
+ hubspot_deal: {
243
+ shape: "entity",
244
+ description: "CRM deals with name, stage, pipeline, amount, close date, owner, and creation time.",
245
+ endpoint: "POST /crm/v3/objects/deals/search",
246
+ responses: { deals: dealsSchema }
247
+ },
248
+ hubspot_deal_stage_change: {
249
+ shape: "event",
250
+ description: "Deal stage-change events derived from deal property history, one event per stage transition.",
251
+ endpoint: "GET /crm/v3/objects/deals?propertiesWithHistory=dealstage",
252
+ responses: { deal_events: dealEventsSchema }
253
+ },
254
+ hubspot_email_campaign: {
255
+ shape: "entity",
256
+ description: "Marketing email campaigns with name, subject, sender, type, send date, and recipient count.",
257
+ endpoint: "GET /email/public/v1/campaigns",
258
+ responses: { email_campaigns: campaignsSchema }
259
+ },
260
+ hubspot_email_stats: {
261
+ shape: "metric",
262
+ description: "Per-campaign marketing email engagement stats (sent, delivered, opened, clicked, bounced, unsubscribed) timestamped at the campaign send time.",
263
+ endpoint: "GET /email/public/v1/campaigns/{id}",
264
+ unit: "emails",
265
+ notes: "One sample per campaign; value is the sent count, and every counter (delivered, opened, clicked, bounced, unsubscribed) is also exposed in attributes.",
266
+ dimensions: [
267
+ { name: "campaignId", description: "HubSpot campaign id." },
268
+ { name: "campaignName", description: "Campaign name." },
269
+ { name: "delivered", description: "Number of emails delivered." },
270
+ { name: "opened", description: "Number of emails opened." },
271
+ { name: "clicked", description: "Number of emails clicked." },
272
+ { name: "bounced", description: "Number of emails bounced." },
273
+ {
274
+ name: "unsubscribed",
275
+ description: "Number of recipients who unsubscribed."
276
+ }
277
+ ],
278
+ responses: { email_stats: campaignsSchema }
279
+ }
280
+ });
214
281
  var HubSpotConnector = class _HubSpotConnector extends BaseConnector {
215
282
  static id = "hubspot";
216
- static schemas = {
217
- contacts: z.array(crmRecordSchema(contactProperties)),
218
- companies: z.array(crmRecordSchema(companyProperties)),
219
- deals: z.array(crmRecordSchema(dealProperties)),
220
- deal_events: z.array(dealHistoryRecordSchema),
221
- email_campaigns: z.array(campaignDetailSchema),
222
- email_stats: z.array(campaignDetailSchema)
223
- };
283
+ static resources = hubspotResources;
284
+ static schemas = schemasFromResources(hubspotResources);
224
285
  static create(input, ctx) {
225
286
  const parsed = configFields.parse(input);
226
287
  return new _HubSpotConnector(
@@ -525,69 +586,6 @@ var HubSpotConnector = class _HubSpotConnector extends BaseConnector {
525
586
  }
526
587
  });
527
588
  }
528
- // -------------------------------------------------------------------------
529
- // Aggregates — count via the CRM Search API `total` (one request)
530
- // -------------------------------------------------------------------------
531
- async aggregate(req, signal) {
532
- if (req.fn !== "count") {
533
- throw unsupportedAggregate(req);
534
- }
535
- const object = COUNT_RESOURCE_TO_OBJECT[req.resource];
536
- if (!object) {
537
- throw unsupportedAggregate(req);
538
- }
539
- const filterGroups = this.translateCountFilter(req.filter);
540
- const res = await this.apiPost(
541
- `${BASE_URL}/crm/v3/objects/${object}/search`,
542
- object,
543
- { filterGroups, properties: [], limit: 1 },
544
- signal
545
- );
546
- const value = res.body.total ?? 0;
547
- this.logger.info("aggregate", {
548
- fn: "count",
549
- resource: req.resource,
550
- filter: req.filter,
551
- value,
552
- via: "CRM search API"
553
- });
554
- return value;
555
- }
556
- validateCountFilter(resource, filter) {
557
- if (!COUNT_RESOURCE_TO_OBJECT[resource]) {
558
- throw new Error(
559
- `HubSpot aggregate count: unsupported resource=${resource}`
560
- );
561
- }
562
- this.translateCountFilter(filter);
563
- }
564
- // Translates flat AND filter conditions into HubSpot search `filterGroups`.
565
- // OR clauses aren't expressible alongside the rest of the group model, so
566
- // they throw "unsupported" and the runner falls back to storage rows.
567
- translateCountFilter(filter) {
568
- if (!filter || filter.length === 0) {
569
- return [];
570
- }
571
- const filters = filter.map((clause) => {
572
- if ("or" in clause) {
573
- throw new Error(
574
- "HubSpot aggregate count: OR filter clauses are not supported"
575
- );
576
- }
577
- const operator = FILTER_OP_TO_HUBSPOT[clause.op];
578
- if (!operator) {
579
- throw new Error(
580
- `HubSpot aggregate count: unsupported filter operator ${clause.op}`
581
- );
582
- }
583
- return {
584
- propertyName: clause.field,
585
- operator,
586
- value: String(clause.value)
587
- };
588
- });
589
- return [{ filters }];
590
- }
591
589
  };
592
590
 
593
591
  // src/index.ts
@@ -595,6 +593,7 @@ var index_default = HubSpotConnector;
595
593
  export {
596
594
  HubSpotConnector,
597
595
  configFields,
598
- index_default as default
596
+ index_default as default,
597
+ doc
599
598
  };
600
599
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/hubspot.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n type AggregateRequest,\n type AggregateValue,\n BaseConnector,\n type ConnectorContext,\n type CredentialsSchema,\n type FilterClause,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n makeChunkedCursorGuard,\n paginateChunked,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n accessToken: z.object({ $secret: z.string() }).meta({\n label: 'Private App access token',\n description:\n 'HubSpot private app access token with read scopes for contacts, companies, deals, and marketing email. Create one at Settings → Integrations → Private Apps.',\n placeholder: 'pat-na1-...',\n secret: true,\n }),\n resources: z\n .array(\n z.enum([\n 'contacts',\n 'companies',\n 'deals',\n 'deal_events',\n 'email_campaigns',\n 'email_stats',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which HubSpot resources to sync. Omit to sync all resources. The access token only needs read scopes for the resources listed here.',\n }),\n }),\n);\n\nexport interface HubSpotSettings {\n resources?: readonly HubSpotResource[];\n}\n\n// ---------------------------------------------------------------------------\n// HubSpot API types\n// ---------------------------------------------------------------------------\n\ntype HubSpotProperties = Record<string, string | null | undefined>;\n\ninterface CrmRecord {\n id: string;\n properties: HubSpotProperties;\n createdAt: string;\n updatedAt: string;\n archived?: boolean;\n}\n\ninterface CrmSearchResponse {\n total?: number;\n results: CrmRecord[];\n paging?: { next?: { after?: string } };\n}\n\ninterface CrmListResponse {\n results: DealHistoryRecord[];\n paging?: { next?: { after?: string } };\n}\n\ninterface DealHistoryEntry {\n value?: string | null;\n timestamp?: string | null;\n sourceType?: string | null;\n}\n\ninterface DealHistoryRecord {\n id: string;\n propertiesWithHistory?: {\n dealstage?: DealHistoryEntry[];\n };\n}\n\ninterface CampaignListResponse {\n campaigns: Array<{ id: number | string }>;\n hasMore?: boolean;\n offset?: number | string;\n}\n\ninterface CampaignCounters {\n sent?: number;\n delivered?: number;\n open?: number;\n click?: number;\n bounce?: number;\n unsubscribed?: number;\n}\n\ninterface CampaignDetail {\n id: number | string;\n name?: string | null;\n subject?: string | null;\n fromName?: string | null;\n type?: string | null;\n lastProcessingFinishedAt?: number | string | null;\n numIncluded?: number | null;\n counters?: CampaignCounters;\n}\n\n// ---------------------------------------------------------------------------\n// Credentials\n// ---------------------------------------------------------------------------\n\nconst hubspotCredentials = {\n accessToken: {\n description: 'HubSpot private app access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype HubSpotCredentials = typeof hubspotCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'contacts',\n 'companies',\n 'deals',\n 'deal_events',\n 'email_campaigns',\n 'email_stats',\n] as const;\n\ntype HubSpotPhase = (typeof PHASE_ORDER)[number];\n\nexport type HubSpotResource = HubSpotPhase;\n\nconst isHubSpotSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst BASE_URL = 'https://api.hubapi.com';\nconst SEARCH_LIMIT = 100;\nconst LIST_LIMIT = 100;\n\ntype CrmObjectPhase = 'contacts' | 'companies' | 'deals';\n\n// CRM object name + property names requested per search phase.\nconst SEARCH_PROPERTIES: Record<CrmObjectPhase, readonly string[]> = {\n contacts: [\n 'email',\n 'lifecyclestage',\n 'hs_lead_status',\n 'createdate',\n 'lastmodifieddate',\n 'hubspot_owner_id',\n ],\n companies: [\n 'name',\n 'domain',\n 'industry',\n 'createdate',\n 'lifecyclestage',\n 'hs_lastmodifieddate',\n ],\n deals: [\n 'dealname',\n 'dealstage',\n 'pipeline',\n 'amount',\n 'closedate',\n 'hubspot_owner_id',\n 'createdate',\n 'hs_lastmodifieddate',\n ],\n};\n\n// Property each CRM object stamps with its last-modified time, used both for\n// the incremental `since` filter and the entity `updated_at` fallback.\nconst MODIFIED_PROPERTY: Record<CrmObjectPhase, string> = {\n contacts: 'lastmodifieddate',\n companies: 'hs_lastmodifieddate',\n deals: 'hs_lastmodifieddate',\n};\n\nconst ENTITY_TYPE_BY_PHASE: Partial<Record<HubSpotPhase, string>> = {\n contacts: 'hubspot_contact',\n companies: 'hubspot_company',\n deals: 'hubspot_deal',\n email_campaigns: 'hubspot_email_campaign',\n};\n\nconst DEAL_STAGE_EVENT = 'hubspot_deal_stage_change';\nconst EMAIL_STATS_METRIC = 'hubspot_email_stats';\n\n// Aggregate `resource` (the widget's entity type) → CRM search object.\nconst COUNT_RESOURCE_TO_OBJECT: Record<string, CrmObjectPhase> = {\n hubspot_contact: 'contacts',\n hubspot_company: 'companies',\n hubspot_deal: 'deals',\n};\n\nconst FILTER_OP_TO_HUBSPOT: Record<string, string> = {\n eq: 'EQ',\n neq: 'NEQ',\n gt: 'GT',\n gte: 'GTE',\n lt: 'LT',\n lte: 'LTE',\n contains: 'CONTAINS_TOKEN',\n};\n\n// ---------------------------------------------------------------------------\n// Value helpers\n// ---------------------------------------------------------------------------\n\nfunction finiteNumberOrNull(value: string | null | undefined): number | null {\n if (value === null || value === undefined || value.trim() === '') {\n return null;\n }\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction counterValue(value: number | undefined): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction unsupportedAggregate(req: AggregateRequest): Error {\n return new Error(\n `HubSpot aggregate: unsupported ${req.fn} for resource=${req.resource}`,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst idString = z.string().min(1);\n\nconst contactProperties = z.object({\n email: z.string().nullish(),\n lifecyclestage: z.string().nullish(),\n hs_lead_status: z.string().nullish(),\n createdate: z.string().nullish(),\n lastmodifieddate: z.string().nullish(),\n hubspot_owner_id: z.string().nullish(),\n});\n\nconst companyProperties = z.object({\n name: z.string().nullish(),\n domain: z.string().nullish(),\n industry: z.string().nullish(),\n createdate: z.string().nullish(),\n lifecyclestage: z.string().nullish(),\n hs_lastmodifieddate: z.string().nullish(),\n});\n\nconst dealProperties = z.object({\n dealname: z.string().nullish(),\n dealstage: z.string().nullish(),\n pipeline: z.string().nullish(),\n amount: z.string().nullish(),\n closedate: z.string().nullish(),\n hubspot_owner_id: z.string().nullish(),\n createdate: z.string().nullish(),\n hs_lastmodifieddate: z.string().nullish(),\n});\n\nfunction crmRecordSchema(props: z.ZodType): z.ZodType {\n return z.object({\n id: idString,\n properties: props,\n createdAt: z.string(),\n updatedAt: z.string(),\n archived: z.boolean().optional(),\n });\n}\n\nconst dealHistoryRecordSchema = z.object({\n id: idString,\n propertiesWithHistory: z\n .object({\n dealstage: z\n .array(\n z.object({\n value: z.string().nullish(),\n timestamp: z.string().nullish(),\n sourceType: z.string().nullish(),\n }),\n )\n .optional(),\n })\n .optional(),\n});\n\nconst campaignDetailSchema = z.object({\n id: z.union([z.string(), z.number()]),\n name: z.string().nullish(),\n subject: z.string().nullish(),\n fromName: z.string().nullish(),\n type: z.string().nullish(),\n lastProcessingFinishedAt: z.union([z.string(), z.number()]).nullish(),\n numIncluded: z.number().nullish(),\n counters: z\n .object({\n sent: z.number().optional(),\n delivered: z.number().optional(),\n open: z.number().optional(),\n click: z.number().optional(),\n bounce: z.number().optional(),\n unsubscribed: z.number().optional(),\n })\n .optional(),\n});\n\n// ---------------------------------------------------------------------------\n// HubSpotConnector\n// ---------------------------------------------------------------------------\n\nexport class HubSpotConnector extends BaseConnector<\n HubSpotSettings,\n HubSpotCredentials\n> {\n static readonly id = 'hubspot';\n\n static readonly schemas = {\n contacts: z.array(crmRecordSchema(contactProperties)),\n companies: z.array(crmRecordSchema(companyProperties)),\n deals: z.array(crmRecordSchema(dealProperties)),\n deal_events: z.array(dealHistoryRecordSchema),\n email_campaigns: z.array(campaignDetailSchema),\n email_stats: z.array(campaignDetailSchema),\n } as const;\n\n static create(input: unknown, ctx?: ConnectorContext): HubSpotConnector {\n const parsed = configFields.parse(input);\n return new HubSpotConnector(\n { resources: parsed.resources },\n { accessToken: parsed.accessToken },\n ctx,\n );\n }\n\n readonly id = 'hubspot';\n override readonly credentials = hubspotCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.accessToken}`,\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('hubspot'),\n };\n }\n\n private apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n private apiPost<T>(\n url: string,\n resource: string,\n body: unknown,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: this.buildHeaders(),\n body: JSON.stringify(body),\n signal,\n });\n }\n\n // -------------------------------------------------------------------------\n // CRM search phases (contacts / companies / deals)\n // -------------------------------------------------------------------------\n\n private buildSearchBody(\n phase: CrmObjectPhase,\n after: string | null,\n options: SyncOptions,\n ): Record<string, unknown> {\n const modifiedProperty = MODIFIED_PROPERTY[phase];\n const filterGroups: unknown[] = [];\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs)) {\n filterGroups.push({\n filters: [\n {\n propertyName: modifiedProperty,\n operator: 'GTE',\n value: String(sinceMs),\n },\n ],\n });\n }\n }\n return {\n filterGroups,\n // Ascending modified-time keeps pagination stable while the `since`\n // filter trims the set upstream, so an incremental sync never scans\n // the whole object.\n sorts: [{ propertyName: modifiedProperty, direction: 'ASCENDING' }],\n properties: SEARCH_PROPERTIES[phase],\n limit: SEARCH_LIMIT,\n ...(after ? { after } : {}),\n };\n }\n\n private async fetchSearchPage(\n phase: CrmObjectPhase,\n after: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const body = this.buildSearchBody(phase, after, options);\n const res = await this.apiPost<CrmSearchResponse>(\n `${BASE_URL}/crm/v3/objects/${phase}/search`,\n phase,\n body,\n signal,\n );\n return {\n items: res.body.results,\n next: res.body.paging?.next?.after ?? null,\n };\n }\n\n private async writeSearchPhase(\n storage: StorageHandle,\n phase: CrmObjectPhase,\n items: CrmRecord[],\n ): Promise<void> {\n for (const record of items) {\n const props = record.properties;\n const modifiedProperty = MODIFIED_PROPERTY[phase];\n const updatedAt =\n parseEpoch(record.updatedAt, 'iso') ??\n parseEpoch(props[modifiedProperty], 'ms') ??\n 0;\n\n let attributes: Record<string, string | number | null>;\n if (phase === 'contacts') {\n attributes = {\n email: props.email ?? null,\n lifecycleStage: props.lifecyclestage ?? null,\n leadStatus: props.hs_lead_status ?? null,\n ownerId: props.hubspot_owner_id ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n } else if (phase === 'companies') {\n attributes = {\n name: props.name ?? null,\n domain: props.domain ?? null,\n industry: props.industry ?? null,\n lifecycleStage: props.lifecyclestage ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n } else {\n attributes = {\n dealName: props.dealname ?? null,\n dealStage: props.dealstage ?? null,\n pipeline: props.pipeline ?? null,\n amount: finiteNumberOrNull(props.amount),\n closeDate: parseEpoch(props.closedate, 'ms'),\n ownerId: props.hubspot_owner_id ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n }\n\n await storage.entity({\n type: ENTITY_TYPE_BY_PHASE[phase]!,\n id: record.id,\n attributes,\n updated_at: updatedAt,\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Deal stage-change events (deal property history)\n // -------------------------------------------------------------------------\n\n private async fetchDealHistoryPage(\n after: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${BASE_URL}/crm/v3/objects/deals`);\n url.searchParams.set('limit', String(LIST_LIMIT));\n url.searchParams.set('properties', 'dealstage');\n url.searchParams.set('propertiesWithHistory', 'dealstage');\n if (after) {\n url.searchParams.set('after', after);\n }\n const res = await this.apiGet<CrmListResponse>(\n url.toString(),\n 'deal_events',\n signal,\n );\n return {\n items: res.body.results,\n next: res.body.paging?.next?.after ?? null,\n };\n }\n\n private async writeDealEvents(\n storage: StorageHandle,\n items: DealHistoryRecord[],\n _options: SyncOptions,\n ): Promise<void> {\n for (const record of items) {\n const history = record.propertiesWithHistory?.dealstage ?? [];\n for (const entry of history) {\n const ts = parseEpoch(entry.timestamp, 'iso');\n if (ts === null) {\n continue;\n }\n await storage.event({\n name: DEAL_STAGE_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes: {\n dealId: record.id,\n stage: entry.value ?? null,\n sourceType: entry.sourceType ?? null,\n },\n });\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Marketing email campaigns + stats (legacy email campaigns API)\n // -------------------------------------------------------------------------\n\n private async fetchCampaignDetail(\n id: number | string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<CampaignDetail> {\n const res = await this.apiGet<CampaignDetail>(\n `${BASE_URL}/email/public/v1/campaigns/${id}`,\n resource,\n signal,\n );\n return res.body;\n }\n\n private async fetchCampaignsPage(\n phase: 'email_campaigns' | 'email_stats',\n after: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${BASE_URL}/email/public/v1/campaigns`);\n url.searchParams.set('limit', String(LIST_LIMIT));\n if (after) {\n url.searchParams.set('offset', after);\n }\n const listRes = await this.apiGet<CampaignListResponse>(\n url.toString(),\n `${phase}_list`,\n signal,\n );\n const { campaigns, hasMore, offset } = listRes.body;\n\n const details: CampaignDetail[] = [];\n for (const campaign of campaigns) {\n details.push(await this.fetchCampaignDetail(campaign.id, phase, signal));\n }\n\n const next =\n hasMore && offset !== undefined && offset !== null\n ? String(offset)\n : null;\n return { items: details, next };\n }\n\n private async writeEmailCampaigns(\n storage: StorageHandle,\n items: CampaignDetail[],\n ): Promise<void> {\n for (const detail of items) {\n const sentDate = parseEpoch(detail.lastProcessingFinishedAt, 'ms');\n await storage.entity({\n type: ENTITY_TYPE_BY_PHASE.email_campaigns!,\n id: String(detail.id),\n attributes: {\n name: detail.name ?? null,\n subject: detail.subject ?? null,\n fromName: detail.fromName ?? null,\n type: detail.type ?? null,\n sentDate,\n numIncluded: detail.numIncluded ?? null,\n },\n updated_at: sentDate ?? 0,\n });\n }\n }\n\n private async writeEmailStats(\n storage: StorageHandle,\n items: CampaignDetail[],\n ): Promise<void> {\n for (const detail of items) {\n const ts = parseEpoch(detail.lastProcessingFinishedAt, 'ms');\n if (ts === null) {\n continue;\n }\n const counters = detail.counters ?? {};\n const sent = counterValue(counters.sent);\n await storage.metric({\n name: EMAIL_STATS_METRIC,\n ts,\n value: sent,\n attributes: {\n campaignId: String(detail.id),\n campaignName: detail.name ?? null,\n sent,\n delivered: counterValue(counters.delivered),\n opened: counterValue(counters.open),\n clicked: counterValue(counters.click),\n bounced: counterValue(counters.bounce),\n unsubscribed: counterValue(counters.unsubscribed),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Scope clearing (idempotency)\n // -------------------------------------------------------------------------\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: HubSpotPhase,\n isFull: boolean,\n ): Promise<void> {\n if (phase === 'deal_events') {\n // Events never upsert and the list endpoint has no `since` filter, so\n // every sync rewrites the requested window — clear in both modes.\n await storage.events([], { names: [DEAL_STAGE_EVENT] });\n return;\n }\n if (phase === 'email_stats') {\n await storage.metrics([], { names: [EMAIL_STATS_METRIC] });\n return;\n }\n // Entity phases upsert by id, so only a full backfill needs to drop stale\n // rows; incremental ticks just overwrite the records they touch.\n if (!isFull) {\n return;\n }\n const entityType = ENTITY_TYPE_BY_PHASE[phase];\n if (entityType) {\n await storage.entities([], { types: [entityType] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: HubSpotPhase,\n items: unknown[],\n options: SyncOptions,\n ): Promise<void> {\n switch (phase) {\n case 'contacts':\n case 'companies':\n case 'deals':\n await this.writeSearchPhase(storage, phase, items as CrmRecord[]);\n return;\n case 'deal_events':\n await this.writeDealEvents(\n storage,\n items as DealHistoryRecord[],\n options,\n );\n return;\n case 'email_campaigns':\n await this.writeEmailCampaigns(storage, items as CampaignDetail[]);\n return;\n case 'email_stats':\n await this.writeEmailStats(storage, items as CampaignDetail[]);\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isHubSpotSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<HubSpotResource, HubSpotPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<HubSpotPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (\n phase === 'contacts' ||\n phase === 'companies' ||\n phase === 'deals'\n ) {\n return this.fetchSearchPage(phase, page, options, sig);\n }\n if (phase === 'deal_events') {\n return this.fetchDealHistoryPage(page, sig);\n }\n return this.fetchCampaignsPage(phase, page, sig);\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items, options);\n },\n });\n }\n\n // -------------------------------------------------------------------------\n // Aggregates — count via the CRM Search API `total` (one request)\n // -------------------------------------------------------------------------\n\n override async aggregate(\n req: AggregateRequest,\n signal?: AbortSignal,\n ): Promise<AggregateValue> {\n if (req.fn !== 'count') {\n throw unsupportedAggregate(req);\n }\n const object = COUNT_RESOURCE_TO_OBJECT[req.resource];\n if (!object) {\n throw unsupportedAggregate(req);\n }\n const filterGroups = this.translateCountFilter(req.filter);\n const res = await this.apiPost<CrmSearchResponse>(\n `${BASE_URL}/crm/v3/objects/${object}/search`,\n object,\n { filterGroups, properties: [], limit: 1 },\n signal,\n );\n const value = res.body.total ?? 0;\n this.logger.info('aggregate', {\n fn: 'count',\n resource: req.resource,\n filter: req.filter,\n value,\n via: 'CRM search API',\n });\n return value;\n }\n\n validateCountFilter(resource: string, filter: FilterClause[]): void {\n if (!COUNT_RESOURCE_TO_OBJECT[resource]) {\n throw new Error(\n `HubSpot aggregate count: unsupported resource=${resource}`,\n );\n }\n this.translateCountFilter(filter);\n }\n\n // Translates flat AND filter conditions into HubSpot search `filterGroups`.\n // OR clauses aren't expressible alongside the rest of the group model, so\n // they throw \"unsupported\" and the runner falls back to storage rows.\n private translateCountFilter(\n filter: FilterClause[] | undefined,\n ): Array<{ filters: unknown[] }> {\n if (!filter || filter.length === 0) {\n return [];\n }\n const filters = filter.map((clause) => {\n if ('or' in clause) {\n throw new Error(\n 'HubSpot aggregate count: OR filter clauses are not supported',\n );\n }\n const operator = FILTER_OP_TO_HUBSPOT[clause.op];\n if (!operator) {\n throw new Error(\n `HubSpot aggregate count: unsupported filter operator ${clause.op}`,\n );\n }\n return {\n propertyName: clause.field,\n operator,\n value: String(clause.value),\n };\n });\n return [{ filters }];\n }\n}\n","import { HubSpotConnector } from './hubspot';\n\nexport { configFields, HubSpotConnector } from './hubspot';\nexport type { HubSpotSettings, HubSpotResource } from './hubspot';\nexport default HubSpotConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AIJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB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,wDAAwD,OAAO,EAAE;AAAA,QACnE;AAAA,MACF;AACA,aAAO;AAAA,QACL,cAAc,OAAO;AAAA,QACrB;AAAA,QACA,OAAO,OAAO,OAAO,KAAK;AAAA,MAC5B;AAAA,IACF,CAAC;AACD,WAAO,CAAC,EAAE,QAAQ,CAAC;AAAA,EACrB;AACF;;;AChzBA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/hubspot.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n accessToken: z.object({ $secret: z.string() }).meta({\n label: 'Private App access token',\n description:\n 'HubSpot private app access token with read scopes for contacts, companies, deals, and marketing email. Create one at Settings → Integrations → Private Apps.',\n placeholder: 'pat-na1-...',\n secret: true,\n }),\n resources: z\n .array(\n z.enum([\n 'contacts',\n 'companies',\n 'deals',\n 'deal_events',\n 'email_campaigns',\n 'email_stats',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which HubSpot resources to sync. Omit to sync all resources. The access token only needs read scopes for the resources listed here.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'HubSpot',\n category: 'sales',\n brandColor: '#FF7A59',\n tagline:\n 'Sync CRM contacts, companies, and deals plus deal stage-change events and marketing email campaign stats from HubSpot.',\n vendor: {\n name: 'HubSpot',\n apiDocs: 'https://developers.hubspot.com/docs/api/overview',\n website: 'https://www.hubspot.com',\n },\n auth: {\n summary:\n 'A HubSpot private app access token with read scopes for the resources you sync (contacts, companies, deals, and marketing email).',\n setup: [\n 'In HubSpot, go to Settings → Integrations → Private Apps and create a private app.',\n 'Grant read scopes for the resources you intend to sync (CRM contacts, companies, deals, and marketing email).',\n 'Copy the generated access token (starts with `pat-`).',\n 'Store it as a secret and reference it from the connector config as `accessToken: secret(\"HUBSPOT_ACCESS_TOKEN\")`.',\n ],\n },\n rateLimit:\n 'HubSpot allows 100 requests / 10s; the Search API caps results at 10,000 per query.',\n limitations: [\n 'Deal stage-change events are rewritten on every sync because the deal list endpoint has no incremental `since` filter.',\n 'Marketing email campaign data comes from the legacy email campaigns API and is only available for marketing emails.',\n 'Very large CRM portfolios may not backfill in full because the Search API caps at 10,000 results per query.',\n ],\n});\n\nexport interface HubSpotSettings {\n resources?: readonly HubSpotResource[];\n}\n\n// ---------------------------------------------------------------------------\n// HubSpot API types\n// ---------------------------------------------------------------------------\n\ntype HubSpotProperties = Record<string, string | null | undefined>;\n\ninterface CrmRecord {\n id: string;\n properties: HubSpotProperties;\n createdAt: string;\n updatedAt: string;\n archived?: boolean;\n}\n\ninterface CrmSearchResponse {\n total?: number;\n results: CrmRecord[];\n paging?: { next?: { after?: string } };\n}\n\ninterface CrmListResponse {\n results: DealHistoryRecord[];\n paging?: { next?: { after?: string } };\n}\n\ninterface DealHistoryEntry {\n value?: string | null;\n timestamp?: string | null;\n sourceType?: string | null;\n}\n\ninterface DealHistoryRecord {\n id: string;\n propertiesWithHistory?: {\n dealstage?: DealHistoryEntry[];\n };\n}\n\ninterface CampaignListResponse {\n campaigns: Array<{ id: number | string }>;\n hasMore?: boolean;\n offset?: number | string;\n}\n\ninterface CampaignCounters {\n sent?: number;\n delivered?: number;\n open?: number;\n click?: number;\n bounce?: number;\n unsubscribed?: number;\n}\n\ninterface CampaignDetail {\n id: number | string;\n name?: string | null;\n subject?: string | null;\n fromName?: string | null;\n type?: string | null;\n lastProcessingFinishedAt?: number | string | null;\n numIncluded?: number | null;\n counters?: CampaignCounters;\n}\n\n// ---------------------------------------------------------------------------\n// Credentials\n// ---------------------------------------------------------------------------\n\nconst hubspotCredentials = {\n accessToken: {\n description: 'HubSpot private app access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype HubSpotCredentials = typeof hubspotCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'contacts',\n 'companies',\n 'deals',\n 'deal_events',\n 'email_campaigns',\n 'email_stats',\n] as const;\n\ntype HubSpotPhase = (typeof PHASE_ORDER)[number];\n\nexport type HubSpotResource = HubSpotPhase;\n\nconst isHubSpotSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst BASE_URL = 'https://api.hubapi.com';\nconst SEARCH_LIMIT = 100;\nconst LIST_LIMIT = 100;\n\ntype CrmObjectPhase = 'contacts' | 'companies' | 'deals';\n\n// CRM object name + property names requested per search phase.\nconst SEARCH_PROPERTIES: Record<CrmObjectPhase, readonly string[]> = {\n contacts: [\n 'email',\n 'lifecyclestage',\n 'hs_lead_status',\n 'createdate',\n 'lastmodifieddate',\n 'hubspot_owner_id',\n ],\n companies: [\n 'name',\n 'domain',\n 'industry',\n 'createdate',\n 'lifecyclestage',\n 'hs_lastmodifieddate',\n ],\n deals: [\n 'dealname',\n 'dealstage',\n 'pipeline',\n 'amount',\n 'closedate',\n 'hubspot_owner_id',\n 'createdate',\n 'hs_lastmodifieddate',\n ],\n};\n\n// Property each CRM object stamps with its last-modified time, used both for\n// the incremental `since` filter and the entity `updated_at` fallback.\nconst MODIFIED_PROPERTY: Record<CrmObjectPhase, string> = {\n contacts: 'lastmodifieddate',\n companies: 'hs_lastmodifieddate',\n deals: 'hs_lastmodifieddate',\n};\n\nconst ENTITY_TYPE_BY_PHASE: Partial<Record<HubSpotPhase, string>> = {\n contacts: 'hubspot_contact',\n companies: 'hubspot_company',\n deals: 'hubspot_deal',\n email_campaigns: 'hubspot_email_campaign',\n};\n\nconst DEAL_STAGE_EVENT = 'hubspot_deal_stage_change';\nconst EMAIL_STATS_METRIC = 'hubspot_email_stats';\n\n// ---------------------------------------------------------------------------\n// Value helpers\n// ---------------------------------------------------------------------------\n\nfunction finiteNumberOrNull(value: string | null | undefined): number | null {\n if (value === null || value === undefined || value.trim() === '') {\n return null;\n }\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction counterValue(value: number | undefined): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst idString = z.string().min(1);\n\nconst contactProperties = z.object({\n email: z.string().nullish(),\n lifecyclestage: z.string().nullish(),\n hs_lead_status: z.string().nullish(),\n createdate: z.string().nullish(),\n lastmodifieddate: z.string().nullish(),\n hubspot_owner_id: z.string().nullish(),\n});\n\nconst companyProperties = z.object({\n name: z.string().nullish(),\n domain: z.string().nullish(),\n industry: z.string().nullish(),\n createdate: z.string().nullish(),\n lifecyclestage: z.string().nullish(),\n hs_lastmodifieddate: z.string().nullish(),\n});\n\nconst dealProperties = z.object({\n dealname: z.string().nullish(),\n dealstage: z.string().nullish(),\n pipeline: z.string().nullish(),\n amount: z.string().nullish(),\n closedate: z.string().nullish(),\n hubspot_owner_id: z.string().nullish(),\n createdate: z.string().nullish(),\n hs_lastmodifieddate: z.string().nullish(),\n});\n\nfunction crmRecordSchema(props: z.ZodType): z.ZodType {\n return z.object({\n id: idString,\n properties: props,\n createdAt: z.string(),\n updatedAt: z.string(),\n archived: z.boolean().optional(),\n });\n}\n\nconst dealHistoryRecordSchema = z.object({\n id: idString,\n propertiesWithHistory: z\n .object({\n dealstage: z\n .array(\n z.object({\n value: z.string().nullish(),\n timestamp: z.string().nullish(),\n sourceType: z.string().nullish(),\n }),\n )\n .optional(),\n })\n .optional(),\n});\n\nconst campaignDetailSchema = z.object({\n id: z.union([z.string(), z.number()]),\n name: z.string().nullish(),\n subject: z.string().nullish(),\n fromName: z.string().nullish(),\n type: z.string().nullish(),\n lastProcessingFinishedAt: z.union([z.string(), z.number()]).nullish(),\n numIncluded: z.number().nullish(),\n counters: z\n .object({\n sent: z.number().optional(),\n delivered: z.number().optional(),\n open: z.number().optional(),\n click: z.number().optional(),\n bounce: z.number().optional(),\n unsubscribed: z.number().optional(),\n })\n .optional(),\n});\n\nconst contactsSchema = z.array(crmRecordSchema(contactProperties));\nconst companiesSchema = z.array(crmRecordSchema(companyProperties));\nconst dealsSchema = z.array(crmRecordSchema(dealProperties));\nconst dealEventsSchema = z.array(dealHistoryRecordSchema);\nconst campaignsSchema = z.array(campaignDetailSchema);\n\nconst hubspotResources = defineResources({\n hubspot_contact: {\n shape: 'entity',\n description:\n 'CRM contacts with email, lifecycle stage, lead status, owner, and creation time.',\n endpoint: 'POST /crm/v3/objects/contacts/search',\n responses: { contacts: contactsSchema },\n },\n hubspot_company: {\n shape: 'entity',\n description:\n 'CRM companies with name, domain, industry, lifecycle stage, and creation time.',\n endpoint: 'POST /crm/v3/objects/companies/search',\n responses: { companies: companiesSchema },\n },\n hubspot_deal: {\n shape: 'entity',\n description:\n 'CRM deals with name, stage, pipeline, amount, close date, owner, and creation time.',\n endpoint: 'POST /crm/v3/objects/deals/search',\n responses: { deals: dealsSchema },\n },\n hubspot_deal_stage_change: {\n shape: 'event',\n description:\n 'Deal stage-change events derived from deal property history, one event per stage transition.',\n endpoint: 'GET /crm/v3/objects/deals?propertiesWithHistory=dealstage',\n responses: { deal_events: dealEventsSchema },\n },\n hubspot_email_campaign: {\n shape: 'entity',\n description:\n 'Marketing email campaigns with name, subject, sender, type, send date, and recipient count.',\n endpoint: 'GET /email/public/v1/campaigns',\n responses: { email_campaigns: campaignsSchema },\n },\n hubspot_email_stats: {\n shape: 'metric',\n description:\n 'Per-campaign marketing email engagement stats (sent, delivered, opened, clicked, bounced, unsubscribed) timestamped at the campaign send time.',\n endpoint: 'GET /email/public/v1/campaigns/{id}',\n unit: 'emails',\n notes:\n 'One sample per campaign; value is the sent count, and every counter (delivered, opened, clicked, bounced, unsubscribed) is also exposed in attributes.',\n dimensions: [\n { name: 'campaignId', description: 'HubSpot campaign id.' },\n { name: 'campaignName', description: 'Campaign name.' },\n { name: 'delivered', description: 'Number of emails delivered.' },\n { name: 'opened', description: 'Number of emails opened.' },\n { name: 'clicked', description: 'Number of emails clicked.' },\n { name: 'bounced', description: 'Number of emails bounced.' },\n {\n name: 'unsubscribed',\n description: 'Number of recipients who unsubscribed.',\n },\n ],\n responses: { email_stats: campaignsSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// HubSpotConnector\n// ---------------------------------------------------------------------------\n\nexport class HubSpotConnector extends BaseConnector<\n HubSpotSettings,\n HubSpotCredentials\n> {\n static readonly id = 'hubspot';\n\n static readonly resources = hubspotResources;\n\n static readonly schemas = schemasFromResources(hubspotResources);\n\n static create(input: unknown, ctx?: ConnectorContext): HubSpotConnector {\n const parsed = configFields.parse(input);\n return new HubSpotConnector(\n { resources: parsed.resources },\n { accessToken: parsed.accessToken },\n ctx,\n );\n }\n\n readonly id = 'hubspot';\n override readonly credentials = hubspotCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.accessToken}`,\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('hubspot'),\n };\n }\n\n private apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n private apiPost<T>(\n url: string,\n resource: string,\n body: unknown,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: this.buildHeaders(),\n body: JSON.stringify(body),\n signal,\n });\n }\n\n // -------------------------------------------------------------------------\n // CRM search phases (contacts / companies / deals)\n // -------------------------------------------------------------------------\n\n private buildSearchBody(\n phase: CrmObjectPhase,\n after: string | null,\n options: SyncOptions,\n ): Record<string, unknown> {\n const modifiedProperty = MODIFIED_PROPERTY[phase];\n const filterGroups: unknown[] = [];\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs)) {\n filterGroups.push({\n filters: [\n {\n propertyName: modifiedProperty,\n operator: 'GTE',\n value: String(sinceMs),\n },\n ],\n });\n }\n }\n return {\n filterGroups,\n // Ascending modified-time keeps pagination stable while the `since`\n // filter trims the set upstream, so an incremental sync never scans\n // the whole object.\n sorts: [{ propertyName: modifiedProperty, direction: 'ASCENDING' }],\n properties: SEARCH_PROPERTIES[phase],\n limit: SEARCH_LIMIT,\n ...(after ? { after } : {}),\n };\n }\n\n private async fetchSearchPage(\n phase: CrmObjectPhase,\n after: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const body = this.buildSearchBody(phase, after, options);\n const res = await this.apiPost<CrmSearchResponse>(\n `${BASE_URL}/crm/v3/objects/${phase}/search`,\n phase,\n body,\n signal,\n );\n return {\n items: res.body.results,\n next: res.body.paging?.next?.after ?? null,\n };\n }\n\n private async writeSearchPhase(\n storage: StorageHandle,\n phase: CrmObjectPhase,\n items: CrmRecord[],\n ): Promise<void> {\n for (const record of items) {\n const props = record.properties;\n const modifiedProperty = MODIFIED_PROPERTY[phase];\n const updatedAt =\n parseEpoch(record.updatedAt, 'iso') ??\n parseEpoch(props[modifiedProperty], 'ms') ??\n 0;\n\n let attributes: Record<string, string | number | null>;\n if (phase === 'contacts') {\n attributes = {\n email: props.email ?? null,\n lifecycleStage: props.lifecyclestage ?? null,\n leadStatus: props.hs_lead_status ?? null,\n ownerId: props.hubspot_owner_id ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n } else if (phase === 'companies') {\n attributes = {\n name: props.name ?? null,\n domain: props.domain ?? null,\n industry: props.industry ?? null,\n lifecycleStage: props.lifecyclestage ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n } else {\n attributes = {\n dealName: props.dealname ?? null,\n dealStage: props.dealstage ?? null,\n pipeline: props.pipeline ?? null,\n amount: finiteNumberOrNull(props.amount),\n closeDate: parseEpoch(props.closedate, 'ms'),\n ownerId: props.hubspot_owner_id ?? null,\n createdAt: parseEpoch(props.createdate, 'ms'),\n };\n }\n\n await storage.entity({\n type: ENTITY_TYPE_BY_PHASE[phase]!,\n id: record.id,\n attributes,\n updated_at: updatedAt,\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Deal stage-change events (deal property history)\n // -------------------------------------------------------------------------\n\n private async fetchDealHistoryPage(\n after: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${BASE_URL}/crm/v3/objects/deals`);\n url.searchParams.set('limit', String(LIST_LIMIT));\n url.searchParams.set('properties', 'dealstage');\n url.searchParams.set('propertiesWithHistory', 'dealstage');\n if (after) {\n url.searchParams.set('after', after);\n }\n const res = await this.apiGet<CrmListResponse>(\n url.toString(),\n 'deal_events',\n signal,\n );\n return {\n items: res.body.results,\n next: res.body.paging?.next?.after ?? null,\n };\n }\n\n private async writeDealEvents(\n storage: StorageHandle,\n items: DealHistoryRecord[],\n _options: SyncOptions,\n ): Promise<void> {\n for (const record of items) {\n const history = record.propertiesWithHistory?.dealstage ?? [];\n for (const entry of history) {\n const ts = parseEpoch(entry.timestamp, 'iso');\n if (ts === null) {\n continue;\n }\n await storage.event({\n name: DEAL_STAGE_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes: {\n dealId: record.id,\n stage: entry.value ?? null,\n sourceType: entry.sourceType ?? null,\n },\n });\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Marketing email campaigns + stats (legacy email campaigns API)\n // -------------------------------------------------------------------------\n\n private async fetchCampaignDetail(\n id: number | string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<CampaignDetail> {\n const res = await this.apiGet<CampaignDetail>(\n `${BASE_URL}/email/public/v1/campaigns/${id}`,\n resource,\n signal,\n );\n return res.body;\n }\n\n private async fetchCampaignsPage(\n phase: 'email_campaigns' | 'email_stats',\n after: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const url = new URL(`${BASE_URL}/email/public/v1/campaigns`);\n url.searchParams.set('limit', String(LIST_LIMIT));\n if (after) {\n url.searchParams.set('offset', after);\n }\n const listRes = await this.apiGet<CampaignListResponse>(\n url.toString(),\n `${phase}_list`,\n signal,\n );\n const { campaigns, hasMore, offset } = listRes.body;\n\n const details: CampaignDetail[] = [];\n for (const campaign of campaigns) {\n details.push(await this.fetchCampaignDetail(campaign.id, phase, signal));\n }\n\n const next =\n hasMore && offset !== undefined && offset !== null\n ? String(offset)\n : null;\n return { items: details, next };\n }\n\n private async writeEmailCampaigns(\n storage: StorageHandle,\n items: CampaignDetail[],\n ): Promise<void> {\n for (const detail of items) {\n const sentDate = parseEpoch(detail.lastProcessingFinishedAt, 'ms');\n await storage.entity({\n type: ENTITY_TYPE_BY_PHASE.email_campaigns!,\n id: String(detail.id),\n attributes: {\n name: detail.name ?? null,\n subject: detail.subject ?? null,\n fromName: detail.fromName ?? null,\n type: detail.type ?? null,\n sentDate,\n numIncluded: detail.numIncluded ?? null,\n },\n updated_at: sentDate ?? 0,\n });\n }\n }\n\n private async writeEmailStats(\n storage: StorageHandle,\n items: CampaignDetail[],\n ): Promise<void> {\n for (const detail of items) {\n const ts = parseEpoch(detail.lastProcessingFinishedAt, 'ms');\n if (ts === null) {\n continue;\n }\n const counters = detail.counters ?? {};\n const sent = counterValue(counters.sent);\n await storage.metric({\n name: EMAIL_STATS_METRIC,\n ts,\n value: sent,\n attributes: {\n campaignId: String(detail.id),\n campaignName: detail.name ?? null,\n sent,\n delivered: counterValue(counters.delivered),\n opened: counterValue(counters.open),\n clicked: counterValue(counters.click),\n bounced: counterValue(counters.bounce),\n unsubscribed: counterValue(counters.unsubscribed),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Scope clearing (idempotency)\n // -------------------------------------------------------------------------\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: HubSpotPhase,\n isFull: boolean,\n ): Promise<void> {\n if (phase === 'deal_events') {\n // Events never upsert and the list endpoint has no `since` filter, so\n // every sync rewrites the requested window — clear in both modes.\n await storage.events([], { names: [DEAL_STAGE_EVENT] });\n return;\n }\n if (phase === 'email_stats') {\n await storage.metrics([], { names: [EMAIL_STATS_METRIC] });\n return;\n }\n // Entity phases upsert by id, so only a full backfill needs to drop stale\n // rows; incremental ticks just overwrite the records they touch.\n if (!isFull) {\n return;\n }\n const entityType = ENTITY_TYPE_BY_PHASE[phase];\n if (entityType) {\n await storage.entities([], { types: [entityType] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: HubSpotPhase,\n items: unknown[],\n options: SyncOptions,\n ): Promise<void> {\n switch (phase) {\n case 'contacts':\n case 'companies':\n case 'deals':\n await this.writeSearchPhase(storage, phase, items as CrmRecord[]);\n return;\n case 'deal_events':\n await this.writeDealEvents(\n storage,\n items as DealHistoryRecord[],\n options,\n );\n return;\n case 'email_campaigns':\n await this.writeEmailCampaigns(storage, items as CampaignDetail[]);\n return;\n case 'email_stats':\n await this.writeEmailStats(storage, items as CampaignDetail[]);\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isHubSpotSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<HubSpotResource, HubSpotPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<HubSpotPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (\n phase === 'contacts' ||\n phase === 'companies' ||\n phase === 'deals'\n ) {\n return this.fetchSearchPage(phase, page, options, sig);\n }\n if (phase === 'deal_events') {\n return this.fetchDealHistoryPage(page, sig);\n }\n return this.fetchCampaignsPage(phase, page, sig);\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items, options);\n },\n });\n }\n}\n","import { HubSpotConnector } from './hubspot';\n\nexport { configFields, doc, HubSpotConnector } from './hubspot';\nexport type { HubSpotSettings, HubSpotResource } from './hubspot';\nexport default HubSpotConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AIJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KAAK,EAAE,QAAQ;AACnC,WAAO,OAAO,SAAS,EAAE,IAAI,KAAK;EACpC;AACA,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;AACpD,WAAO;EACT;AACA,QAAM,IAAI,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AAC1D,MAAI,CAAC,OAAO,SAAS,CAAC,GAAG;AACvB,WAAO;EACT;AACA,QAAM,SAAS,SAAS,MAAM,IAAI,MAAO;AACzC,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;;AGpBA;AAAA,EACE;AAAA,EAOA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAClD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,WAAW,EACR;AAAA,MACC,EAAE,KAAK;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,EACC,SAAS,EACT,SAAS,EACT,KA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AK,gBAAgB,OAAO,MAAM,SAAS,GAAG;AAAA,QACvD;AACA,YAAI,UAAU,eAAe;AAC3B,iBAAO,KAAK,qBAAqB,MAAM,GAAG;AAAA,QAC5C;AACA,eAAO,KAAK,mBAAmB,OAAO,MAAM,GAAG;AAAA,MACjD;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,SAAS,OAAO,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,OAAO,OAAO;AAAA,MACtD;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC7yBA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rawdash/connector-hubspot",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Rawdash connector for HubSpot — CRM contacts, companies, deals, and marketing email performance",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -21,22 +21,22 @@
21
21
  "import": "./dist/index.js"
22
22
  }
23
23
  },
24
- "scripts": {
25
- "build": "tsup",
26
- "typecheck": "tsc --noEmit",
27
- "lint": "eslint src",
28
- "test": "vitest run"
29
- },
30
24
  "dependencies": {
31
- "@rawdash/core": "workspace:*",
32
- "zod": "^4.4.3"
25
+ "zod": "^4.4.3",
26
+ "@rawdash/core": "0.16.0"
33
27
  },
34
28
  "devDependencies": {
35
- "@rawdash/connector-shared": "workspace:*",
36
- "@rawdash/connector-test-utils": "workspace:*",
37
29
  "fast-check": "^4.8.0",
38
30
  "tsup": "^8.0.0",
39
31
  "typescript": "^5.7.2",
40
- "vitest": "^4.1.4"
32
+ "vitest": "^4.1.4",
33
+ "@rawdash/connector-shared": "0.3.0",
34
+ "@rawdash/connector-test-utils": "0.0.3"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "typecheck": "tsc --noEmit",
39
+ "lint": "eslint src",
40
+ "test": "vitest run"
41
41
  }
42
- }
42
+ }