@rawdash/connector-shopify 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,104 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
3
+ # @rawdash/connector-shopify
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-shopify)](https://www.npmjs.com/package/@rawdash/connector-shopify)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-shopify)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
7
+
8
+ Sync orders, customers, products, and refund events from a Shopify store via the Admin GraphQL API.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @rawdash/connector-shopify
14
+ ```
15
+
16
+ ## Authentication
17
+
18
+ A Custom App Admin API access token authenticates every GraphQL request. The token scopes the sync to the store it was created in and the read scopes granted to the app.
19
+
20
+ 1. In the Shopify admin, open Settings -> Apps and sales channels -> Develop apps.
21
+ 2. Create a new app (or open an existing custom app) and open the Configuration tab.
22
+ 3. Under Admin API integration, grant the read_orders, read_customers, and read_products scopes and save.
23
+ 4. Open the API credentials tab and install the app to reveal the Admin API access token (starts with shpat\_).
24
+ 5. Store the token as a secret and reference it from the connector config as `accessToken: secret("SHOPIFY_ACCESS_TOKEN")`, and set `shopDomain` to your yourshop.myshopify.com domain.
25
+
26
+ ## Configuration
27
+
28
+ | Field | Type | Required | Description |
29
+ | ------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
30
+ | `shopDomain` | string | Yes | Your store myshopify.com domain, without protocol, e.g. yourshop.myshopify.com. |
31
+ | `accessToken` | secret | Yes | Custom App Admin API access token with read_orders, read_customers, and read_products scopes. |
32
+ | `resources` | array | No | Which Shopify resources to sync. Omit to sync all resources. The `orders` phase also emits a refund event for each refund attached to an order. |
33
+
34
+ ## Resources
35
+
36
+ - **`shopify_product`** _(entity)_ - Store products with their title, vendor, status, and total inventory.
37
+ - Endpoint: `GraphQL query: products { nodes { ... } }`
38
+ - **`shopify_customer`** _(entity)_ - Store customers with their email, lifetime order count, and total amount spent.
39
+ - Endpoint: `GraphQL query: customers { nodes { ... } }`
40
+ - **`shopify_order`** _(entity)_ - Orders with their total price, currency, financial and fulfillment status, customer, and lifecycle timestamps.
41
+ - Endpoint: `GraphQL query: orders { nodes { ... } }`
42
+ - **`shopify_refund`** _(event)_ - Refund events derived from each order, carrying the refunded amount and currency.
43
+ - Endpoint: `GraphQL query: orders { nodes { refunds { ... } } }`
44
+ - Derived from the `refunds` list on each synced order. Each refund becomes one append-only event keyed by its refund id; refunds attached to orders outside the current incremental window are not revisited.
45
+
46
+ ## Example
47
+
48
+ ```ts
49
+ import {
50
+ defineConfig,
51
+ defineDashboard,
52
+ defineMetric,
53
+ secret,
54
+ } from '@rawdash/core';
55
+
56
+ const shopify = {
57
+ name: 'shopify',
58
+ connectorId: 'shopify',
59
+ config: {
60
+ shopDomain: 'yourshop.myshopify.com',
61
+ accessToken: secret('SHOPIFY_ACCESS_TOKEN'),
62
+ },
63
+ };
64
+
65
+ export default defineConfig({
66
+ connectors: [shopify],
67
+ dashboards: {
68
+ sales: defineDashboard({
69
+ widgets: {
70
+ paid_orders: {
71
+ kind: 'stat',
72
+ title: 'Paid orders',
73
+ metric: defineMetric({
74
+ connector: shopify,
75
+ shape: 'entity',
76
+ entityType: 'shopify_order',
77
+ fn: 'count',
78
+ filter: [{ field: 'financialStatus', op: 'eq', value: 'PAID' }],
79
+ }),
80
+ },
81
+ },
82
+ }),
83
+ },
84
+ });
85
+ ```
86
+
87
+ ## Rate limits
88
+
89
+ The Admin GraphQL API uses a cost-based leaky-bucket limit per access token; this connector pages 250 records at a time and relies on standard HTTP 429 retry/backoff.
90
+
91
+ ## Limitations
92
+
93
+ - Custom App access token auth only (OAuth app distribution not supported).
94
+ - Order status-transition history and inventory-level resources are out of scope; refund events are derived from each order.
95
+
96
+ ## Links
97
+
98
+ - [Rawdash docs](https://rawdash.dev/docs/connectors)
99
+ - [Shopify API docs](https://shopify.dev/docs/api/admin-graphql)
100
+ - [GitHub](https://github.com/rawdash/rawdash)
101
+
102
+ ## License
103
+
104
+ Apache-2.0
@@ -0,0 +1,307 @@
1
+ import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
2
+ import { z } from 'zod';
3
+
4
+ declare const configFields: z.ZodObject<{
5
+ shopDomain: z.ZodString;
6
+ accessToken: z.ZodObject<{
7
+ $secret: z.ZodString;
8
+ }, z.core.$strip>;
9
+ resources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
10
+ products: "products";
11
+ customers: "customers";
12
+ orders: "orders";
13
+ }>>>;
14
+ }, z.core.$strip>;
15
+ declare const doc: ConnectorDoc;
16
+ interface ShopifySettings {
17
+ shopDomain: string;
18
+ resources?: readonly ShopifyResource[];
19
+ }
20
+ declare const shopifyCredentials: {
21
+ accessToken: {
22
+ description: string;
23
+ auth: "required";
24
+ };
25
+ };
26
+ type ShopifyCredentials = typeof shopifyCredentials;
27
+ declare const PHASE_ORDER: readonly ["products", "customers", "orders"];
28
+ type ShopifyPhase = (typeof PHASE_ORDER)[number];
29
+ type ShopifyResource = ShopifyPhase;
30
+ declare const shopifyResources: {
31
+ readonly shopify_product: {
32
+ readonly shape: "entity";
33
+ readonly filterable: [{
34
+ readonly field: "status";
35
+ readonly ops: ["eq"];
36
+ readonly values: ["ACTIVE", "ARCHIVED", "DRAFT"];
37
+ }, {
38
+ readonly field: "vendor";
39
+ readonly ops: ["eq"];
40
+ }];
41
+ readonly description: "Store products with their title, vendor, status, and total inventory.";
42
+ readonly endpoint: "GraphQL query: products { nodes { ... } }";
43
+ readonly responses: {
44
+ readonly products: z.ZodArray<z.ZodObject<{
45
+ id: z.ZodString;
46
+ title: z.ZodString;
47
+ vendor: z.ZodString;
48
+ status: z.ZodString;
49
+ totalInventory: z.ZodNullable<z.ZodNumber>;
50
+ createdAt: z.ZodISODateTime;
51
+ updatedAt: z.ZodISODateTime;
52
+ }, z.core.$strip>>;
53
+ };
54
+ };
55
+ readonly shopify_customer: {
56
+ readonly shape: "entity";
57
+ readonly filterable: [];
58
+ readonly description: "Store customers with their email, lifetime order count, and total amount spent.";
59
+ readonly endpoint: "GraphQL query: customers { nodes { ... } }";
60
+ readonly responses: {
61
+ readonly customers: z.ZodArray<z.ZodObject<{
62
+ id: z.ZodString;
63
+ defaultEmailAddress: z.ZodNullable<z.ZodObject<{
64
+ emailAddress: z.ZodNullable<z.ZodString>;
65
+ }, z.core.$strip>>;
66
+ numberOfOrders: z.ZodString;
67
+ amountSpent: z.ZodObject<{
68
+ amount: z.ZodString;
69
+ currencyCode: z.ZodString;
70
+ }, z.core.$strip>;
71
+ createdAt: z.ZodISODateTime;
72
+ updatedAt: z.ZodISODateTime;
73
+ }, z.core.$strip>>;
74
+ };
75
+ };
76
+ readonly shopify_order: {
77
+ readonly shape: "entity";
78
+ readonly filterable: [{
79
+ readonly field: "financialStatus";
80
+ readonly ops: ["eq"];
81
+ readonly values: ["PENDING", "AUTHORIZED", "PARTIALLY_PAID", "PAID", "PARTIALLY_REFUNDED", "REFUNDED", "VOIDED"];
82
+ }, {
83
+ readonly field: "fulfillmentStatus";
84
+ readonly ops: ["eq"];
85
+ readonly values: ["FULFILLED", "IN_PROGRESS", "ON_HOLD", "OPEN", "PARTIALLY_FULFILLED", "PENDING_FULFILLMENT", "RESTOCKED", "SCHEDULED", "UNFULFILLED"];
86
+ }];
87
+ readonly description: "Orders with their total price, currency, financial and fulfillment status, customer, and lifecycle timestamps.";
88
+ readonly endpoint: "GraphQL query: orders { nodes { ... } }";
89
+ readonly responses: {
90
+ readonly orders: z.ZodArray<z.ZodObject<{
91
+ id: z.ZodString;
92
+ name: z.ZodString;
93
+ currentTotalPriceSet: z.ZodObject<{
94
+ shopMoney: z.ZodObject<{
95
+ amount: z.ZodString;
96
+ currencyCode: z.ZodString;
97
+ }, z.core.$strip>;
98
+ }, z.core.$strip>;
99
+ displayFinancialStatus: z.ZodNullable<z.ZodString>;
100
+ displayFulfillmentStatus: z.ZodString;
101
+ customer: z.ZodNullable<z.ZodObject<{
102
+ id: z.ZodString;
103
+ }, z.core.$strip>>;
104
+ createdAt: z.ZodISODateTime;
105
+ processedAt: z.ZodISODateTime;
106
+ cancelledAt: z.ZodNullable<z.ZodISODateTime>;
107
+ updatedAt: z.ZodISODateTime;
108
+ refunds: z.ZodArray<z.ZodObject<{
109
+ id: z.ZodString;
110
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
111
+ totalRefundedSet: z.ZodObject<{
112
+ shopMoney: z.ZodObject<{
113
+ amount: z.ZodString;
114
+ currencyCode: z.ZodString;
115
+ }, z.core.$strip>;
116
+ }, z.core.$strip>;
117
+ }, z.core.$strip>>;
118
+ }, z.core.$strip>>;
119
+ };
120
+ };
121
+ readonly shopify_refund: {
122
+ readonly shape: "event";
123
+ readonly filterable: [];
124
+ readonly description: "Refund events derived from each order, carrying the refunded amount and currency.";
125
+ readonly endpoint: "GraphQL query: orders { nodes { refunds { ... } } }";
126
+ readonly notes: "Derived from the `refunds` list on each synced order. Each refund becomes one append-only event keyed by its refund id; refunds attached to orders outside the current incremental window are not revisited.";
127
+ };
128
+ };
129
+ declare const id = "shopify";
130
+ declare class ShopifyConnector extends BaseConnector<ShopifySettings, ShopifyCredentials> {
131
+ static readonly id = "shopify";
132
+ static readonly resources: {
133
+ readonly shopify_product: {
134
+ readonly shape: "entity";
135
+ readonly filterable: [{
136
+ readonly field: "status";
137
+ readonly ops: ["eq"];
138
+ readonly values: ["ACTIVE", "ARCHIVED", "DRAFT"];
139
+ }, {
140
+ readonly field: "vendor";
141
+ readonly ops: ["eq"];
142
+ }];
143
+ readonly description: "Store products with their title, vendor, status, and total inventory.";
144
+ readonly endpoint: "GraphQL query: products { nodes { ... } }";
145
+ readonly responses: {
146
+ readonly products: z.ZodArray<z.ZodObject<{
147
+ id: z.ZodString;
148
+ title: z.ZodString;
149
+ vendor: z.ZodString;
150
+ status: z.ZodString;
151
+ totalInventory: z.ZodNullable<z.ZodNumber>;
152
+ createdAt: z.ZodISODateTime;
153
+ updatedAt: z.ZodISODateTime;
154
+ }, z.core.$strip>>;
155
+ };
156
+ };
157
+ readonly shopify_customer: {
158
+ readonly shape: "entity";
159
+ readonly filterable: [];
160
+ readonly description: "Store customers with their email, lifetime order count, and total amount spent.";
161
+ readonly endpoint: "GraphQL query: customers { nodes { ... } }";
162
+ readonly responses: {
163
+ readonly customers: z.ZodArray<z.ZodObject<{
164
+ id: z.ZodString;
165
+ defaultEmailAddress: z.ZodNullable<z.ZodObject<{
166
+ emailAddress: z.ZodNullable<z.ZodString>;
167
+ }, z.core.$strip>>;
168
+ numberOfOrders: z.ZodString;
169
+ amountSpent: z.ZodObject<{
170
+ amount: z.ZodString;
171
+ currencyCode: z.ZodString;
172
+ }, z.core.$strip>;
173
+ createdAt: z.ZodISODateTime;
174
+ updatedAt: z.ZodISODateTime;
175
+ }, z.core.$strip>>;
176
+ };
177
+ };
178
+ readonly shopify_order: {
179
+ readonly shape: "entity";
180
+ readonly filterable: [{
181
+ readonly field: "financialStatus";
182
+ readonly ops: ["eq"];
183
+ readonly values: ["PENDING", "AUTHORIZED", "PARTIALLY_PAID", "PAID", "PARTIALLY_REFUNDED", "REFUNDED", "VOIDED"];
184
+ }, {
185
+ readonly field: "fulfillmentStatus";
186
+ readonly ops: ["eq"];
187
+ readonly values: ["FULFILLED", "IN_PROGRESS", "ON_HOLD", "OPEN", "PARTIALLY_FULFILLED", "PENDING_FULFILLMENT", "RESTOCKED", "SCHEDULED", "UNFULFILLED"];
188
+ }];
189
+ readonly description: "Orders with their total price, currency, financial and fulfillment status, customer, and lifecycle timestamps.";
190
+ readonly endpoint: "GraphQL query: orders { nodes { ... } }";
191
+ readonly responses: {
192
+ readonly orders: z.ZodArray<z.ZodObject<{
193
+ id: z.ZodString;
194
+ name: z.ZodString;
195
+ currentTotalPriceSet: z.ZodObject<{
196
+ shopMoney: z.ZodObject<{
197
+ amount: z.ZodString;
198
+ currencyCode: z.ZodString;
199
+ }, z.core.$strip>;
200
+ }, z.core.$strip>;
201
+ displayFinancialStatus: z.ZodNullable<z.ZodString>;
202
+ displayFulfillmentStatus: z.ZodString;
203
+ customer: z.ZodNullable<z.ZodObject<{
204
+ id: z.ZodString;
205
+ }, z.core.$strip>>;
206
+ createdAt: z.ZodISODateTime;
207
+ processedAt: z.ZodISODateTime;
208
+ cancelledAt: z.ZodNullable<z.ZodISODateTime>;
209
+ updatedAt: z.ZodISODateTime;
210
+ refunds: z.ZodArray<z.ZodObject<{
211
+ id: z.ZodString;
212
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
213
+ totalRefundedSet: z.ZodObject<{
214
+ shopMoney: z.ZodObject<{
215
+ amount: z.ZodString;
216
+ currencyCode: z.ZodString;
217
+ }, z.core.$strip>;
218
+ }, z.core.$strip>;
219
+ }, z.core.$strip>>;
220
+ }, z.core.$strip>>;
221
+ };
222
+ };
223
+ readonly shopify_refund: {
224
+ readonly shape: "event";
225
+ readonly filterable: [];
226
+ readonly description: "Refund events derived from each order, carrying the refunded amount and currency.";
227
+ readonly endpoint: "GraphQL query: orders { nodes { refunds { ... } } }";
228
+ readonly notes: "Derived from the `refunds` list on each synced order. Each refund becomes one append-only event keyed by its refund id; refunds attached to orders outside the current incremental window are not revisited.";
229
+ };
230
+ };
231
+ static readonly schemas: object & {
232
+ readonly products: z.ZodArray<z.ZodObject<{
233
+ id: z.ZodString;
234
+ title: z.ZodString;
235
+ vendor: z.ZodString;
236
+ status: z.ZodString;
237
+ totalInventory: z.ZodNullable<z.ZodNumber>;
238
+ createdAt: z.ZodISODateTime;
239
+ updatedAt: z.ZodISODateTime;
240
+ }, z.core.$strip>>;
241
+ } & {
242
+ readonly customers: z.ZodArray<z.ZodObject<{
243
+ id: z.ZodString;
244
+ defaultEmailAddress: z.ZodNullable<z.ZodObject<{
245
+ emailAddress: z.ZodNullable<z.ZodString>;
246
+ }, z.core.$strip>>;
247
+ numberOfOrders: z.ZodString;
248
+ amountSpent: z.ZodObject<{
249
+ amount: z.ZodString;
250
+ currencyCode: z.ZodString;
251
+ }, z.core.$strip>;
252
+ createdAt: z.ZodISODateTime;
253
+ updatedAt: z.ZodISODateTime;
254
+ }, z.core.$strip>>;
255
+ } & {
256
+ readonly orders: z.ZodArray<z.ZodObject<{
257
+ id: z.ZodString;
258
+ name: z.ZodString;
259
+ currentTotalPriceSet: z.ZodObject<{
260
+ shopMoney: z.ZodObject<{
261
+ amount: z.ZodString;
262
+ currencyCode: z.ZodString;
263
+ }, z.core.$strip>;
264
+ }, z.core.$strip>;
265
+ displayFinancialStatus: z.ZodNullable<z.ZodString>;
266
+ displayFulfillmentStatus: z.ZodString;
267
+ customer: z.ZodNullable<z.ZodObject<{
268
+ id: z.ZodString;
269
+ }, z.core.$strip>>;
270
+ createdAt: z.ZodISODateTime;
271
+ processedAt: z.ZodISODateTime;
272
+ cancelledAt: z.ZodNullable<z.ZodISODateTime>;
273
+ updatedAt: z.ZodISODateTime;
274
+ refunds: z.ZodArray<z.ZodObject<{
275
+ id: z.ZodString;
276
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
277
+ totalRefundedSet: z.ZodObject<{
278
+ shopMoney: z.ZodObject<{
279
+ amount: z.ZodString;
280
+ currencyCode: z.ZodString;
281
+ }, z.core.$strip>;
282
+ }, z.core.$strip>;
283
+ }, z.core.$strip>>;
284
+ }, z.core.$strip>>;
285
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
286
+ static create(input: unknown, ctx?: ConnectorContext): ShopifyConnector;
287
+ readonly id = "shopify";
288
+ readonly credentials: {
289
+ accessToken: {
290
+ description: string;
291
+ auth: "required";
292
+ };
293
+ };
294
+ private endpoint;
295
+ private buildHeaders;
296
+ private graphql;
297
+ private sinceQuery;
298
+ private fetchProductsPage;
299
+ private fetchCustomersPage;
300
+ private fetchOrdersPage;
301
+ private writeProducts;
302
+ private writeCustomers;
303
+ private writeOrders;
304
+ sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
305
+ }
306
+
307
+ export { ShopifyConnector, type ShopifyResource, type ShopifySettings, configFields, ShopifyConnector as default, doc, id, shopifyResources as resources };
package/dist/index.js ADDED
@@ -0,0 +1,482 @@
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
+
8
+ // src/shopify.ts
9
+ import {
10
+ BaseConnector,
11
+ defineConfigFields,
12
+ defineConnectorDoc,
13
+ defineResources,
14
+ makeChunkedCursorGuard,
15
+ paginateChunked,
16
+ schemasFromResources,
17
+ selectActivePhases
18
+ } from "@rawdash/core";
19
+ import { z } from "zod";
20
+ var API_VERSION = "2025-01";
21
+ var configFields = defineConfigFields(
22
+ z.object({
23
+ shopDomain: z.string().min(1).regex(
24
+ /^[a-z0-9][a-z0-9-]*\.myshopify\.com$/i,
25
+ "Must be a myshopify.com domain, e.g. yourshop.myshopify.com"
26
+ ).meta({
27
+ label: "Shop domain",
28
+ description: "Your store myshopify.com domain, without protocol, e.g. yourshop.myshopify.com.",
29
+ placeholder: "yourshop.myshopify.com"
30
+ }),
31
+ accessToken: z.object({ $secret: z.string() }).meta({
32
+ label: "Admin API access token",
33
+ description: "Custom App Admin API access token with read_orders, read_customers, and read_products scopes.",
34
+ placeholder: "shpat_...",
35
+ secret: true
36
+ }),
37
+ resources: z.array(z.enum(["products", "customers", "orders"])).nonempty().optional().meta({
38
+ label: "Resources",
39
+ description: "Which Shopify resources to sync. Omit to sync all resources. The `orders` phase also emits a refund event for each refund attached to an order."
40
+ })
41
+ })
42
+ );
43
+ var doc = defineConnectorDoc({
44
+ displayName: "Shopify",
45
+ category: "sales",
46
+ brandColor: "#7AB55C",
47
+ tagline: "Sync orders, customers, products, and refund events from a Shopify store via the Admin GraphQL API.",
48
+ vendor: {
49
+ name: "Shopify",
50
+ domain: "shopify.com",
51
+ apiDocs: "https://shopify.dev/docs/api/admin-graphql",
52
+ website: "https://www.shopify.com"
53
+ },
54
+ auth: {
55
+ summary: "A Custom App Admin API access token authenticates every GraphQL request. The token scopes the sync to the store it was created in and the read scopes granted to the app.",
56
+ setup: [
57
+ "In the Shopify admin, open Settings -> Apps and sales channels -> Develop apps.",
58
+ "Create a new app (or open an existing custom app) and open the Configuration tab.",
59
+ "Under Admin API integration, grant the read_orders, read_customers, and read_products scopes and save.",
60
+ "Open the API credentials tab and install the app to reveal the Admin API access token (starts with shpat_).",
61
+ 'Store the token as a secret and reference it from the connector config as `accessToken: secret("SHOPIFY_ACCESS_TOKEN")`, and set `shopDomain` to your yourshop.myshopify.com domain.'
62
+ ]
63
+ },
64
+ rateLimit: "The Admin GraphQL API uses a cost-based leaky-bucket limit per access token; this connector pages 250 records at a time and relies on standard HTTP 429 retry/backoff.",
65
+ limitations: [
66
+ "Custom App access token auth only (OAuth app distribution not supported).",
67
+ "Order status-transition history and inventory-level resources are out of scope; refund events are derived from each order."
68
+ ]
69
+ });
70
+ var shopifyCredentials = {
71
+ accessToken: {
72
+ description: "Shopify Admin API access token",
73
+ auth: "required"
74
+ }
75
+ };
76
+ var PHASE_ORDER = ["products", "customers", "orders"];
77
+ var isShopifySyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
78
+ var PRODUCTS_QUERY = `
79
+ query Products($cursor: String, $first: Int!, $query: String) {
80
+ products(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {
81
+ nodes { id title vendor status totalInventory createdAt updatedAt }
82
+ pageInfo { hasNextPage endCursor }
83
+ }
84
+ }
85
+ `;
86
+ var CUSTOMERS_QUERY = `
87
+ query Customers($cursor: String, $first: Int!, $query: String) {
88
+ customers(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {
89
+ nodes {
90
+ id
91
+ defaultEmailAddress { emailAddress }
92
+ numberOfOrders
93
+ amountSpent { amount currencyCode }
94
+ createdAt updatedAt
95
+ }
96
+ pageInfo { hasNextPage endCursor }
97
+ }
98
+ }
99
+ `;
100
+ var ORDERS_QUERY = `
101
+ query Orders($cursor: String, $first: Int!, $query: String) {
102
+ orders(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {
103
+ nodes {
104
+ id name
105
+ currentTotalPriceSet { shopMoney { amount currencyCode } }
106
+ displayFinancialStatus displayFulfillmentStatus
107
+ customer { id }
108
+ createdAt processedAt cancelledAt updatedAt
109
+ refunds {
110
+ id createdAt
111
+ totalRefundedSet { shopMoney { amount currencyCode } }
112
+ }
113
+ }
114
+ pageInfo { hasNextPage endCursor }
115
+ }
116
+ }
117
+ `;
118
+ var MAX_PAGE_SIZE = 250;
119
+ var DEFAULT_PAGE_SIZE = 250;
120
+ var CHUNK_BUDGET_MS = 25e3;
121
+ function clampPageSize(requested) {
122
+ const n = requested ?? DEFAULT_PAGE_SIZE;
123
+ if (!Number.isFinite(n) || n < 1) {
124
+ return 1;
125
+ }
126
+ return Math.min(Math.floor(n), MAX_PAGE_SIZE);
127
+ }
128
+ function parseMoney(amount) {
129
+ if (amount == null) {
130
+ return null;
131
+ }
132
+ const n = Number(amount);
133
+ return Number.isFinite(n) ? n : null;
134
+ }
135
+ function parseCount(value) {
136
+ if (value == null) {
137
+ return null;
138
+ }
139
+ const n = Number(value);
140
+ return Number.isFinite(n) ? n : null;
141
+ }
142
+ var idString = z.string().min(1);
143
+ var moneyV2Schema = z.object({
144
+ amount: z.string(),
145
+ currencyCode: z.string()
146
+ });
147
+ var moneyBagSchema = z.object({ shopMoney: moneyV2Schema });
148
+ var productSchema = z.object({
149
+ id: idString,
150
+ title: z.string(),
151
+ vendor: z.string(),
152
+ status: z.string(),
153
+ totalInventory: z.number().nullable(),
154
+ createdAt: z.iso.datetime(),
155
+ updatedAt: z.iso.datetime()
156
+ });
157
+ var customerSchema = z.object({
158
+ id: idString,
159
+ defaultEmailAddress: z.object({ emailAddress: z.string().nullable() }).nullable(),
160
+ numberOfOrders: z.string(),
161
+ amountSpent: moneyV2Schema,
162
+ createdAt: z.iso.datetime(),
163
+ updatedAt: z.iso.datetime()
164
+ });
165
+ var refundSchema = z.object({
166
+ id: idString,
167
+ createdAt: z.iso.datetime().nullable(),
168
+ totalRefundedSet: moneyBagSchema
169
+ });
170
+ var orderSchema = z.object({
171
+ id: idString,
172
+ name: z.string(),
173
+ currentTotalPriceSet: moneyBagSchema,
174
+ displayFinancialStatus: z.string().nullable(),
175
+ displayFulfillmentStatus: z.string(),
176
+ customer: z.object({ id: idString }).nullable(),
177
+ createdAt: z.iso.datetime(),
178
+ processedAt: z.iso.datetime(),
179
+ cancelledAt: z.iso.datetime().nullable(),
180
+ updatedAt: z.iso.datetime(),
181
+ refunds: z.array(refundSchema)
182
+ });
183
+ var shopifyResources = defineResources({
184
+ shopify_product: {
185
+ shape: "entity",
186
+ filterable: [
187
+ {
188
+ field: "status",
189
+ ops: ["eq"],
190
+ values: ["ACTIVE", "ARCHIVED", "DRAFT"]
191
+ },
192
+ { field: "vendor", ops: ["eq"] }
193
+ ],
194
+ description: "Store products with their title, vendor, status, and total inventory.",
195
+ endpoint: "GraphQL query: products { nodes { ... } }",
196
+ responses: { products: z.array(productSchema) }
197
+ },
198
+ shopify_customer: {
199
+ shape: "entity",
200
+ filterable: [],
201
+ description: "Store customers with their email, lifetime order count, and total amount spent.",
202
+ endpoint: "GraphQL query: customers { nodes { ... } }",
203
+ responses: { customers: z.array(customerSchema) }
204
+ },
205
+ shopify_order: {
206
+ shape: "entity",
207
+ filterable: [
208
+ {
209
+ field: "financialStatus",
210
+ ops: ["eq"],
211
+ values: [
212
+ "PENDING",
213
+ "AUTHORIZED",
214
+ "PARTIALLY_PAID",
215
+ "PAID",
216
+ "PARTIALLY_REFUNDED",
217
+ "REFUNDED",
218
+ "VOIDED"
219
+ ]
220
+ },
221
+ {
222
+ field: "fulfillmentStatus",
223
+ ops: ["eq"],
224
+ values: [
225
+ "FULFILLED",
226
+ "IN_PROGRESS",
227
+ "ON_HOLD",
228
+ "OPEN",
229
+ "PARTIALLY_FULFILLED",
230
+ "PENDING_FULFILLMENT",
231
+ "RESTOCKED",
232
+ "SCHEDULED",
233
+ "UNFULFILLED"
234
+ ]
235
+ }
236
+ ],
237
+ description: "Orders with their total price, currency, financial and fulfillment status, customer, and lifecycle timestamps.",
238
+ endpoint: "GraphQL query: orders { nodes { ... } }",
239
+ responses: { orders: z.array(orderSchema) }
240
+ },
241
+ shopify_refund: {
242
+ shape: "event",
243
+ filterable: [],
244
+ description: "Refund events derived from each order, carrying the refunded amount and currency.",
245
+ endpoint: "GraphQL query: orders { nodes { refunds { ... } } }",
246
+ notes: "Derived from the `refunds` list on each synced order. Each refund becomes one append-only event keyed by its refund id; refunds attached to orders outside the current incremental window are not revisited."
247
+ }
248
+ });
249
+ var id = "shopify";
250
+ var ShopifyConnector = class _ShopifyConnector extends BaseConnector {
251
+ static id = id;
252
+ static resources = shopifyResources;
253
+ static schemas = schemasFromResources(shopifyResources);
254
+ static create(input, ctx) {
255
+ const parsed = configFields.parse(input);
256
+ return new _ShopifyConnector(
257
+ { shopDomain: parsed.shopDomain, resources: parsed.resources },
258
+ { accessToken: parsed.accessToken },
259
+ ctx
260
+ );
261
+ }
262
+ id = id;
263
+ credentials = shopifyCredentials;
264
+ endpoint() {
265
+ return `https://${this.settings.shopDomain}/admin/api/${API_VERSION}/graphql.json`;
266
+ }
267
+ buildHeaders() {
268
+ return {
269
+ "X-Shopify-Access-Token": this.creds.accessToken,
270
+ "Content-Type": "application/json",
271
+ "User-Agent": connectorUserAgent("shopify")
272
+ };
273
+ }
274
+ async graphql(query, variables, resource, signal) {
275
+ const res = await this.post(this.endpoint(), {
276
+ resource,
277
+ headers: this.buildHeaders(),
278
+ body: JSON.stringify({ query, variables }),
279
+ signal
280
+ });
281
+ if (res.body.errors && res.body.errors.length > 0) {
282
+ const messages = res.body.errors.map((e) => e.message).join("; ");
283
+ throw new Error(`Shopify GraphQL error: ${messages}`);
284
+ }
285
+ if (!res.body.data) {
286
+ throw new Error(
287
+ `Shopify GraphQL response missing data for resource '${resource}'`
288
+ );
289
+ }
290
+ return res;
291
+ }
292
+ sinceQuery(options) {
293
+ if (!options.since) {
294
+ return void 0;
295
+ }
296
+ return `updated_at:>'${options.since}'`;
297
+ }
298
+ async fetchProductsPage(page, options, signal) {
299
+ const res = await this.graphql(
300
+ PRODUCTS_QUERY,
301
+ {
302
+ cursor: page ?? null,
303
+ first: clampPageSize(options.pageSize),
304
+ query: this.sinceQuery(options) ?? null
305
+ },
306
+ "products",
307
+ signal
308
+ );
309
+ const conn = res.body.data.products;
310
+ return {
311
+ items: conn.nodes,
312
+ next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null
313
+ };
314
+ }
315
+ async fetchCustomersPage(page, options, signal) {
316
+ const res = await this.graphql(
317
+ CUSTOMERS_QUERY,
318
+ {
319
+ cursor: page ?? null,
320
+ first: clampPageSize(options.pageSize),
321
+ query: this.sinceQuery(options) ?? null
322
+ },
323
+ "customers",
324
+ signal
325
+ );
326
+ const conn = res.body.data.customers;
327
+ return {
328
+ items: conn.nodes,
329
+ next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null
330
+ };
331
+ }
332
+ async fetchOrdersPage(page, options, signal) {
333
+ const res = await this.graphql(
334
+ ORDERS_QUERY,
335
+ {
336
+ cursor: page ?? null,
337
+ first: clampPageSize(options.pageSize),
338
+ query: this.sinceQuery(options) ?? null
339
+ },
340
+ "orders",
341
+ signal
342
+ );
343
+ const conn = res.body.data.orders;
344
+ return {
345
+ items: conn.nodes,
346
+ next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null
347
+ };
348
+ }
349
+ async writeProducts(storage, products) {
350
+ for (const p of products) {
351
+ await storage.entity({
352
+ type: "shopify_product",
353
+ id: p.id,
354
+ attributes: {
355
+ title: p.title,
356
+ vendor: p.vendor,
357
+ status: p.status,
358
+ totalInventory: p.totalInventory,
359
+ createdAt: new Date(p.createdAt).getTime()
360
+ },
361
+ updated_at: new Date(p.updatedAt).getTime()
362
+ });
363
+ }
364
+ }
365
+ async writeCustomers(storage, customers) {
366
+ for (const c of customers) {
367
+ await storage.entity({
368
+ type: "shopify_customer",
369
+ id: c.id,
370
+ attributes: {
371
+ email: c.defaultEmailAddress?.emailAddress ?? null,
372
+ ordersCount: parseCount(c.numberOfOrders),
373
+ totalSpent: parseMoney(c.amountSpent.amount),
374
+ currency: c.amountSpent.currencyCode,
375
+ createdAt: new Date(c.createdAt).getTime()
376
+ },
377
+ updated_at: new Date(c.updatedAt).getTime()
378
+ });
379
+ }
380
+ }
381
+ async writeOrders(storage, orders) {
382
+ for (const o of orders) {
383
+ const money = o.currentTotalPriceSet.shopMoney;
384
+ await storage.entity({
385
+ type: "shopify_order",
386
+ id: o.id,
387
+ attributes: {
388
+ name: o.name,
389
+ totalPrice: parseMoney(money.amount),
390
+ currency: money.currencyCode,
391
+ financialStatus: o.displayFinancialStatus,
392
+ fulfillmentStatus: o.displayFulfillmentStatus,
393
+ customerId: o.customer?.id ?? null,
394
+ createdAt: new Date(o.createdAt).getTime(),
395
+ processedAt: new Date(o.processedAt).getTime(),
396
+ cancelledAt: o.cancelledAt ? new Date(o.cancelledAt).getTime() : null
397
+ },
398
+ updated_at: new Date(o.updatedAt).getTime()
399
+ });
400
+ for (const r of o.refunds) {
401
+ const refundMoney = r.totalRefundedSet.shopMoney;
402
+ const refundTs = r.createdAt ? new Date(r.createdAt).getTime() : new Date(o.updatedAt).getTime();
403
+ await storage.event({
404
+ name: "shopify_refund",
405
+ start_ts: refundTs,
406
+ end_ts: null,
407
+ attributes: {
408
+ refundId: r.id,
409
+ orderId: o.id,
410
+ orderName: o.name,
411
+ customerId: o.customer?.id ?? null,
412
+ amount: parseMoney(refundMoney.amount),
413
+ currency: refundMoney.currencyCode
414
+ }
415
+ });
416
+ }
417
+ }
418
+ }
419
+ async sync(options, storage, signal) {
420
+ const cursor = isShopifySyncCursor(options.cursor) ? options.cursor : void 0;
421
+ const isFull = options.mode === "full";
422
+ const phases = selectActivePhases(
423
+ (r) => r,
424
+ PHASE_ORDER,
425
+ this.settings.resources
426
+ );
427
+ return paginateChunked({
428
+ phases,
429
+ cursor,
430
+ signal,
431
+ logger: this.logger,
432
+ pipeline: true,
433
+ maxChunkMs: CHUNK_BUDGET_MS,
434
+ fetchPage: async (phase, page, sig) => {
435
+ switch (phase) {
436
+ case "products":
437
+ return this.fetchProductsPage(page, options, sig);
438
+ case "customers":
439
+ return this.fetchCustomersPage(page, options, sig);
440
+ case "orders":
441
+ return this.fetchOrdersPage(page, options, sig);
442
+ }
443
+ },
444
+ writeBatch: async (phase, items, page) => {
445
+ if (isFull && page === null) {
446
+ switch (phase) {
447
+ case "products":
448
+ await storage.entities([], { types: ["shopify_product"] });
449
+ break;
450
+ case "customers":
451
+ await storage.entities([], { types: ["shopify_customer"] });
452
+ break;
453
+ case "orders":
454
+ await storage.entities([], { types: ["shopify_order"] });
455
+ await storage.events([], { names: ["shopify_refund"] });
456
+ break;
457
+ }
458
+ }
459
+ switch (phase) {
460
+ case "products":
461
+ return this.writeProducts(storage, items);
462
+ case "customers":
463
+ return this.writeCustomers(storage, items);
464
+ case "orders":
465
+ return this.writeOrders(storage, items);
466
+ }
467
+ }
468
+ });
469
+ }
470
+ };
471
+
472
+ // src/index.ts
473
+ var index_default = ShopifyConnector;
474
+ export {
475
+ ShopifyConnector,
476
+ configFields,
477
+ index_default as default,
478
+ doc,
479
+ id,
480
+ shopifyResources as resources
481
+ };
482
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/shopify.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 async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\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\nconst API_VERSION = '2025-01';\n\nexport const configFields = defineConfigFields(\n z.object({\n shopDomain: z\n .string()\n .min(1)\n .regex(\n /^[a-z0-9][a-z0-9-]*\\.myshopify\\.com$/i,\n 'Must be a myshopify.com domain, e.g. yourshop.myshopify.com',\n )\n .meta({\n label: 'Shop domain',\n description:\n 'Your store myshopify.com domain, without protocol, e.g. yourshop.myshopify.com.',\n placeholder: 'yourshop.myshopify.com',\n }),\n accessToken: z.object({ $secret: z.string() }).meta({\n label: 'Admin API access token',\n description:\n 'Custom App Admin API access token with read_orders, read_customers, and read_products scopes.',\n placeholder: 'shpat_...',\n secret: true,\n }),\n resources: z\n .array(z.enum(['products', 'customers', 'orders']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Shopify resources to sync. Omit to sync all resources. The `orders` phase also emits a refund event for each refund attached to an order.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Shopify',\n category: 'sales',\n brandColor: '#7AB55C',\n tagline:\n 'Sync orders, customers, products, and refund events from a Shopify store via the Admin GraphQL API.',\n vendor: {\n name: 'Shopify',\n domain: 'shopify.com',\n apiDocs: 'https://shopify.dev/docs/api/admin-graphql',\n website: 'https://www.shopify.com',\n },\n auth: {\n summary:\n 'A Custom App Admin API access token authenticates every GraphQL request. The token scopes the sync to the store it was created in and the read scopes granted to the app.',\n setup: [\n 'In the Shopify admin, open Settings -> Apps and sales channels -> Develop apps.',\n 'Create a new app (or open an existing custom app) and open the Configuration tab.',\n 'Under Admin API integration, grant the read_orders, read_customers, and read_products scopes and save.',\n 'Open the API credentials tab and install the app to reveal the Admin API access token (starts with shpat_).',\n 'Store the token as a secret and reference it from the connector config as `accessToken: secret(\"SHOPIFY_ACCESS_TOKEN\")`, and set `shopDomain` to your yourshop.myshopify.com domain.',\n ],\n },\n rateLimit:\n 'The Admin GraphQL API uses a cost-based leaky-bucket limit per access token; this connector pages 250 records at a time and relies on standard HTTP 429 retry/backoff.',\n limitations: [\n 'Custom App access token auth only (OAuth app distribution not supported).',\n 'Order status-transition history and inventory-level resources are out of scope; refund events are derived from each order.',\n ],\n});\n\nexport interface ShopifySettings {\n shopDomain: string;\n resources?: readonly ShopifyResource[];\n}\n\nconst shopifyCredentials = {\n accessToken: {\n description: 'Shopify Admin API access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype ShopifyCredentials = typeof shopifyCredentials;\n\nconst PHASE_ORDER = ['products', 'customers', 'orders'] as const;\n\ntype ShopifyPhase = (typeof PHASE_ORDER)[number];\n\nexport type ShopifyResource = ShopifyPhase;\n\nconst isShopifySyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ninterface PageInfo {\n hasNextPage: boolean;\n endCursor: string | null;\n}\n\ninterface Connection<T> {\n nodes: T[];\n pageInfo: PageInfo;\n}\n\ninterface MoneyV2 {\n amount: string;\n currencyCode: string;\n}\n\ninterface MoneyBag {\n shopMoney: MoneyV2;\n}\n\ninterface ShopifyProduct {\n id: string;\n title: string;\n vendor: string;\n status: string;\n totalInventory: number | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface ShopifyCustomer {\n id: string;\n defaultEmailAddress: { emailAddress: string | null } | null;\n numberOfOrders: string;\n amountSpent: MoneyV2;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface ShopifyRefund {\n id: string;\n createdAt: string | null;\n totalRefundedSet: MoneyBag;\n}\n\ninterface ShopifyOrder {\n id: string;\n name: string;\n currentTotalPriceSet: MoneyBag;\n displayFinancialStatus: string | null;\n displayFulfillmentStatus: string;\n customer: { id: string } | null;\n createdAt: string;\n processedAt: string;\n cancelledAt: string | null;\n updatedAt: string;\n refunds: ShopifyRefund[];\n}\n\ninterface GraphQLError {\n message: string;\n extensions?: { code?: string };\n}\n\ninterface GraphQLResponse<T> {\n data?: T;\n errors?: GraphQLError[];\n}\n\nconst PRODUCTS_QUERY = `\n query Products($cursor: String, $first: Int!, $query: String) {\n products(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {\n nodes { id title vendor status totalInventory createdAt updatedAt }\n pageInfo { hasNextPage endCursor }\n }\n }\n`;\n\nconst CUSTOMERS_QUERY = `\n query Customers($cursor: String, $first: Int!, $query: String) {\n customers(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {\n nodes {\n id\n defaultEmailAddress { emailAddress }\n numberOfOrders\n amountSpent { amount currencyCode }\n createdAt updatedAt\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n`;\n\nconst ORDERS_QUERY = `\n query Orders($cursor: String, $first: Int!, $query: String) {\n orders(after: $cursor, first: $first, query: $query, sortKey: UPDATED_AT) {\n nodes {\n id name\n currentTotalPriceSet { shopMoney { amount currencyCode } }\n displayFinancialStatus displayFulfillmentStatus\n customer { id }\n createdAt processedAt cancelledAt updatedAt\n refunds {\n id createdAt\n totalRefundedSet { shopMoney { amount currencyCode } }\n }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n`;\n\nconst MAX_PAGE_SIZE = 250;\nconst DEFAULT_PAGE_SIZE = 250;\nconst CHUNK_BUDGET_MS = 25_000;\n\nfunction clampPageSize(requested: number | undefined): number {\n const n = requested ?? DEFAULT_PAGE_SIZE;\n if (!Number.isFinite(n) || n < 1) {\n return 1;\n }\n return Math.min(Math.floor(n), MAX_PAGE_SIZE);\n}\n\nfunction parseMoney(amount: string | null | undefined): number | null {\n if (amount == null) {\n return null;\n }\n const n = Number(amount);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction parseCount(value: string | null | undefined): number | null {\n if (value == null) {\n return null;\n }\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nconst idString = z.string().min(1);\nconst moneyV2Schema = z.object({\n amount: z.string(),\n currencyCode: z.string(),\n});\nconst moneyBagSchema = z.object({ shopMoney: moneyV2Schema });\n\nconst productSchema = z.object({\n id: idString,\n title: z.string(),\n vendor: z.string(),\n status: z.string(),\n totalInventory: z.number().nullable(),\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n});\n\nconst customerSchema = z.object({\n id: idString,\n defaultEmailAddress: z\n .object({ emailAddress: z.string().nullable() })\n .nullable(),\n numberOfOrders: z.string(),\n amountSpent: moneyV2Schema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n});\n\nconst refundSchema = z.object({\n id: idString,\n createdAt: z.iso.datetime().nullable(),\n totalRefundedSet: moneyBagSchema,\n});\n\nconst orderSchema = z.object({\n id: idString,\n name: z.string(),\n currentTotalPriceSet: moneyBagSchema,\n displayFinancialStatus: z.string().nullable(),\n displayFulfillmentStatus: z.string(),\n customer: z.object({ id: idString }).nullable(),\n createdAt: z.iso.datetime(),\n processedAt: z.iso.datetime(),\n cancelledAt: z.iso.datetime().nullable(),\n updatedAt: z.iso.datetime(),\n refunds: z.array(refundSchema),\n});\n\nexport const shopifyResources = defineResources({\n shopify_product: {\n shape: 'entity',\n filterable: [\n {\n field: 'status',\n ops: ['eq'],\n values: ['ACTIVE', 'ARCHIVED', 'DRAFT'],\n },\n { field: 'vendor', ops: ['eq'] },\n ],\n description:\n 'Store products with their title, vendor, status, and total inventory.',\n endpoint: 'GraphQL query: products { nodes { ... } }',\n responses: { products: z.array(productSchema) },\n },\n shopify_customer: {\n shape: 'entity',\n filterable: [],\n description:\n 'Store customers with their email, lifetime order count, and total amount spent.',\n endpoint: 'GraphQL query: customers { nodes { ... } }',\n responses: { customers: z.array(customerSchema) },\n },\n shopify_order: {\n shape: 'entity',\n filterable: [\n {\n field: 'financialStatus',\n ops: ['eq'],\n values: [\n 'PENDING',\n 'AUTHORIZED',\n 'PARTIALLY_PAID',\n 'PAID',\n 'PARTIALLY_REFUNDED',\n 'REFUNDED',\n 'VOIDED',\n ],\n },\n {\n field: 'fulfillmentStatus',\n ops: ['eq'],\n values: [\n 'FULFILLED',\n 'IN_PROGRESS',\n 'ON_HOLD',\n 'OPEN',\n 'PARTIALLY_FULFILLED',\n 'PENDING_FULFILLMENT',\n 'RESTOCKED',\n 'SCHEDULED',\n 'UNFULFILLED',\n ],\n },\n ],\n description:\n 'Orders with their total price, currency, financial and fulfillment status, customer, and lifecycle timestamps.',\n endpoint: 'GraphQL query: orders { nodes { ... } }',\n responses: { orders: z.array(orderSchema) },\n },\n shopify_refund: {\n shape: 'event',\n filterable: [],\n description:\n 'Refund events derived from each order, carrying the refunded amount and currency.',\n endpoint: 'GraphQL query: orders { nodes { refunds { ... } } }',\n notes:\n 'Derived from the `refunds` list on each synced order. Each refund becomes one append-only event keyed by its refund id; refunds attached to orders outside the current incremental window are not revisited.',\n },\n});\n\nexport const id = 'shopify';\n\nexport class ShopifyConnector extends BaseConnector<\n ShopifySettings,\n ShopifyCredentials\n> {\n static readonly id = id;\n\n static readonly resources = shopifyResources;\n\n static readonly schemas = schemasFromResources(shopifyResources);\n\n static create(input: unknown, ctx?: ConnectorContext): ShopifyConnector {\n const parsed = configFields.parse(input);\n return new ShopifyConnector(\n { shopDomain: parsed.shopDomain, resources: parsed.resources },\n { accessToken: parsed.accessToken },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = shopifyCredentials;\n\n private endpoint(): string {\n return `https://${this.settings.shopDomain}/admin/api/${API_VERSION}/graphql.json`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n 'X-Shopify-Access-Token': this.creds.accessToken,\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('shopify'),\n };\n }\n\n private async graphql<T>(\n query: string,\n variables: Record<string, unknown>,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<GraphQLResponse<T>>> {\n const res = await this.post<GraphQLResponse<T>>(this.endpoint(), {\n resource,\n headers: this.buildHeaders(),\n body: JSON.stringify({ query, variables }),\n signal,\n });\n if (res.body.errors && res.body.errors.length > 0) {\n const messages = res.body.errors.map((e) => e.message).join('; ');\n throw new Error(`Shopify GraphQL error: ${messages}`);\n }\n if (!res.body.data) {\n throw new Error(\n `Shopify GraphQL response missing data for resource '${resource}'`,\n );\n }\n return res;\n }\n\n private sinceQuery(options: SyncOptions): string | undefined {\n if (!options.since) {\n return undefined;\n }\n return `updated_at:>'${options.since}'`;\n }\n\n private async fetchProductsPage(\n page: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<{ items: ShopifyProduct[]; next: string | null }> {\n const res = await this.graphql<{ products: Connection<ShopifyProduct> }>(\n PRODUCTS_QUERY,\n {\n cursor: page ?? null,\n first: clampPageSize(options.pageSize),\n query: this.sinceQuery(options) ?? null,\n },\n 'products',\n signal,\n );\n const conn = res.body.data!.products;\n return {\n items: conn.nodes,\n next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null,\n };\n }\n\n private async fetchCustomersPage(\n page: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<{ items: ShopifyCustomer[]; next: string | null }> {\n const res = await this.graphql<{ customers: Connection<ShopifyCustomer> }>(\n CUSTOMERS_QUERY,\n {\n cursor: page ?? null,\n first: clampPageSize(options.pageSize),\n query: this.sinceQuery(options) ?? null,\n },\n 'customers',\n signal,\n );\n const conn = res.body.data!.customers;\n return {\n items: conn.nodes,\n next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null,\n };\n }\n\n private async fetchOrdersPage(\n page: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<{ items: ShopifyOrder[]; next: string | null }> {\n const res = await this.graphql<{ orders: Connection<ShopifyOrder> }>(\n ORDERS_QUERY,\n {\n cursor: page ?? null,\n first: clampPageSize(options.pageSize),\n query: this.sinceQuery(options) ?? null,\n },\n 'orders',\n signal,\n );\n const conn = res.body.data!.orders;\n return {\n items: conn.nodes,\n next: conn.pageInfo.hasNextPage ? conn.pageInfo.endCursor : null,\n };\n }\n\n private async writeProducts(\n storage: StorageHandle,\n products: ShopifyProduct[],\n ): Promise<void> {\n for (const p of products) {\n await storage.entity({\n type: 'shopify_product',\n id: p.id,\n attributes: {\n title: p.title,\n vendor: p.vendor,\n status: p.status,\n totalInventory: p.totalInventory,\n createdAt: new Date(p.createdAt).getTime(),\n },\n updated_at: new Date(p.updatedAt).getTime(),\n });\n }\n }\n\n private async writeCustomers(\n storage: StorageHandle,\n customers: ShopifyCustomer[],\n ): Promise<void> {\n for (const c of customers) {\n await storage.entity({\n type: 'shopify_customer',\n id: c.id,\n attributes: {\n email: c.defaultEmailAddress?.emailAddress ?? null,\n ordersCount: parseCount(c.numberOfOrders),\n totalSpent: parseMoney(c.amountSpent.amount),\n currency: c.amountSpent.currencyCode,\n createdAt: new Date(c.createdAt).getTime(),\n },\n updated_at: new Date(c.updatedAt).getTime(),\n });\n }\n }\n\n private async writeOrders(\n storage: StorageHandle,\n orders: ShopifyOrder[],\n ): Promise<void> {\n for (const o of orders) {\n const money = o.currentTotalPriceSet.shopMoney;\n await storage.entity({\n type: 'shopify_order',\n id: o.id,\n attributes: {\n name: o.name,\n totalPrice: parseMoney(money.amount),\n currency: money.currencyCode,\n financialStatus: o.displayFinancialStatus,\n fulfillmentStatus: o.displayFulfillmentStatus,\n customerId: o.customer?.id ?? null,\n createdAt: new Date(o.createdAt).getTime(),\n processedAt: new Date(o.processedAt).getTime(),\n cancelledAt: o.cancelledAt ? new Date(o.cancelledAt).getTime() : null,\n },\n updated_at: new Date(o.updatedAt).getTime(),\n });\n\n for (const r of o.refunds) {\n const refundMoney = r.totalRefundedSet.shopMoney;\n const refundTs = r.createdAt\n ? new Date(r.createdAt).getTime()\n : new Date(o.updatedAt).getTime();\n await storage.event({\n name: 'shopify_refund',\n start_ts: refundTs,\n end_ts: null,\n attributes: {\n refundId: r.id,\n orderId: o.id,\n orderName: o.name,\n customerId: o.customer?.id ?? null,\n amount: parseMoney(refundMoney.amount),\n currency: refundMoney.currencyCode,\n },\n });\n }\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isShopifySyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<ShopifyResource, ShopifyPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<ShopifyPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n pipeline: true,\n maxChunkMs: CHUNK_BUDGET_MS,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'products':\n return this.fetchProductsPage(page, options, sig);\n case 'customers':\n return this.fetchCustomersPage(page, options, sig);\n case 'orders':\n return this.fetchOrdersPage(page, options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'products':\n await storage.entities([], { types: ['shopify_product'] });\n break;\n case 'customers':\n await storage.entities([], { types: ['shopify_customer'] });\n break;\n case 'orders':\n await storage.entities([], { types: ['shopify_order'] });\n await storage.events([], { names: ['shopify_refund'] });\n break;\n }\n }\n switch (phase) {\n case 'products':\n return this.writeProducts(storage, items as ShopifyProduct[]);\n case 'customers':\n return this.writeCustomers(storage, items as ShopifyCustomer[]);\n case 'orders':\n return this.writeOrders(storage, items as ShopifyOrder[]);\n }\n },\n });\n }\n}\n","import { ShopifyConnector } from './shopify';\n\nexport {\n configFields,\n doc,\n id,\n ShopifyConnector,\n shopifyResources as resources,\n} from './shopify';\nexport type { ShopifySettings, ShopifyResource } from './shopify';\nexport default ShopifyConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;;;AQFA;AAAA,EACE;AAAA,EAOA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAElB,IAAM,cAAc;AAEb,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,YAAY,EACT,OAAO,EACP,IAAI,CAAC,EACL;AAAA,MACC;AAAA,MACA;AAAA,IACF,EACC,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACH,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAClD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,WAAW,EACR,MAAM,EAAE,KAAK,CAAC,YAAY,aAAa,QAAQ,CAAC,CAAC,EACjD,SAAS,EACT,SAAS,EACT,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,IACJ,CAAC;AAAA,EACL,CAAC;AACH;AAEO,IAAM,MAAoB,mBAAmB;AAAA,EAClD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,SACE;AAAA,EACF,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,SACE;AAAA,IACF,OAAO;AAAA,MACL;AAAA,MAC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GAAG;AAAA,UACnD,KAAK;AACH,mBAAO,KAAK,gBAAgB,MAAM,SAAS,GAAG;AAAA,QAClD;AAAA,MACF;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,UAAU,SAAS,MAAM;AAC3B,kBAAQ,OAAO;AAAA,YACb,KAAK;AACH,oBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC;AACzD;AAAA,YACF,KAAK;AACH,oBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,kBAAkB,EAAE,CAAC;AAC1D;AAAA,YACF,KAAK;AACH,oBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,eAAe,EAAE,CAAC;AACvD,oBAAM,QAAQ,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAAC;AACtD;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK,cAAc,SAAS,KAAyB;AAAA,UAC9D,KAAK;AACH,mBAAO,KAAK,eAAe,SAAS,KAA0B;AAAA,UAChE,KAAK;AACH,mBAAO,KAAK,YAAY,SAAS,KAAuB;AAAA,QAC5D;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC7nBA,IAAO,gBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@rawdash/connector-shopify",
3
+ "version": "0.0.1",
4
+ "description": "Rawdash connector for Shopify — orders, customers, products, and refund events",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/rawdash/rawdash.git",
11
+ "directory": "packages/connectors/shopify"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "@rawdash/source": "./src/index.ts",
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "scripts": {
26
+ "build": "tsup",
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "eslint src",
29
+ "test": "vitest run"
30
+ },
31
+ "dependencies": {
32
+ "@rawdash/core": "workspace:*",
33
+ "zod": "^4.4.3"
34
+ },
35
+ "devDependencies": {
36
+ "@rawdash/connector-shared": "workspace:*",
37
+ "@rawdash/connector-test-utils": "workspace:*",
38
+ "fast-check": "^4.8.0",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.7.2",
41
+ "vitest": "^4.1.4"
42
+ }
43
+ }