@rawdash/connector-stripe 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,87 +1,80 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
1
3
  # @rawdash/connector-stripe
2
4
 
3
- Rawdash connector for Stripe — syncs customers, subscriptions, invoices, charges, payment intents, products, prices, disputes, and refunds into the six-shape storage model.
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-stripe)](https://www.npmjs.com/package/@rawdash/connector-stripe)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-stripe)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
4
7
 
5
- ## Auth setup
8
+ Sync customers, products, prices, subscriptions, and invoices alongside charge, payment, dispute, and refund events from your Stripe account.
6
9
 
7
- ### Creating a Restricted API key
10
+ ## Install
8
11
 
9
- 1. Log in to your Stripe Dashboard and navigate to **Developers → API keys**.
10
- 2. Click **+ Create restricted key**.
11
- 3. Give it a name (e.g. `rawdash-readonly`).
12
- 4. Enable **Read** access only for the resources you want to sync. The connector supports any subset of:
13
- - Customers
14
- - Subscriptions
15
- - Invoices
16
- - Charges
17
- - Payment Intents
18
- - Products
19
- - Prices
20
- - Disputes
21
- - Refunds
22
- 5. Click **Create key** and copy the key value starting with `rk_live_…` (or `rk_test_…` for test mode).
12
+ ```sh
13
+ npm install @rawdash/connector-stripe
14
+ ```
23
15
 
24
- > **Note:** Never use your full Secret key — a Restricted key with only the scopes above is safer and sufficient.
16
+ ## Authentication
25
17
 
26
- ### Stripe Connect platforms
18
+ Authenticates with a Stripe restricted API key that has read-only access to the resources you want to sync.
27
19
 
28
- If you are a platform and want to sync data for a connected account, supply the `accountId` field (format: `acct_…`). The connector will send the `Stripe-Account` header on every request.
20
+ 1. Open the Stripe Dashboard Developers API keys.
21
+ 2. Create a restricted key with Read access for the resources you plan to sync (customers, products, prices, subscriptions, invoices, charges, payment intents, disputes, refunds).
22
+ 3. Store the key as a secret and reference it from the connector config as `apiKey: secret("STRIPE_API_KEY")`.
29
23
 
30
24
  ## Configuration
31
25
 
26
+ | Field | Type | Required | Description |
27
+ | ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
28
+ | `apiKey` | secret | Yes | Stripe Restricted API key with read-only access. Create one at Dashboard → Developers → API keys. |
29
+ | `accountId` | string | No | Stripe Connect account ID. Only needed if you are a platform accessing a connected account. |
30
+ | `resources` | array | No | Which Stripe resources to sync. Omit to sync all resources. The API key only needs Read scope for the resources listed here. |
31
+
32
+ ## Resources
33
+
34
+ - **`stripe_customer`** _(entity)_ - Customers with email, name, default currency, and delinquency state.
35
+ - Endpoint: `GET /v1/customers`
36
+ - **`stripe_product`** _(entity)_ - Products in your catalog, including active state.
37
+ - Endpoint: `GET /v1/products`
38
+ - **`stripe_price`** _(entity)_ - Prices with unit amount, currency, and recurring interval, linked to their product.
39
+ - Endpoint: `GET /v1/prices`
40
+ - **`stripe_subscription`** _(entity)_ - Subscriptions with status, current period, cancellation state, and computed monthly recurring revenue (mrrAmount, in the smallest currency unit).
41
+ - Endpoint: `GET /v1/subscriptions`
42
+ - mrrAmount is computed as unit_amount x quantity, normalized to a monthly cadence (yearly / 12, weekly x 52 / 12, etc.).
43
+ - **`stripe_invoice`** _(entity)_ - Invoices with amount due, amount paid, status, and due date, linked to their customer and subscription.
44
+ - Endpoint: `GET /v1/invoices`
45
+ - **`stripe_charge`** _(event)_ - Charge attempts with amount, currency, status, and failure code, timestamped at creation.
46
+ - Endpoint: `GET /v1/charges`
47
+ - **`stripe_payment_intent`** _(event)_ - Payment intents with amount, currency, and status, timestamped at creation.
48
+ - Endpoint: `GET /v1/payment_intents`
49
+ - **`stripe_dispute`** _(event)_ - Disputes with amount, currency, reason, and status, linked to the disputed charge.
50
+ - Endpoint: `GET /v1/disputes`
51
+ - **`stripe_refund`** _(event)_ - Refunds with amount, currency, reason, and status, linked to the refunded charge.
52
+ - Endpoint: `GET /v1/refunds`
53
+
54
+ ## Example
55
+
32
56
  ```ts
33
- import { secret } from '@rawdash/core';
57
+ import {
58
+ defineConfig,
59
+ defineDashboard,
60
+ defineMetric,
61
+ secret,
62
+ } from '@rawdash/core';
34
63
 
35
64
  const stripe = {
36
65
  name: 'stripe',
37
66
  connectorId: 'stripe',
38
67
  config: {
39
68
  apiKey: secret('STRIPE_API_KEY'),
40
- // accountId: 'acct_…', // optional, Stripe Connect only
41
- // resources: ['customers', 'subscriptions', 'invoices'], // optional, defaults to all
69
+ resources: ['customers', 'subscriptions', 'invoices', 'charges'],
42
70
  },
43
71
  };
44
- ```
45
-
46
- Register the connector class when mounting the engine:
47
-
48
- ```ts
49
- import { StripeConnector } from '@rawdash/connector-stripe';
50
- import { mountEngine } from '@rawdash/hono';
51
-
52
- mountEngine(config, { connectorRegistry: { stripe: StripeConnector } });
53
- ```
54
-
55
- ### Choosing resources
56
-
57
- By default the connector syncs every supported resource. To sync only a subset, pass `resources` with any combination of:
58
-
59
- `customers`, `products`, `prices`, `subscriptions`, `invoices`, `charges`, `payment_intents`, `disputes`, `refunds`
60
-
61
- Each name is a Stripe API resource. The list you choose should match the Read scopes on your Restricted API key — picking only what you need also reduces API calls during full syncs.
62
-
63
- Then pass it to `defineConfig`:
64
-
65
- ```ts
66
- import { defineConfig, defineDashboard, defineMetric } from '@rawdash/core';
67
72
 
68
73
  export default defineConfig({
69
74
  connectors: [stripe],
70
75
  dashboards: {
71
- billing: defineDashboard({
76
+ revenue: defineDashboard({
72
77
  widgets: {
73
- mrr: {
74
- kind: 'stat',
75
- title: 'MRR',
76
- metric: defineMetric({
77
- connector: stripe,
78
- shape: 'entity',
79
- entityType: 'stripe_subscription',
80
- field: 'mrrAmount',
81
- fn: 'sum',
82
- filter: [{ field: 'status', op: 'eq', value: 'active' }],
83
- }),
84
- },
85
78
  active_subscriptions: {
86
79
  kind: 'stat',
87
80
  title: 'Active subscriptions',
@@ -93,107 +86,28 @@ export default defineConfig({
93
86
  filter: [{ field: 'status', op: 'eq', value: 'active' }],
94
87
  }),
95
88
  },
96
- failed_charges_today: {
97
- kind: 'stat',
98
- title: 'Failed charges today',
99
- metric: defineMetric({
100
- connector: stripe,
101
- shape: 'event',
102
- name: 'stripe_charge',
103
- fn: 'count',
104
- window: '1d',
105
- filter: [{ field: 'status', op: 'eq', value: 'failed' }],
106
- }),
107
- },
108
- daily_revenue: {
109
- kind: 'timeseries',
110
- title: 'Daily revenue',
111
- window: '30d',
112
- metric: defineMetric({
113
- connector: stripe,
114
- shape: 'event',
115
- name: 'stripe_charge',
116
- field: 'amount',
117
- fn: 'sum',
118
- window: '30d',
119
- filter: [{ field: 'status', op: 'eq', value: 'succeeded' }],
120
- groupBy: { field: 'start_ts', granularity: 'day' },
121
- }),
122
- },
123
89
  },
124
90
  }),
125
91
  },
126
92
  });
127
93
  ```
128
94
 
129
- ## Data model
130
-
131
- All monetary amounts are in the **smallest currency unit** (e.g. cents for USD).
95
+ ## Rate limits
132
96
 
133
- | Storage shape | Entity/event type | Key attributes |
134
- | ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
135
- | entity | `stripe_customer` | email, name, created, currency, delinquent, livemode |
136
- | entity | `stripe_product` | name, active, created |
137
- | entity | `stripe_price` | productId, unitAmount, currency, interval, intervalCount, active, created |
138
- | entity | `stripe_subscription` | customerId, status, planId, currentPeriodStart, currentPeriodEnd, cancelAtPeriodEnd, canceledAt, trialEnd, mrrAmount, currency |
139
- | entity | `stripe_invoice` | customerId, subscriptionId, status, amountDue, amountPaid, currency, created, dueDate, hostedInvoiceUrl |
140
- | event | `stripe_charge` | id, customerId, amount, currency, status, failureCode, paymentIntentId |
141
- | event | `stripe_payment_intent` | id, customerId, amount, currency, status |
142
- | event | `stripe_dispute` | id, chargeId, amount, currency, reason, status |
143
- | event | `stripe_refund` | id, chargeId, amount, currency, reason, status |
97
+ Stripe 429 responses carry a Retry-After header; requests are retried with exponential backoff. List pagination uses the starting_after cursor (limit 100).
144
98
 
145
- ### `mrrAmount`
99
+ ## Limitations
146
100
 
147
- Pre-computed monthly-equivalent revenue for each subscription in the smallest currency unit. Formula: `unit_amount × quantity`, normalised to a monthly cadence (yearly ÷ 12, weekly × 52 ÷ 12, etc.).
148
-
149
- ## Schemas
150
-
151
- `StripeConnector.schemas` declares the Zod schema for each resource's raw API response (one key per `GET /v1/{resource}` list endpoint). Used by the cloud shape-drift pipeline to populate `connector_baselines`, and by the package's property tests.
152
-
153
- | Resource | Represents |
154
- | ----------------- | ------------------------------ |
155
- | `customers` | `GET /v1/customers` page |
156
- | `products` | `GET /v1/products` page |
157
- | `prices` | `GET /v1/prices` page |
158
- | `subscriptions` | `GET /v1/subscriptions` page |
159
- | `invoices` | `GET /v1/invoices` page |
160
- | `charges` | `GET /v1/charges` page |
161
- | `payment_intents` | `GET /v1/payment_intents` page |
162
- | `disputes` | `GET /v1/disputes` page |
163
- | `refunds` | `GET /v1/refunds` page |
164
-
165
- ## Sync behaviour
166
-
167
- - **Backfill** (`mode: 'full'`): fetches all records via `starting_after` cursor pagination (`limit=100`).
168
- - **Incremental** (`mode: 'latest'`): entity phases use a 7-day lookback (`created[gte]`) to catch status mutations; event phases use `created[gt]` to fetch only new records.
169
- - **Rate limits**: Stripe's 429 responses carry a `Retry-After` header. The built-in HTTP client retries automatically with exponential back-off.
170
- - **Resumable**: if a sync is interrupted (signal abort), the connector returns a cursor so the engine can resume from the same page.
171
-
172
- ## Registering in the MCP server
173
-
174
- To make the connector available via the `add_connector` MCP tool, include it in `connectorFactories`:
175
-
176
- ```ts
177
- import { StripeConnector, configFields } from '@rawdash/connector-stripe';
178
-
179
- createMcpServer({
180
- // ...
181
- connectorFactories: [
182
- {
183
- id: 'stripe',
184
- configFields,
185
- create: StripeConnector.create,
186
- },
187
- ],
188
- });
189
- ```
101
+ - Monetary amounts are stored in the smallest currency unit (e.g. cents), matching the Stripe API.
102
+ - The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.
103
+ - Incremental syncs use a 7-day lookback for entities and created[gt] for events.
190
104
 
191
- ## Property tests
105
+ ## Links
192
106
 
193
- Resources in this connector have fast-check property tests under `src/property.test.ts` that:
107
+ - [Rawdash docs](https://rawdash.dev/docs/connectors/)
108
+ - [Stripe API docs](https://stripe.com/docs/api)
109
+ - [GitHub](https://github.com/rawdash/rawdash)
194
110
 
195
- 1. Generate N≥50 synthetic API payloads from a Zod schema mirroring the upstream API response.
196
- 2. Pipe them through `connector.sync()` against an `InMemoryStorage` instance.
197
- 3. Assert universal invariants — non-empty entity ids, finite event timestamps, no `undefined` leaking into storage, no thrown errors on any valid input — plus per-resource counts.
111
+ ## License
198
112
 
199
- The helper lives in `@rawdash/connector-test-utils`. When adding a new resource, add a Zod schema for its payload and a test wired up via `runPropertySyncTest`.
113
+ Apache-2.0
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult } 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<{
@@ -18,6 +18,7 @@ declare const configFields: z.ZodObject<{
18
18
  refunds: "refunds";
19
19
  }>>>;
20
20
  }, z.core.$strip>;
21
+ declare const doc: ConnectorDoc;
21
22
  interface StripeSettings {
22
23
  accountId?: string;
23
24
  resources?: readonly StripeResource[];
@@ -65,8 +66,369 @@ declare const PHASE_ORDER: readonly ["customers", "products", "prices", "subscri
65
66
  type StripePhase = (typeof PHASE_ORDER)[number];
66
67
  type StripeResource = StripePhase;
67
68
  declare function computeMrrAmountCents(subscription: StripeSubscription): number | null;
69
+ declare const stripeResources: {
70
+ readonly stripe_customer: {
71
+ readonly shape: "entity";
72
+ readonly description: "Customers with email, name, default currency, and delinquency state.";
73
+ readonly endpoint: "GET /v1/customers";
74
+ readonly responses: {
75
+ readonly customers: z.ZodArray<z.ZodObject<{
76
+ id: z.ZodString;
77
+ email: z.ZodNullable<z.ZodString>;
78
+ name: z.ZodNullable<z.ZodString>;
79
+ created: z.ZodNumber;
80
+ currency: z.ZodNullable<z.ZodString>;
81
+ delinquent: z.ZodNullable<z.ZodBoolean>;
82
+ livemode: z.ZodBoolean;
83
+ }, z.core.$strip>>;
84
+ };
85
+ };
86
+ readonly stripe_product: {
87
+ readonly shape: "entity";
88
+ readonly description: "Products in your catalog, including active state.";
89
+ readonly endpoint: "GET /v1/products";
90
+ readonly responses: {
91
+ readonly products: z.ZodArray<z.ZodObject<{
92
+ id: z.ZodString;
93
+ name: z.ZodString;
94
+ active: z.ZodBoolean;
95
+ created: z.ZodNumber;
96
+ }, z.core.$strip>>;
97
+ };
98
+ };
99
+ readonly stripe_price: {
100
+ readonly shape: "entity";
101
+ readonly description: "Prices with unit amount, currency, and recurring interval, linked to their product.";
102
+ readonly endpoint: "GET /v1/prices";
103
+ readonly responses: {
104
+ readonly prices: z.ZodArray<z.ZodObject<{
105
+ id: z.ZodString;
106
+ product: z.ZodString;
107
+ unit_amount: z.ZodNullable<z.ZodNumber>;
108
+ currency: z.ZodString;
109
+ recurring: z.ZodNullable<z.ZodObject<{
110
+ interval: z.ZodEnum<{
111
+ day: "day";
112
+ week: "week";
113
+ month: "month";
114
+ year: "year";
115
+ }>;
116
+ interval_count: z.ZodNumber;
117
+ }, z.core.$strip>>;
118
+ active: z.ZodBoolean;
119
+ created: z.ZodNumber;
120
+ }, z.core.$strip>>;
121
+ };
122
+ };
123
+ readonly stripe_subscription: {
124
+ readonly shape: "entity";
125
+ readonly description: "Subscriptions with status, current period, cancellation state, and computed monthly recurring revenue (mrrAmount, in the smallest currency unit).";
126
+ readonly endpoint: "GET /v1/subscriptions";
127
+ readonly notes: "mrrAmount is computed as unit_amount x quantity, normalized to a monthly cadence (yearly / 12, weekly x 52 / 12, etc.).";
128
+ readonly responses: {
129
+ readonly subscriptions: z.ZodArray<z.ZodObject<{
130
+ id: z.ZodString;
131
+ customer: z.ZodString;
132
+ status: z.ZodString;
133
+ items: z.ZodObject<{
134
+ data: z.ZodArray<z.ZodObject<{
135
+ price: z.ZodObject<{
136
+ id: z.ZodString;
137
+ product: z.ZodString;
138
+ unit_amount: z.ZodNullable<z.ZodNumber>;
139
+ currency: z.ZodString;
140
+ recurring: z.ZodNullable<z.ZodObject<{
141
+ interval: z.ZodEnum<{
142
+ day: "day";
143
+ week: "week";
144
+ month: "month";
145
+ year: "year";
146
+ }>;
147
+ interval_count: z.ZodNumber;
148
+ }, z.core.$strip>>;
149
+ active: z.ZodBoolean;
150
+ created: z.ZodNumber;
151
+ }, z.core.$strip>;
152
+ quantity: z.ZodNullable<z.ZodNumber>;
153
+ }, z.core.$strip>>;
154
+ }, z.core.$strip>;
155
+ current_period_start: z.ZodNumber;
156
+ current_period_end: z.ZodNumber;
157
+ cancel_at_period_end: z.ZodBoolean;
158
+ canceled_at: z.ZodNullable<z.ZodNumber>;
159
+ trial_end: z.ZodNullable<z.ZodNumber>;
160
+ currency: z.ZodString;
161
+ created: z.ZodNumber;
162
+ }, z.core.$strip>>;
163
+ };
164
+ };
165
+ readonly stripe_invoice: {
166
+ readonly shape: "entity";
167
+ readonly description: "Invoices with amount due, amount paid, status, and due date, linked to their customer and subscription.";
168
+ readonly endpoint: "GET /v1/invoices";
169
+ readonly responses: {
170
+ readonly invoices: z.ZodArray<z.ZodObject<{
171
+ id: z.ZodString;
172
+ customer: z.ZodNullable<z.ZodString>;
173
+ subscription: z.ZodNullable<z.ZodString>;
174
+ status: z.ZodNullable<z.ZodString>;
175
+ amount_due: z.ZodNumber;
176
+ amount_paid: z.ZodNumber;
177
+ currency: z.ZodString;
178
+ created: z.ZodNumber;
179
+ due_date: z.ZodNullable<z.ZodNumber>;
180
+ hosted_invoice_url: z.ZodNullable<z.ZodString>;
181
+ }, z.core.$strip>>;
182
+ };
183
+ };
184
+ readonly stripe_charge: {
185
+ readonly shape: "event";
186
+ readonly description: "Charge attempts with amount, currency, status, and failure code, timestamped at creation.";
187
+ readonly endpoint: "GET /v1/charges";
188
+ readonly responses: {
189
+ readonly charges: z.ZodArray<z.ZodObject<{
190
+ id: z.ZodString;
191
+ customer: z.ZodNullable<z.ZodString>;
192
+ amount: z.ZodNumber;
193
+ currency: z.ZodString;
194
+ status: z.ZodString;
195
+ failure_code: z.ZodNullable<z.ZodString>;
196
+ created: z.ZodNumber;
197
+ payment_intent: z.ZodNullable<z.ZodString>;
198
+ }, z.core.$strip>>;
199
+ };
200
+ };
201
+ readonly stripe_payment_intent: {
202
+ readonly shape: "event";
203
+ readonly description: "Payment intents with amount, currency, and status, timestamped at creation.";
204
+ readonly endpoint: "GET /v1/payment_intents";
205
+ readonly responses: {
206
+ readonly payment_intents: z.ZodArray<z.ZodObject<{
207
+ id: z.ZodString;
208
+ customer: z.ZodNullable<z.ZodString>;
209
+ amount: z.ZodNumber;
210
+ currency: z.ZodString;
211
+ status: z.ZodString;
212
+ created: z.ZodNumber;
213
+ }, z.core.$strip>>;
214
+ };
215
+ };
216
+ readonly stripe_dispute: {
217
+ readonly shape: "event";
218
+ readonly description: "Disputes with amount, currency, reason, and status, linked to the disputed charge.";
219
+ readonly endpoint: "GET /v1/disputes";
220
+ readonly responses: {
221
+ readonly disputes: z.ZodArray<z.ZodObject<{
222
+ id: z.ZodString;
223
+ charge: z.ZodString;
224
+ amount: z.ZodNumber;
225
+ currency: z.ZodString;
226
+ reason: z.ZodString;
227
+ status: z.ZodString;
228
+ created: z.ZodNumber;
229
+ }, z.core.$strip>>;
230
+ };
231
+ };
232
+ readonly stripe_refund: {
233
+ readonly shape: "event";
234
+ readonly description: "Refunds with amount, currency, reason, and status, linked to the refunded charge.";
235
+ readonly endpoint: "GET /v1/refunds";
236
+ readonly responses: {
237
+ readonly refunds: z.ZodArray<z.ZodObject<{
238
+ id: z.ZodString;
239
+ charge: z.ZodNullable<z.ZodString>;
240
+ amount: z.ZodNumber;
241
+ currency: z.ZodString;
242
+ reason: z.ZodNullable<z.ZodString>;
243
+ status: z.ZodNullable<z.ZodString>;
244
+ created: z.ZodNumber;
245
+ }, z.core.$strip>>;
246
+ };
247
+ };
248
+ };
249
+ declare const id = "stripe";
68
250
  declare class StripeConnector extends BaseConnector<StripeSettings, StripeCredentials> {
69
251
  static readonly id = "stripe";
252
+ static readonly resources: {
253
+ readonly stripe_customer: {
254
+ readonly shape: "entity";
255
+ readonly description: "Customers with email, name, default currency, and delinquency state.";
256
+ readonly endpoint: "GET /v1/customers";
257
+ readonly responses: {
258
+ readonly customers: z.ZodArray<z.ZodObject<{
259
+ id: z.ZodString;
260
+ email: z.ZodNullable<z.ZodString>;
261
+ name: z.ZodNullable<z.ZodString>;
262
+ created: z.ZodNumber;
263
+ currency: z.ZodNullable<z.ZodString>;
264
+ delinquent: z.ZodNullable<z.ZodBoolean>;
265
+ livemode: z.ZodBoolean;
266
+ }, z.core.$strip>>;
267
+ };
268
+ };
269
+ readonly stripe_product: {
270
+ readonly shape: "entity";
271
+ readonly description: "Products in your catalog, including active state.";
272
+ readonly endpoint: "GET /v1/products";
273
+ readonly responses: {
274
+ readonly products: z.ZodArray<z.ZodObject<{
275
+ id: z.ZodString;
276
+ name: z.ZodString;
277
+ active: z.ZodBoolean;
278
+ created: z.ZodNumber;
279
+ }, z.core.$strip>>;
280
+ };
281
+ };
282
+ readonly stripe_price: {
283
+ readonly shape: "entity";
284
+ readonly description: "Prices with unit amount, currency, and recurring interval, linked to their product.";
285
+ readonly endpoint: "GET /v1/prices";
286
+ readonly responses: {
287
+ readonly prices: z.ZodArray<z.ZodObject<{
288
+ id: z.ZodString;
289
+ product: z.ZodString;
290
+ unit_amount: z.ZodNullable<z.ZodNumber>;
291
+ currency: z.ZodString;
292
+ recurring: z.ZodNullable<z.ZodObject<{
293
+ interval: z.ZodEnum<{
294
+ day: "day";
295
+ week: "week";
296
+ month: "month";
297
+ year: "year";
298
+ }>;
299
+ interval_count: z.ZodNumber;
300
+ }, z.core.$strip>>;
301
+ active: z.ZodBoolean;
302
+ created: z.ZodNumber;
303
+ }, z.core.$strip>>;
304
+ };
305
+ };
306
+ readonly stripe_subscription: {
307
+ readonly shape: "entity";
308
+ readonly description: "Subscriptions with status, current period, cancellation state, and computed monthly recurring revenue (mrrAmount, in the smallest currency unit).";
309
+ readonly endpoint: "GET /v1/subscriptions";
310
+ readonly notes: "mrrAmount is computed as unit_amount x quantity, normalized to a monthly cadence (yearly / 12, weekly x 52 / 12, etc.).";
311
+ readonly responses: {
312
+ readonly subscriptions: z.ZodArray<z.ZodObject<{
313
+ id: z.ZodString;
314
+ customer: z.ZodString;
315
+ status: z.ZodString;
316
+ items: z.ZodObject<{
317
+ data: z.ZodArray<z.ZodObject<{
318
+ price: z.ZodObject<{
319
+ id: z.ZodString;
320
+ product: z.ZodString;
321
+ unit_amount: z.ZodNullable<z.ZodNumber>;
322
+ currency: z.ZodString;
323
+ recurring: z.ZodNullable<z.ZodObject<{
324
+ interval: z.ZodEnum<{
325
+ day: "day";
326
+ week: "week";
327
+ month: "month";
328
+ year: "year";
329
+ }>;
330
+ interval_count: z.ZodNumber;
331
+ }, z.core.$strip>>;
332
+ active: z.ZodBoolean;
333
+ created: z.ZodNumber;
334
+ }, z.core.$strip>;
335
+ quantity: z.ZodNullable<z.ZodNumber>;
336
+ }, z.core.$strip>>;
337
+ }, z.core.$strip>;
338
+ current_period_start: z.ZodNumber;
339
+ current_period_end: z.ZodNumber;
340
+ cancel_at_period_end: z.ZodBoolean;
341
+ canceled_at: z.ZodNullable<z.ZodNumber>;
342
+ trial_end: z.ZodNullable<z.ZodNumber>;
343
+ currency: z.ZodString;
344
+ created: z.ZodNumber;
345
+ }, z.core.$strip>>;
346
+ };
347
+ };
348
+ readonly stripe_invoice: {
349
+ readonly shape: "entity";
350
+ readonly description: "Invoices with amount due, amount paid, status, and due date, linked to their customer and subscription.";
351
+ readonly endpoint: "GET /v1/invoices";
352
+ readonly responses: {
353
+ readonly invoices: z.ZodArray<z.ZodObject<{
354
+ id: z.ZodString;
355
+ customer: z.ZodNullable<z.ZodString>;
356
+ subscription: z.ZodNullable<z.ZodString>;
357
+ status: z.ZodNullable<z.ZodString>;
358
+ amount_due: z.ZodNumber;
359
+ amount_paid: z.ZodNumber;
360
+ currency: z.ZodString;
361
+ created: z.ZodNumber;
362
+ due_date: z.ZodNullable<z.ZodNumber>;
363
+ hosted_invoice_url: z.ZodNullable<z.ZodString>;
364
+ }, z.core.$strip>>;
365
+ };
366
+ };
367
+ readonly stripe_charge: {
368
+ readonly shape: "event";
369
+ readonly description: "Charge attempts with amount, currency, status, and failure code, timestamped at creation.";
370
+ readonly endpoint: "GET /v1/charges";
371
+ readonly responses: {
372
+ readonly charges: z.ZodArray<z.ZodObject<{
373
+ id: z.ZodString;
374
+ customer: z.ZodNullable<z.ZodString>;
375
+ amount: z.ZodNumber;
376
+ currency: z.ZodString;
377
+ status: z.ZodString;
378
+ failure_code: z.ZodNullable<z.ZodString>;
379
+ created: z.ZodNumber;
380
+ payment_intent: z.ZodNullable<z.ZodString>;
381
+ }, z.core.$strip>>;
382
+ };
383
+ };
384
+ readonly stripe_payment_intent: {
385
+ readonly shape: "event";
386
+ readonly description: "Payment intents with amount, currency, and status, timestamped at creation.";
387
+ readonly endpoint: "GET /v1/payment_intents";
388
+ readonly responses: {
389
+ readonly payment_intents: z.ZodArray<z.ZodObject<{
390
+ id: z.ZodString;
391
+ customer: z.ZodNullable<z.ZodString>;
392
+ amount: z.ZodNumber;
393
+ currency: z.ZodString;
394
+ status: z.ZodString;
395
+ created: z.ZodNumber;
396
+ }, z.core.$strip>>;
397
+ };
398
+ };
399
+ readonly stripe_dispute: {
400
+ readonly shape: "event";
401
+ readonly description: "Disputes with amount, currency, reason, and status, linked to the disputed charge.";
402
+ readonly endpoint: "GET /v1/disputes";
403
+ readonly responses: {
404
+ readonly disputes: z.ZodArray<z.ZodObject<{
405
+ id: z.ZodString;
406
+ charge: z.ZodString;
407
+ amount: z.ZodNumber;
408
+ currency: z.ZodString;
409
+ reason: z.ZodString;
410
+ status: z.ZodString;
411
+ created: z.ZodNumber;
412
+ }, z.core.$strip>>;
413
+ };
414
+ };
415
+ readonly stripe_refund: {
416
+ readonly shape: "event";
417
+ readonly description: "Refunds with amount, currency, reason, and status, linked to the refunded charge.";
418
+ readonly endpoint: "GET /v1/refunds";
419
+ readonly responses: {
420
+ readonly refunds: z.ZodArray<z.ZodObject<{
421
+ id: z.ZodString;
422
+ charge: z.ZodNullable<z.ZodString>;
423
+ amount: z.ZodNumber;
424
+ currency: z.ZodString;
425
+ reason: z.ZodNullable<z.ZodString>;
426
+ status: z.ZodNullable<z.ZodString>;
427
+ created: z.ZodNumber;
428
+ }, z.core.$strip>>;
429
+ };
430
+ };
431
+ };
70
432
  static readonly schemas: {
71
433
  readonly customers: z.ZodArray<z.ZodObject<{
72
434
  id: z.ZodString;
@@ -77,12 +439,14 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
77
439
  delinquent: z.ZodNullable<z.ZodBoolean>;
78
440
  livemode: z.ZodBoolean;
79
441
  }, z.core.$strip>>;
442
+ } & {
80
443
  readonly products: z.ZodArray<z.ZodObject<{
81
444
  id: z.ZodString;
82
445
  name: z.ZodString;
83
446
  active: z.ZodBoolean;
84
447
  created: z.ZodNumber;
85
448
  }, z.core.$strip>>;
449
+ } & {
86
450
  readonly prices: z.ZodArray<z.ZodObject<{
87
451
  id: z.ZodString;
88
452
  product: z.ZodString;
@@ -100,6 +464,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
100
464
  active: z.ZodBoolean;
101
465
  created: z.ZodNumber;
102
466
  }, z.core.$strip>>;
467
+ } & {
103
468
  readonly subscriptions: z.ZodArray<z.ZodObject<{
104
469
  id: z.ZodString;
105
470
  customer: z.ZodString;
@@ -134,6 +499,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
134
499
  currency: z.ZodString;
135
500
  created: z.ZodNumber;
136
501
  }, z.core.$strip>>;
502
+ } & {
137
503
  readonly invoices: z.ZodArray<z.ZodObject<{
138
504
  id: z.ZodString;
139
505
  customer: z.ZodNullable<z.ZodString>;
@@ -146,6 +512,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
146
512
  due_date: z.ZodNullable<z.ZodNumber>;
147
513
  hosted_invoice_url: z.ZodNullable<z.ZodString>;
148
514
  }, z.core.$strip>>;
515
+ } & {
149
516
  readonly charges: z.ZodArray<z.ZodObject<{
150
517
  id: z.ZodString;
151
518
  customer: z.ZodNullable<z.ZodString>;
@@ -156,6 +523,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
156
523
  created: z.ZodNumber;
157
524
  payment_intent: z.ZodNullable<z.ZodString>;
158
525
  }, z.core.$strip>>;
526
+ } & {
159
527
  readonly payment_intents: z.ZodArray<z.ZodObject<{
160
528
  id: z.ZodString;
161
529
  customer: z.ZodNullable<z.ZodString>;
@@ -164,6 +532,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
164
532
  status: z.ZodString;
165
533
  created: z.ZodNumber;
166
534
  }, z.core.$strip>>;
535
+ } & {
167
536
  readonly disputes: z.ZodArray<z.ZodObject<{
168
537
  id: z.ZodString;
169
538
  charge: z.ZodString;
@@ -173,6 +542,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
173
542
  status: z.ZodString;
174
543
  created: z.ZodNumber;
175
544
  }, z.core.$strip>>;
545
+ } & {
176
546
  readonly refunds: z.ZodArray<z.ZodObject<{
177
547
  id: z.ZodString;
178
548
  charge: z.ZodNullable<z.ZodString>;
@@ -182,7 +552,7 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
182
552
  status: z.ZodNullable<z.ZodString>;
183
553
  created: z.ZodNumber;
184
554
  }, z.core.$strip>>;
185
- };
555
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
186
556
  static create(input: unknown, ctx?: ConnectorContext): StripeConnector;
187
557
  readonly id = "stripe";
188
558
  readonly credentials: {
@@ -202,4 +572,4 @@ declare class StripeConnector extends BaseConnector<StripeSettings, StripeCreden
202
572
  sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
203
573
  }
204
574
 
205
- export { StripeConnector, type StripeSettings, computeMrrAmountCents, configFields, StripeConnector as default };
575
+ export { StripeConnector, type StripeSettings, computeMrrAmountCents, configFields, StripeConnector as default, doc, id, stripeResources as resources };
package/dist/index.js CHANGED
@@ -1,8 +1,20 @@
1
+ // ../../connector-shared/dist/index.js
2
+ var HTTP_CLIENT_VERSION = "0.0.0";
3
+ var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
4
+ function connectorUserAgent(connectorId) {
5
+ return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
6
+ }
7
+
1
8
  // src/stripe.ts
2
9
  import {
3
10
  BaseConnector,
4
11
  defineConfigFields,
5
- paginateChunked
12
+ defineConnectorDoc,
13
+ defineResources,
14
+ makeChunkedCursorGuard,
15
+ paginateChunked,
16
+ schemasFromResources,
17
+ selectActivePhases
6
18
  } from "@rawdash/core";
7
19
  import { z } from "zod";
8
20
  var configFields = defineConfigFields(
@@ -36,6 +48,31 @@ var configFields = defineConfigFields(
36
48
  })
37
49
  })
38
50
  );
51
+ var doc = defineConnectorDoc({
52
+ displayName: "Stripe",
53
+ category: "finance",
54
+ brandColor: "#635BFF",
55
+ tagline: "Sync customers, products, prices, subscriptions, and invoices alongside charge, payment, dispute, and refund events from your Stripe account.",
56
+ vendor: {
57
+ name: "Stripe",
58
+ apiDocs: "https://stripe.com/docs/api",
59
+ website: "https://stripe.com"
60
+ },
61
+ auth: {
62
+ summary: "Authenticates with a Stripe restricted API key that has read-only access to the resources you want to sync.",
63
+ setup: [
64
+ "Open the Stripe Dashboard \u2192 Developers \u2192 API keys.",
65
+ "Create a restricted key with Read access for the resources you plan to sync (customers, products, prices, subscriptions, invoices, charges, payment intents, disputes, refunds).",
66
+ 'Store the key as a secret and reference it from the connector config as `apiKey: secret("STRIPE_API_KEY")`.'
67
+ ]
68
+ },
69
+ rateLimit: "Stripe 429 responses carry a Retry-After header; requests are retried with exponential backoff. List pagination uses the starting_after cursor (limit 100).",
70
+ limitations: [
71
+ "Monetary amounts are stored in the smallest currency unit (e.g. cents), matching the Stripe API.",
72
+ "The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.",
73
+ "Incremental syncs use a 7-day lookback for entities and created[gt] for events."
74
+ ]
75
+ });
39
76
  var stripeCredentials = {
40
77
  apiKey: {
41
78
  description: "Stripe API key",
@@ -53,22 +90,7 @@ var PHASE_ORDER = [
53
90
  "disputes",
54
91
  "refunds"
55
92
  ];
56
- function isStripeSyncCursor(value) {
57
- if (typeof value !== "object" || value === null) {
58
- return false;
59
- }
60
- const v = value;
61
- if (typeof v.phase !== "string") {
62
- return false;
63
- }
64
- if (!PHASE_ORDER.includes(v.phase)) {
65
- return false;
66
- }
67
- if (v.page !== null && typeof v.page !== "string") {
68
- return false;
69
- }
70
- return true;
71
- }
93
+ var isStripeSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
72
94
  var ENTITY_TYPE_BY_PHASE = {
73
95
  customers: "stripe_customer",
74
96
  products: "stripe_product",
@@ -217,19 +239,68 @@ var refundSchema = z.object({
217
239
  status: z.string().nullable(),
218
240
  created: z.number().int().nonnegative()
219
241
  });
242
+ var stripeResources = defineResources({
243
+ stripe_customer: {
244
+ shape: "entity",
245
+ description: "Customers with email, name, default currency, and delinquency state.",
246
+ endpoint: "GET /v1/customers",
247
+ responses: { customers: z.array(customerSchema) }
248
+ },
249
+ stripe_product: {
250
+ shape: "entity",
251
+ description: "Products in your catalog, including active state.",
252
+ endpoint: "GET /v1/products",
253
+ responses: { products: z.array(productSchema) }
254
+ },
255
+ stripe_price: {
256
+ shape: "entity",
257
+ description: "Prices with unit amount, currency, and recurring interval, linked to their product.",
258
+ endpoint: "GET /v1/prices",
259
+ responses: { prices: z.array(priceSchema) }
260
+ },
261
+ stripe_subscription: {
262
+ shape: "entity",
263
+ description: "Subscriptions with status, current period, cancellation state, and computed monthly recurring revenue (mrrAmount, in the smallest currency unit).",
264
+ endpoint: "GET /v1/subscriptions",
265
+ notes: "mrrAmount is computed as unit_amount x quantity, normalized to a monthly cadence (yearly / 12, weekly x 52 / 12, etc.).",
266
+ responses: { subscriptions: z.array(subscriptionSchema) }
267
+ },
268
+ stripe_invoice: {
269
+ shape: "entity",
270
+ description: "Invoices with amount due, amount paid, status, and due date, linked to their customer and subscription.",
271
+ endpoint: "GET /v1/invoices",
272
+ responses: { invoices: z.array(invoiceSchema) }
273
+ },
274
+ stripe_charge: {
275
+ shape: "event",
276
+ description: "Charge attempts with amount, currency, status, and failure code, timestamped at creation.",
277
+ endpoint: "GET /v1/charges",
278
+ responses: { charges: z.array(chargeSchema) }
279
+ },
280
+ stripe_payment_intent: {
281
+ shape: "event",
282
+ description: "Payment intents with amount, currency, and status, timestamped at creation.",
283
+ endpoint: "GET /v1/payment_intents",
284
+ responses: { payment_intents: z.array(paymentIntentSchema) }
285
+ },
286
+ stripe_dispute: {
287
+ shape: "event",
288
+ description: "Disputes with amount, currency, reason, and status, linked to the disputed charge.",
289
+ endpoint: "GET /v1/disputes",
290
+ responses: { disputes: z.array(disputeSchema) }
291
+ },
292
+ stripe_refund: {
293
+ shape: "event",
294
+ description: "Refunds with amount, currency, reason, and status, linked to the refunded charge.",
295
+ endpoint: "GET /v1/refunds",
296
+ responses: { refunds: z.array(refundSchema) }
297
+ }
298
+ });
299
+ var id = "stripe";
220
300
  var StripeConnector = class _StripeConnector extends BaseConnector {
221
- static id = "stripe";
222
- static schemas = {
223
- customers: z.array(customerSchema),
224
- products: z.array(productSchema),
225
- prices: z.array(priceSchema),
226
- subscriptions: z.array(subscriptionSchema),
227
- invoices: z.array(invoiceSchema),
228
- charges: z.array(chargeSchema),
229
- payment_intents: z.array(paymentIntentSchema),
230
- disputes: z.array(disputeSchema),
231
- refunds: z.array(refundSchema)
232
- };
301
+ static id = id;
302
+ static resources = stripeResources;
303
+ static schemas = schemasFromResources(stripeResources);
233
304
  static create(input, ctx) {
234
305
  const parsed = configFields.parse(input);
235
306
  return new _StripeConnector(
@@ -238,13 +309,13 @@ var StripeConnector = class _StripeConnector extends BaseConnector {
238
309
  ctx
239
310
  );
240
311
  }
241
- id = "stripe";
312
+ id = id;
242
313
  credentials = stripeCredentials;
243
314
  buildHeaders() {
244
315
  const headers = {
245
316
  Authorization: `Bearer ${this.creds.apiKey}`,
246
317
  "Stripe-Version": "2024-06-20",
247
- "User-Agent": "rawdash/connector-stripe (+https://rawdash.dev)"
318
+ "User-Agent": connectorUserAgent("stripe")
248
319
  };
249
320
  if (this.settings.accountId) {
250
321
  headers["Stripe-Account"] = this.settings.accountId;
@@ -268,17 +339,28 @@ var StripeConnector = class _StripeConnector extends BaseConnector {
268
339
  }
269
340
  return url.toString();
270
341
  }
271
- // created[gte] cutoff for entity phases in incremental mode (7-day lookback)
272
- entityCreatedGte(options) {
273
- if (options.mode !== "latest" || !options.since) {
342
+ // created[gte] cutoff for entity phases in incremental (latest) mode adds
343
+ // a 7-day grace so recent edits to slightly older entities still surface.
344
+ // Subscriptions are intentionally exempt in full mode: a subscription's
345
+ // updated_at is derived from current_period_end, so a still-active sub
346
+ // created well before the cutoff would otherwise be dropped on backfill.
347
+ entityCreatedGte(phase, options) {
348
+ if (!options.since) {
274
349
  return void 0;
275
350
  }
276
351
  const sinceMs = new Date(options.since).getTime();
277
- return String(Math.floor((sinceMs - 7 * 24 * 60 * 60 * 1e3) / 1e3));
352
+ if (options.mode === "latest") {
353
+ return String(Math.floor((sinceMs - 7 * 24 * 60 * 60 * 1e3) / 1e3));
354
+ }
355
+ if (phase === "subscriptions") {
356
+ return void 0;
357
+ }
358
+ return String(Math.floor(sinceMs / 1e3));
278
359
  }
279
- // created[gt] cutoff for event phases in incremental mode
360
+ // created[gt] cutoff for event phases — applied in both full and incremental
361
+ // modes so backfill respects the widget-driven window.
280
362
  eventCreatedGt(options) {
281
- if (options.mode !== "latest" || !options.since) {
363
+ if (!options.since) {
282
364
  return void 0;
283
365
  }
284
366
  return String(Math.floor(new Date(options.since).getTime() / 1e3));
@@ -290,7 +372,7 @@ var StripeConnector = class _StripeConnector extends BaseConnector {
290
372
  return this.buildListUrl(phase, {
291
373
  ...extra,
292
374
  starting_after: startingAfter,
293
- "created[gte]": this.entityCreatedGte(options)
375
+ "created[gte]": this.entityCreatedGte(phase, options)
294
376
  });
295
377
  }
296
378
  return this.buildListUrl(phase, {
@@ -471,12 +553,16 @@ var StripeConnector = class _StripeConnector extends BaseConnector {
471
553
  async sync(options, storage, signal) {
472
554
  const cursor = isStripeSyncCursor(options.cursor) ? options.cursor : void 0;
473
555
  const isFull = options.mode === "full";
474
- const enabled = this.settings.resources;
475
- const phases = enabled && enabled.length > 0 ? PHASE_ORDER.filter((p) => enabled.includes(p)) : PHASE_ORDER;
556
+ const phases = selectActivePhases(
557
+ (r) => r,
558
+ PHASE_ORDER,
559
+ this.settings.resources
560
+ );
476
561
  return paginateChunked({
477
562
  phases,
478
563
  cursor,
479
564
  signal,
565
+ logger: this.logger,
480
566
  fetchPage: async (phase, page, sig) => {
481
567
  const url = this.buildPhaseUrl(phase, page, options);
482
568
  const res = await this.fetch(
@@ -504,6 +590,9 @@ export {
504
590
  StripeConnector,
505
591
  computeMrrAmountCents,
506
592
  configFields,
507
- index_default as default
593
+ index_default as default,
594
+ doc,
595
+ id,
596
+ stripeResources as resources
508
597
  };
509
598
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stripe.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n paginateChunked,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string() }).meta({\n label: 'API Key',\n description:\n 'Stripe Restricted API key with read-only access. Create one at Dashboard → Developers → API keys.',\n placeholder: 'rk_live_...',\n secret: true,\n }),\n accountId: z.string().optional().meta({\n label: 'Account ID (optional)',\n description:\n 'Stripe Connect account ID. Only needed if you are a platform accessing a connected account.',\n placeholder: 'acct_...',\n }),\n resources: z\n .array(\n z.enum([\n 'customers',\n 'products',\n 'prices',\n 'subscriptions',\n 'invoices',\n 'charges',\n 'payment_intents',\n 'disputes',\n 'refunds',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Stripe resources to sync. Omit to sync all resources. The API key only needs Read scope for the resources listed here.',\n }),\n }),\n);\n\nexport interface StripeSettings {\n accountId?: string;\n resources?: readonly StripeResource[];\n}\n\n// ---------------------------------------------------------------------------\n// Stripe API types\n// ---------------------------------------------------------------------------\n\ninterface StripeListResponse<T> {\n object: 'list';\n data: T[];\n has_more: boolean;\n url: string;\n}\n\ninterface StripeCustomer {\n id: string;\n email: string | null;\n name: string | null;\n created: number;\n currency: string | null;\n delinquent: boolean | null;\n livemode: boolean;\n}\n\ninterface StripePriceRecurring {\n interval: 'day' | 'week' | 'month' | 'year';\n interval_count: number;\n}\n\ninterface StripePrice {\n id: string;\n product: string;\n unit_amount: number | null;\n currency: string;\n recurring: StripePriceRecurring | null;\n active: boolean;\n created: number;\n}\n\ninterface StripeSubscriptionItem {\n price: StripePrice;\n quantity: number | null;\n}\n\ninterface StripeSubscription {\n id: string;\n customer: string;\n status: string;\n items: { data: StripeSubscriptionItem[] };\n current_period_start: number;\n current_period_end: number;\n cancel_at_period_end: boolean;\n canceled_at: number | null;\n trial_end: number | null;\n currency: string;\n created: number;\n}\n\ninterface StripeInvoice {\n id: string;\n customer: string | null;\n subscription: string | null;\n status: string | null;\n amount_due: number;\n amount_paid: number;\n currency: string;\n created: number;\n due_date: number | null;\n hosted_invoice_url: string | null;\n}\n\ninterface StripeCharge {\n id: string;\n customer: string | null;\n amount: number;\n currency: string;\n status: string;\n failure_code: string | null;\n created: number;\n payment_intent: string | null;\n}\n\ninterface StripePaymentIntent {\n id: string;\n customer: string | null;\n amount: number;\n currency: string;\n status: string;\n created: number;\n}\n\ninterface StripeProduct {\n id: string;\n name: string;\n active: boolean;\n created: number;\n}\n\ninterface StripeDispute {\n id: string;\n charge: string;\n amount: number;\n currency: string;\n reason: string;\n status: string;\n created: number;\n}\n\ninterface StripeRefund {\n id: string;\n charge: string | null;\n amount: number;\n currency: string;\n reason: string | null;\n status: string | null;\n created: number;\n}\n\n// ---------------------------------------------------------------------------\n// Credentials\n// ---------------------------------------------------------------------------\n\nconst stripeCredentials = {\n apiKey: {\n description: 'Stripe API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype StripeCredentials = typeof stripeCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'customers',\n 'products',\n 'prices',\n 'subscriptions',\n 'invoices',\n 'charges',\n 'payment_intents',\n 'disputes',\n 'refunds',\n] as const;\n\ntype StripePhase = (typeof PHASE_ORDER)[number];\n\nexport type StripeResource = StripePhase;\n\ntype StripeSyncCursor = ChunkedSyncCursor<StripePhase, string>;\n\nfunction isStripeSyncCursor(value: unknown): value is StripeSyncCursor {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const v = value as { phase?: unknown; page?: unknown };\n if (typeof v.phase !== 'string') {\n return false;\n }\n if (!(PHASE_ORDER as readonly string[]).includes(v.phase)) {\n return false;\n }\n if (v.page !== null && typeof v.page !== 'string') {\n return false;\n }\n return true;\n}\n\nconst ENTITY_TYPE_BY_PHASE: Partial<Record<StripePhase, string>> = {\n customers: 'stripe_customer',\n products: 'stripe_product',\n prices: 'stripe_price',\n subscriptions: 'stripe_subscription',\n invoices: 'stripe_invoice',\n};\n\nconst EVENT_NAME_BY_PHASE: Partial<Record<StripePhase, string>> = {\n charges: 'stripe_charge',\n payment_intents: 'stripe_payment_intent',\n disputes: 'stripe_dispute',\n refunds: 'stripe_refund',\n};\n\n// ---------------------------------------------------------------------------\n// MRR helper\n// ---------------------------------------------------------------------------\n\nexport function computeMrrAmountCents(\n subscription: StripeSubscription,\n): number | null {\n let sum = 0;\n let counted = 0;\n for (const item of subscription.items.data) {\n const { unit_amount, recurring } = item.price;\n if (unit_amount === null || unit_amount === undefined || !recurring) {\n continue;\n }\n const quantity = item.quantity ?? 1;\n const total = unit_amount * quantity;\n const intervalCount = recurring.interval_count || 1;\n let monthly: number | null;\n switch (recurring.interval) {\n case 'month':\n monthly = total / intervalCount;\n break;\n case 'year':\n monthly = total / (12 * intervalCount);\n break;\n case 'week':\n monthly = (total * 52) / (12 * intervalCount);\n break;\n case 'day':\n monthly = (total * 365) / (12 * intervalCount);\n break;\n default:\n monthly = null;\n }\n if (monthly === null) {\n continue;\n }\n sum += monthly;\n counted++;\n }\n if (counted === 0) {\n return null;\n }\n return Math.round(sum);\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 customerSchema = z.object({\n id: idString,\n email: z.string().nullable(),\n name: z.string().nullable(),\n created: z.number().int().nonnegative(),\n currency: z.string().nullable(),\n delinquent: z.boolean().nullable(),\n livemode: z.boolean(),\n});\n\nconst productSchema = z.object({\n id: idString,\n name: z.string(),\n active: z.boolean(),\n created: z.number().int().nonnegative(),\n});\n\nconst priceSchema = z.object({\n id: idString,\n product: idString,\n unit_amount: z.number().int().nullable(),\n currency: z.string(),\n recurring: z\n .object({\n interval: z.enum(['day', 'week', 'month', 'year']),\n interval_count: z.number().int().positive(),\n })\n .nullable(),\n active: z.boolean(),\n created: z.number().int().nonnegative(),\n});\n\nconst subscriptionSchema = z.object({\n id: idString,\n customer: idString,\n status: z.string(),\n items: z.object({\n data: z.array(\n z.object({\n price: priceSchema,\n quantity: z.number().int().nullable(),\n }),\n ),\n }),\n current_period_start: z.number().int().nonnegative(),\n current_period_end: z.number().int().nonnegative(),\n cancel_at_period_end: z.boolean(),\n canceled_at: z.number().int().nullable(),\n trial_end: z.number().int().nullable(),\n currency: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst invoiceSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n subscription: idString.nullable(),\n status: z.string().nullable(),\n amount_due: z.number().int(),\n amount_paid: z.number().int(),\n currency: z.string(),\n created: z.number().int().nonnegative(),\n due_date: z.number().int().nullable(),\n hosted_invoice_url: z.string().nullable(),\n});\n\nconst chargeSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n status: z.string(),\n failure_code: z.string().nullable(),\n created: z.number().int().nonnegative(),\n payment_intent: idString.nullable(),\n});\n\nconst paymentIntentSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n status: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst disputeSchema = z.object({\n id: idString,\n charge: idString,\n amount: z.number().int(),\n currency: z.string(),\n reason: z.string(),\n status: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst refundSchema = z.object({\n id: idString,\n charge: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n reason: z.string().nullable(),\n status: z.string().nullable(),\n created: z.number().int().nonnegative(),\n});\n\n// ---------------------------------------------------------------------------\n// StripeConnector\n// ---------------------------------------------------------------------------\n\nexport class StripeConnector extends BaseConnector<\n StripeSettings,\n StripeCredentials\n> {\n static readonly id = 'stripe';\n\n static readonly schemas = {\n customers: z.array(customerSchema),\n products: z.array(productSchema),\n prices: z.array(priceSchema),\n subscriptions: z.array(subscriptionSchema),\n invoices: z.array(invoiceSchema),\n charges: z.array(chargeSchema),\n payment_intents: z.array(paymentIntentSchema),\n disputes: z.array(disputeSchema),\n refunds: z.array(refundSchema),\n } as const;\n\n static create(input: unknown, ctx?: ConnectorContext): StripeConnector {\n const parsed = configFields.parse(input);\n return new StripeConnector(\n { accountId: parsed.accountId, resources: parsed.resources },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = 'stripe';\n override readonly credentials = stripeCredentials;\n\n private buildHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.creds.apiKey}`,\n 'Stripe-Version': '2024-06-20',\n 'User-Agent': 'rawdash/connector-stripe (+https://rawdash.dev)',\n };\n if (this.settings.accountId) {\n headers['Stripe-Account'] = this.settings.accountId;\n }\n return headers;\n }\n\n private fetch<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 buildListUrl(\n path: string,\n params: Record<string, string | undefined>,\n ): string {\n const url = new URL(`https://api.stripe.com/v1/${path}`);\n url.searchParams.set('limit', '100');\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n url.searchParams.set(key, value);\n }\n }\n return url.toString();\n }\n\n // created[gte] cutoff for entity phases in incremental mode (7-day lookback)\n private entityCreatedGte(options: SyncOptions): string | undefined {\n if (options.mode !== 'latest' || !options.since) {\n return undefined;\n }\n const sinceMs = new Date(options.since).getTime();\n return String(Math.floor((sinceMs - 7 * 24 * 60 * 60 * 1000) / 1000));\n }\n\n // created[gt] cutoff for event phases in incremental mode\n private eventCreatedGt(options: SyncOptions): string | undefined {\n if (options.mode !== 'latest' || !options.since) {\n return undefined;\n }\n return String(Math.floor(new Date(options.since).getTime() / 1000));\n }\n\n private buildPhaseUrl(\n phase: StripePhase,\n page: string | null,\n options: SyncOptions,\n ): string {\n const startingAfter = page ?? undefined;\n if (phase in ENTITY_TYPE_BY_PHASE) {\n const extra: Record<string, string | undefined> =\n phase === 'subscriptions' ? { status: 'all' } : {};\n return this.buildListUrl(phase, {\n ...extra,\n starting_after: startingAfter,\n 'created[gte]': this.entityCreatedGte(options),\n });\n }\n return this.buildListUrl(phase, {\n starting_after: startingAfter,\n 'created[gt]': this.eventCreatedGt(options),\n });\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: StripePhase,\n ): Promise<void> {\n const entityType = ENTITY_TYPE_BY_PHASE[phase];\n if (entityType) {\n await storage.entities([], { types: [entityType] });\n return;\n }\n const eventName = EVENT_NAME_BY_PHASE[phase];\n if (eventName) {\n await storage.events([], { names: [eventName] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: StripePhase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'customers':\n for (const c of items as StripeCustomer[]) {\n await storage.entity({\n type: 'stripe_customer',\n id: c.id,\n attributes: {\n email: c.email ?? null,\n name: c.name ?? null,\n created: c.created,\n currency: c.currency ?? null,\n delinquent: c.delinquent ?? false,\n livemode: c.livemode,\n },\n updated_at: c.created * 1000,\n });\n }\n return;\n case 'products':\n for (const p of items as StripeProduct[]) {\n await storage.entity({\n type: 'stripe_product',\n id: p.id,\n attributes: { name: p.name, active: p.active, created: p.created },\n updated_at: p.created * 1000,\n });\n }\n return;\n case 'prices':\n for (const p of items as StripePrice[]) {\n await storage.entity({\n type: 'stripe_price',\n id: p.id,\n attributes: {\n productId: p.product,\n unitAmount: p.unit_amount ?? null,\n currency: p.currency,\n interval: p.recurring?.interval ?? null,\n intervalCount: p.recurring?.interval_count ?? null,\n active: p.active,\n created: p.created,\n },\n updated_at: p.created * 1000,\n });\n }\n return;\n case 'subscriptions':\n for (const s of items as StripeSubscription[]) {\n await storage.entity({\n type: 'stripe_subscription',\n id: s.id,\n attributes: {\n customerId: s.customer,\n status: s.status,\n planId: s.items.data[0]?.price.id ?? null,\n currentPeriodStart: s.current_period_start,\n currentPeriodEnd: s.current_period_end,\n cancelAtPeriodEnd: s.cancel_at_period_end,\n canceledAt: s.canceled_at ?? null,\n trialEnd: s.trial_end ?? null,\n mrrAmount: computeMrrAmountCents(s),\n currency: s.currency,\n created: s.created,\n },\n updated_at: s.current_period_end * 1000,\n });\n }\n return;\n case 'invoices':\n for (const inv of items as StripeInvoice[]) {\n await storage.entity({\n type: 'stripe_invoice',\n id: inv.id,\n attributes: {\n customerId: inv.customer ?? null,\n subscriptionId: inv.subscription ?? null,\n status: inv.status ?? null,\n amountDue: inv.amount_due,\n amountPaid: inv.amount_paid,\n currency: inv.currency,\n created: inv.created,\n dueDate: inv.due_date ?? null,\n hostedInvoiceUrl: inv.hosted_invoice_url ?? null,\n },\n updated_at: inv.created * 1000,\n });\n }\n return;\n case 'charges':\n for (const c of items as StripeCharge[]) {\n await storage.event({\n name: 'stripe_charge',\n start_ts: c.created * 1000,\n end_ts: null,\n attributes: {\n id: c.id,\n customerId: c.customer ?? null,\n amount: c.amount,\n currency: c.currency,\n status: c.status,\n failureCode: c.failure_code ?? null,\n paymentIntentId: c.payment_intent ?? null,\n },\n });\n }\n return;\n case 'payment_intents':\n for (const pi of items as StripePaymentIntent[]) {\n await storage.event({\n name: 'stripe_payment_intent',\n start_ts: pi.created * 1000,\n end_ts: null,\n attributes: {\n id: pi.id,\n customerId: pi.customer ?? null,\n amount: pi.amount,\n currency: pi.currency,\n status: pi.status,\n },\n });\n }\n return;\n case 'disputes':\n for (const d of items as StripeDispute[]) {\n await storage.event({\n name: 'stripe_dispute',\n start_ts: d.created * 1000,\n end_ts: null,\n attributes: {\n id: d.id,\n chargeId: d.charge,\n amount: d.amount,\n currency: d.currency,\n reason: d.reason,\n status: d.status,\n },\n });\n }\n return;\n case 'refunds':\n for (const r of items as StripeRefund[]) {\n await storage.event({\n name: 'stripe_refund',\n start_ts: r.created * 1000,\n end_ts: null,\n attributes: {\n id: r.id,\n chargeId: r.charge ?? null,\n amount: r.amount,\n currency: r.currency,\n reason: r.reason ?? null,\n status: r.status ?? null,\n },\n });\n }\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isStripeSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const enabled = this.settings.resources;\n const phases =\n enabled && enabled.length > 0\n ? PHASE_ORDER.filter((p) => enabled.includes(p))\n : PHASE_ORDER;\n\n return paginateChunked<StripePhase, string>({\n phases,\n cursor,\n signal,\n fetchPage: async (phase, page, sig) => {\n const url = this.buildPhaseUrl(phase, page, options);\n const res = await this.fetch<StripeListResponse<{ id: string }>>(\n url,\n phase,\n sig,\n );\n const { data, has_more } = res.body;\n const next = has_more && data.length > 0 ? data.at(-1)!.id : null;\n return { items: data, next };\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n await this.clearScopeOnFirstPage(storage, phase);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { StripeConnector } from './stripe';\n\nexport { configFields, StripeConnector, computeMrrAmountCents } from './stripe';\nexport type { StripeSettings } from './stripe';\nexport default StripeConnector;\n"],"mappings":";AACA;AAAA,EACE;AAAA,EAOA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAC7C,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK;AAAA,MACpC,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACD,WAAW,EACR;AAAA,MACC,EAAE,KAAK;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,EACC,SAAS,EACT,SAAS,EACT,KAAK;AAAA,MACJ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AAO,gBAAqC;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW,OAAO,OAAO,MAAM,QAAQ;AACrC,cAAM,MAAM,KAAK,cAAc,OAAO,MAAM,OAAO;AACnD,cAAM,MAAM,MAAM,KAAK;AAAA,UACrB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA,cAAM,EAAE,MAAM,SAAS,IAAI,IAAI;AAC/B,cAAM,OAAO,YAAY,KAAK,SAAS,IAAI,KAAK,GAAG,EAAE,EAAG,KAAK;AAC7D,eAAO,EAAE,OAAO,MAAM,KAAK;AAAA,MAC7B;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,UAAU,SAAS,MAAM;AAC3B,gBAAM,KAAK,sBAAsB,SAAS,KAAK;AAAA,QACjD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACltBA,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/stripe.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} 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 apiKey: z.object({ $secret: z.string() }).meta({\n label: 'API Key',\n description:\n 'Stripe Restricted API key with read-only access. Create one at Dashboard → Developers → API keys.',\n placeholder: 'rk_live_...',\n secret: true,\n }),\n accountId: z.string().optional().meta({\n label: 'Account ID (optional)',\n description:\n 'Stripe Connect account ID. Only needed if you are a platform accessing a connected account.',\n placeholder: 'acct_...',\n }),\n resources: z\n .array(\n z.enum([\n 'customers',\n 'products',\n 'prices',\n 'subscriptions',\n 'invoices',\n 'charges',\n 'payment_intents',\n 'disputes',\n 'refunds',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Stripe resources to sync. Omit to sync all resources. The API key only needs Read scope for the resources listed here.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Stripe',\n category: 'finance',\n brandColor: '#635BFF',\n tagline:\n 'Sync customers, products, prices, subscriptions, and invoices alongside charge, payment, dispute, and refund events from your Stripe account.',\n vendor: {\n name: 'Stripe',\n apiDocs: 'https://stripe.com/docs/api',\n website: 'https://stripe.com',\n },\n auth: {\n summary:\n 'Authenticates with a Stripe restricted API key that has read-only access to the resources you want to sync.',\n setup: [\n 'Open the Stripe Dashboard → Developers → API keys.',\n 'Create a restricted key with Read access for the resources you plan to sync (customers, products, prices, subscriptions, invoices, charges, payment intents, disputes, refunds).',\n 'Store the key as a secret and reference it from the connector config as `apiKey: secret(\"STRIPE_API_KEY\")`.',\n ],\n },\n rateLimit:\n 'Stripe 429 responses carry a Retry-After header; requests are retried with exponential backoff. List pagination uses the starting_after cursor (limit 100).',\n limitations: [\n 'Monetary amounts are stored in the smallest currency unit (e.g. cents), matching the Stripe API.',\n 'The set of synced resources is controlled by the `resources` config field; omit it to sync all of them.',\n 'Incremental syncs use a 7-day lookback for entities and created[gt] for events.',\n ],\n});\n\nexport interface StripeSettings {\n accountId?: string;\n resources?: readonly StripeResource[];\n}\n\n// ---------------------------------------------------------------------------\n// Stripe API types\n// ---------------------------------------------------------------------------\n\ninterface StripeListResponse<T> {\n object: 'list';\n data: T[];\n has_more: boolean;\n url: string;\n}\n\ninterface StripeCustomer {\n id: string;\n email: string | null;\n name: string | null;\n created: number;\n currency: string | null;\n delinquent: boolean | null;\n livemode: boolean;\n}\n\ninterface StripePriceRecurring {\n interval: 'day' | 'week' | 'month' | 'year';\n interval_count: number;\n}\n\ninterface StripePrice {\n id: string;\n product: string;\n unit_amount: number | null;\n currency: string;\n recurring: StripePriceRecurring | null;\n active: boolean;\n created: number;\n}\n\ninterface StripeSubscriptionItem {\n price: StripePrice;\n quantity: number | null;\n}\n\ninterface StripeSubscription {\n id: string;\n customer: string;\n status: string;\n items: { data: StripeSubscriptionItem[] };\n current_period_start: number;\n current_period_end: number;\n cancel_at_period_end: boolean;\n canceled_at: number | null;\n trial_end: number | null;\n currency: string;\n created: number;\n}\n\ninterface StripeInvoice {\n id: string;\n customer: string | null;\n subscription: string | null;\n status: string | null;\n amount_due: number;\n amount_paid: number;\n currency: string;\n created: number;\n due_date: number | null;\n hosted_invoice_url: string | null;\n}\n\ninterface StripeCharge {\n id: string;\n customer: string | null;\n amount: number;\n currency: string;\n status: string;\n failure_code: string | null;\n created: number;\n payment_intent: string | null;\n}\n\ninterface StripePaymentIntent {\n id: string;\n customer: string | null;\n amount: number;\n currency: string;\n status: string;\n created: number;\n}\n\ninterface StripeProduct {\n id: string;\n name: string;\n active: boolean;\n created: number;\n}\n\ninterface StripeDispute {\n id: string;\n charge: string;\n amount: number;\n currency: string;\n reason: string;\n status: string;\n created: number;\n}\n\ninterface StripeRefund {\n id: string;\n charge: string | null;\n amount: number;\n currency: string;\n reason: string | null;\n status: string | null;\n created: number;\n}\n\n// ---------------------------------------------------------------------------\n// Credentials\n// ---------------------------------------------------------------------------\n\nconst stripeCredentials = {\n apiKey: {\n description: 'Stripe API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype StripeCredentials = typeof stripeCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'customers',\n 'products',\n 'prices',\n 'subscriptions',\n 'invoices',\n 'charges',\n 'payment_intents',\n 'disputes',\n 'refunds',\n] as const;\n\ntype StripePhase = (typeof PHASE_ORDER)[number];\n\nexport type StripeResource = StripePhase;\n\nconst isStripeSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst ENTITY_TYPE_BY_PHASE: Partial<Record<StripePhase, string>> = {\n customers: 'stripe_customer',\n products: 'stripe_product',\n prices: 'stripe_price',\n subscriptions: 'stripe_subscription',\n invoices: 'stripe_invoice',\n};\n\nconst EVENT_NAME_BY_PHASE: Partial<Record<StripePhase, string>> = {\n charges: 'stripe_charge',\n payment_intents: 'stripe_payment_intent',\n disputes: 'stripe_dispute',\n refunds: 'stripe_refund',\n};\n\n// ---------------------------------------------------------------------------\n// MRR helper\n// ---------------------------------------------------------------------------\n\nexport function computeMrrAmountCents(\n subscription: StripeSubscription,\n): number | null {\n let sum = 0;\n let counted = 0;\n for (const item of subscription.items.data) {\n const { unit_amount, recurring } = item.price;\n if (unit_amount === null || unit_amount === undefined || !recurring) {\n continue;\n }\n const quantity = item.quantity ?? 1;\n const total = unit_amount * quantity;\n const intervalCount = recurring.interval_count || 1;\n let monthly: number | null;\n switch (recurring.interval) {\n case 'month':\n monthly = total / intervalCount;\n break;\n case 'year':\n monthly = total / (12 * intervalCount);\n break;\n case 'week':\n monthly = (total * 52) / (12 * intervalCount);\n break;\n case 'day':\n monthly = (total * 365) / (12 * intervalCount);\n break;\n default:\n monthly = null;\n }\n if (monthly === null) {\n continue;\n }\n sum += monthly;\n counted++;\n }\n if (counted === 0) {\n return null;\n }\n return Math.round(sum);\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 customerSchema = z.object({\n id: idString,\n email: z.string().nullable(),\n name: z.string().nullable(),\n created: z.number().int().nonnegative(),\n currency: z.string().nullable(),\n delinquent: z.boolean().nullable(),\n livemode: z.boolean(),\n});\n\nconst productSchema = z.object({\n id: idString,\n name: z.string(),\n active: z.boolean(),\n created: z.number().int().nonnegative(),\n});\n\nconst priceSchema = z.object({\n id: idString,\n product: idString,\n unit_amount: z.number().int().nullable(),\n currency: z.string(),\n recurring: z\n .object({\n interval: z.enum(['day', 'week', 'month', 'year']),\n interval_count: z.number().int().positive(),\n })\n .nullable(),\n active: z.boolean(),\n created: z.number().int().nonnegative(),\n});\n\nconst subscriptionSchema = z.object({\n id: idString,\n customer: idString,\n status: z.string(),\n items: z.object({\n data: z.array(\n z.object({\n price: priceSchema,\n quantity: z.number().int().nullable(),\n }),\n ),\n }),\n current_period_start: z.number().int().nonnegative(),\n current_period_end: z.number().int().nonnegative(),\n cancel_at_period_end: z.boolean(),\n canceled_at: z.number().int().nullable(),\n trial_end: z.number().int().nullable(),\n currency: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst invoiceSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n subscription: idString.nullable(),\n status: z.string().nullable(),\n amount_due: z.number().int(),\n amount_paid: z.number().int(),\n currency: z.string(),\n created: z.number().int().nonnegative(),\n due_date: z.number().int().nullable(),\n hosted_invoice_url: z.string().nullable(),\n});\n\nconst chargeSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n status: z.string(),\n failure_code: z.string().nullable(),\n created: z.number().int().nonnegative(),\n payment_intent: idString.nullable(),\n});\n\nconst paymentIntentSchema = z.object({\n id: idString,\n customer: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n status: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst disputeSchema = z.object({\n id: idString,\n charge: idString,\n amount: z.number().int(),\n currency: z.string(),\n reason: z.string(),\n status: z.string(),\n created: z.number().int().nonnegative(),\n});\n\nconst refundSchema = z.object({\n id: idString,\n charge: idString.nullable(),\n amount: z.number().int(),\n currency: z.string(),\n reason: z.string().nullable(),\n status: z.string().nullable(),\n created: z.number().int().nonnegative(),\n});\n\nexport const stripeResources = defineResources({\n stripe_customer: {\n shape: 'entity',\n description:\n 'Customers with email, name, default currency, and delinquency state.',\n endpoint: 'GET /v1/customers',\n responses: { customers: z.array(customerSchema) },\n },\n stripe_product: {\n shape: 'entity',\n description: 'Products in your catalog, including active state.',\n endpoint: 'GET /v1/products',\n responses: { products: z.array(productSchema) },\n },\n stripe_price: {\n shape: 'entity',\n description:\n 'Prices with unit amount, currency, and recurring interval, linked to their product.',\n endpoint: 'GET /v1/prices',\n responses: { prices: z.array(priceSchema) },\n },\n stripe_subscription: {\n shape: 'entity',\n description:\n 'Subscriptions with status, current period, cancellation state, and computed monthly recurring revenue (mrrAmount, in the smallest currency unit).',\n endpoint: 'GET /v1/subscriptions',\n notes:\n 'mrrAmount is computed as unit_amount x quantity, normalized to a monthly cadence (yearly / 12, weekly x 52 / 12, etc.).',\n responses: { subscriptions: z.array(subscriptionSchema) },\n },\n stripe_invoice: {\n shape: 'entity',\n description:\n 'Invoices with amount due, amount paid, status, and due date, linked to their customer and subscription.',\n endpoint: 'GET /v1/invoices',\n responses: { invoices: z.array(invoiceSchema) },\n },\n stripe_charge: {\n shape: 'event',\n description:\n 'Charge attempts with amount, currency, status, and failure code, timestamped at creation.',\n endpoint: 'GET /v1/charges',\n responses: { charges: z.array(chargeSchema) },\n },\n stripe_payment_intent: {\n shape: 'event',\n description:\n 'Payment intents with amount, currency, and status, timestamped at creation.',\n endpoint: 'GET /v1/payment_intents',\n responses: { payment_intents: z.array(paymentIntentSchema) },\n },\n stripe_dispute: {\n shape: 'event',\n description:\n 'Disputes with amount, currency, reason, and status, linked to the disputed charge.',\n endpoint: 'GET /v1/disputes',\n responses: { disputes: z.array(disputeSchema) },\n },\n stripe_refund: {\n shape: 'event',\n description:\n 'Refunds with amount, currency, reason, and status, linked to the refunded charge.',\n endpoint: 'GET /v1/refunds',\n responses: { refunds: z.array(refundSchema) },\n },\n});\n\n// ---------------------------------------------------------------------------\n// StripeConnector\n// ---------------------------------------------------------------------------\n\nexport const id = 'stripe';\n\nexport class StripeConnector extends BaseConnector<\n StripeSettings,\n StripeCredentials\n> {\n static readonly id = id;\n\n static readonly resources = stripeResources;\n\n static readonly schemas = schemasFromResources(stripeResources);\n\n static create(input: unknown, ctx?: ConnectorContext): StripeConnector {\n const parsed = configFields.parse(input);\n return new StripeConnector(\n { accountId: parsed.accountId, resources: parsed.resources },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = stripeCredentials;\n\n private buildHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.creds.apiKey}`,\n 'Stripe-Version': '2024-06-20',\n 'User-Agent': connectorUserAgent('stripe'),\n };\n if (this.settings.accountId) {\n headers['Stripe-Account'] = this.settings.accountId;\n }\n return headers;\n }\n\n private fetch<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 buildListUrl(\n path: string,\n params: Record<string, string | undefined>,\n ): string {\n const url = new URL(`https://api.stripe.com/v1/${path}`);\n url.searchParams.set('limit', '100');\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n url.searchParams.set(key, value);\n }\n }\n return url.toString();\n }\n\n // created[gte] cutoff for entity phases — in incremental (latest) mode adds\n // a 7-day grace so recent edits to slightly older entities still surface.\n // Subscriptions are intentionally exempt in full mode: a subscription's\n // updated_at is derived from current_period_end, so a still-active sub\n // created well before the cutoff would otherwise be dropped on backfill.\n private entityCreatedGte(\n phase: StripePhase,\n options: SyncOptions,\n ): string | undefined {\n if (!options.since) {\n return undefined;\n }\n const sinceMs = new Date(options.since).getTime();\n if (options.mode === 'latest') {\n return String(Math.floor((sinceMs - 7 * 24 * 60 * 60 * 1000) / 1000));\n }\n if (phase === 'subscriptions') {\n return undefined;\n }\n return String(Math.floor(sinceMs / 1000));\n }\n\n // created[gt] cutoff for event phases — applied in both full and incremental\n // modes so backfill respects the widget-driven window.\n private eventCreatedGt(options: SyncOptions): string | undefined {\n if (!options.since) {\n return undefined;\n }\n return String(Math.floor(new Date(options.since).getTime() / 1000));\n }\n\n private buildPhaseUrl(\n phase: StripePhase,\n page: string | null,\n options: SyncOptions,\n ): string {\n const startingAfter = page ?? undefined;\n if (phase in ENTITY_TYPE_BY_PHASE) {\n const extra: Record<string, string | undefined> =\n phase === 'subscriptions' ? { status: 'all' } : {};\n return this.buildListUrl(phase, {\n ...extra,\n starting_after: startingAfter,\n 'created[gte]': this.entityCreatedGte(phase, options),\n });\n }\n return this.buildListUrl(phase, {\n starting_after: startingAfter,\n 'created[gt]': this.eventCreatedGt(options),\n });\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: StripePhase,\n ): Promise<void> {\n const entityType = ENTITY_TYPE_BY_PHASE[phase];\n if (entityType) {\n await storage.entities([], { types: [entityType] });\n return;\n }\n const eventName = EVENT_NAME_BY_PHASE[phase];\n if (eventName) {\n await storage.events([], { names: [eventName] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: StripePhase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'customers':\n for (const c of items as StripeCustomer[]) {\n await storage.entity({\n type: 'stripe_customer',\n id: c.id,\n attributes: {\n email: c.email ?? null,\n name: c.name ?? null,\n created: c.created,\n currency: c.currency ?? null,\n delinquent: c.delinquent ?? false,\n livemode: c.livemode,\n },\n updated_at: c.created * 1000,\n });\n }\n return;\n case 'products':\n for (const p of items as StripeProduct[]) {\n await storage.entity({\n type: 'stripe_product',\n id: p.id,\n attributes: { name: p.name, active: p.active, created: p.created },\n updated_at: p.created * 1000,\n });\n }\n return;\n case 'prices':\n for (const p of items as StripePrice[]) {\n await storage.entity({\n type: 'stripe_price',\n id: p.id,\n attributes: {\n productId: p.product,\n unitAmount: p.unit_amount ?? null,\n currency: p.currency,\n interval: p.recurring?.interval ?? null,\n intervalCount: p.recurring?.interval_count ?? null,\n active: p.active,\n created: p.created,\n },\n updated_at: p.created * 1000,\n });\n }\n return;\n case 'subscriptions':\n for (const s of items as StripeSubscription[]) {\n await storage.entity({\n type: 'stripe_subscription',\n id: s.id,\n attributes: {\n customerId: s.customer,\n status: s.status,\n planId: s.items.data[0]?.price.id ?? null,\n currentPeriodStart: s.current_period_start,\n currentPeriodEnd: s.current_period_end,\n cancelAtPeriodEnd: s.cancel_at_period_end,\n canceledAt: s.canceled_at ?? null,\n trialEnd: s.trial_end ?? null,\n mrrAmount: computeMrrAmountCents(s),\n currency: s.currency,\n created: s.created,\n },\n updated_at: s.current_period_end * 1000,\n });\n }\n return;\n case 'invoices':\n for (const inv of items as StripeInvoice[]) {\n await storage.entity({\n type: 'stripe_invoice',\n id: inv.id,\n attributes: {\n customerId: inv.customer ?? null,\n subscriptionId: inv.subscription ?? null,\n status: inv.status ?? null,\n amountDue: inv.amount_due,\n amountPaid: inv.amount_paid,\n currency: inv.currency,\n created: inv.created,\n dueDate: inv.due_date ?? null,\n hostedInvoiceUrl: inv.hosted_invoice_url ?? null,\n },\n updated_at: inv.created * 1000,\n });\n }\n return;\n case 'charges':\n for (const c of items as StripeCharge[]) {\n await storage.event({\n name: 'stripe_charge',\n start_ts: c.created * 1000,\n end_ts: null,\n attributes: {\n id: c.id,\n customerId: c.customer ?? null,\n amount: c.amount,\n currency: c.currency,\n status: c.status,\n failureCode: c.failure_code ?? null,\n paymentIntentId: c.payment_intent ?? null,\n },\n });\n }\n return;\n case 'payment_intents':\n for (const pi of items as StripePaymentIntent[]) {\n await storage.event({\n name: 'stripe_payment_intent',\n start_ts: pi.created * 1000,\n end_ts: null,\n attributes: {\n id: pi.id,\n customerId: pi.customer ?? null,\n amount: pi.amount,\n currency: pi.currency,\n status: pi.status,\n },\n });\n }\n return;\n case 'disputes':\n for (const d of items as StripeDispute[]) {\n await storage.event({\n name: 'stripe_dispute',\n start_ts: d.created * 1000,\n end_ts: null,\n attributes: {\n id: d.id,\n chargeId: d.charge,\n amount: d.amount,\n currency: d.currency,\n reason: d.reason,\n status: d.status,\n },\n });\n }\n return;\n case 'refunds':\n for (const r of items as StripeRefund[]) {\n await storage.event({\n name: 'stripe_refund',\n start_ts: r.created * 1000,\n end_ts: null,\n attributes: {\n id: r.id,\n chargeId: r.charge ?? null,\n amount: r.amount,\n currency: r.currency,\n reason: r.reason ?? null,\n status: r.status ?? null,\n },\n });\n }\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isStripeSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<StripeResource, StripePhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<StripePhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n const url = this.buildPhaseUrl(phase, page, options);\n const res = await this.fetch<StripeListResponse<{ id: string }>>(\n url,\n phase,\n sig,\n );\n const { data, has_more } = res.body;\n const next = has_more && data.length > 0 ? data.at(-1)!.id : null;\n return { items: data, next };\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n await this.clearScopeOnFirstPage(storage, phase);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { StripeConnector } from './stripe';\n\nexport {\n configFields,\n doc,\n StripeConnector,\n computeMrrAmountCents,\n stripeResources as resources,\n id,\n} from './stripe';\nexport type { StripeSettings } from './stripe';\nexport default StripeConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;;;AOFA;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,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAC7C,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK;AAAA,MACpC,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC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,QAAQ,SACR;AACJ,UAAM,SAAS,QAAQ,SAAS;AAEhC,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAqC;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,OAAO,MAAM,QAAQ;AACrC,cAAM,MAAM,KAAK,cAAc,OAAO,MAAM,OAAO;AACnD,cAAM,MAAM,MAAM,KAAK;AAAA,UACrB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA,cAAM,EAAE,MAAM,SAAS,IAAI,IAAI;AAC/B,cAAM,OAAO,YAAY,KAAK,SAAS,IAAI,KAAK,GAAG,EAAE,EAAG,KAAK;AAC7D,eAAO,EAAE,OAAO,MAAM,KAAK;AAAA,MAC7B;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,UAAU,SAAS,MAAM;AAC3B,gBAAM,KAAK,sBAAsB,SAAS,KAAK;AAAA,QACjD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC3yBA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@rawdash/connector-stripe",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "Rawdash connector for Stripe — billing, subscriptions, and payments",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
+ "sideEffects": false,
7
8
  "repository": {
8
9
  "type": "git",
9
10
  "url": "https://github.com/rawdash/rawdash.git",
@@ -23,15 +24,15 @@
23
24
  },
24
25
  "dependencies": {
25
26
  "zod": "^4.4.3",
26
- "@rawdash/core": "0.15.0"
27
+ "@rawdash/core": "0.17.0"
27
28
  },
28
29
  "devDependencies": {
29
30
  "fast-check": "^4.8.0",
30
31
  "tsup": "^8.0.0",
31
32
  "typescript": "^5.7.2",
32
33
  "vitest": "^4.1.4",
33
- "@rawdash/connector-shared": "0.2.0",
34
- "@rawdash/connector-test-utils": "0.0.2"
34
+ "@rawdash/connector-test-utils": "0.0.4",
35
+ "@rawdash/connector-shared": "0.3.0"
35
36
  },
36
37
  "scripts": {
37
38
  "build": "tsup",