@porulle/adapter-shopify 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 unified-commerce-engine contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @porulle/adapter-shopify
2
+
3
+ Shopify ingress channel connector for Porulle.
@@ -0,0 +1,11 @@
1
+ import type { ChannelConnector } from "@porulle/core";
2
+ export interface ShopifyConnectorOptions {
3
+ fetchImpl?: typeof fetch;
4
+ apiVersion?: string;
5
+ clientId?: string;
6
+ clientSecret?: string;
7
+ appUrl?: string;
8
+ scopes?: string[];
9
+ }
10
+ export declare const REQUIRED_SCOPES: readonly ["read_products", "read_inventory", "read_orders", "write_orders", "read_fulfillments"];
11
+ export declare function shopifyConnector(options?: ShopifyConnectorOptions): ChannelConnector;
package/dist/index.js ADDED
@@ -0,0 +1,260 @@
1
+ import { defineChannelConnector, Err, Ok } from "@porulle/core";
2
+ import { createHmac, timingSafeEqual } from "node:crypto";
3
+ export const REQUIRED_SCOPES = [
4
+ "read_products",
5
+ "read_inventory",
6
+ "read_orders",
7
+ "write_orders",
8
+ "read_fulfillments",
9
+ ];
10
+ function parseMoney(value) {
11
+ if (!value)
12
+ return 0;
13
+ const parsed = Number.parseFloat(value);
14
+ return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
15
+ }
16
+ function apiBase(store, version) {
17
+ return `https://${store.storeDomain.replace(/^https?:\/\//, "").replace(/\/$/, "")}/admin/api/${version}`;
18
+ }
19
+ async function request(fetchImpl, url, accessToken, init) {
20
+ try {
21
+ const response = await fetchImpl(url, {
22
+ ...init,
23
+ headers: { accept: "application/json", ...(init?.headers ?? {}), "x-shopify-access-token": accessToken },
24
+ });
25
+ if (!response.ok)
26
+ return Err({ code: "SHOPIFY_API_FAILED", message: `Shopify API request failed (${response.status}) for ${url}.`, retriable: response.status >= 500 });
27
+ return Ok({ data: await response.json(), response });
28
+ }
29
+ catch (error) {
30
+ return Err({ code: "SHOPIFY_API_FAILED", message: error instanceof Error ? error.message : "Shopify API request failed.", retriable: true });
31
+ }
32
+ }
33
+ function shopifyStatus(order) {
34
+ if (order.cancelled_at)
35
+ return { status: "cancelled" };
36
+ if (order.fulfillment_status === "fulfilled")
37
+ return { status: "fulfilled" };
38
+ if (order.financial_status === "paid" || order.financial_status === "partially_paid")
39
+ return { status: "confirmed" };
40
+ if (order.financial_status === "refunded" || order.financial_status === "voided")
41
+ return { status: "failed" };
42
+ return { status: "pending" };
43
+ }
44
+ function credentials(store) {
45
+ const accessToken = store.credentials.accessToken;
46
+ return typeof accessToken === "string" && accessToken.length > 0 ? accessToken : undefined;
47
+ }
48
+ function validBase64Hmac(secret, body, signature) {
49
+ if (!signature)
50
+ return false;
51
+ const expected = createHmac("sha256", secret).update(body).digest();
52
+ const actual = Buffer.from(signature, "base64");
53
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
54
+ }
55
+ function validShopDomain(value) {
56
+ return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.myshopify\.com$/i.test(value);
57
+ }
58
+ function oauthHmacMessage(searchParams) {
59
+ return [...searchParams.entries()]
60
+ .filter(([key]) => key !== "hmac")
61
+ .sort(([left], [right]) => left.localeCompare(right))
62
+ .map(([key, value]) => `${key}=${value}`)
63
+ .join("&");
64
+ }
65
+ function validOAuthHmac(searchParams, secret) {
66
+ const provided = searchParams.get("hmac");
67
+ if (!provided || !/^[a-f0-9]+$/i.test(provided))
68
+ return false;
69
+ const expected = createHmac("sha256", secret).update(oauthHmacMessage(searchParams)).digest();
70
+ const actual = Buffer.from(provided, "hex");
71
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
72
+ }
73
+ function oauthError(code, message) {
74
+ return Err({ code, message, retriable: false });
75
+ }
76
+ export function shopifyConnector(options = {}) {
77
+ const fetchImpl = options.fetchImpl ?? fetch;
78
+ const version = options.apiVersion ?? "2024-10";
79
+ return defineChannelConnector({
80
+ providerId: "shopify",
81
+ capabilities: { importCatalog: true, importInventory: true, pushOrder: true, receiveWebhooks: true },
82
+ buildAuthUrl(params) {
83
+ if (!options.clientId || !options.clientSecret || !options.appUrl) {
84
+ return oauthError("SHOPIFY_OAUTH_NOT_CONFIGURED", "Shopify OAuth requires clientId, clientSecret, and appUrl.");
85
+ }
86
+ const shopDomain = params.storeDomain.toLowerCase();
87
+ if (!validShopDomain(shopDomain))
88
+ return oauthError("SHOPIFY_INVALID_STORE_DOMAIN", "Shopify storeDomain must be a *.myshopify.com domain.");
89
+ const scopes = [...new Set([...REQUIRED_SCOPES, ...(options.scopes ?? []), ...params.scopes])];
90
+ const url = new URL(`https://${shopDomain}/admin/oauth/authorize`);
91
+ url.searchParams.set("client_id", options.clientId);
92
+ url.searchParams.set("scope", scopes.join(","));
93
+ url.searchParams.set("redirect_uri", params.redirectUri);
94
+ url.searchParams.set("state", params.state);
95
+ return Ok(url.toString());
96
+ },
97
+ async completeAuth(request, ctx) {
98
+ if (!options.clientId || !options.clientSecret || !options.appUrl) {
99
+ return oauthError("SHOPIFY_OAUTH_NOT_CONFIGURED", "Shopify OAuth requires clientId, clientSecret, and appUrl.");
100
+ }
101
+ const url = new URL(request.url);
102
+ const shopDomain = ctx.storeDomain.toLowerCase();
103
+ const callbackShop = url.searchParams.get("shop")?.toLowerCase();
104
+ if (!validShopDomain(shopDomain) || callbackShop !== shopDomain) {
105
+ return oauthError("SHOPIFY_INVALID_STORE_DOMAIN", "Shopify storeDomain must be a *.myshopify.com domain.");
106
+ }
107
+ if (!validOAuthHmac(url.searchParams, options.clientSecret)) {
108
+ return oauthError("SHOPIFY_INVALID_OAUTH_HMAC", "Shopify OAuth callback HMAC is invalid.");
109
+ }
110
+ const timestamp = Number(url.searchParams.get("timestamp"));
111
+ if (!Number.isInteger(timestamp) || Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 300) {
112
+ return oauthError("SHOPIFY_STALE_OAUTH_CALLBACK", "Shopify OAuth callback timestamp is stale.");
113
+ }
114
+ const code = url.searchParams.get("code");
115
+ if (!code)
116
+ return oauthError("SHOPIFY_OAUTH_CODE_REQUIRED", "Shopify OAuth callback code is required.");
117
+ try {
118
+ const response = await fetchImpl(`https://${shopDomain}/admin/oauth/access_token`, {
119
+ method: "POST",
120
+ headers: { accept: "application/json", "content-type": "application/json" },
121
+ body: JSON.stringify({ client_id: options.clientId, client_secret: options.clientSecret, code }),
122
+ });
123
+ if (!response.ok)
124
+ return oauthError("SHOPIFY_TOKEN_EXCHANGE_FAILED", `Shopify token exchange failed (${response.status}).`);
125
+ const body = await response.json();
126
+ if (typeof body.access_token !== "string" || !body.access_token)
127
+ return oauthError("SHOPIFY_TOKEN_INVALID", "Shopify token exchange did not return an access token.");
128
+ return Ok({ credentials: { accessToken: body.access_token }, storeDomain: shopDomain });
129
+ }
130
+ catch (error) {
131
+ return Err({ code: "SHOPIFY_TOKEN_EXCHANGE_FAILED", message: error instanceof Error ? error.message : "Shopify token exchange failed.", retriable: true });
132
+ }
133
+ },
134
+ async importCatalog(store, cursor) {
135
+ const token = credentials(store);
136
+ if (!token)
137
+ return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
138
+ const url = cursor ?? `${apiBase(store, version)}/products.json?limit=250`;
139
+ const result = await request(fetchImpl, url, token);
140
+ if (!result.ok)
141
+ return result;
142
+ const link = result.value.response.headers.get("link") ?? "";
143
+ const next = link.match(/<([^>]+)>;\s*rel="next"/)?.[1] ?? null;
144
+ return Ok({
145
+ items: result.value.data.products.map((product) => ({
146
+ externalId: String(product.id),
147
+ slug: product.handle ?? String(product.id),
148
+ title: product.title,
149
+ ...(product.body_html ? { description: product.body_html } : {}),
150
+ variants: (product.variants ?? []).map((variant) => ({
151
+ externalId: String(variant.id),
152
+ ...(variant.sku ? { sku: variant.sku } : {}),
153
+ ...(variant.barcode ? { barcode: variant.barcode } : {}),
154
+ metadata: { price: parseMoney(variant.price) },
155
+ })),
156
+ })),
157
+ nextCursor: next,
158
+ });
159
+ },
160
+ async fetchInventory(store, ids) {
161
+ const token = credentials(store);
162
+ if (!token)
163
+ return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
164
+ const params = new URLSearchParams({ limit: "250" });
165
+ if (ids?.length)
166
+ params.set("inventory_item_ids", ids.join(","));
167
+ const result = await request(fetchImpl, `${apiBase(store, version)}/inventory_levels.json?${params}`, token);
168
+ if (!result.ok)
169
+ return result;
170
+ return Ok(result.value.data.inventory_levels.map((level) => ({ externalId: String(level.inventory_item_id), available: level.available ?? 0 })));
171
+ },
172
+ async pushOrder(store, slice) {
173
+ const token = credentials(store);
174
+ if (!token)
175
+ return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required.", retriable: false });
176
+ const [firstName, ...lastParts] = slice.customer.name.trim().split(/\s+/);
177
+ const result = await request(fetchImpl, `${apiBase(store, version)}/orders.json`, token, {
178
+ method: "POST",
179
+ headers: { "content-type": "application/json", "idempotency-key": `porulle:${slice.orderId}` },
180
+ body: JSON.stringify({ order: {
181
+ financial_status: "paid",
182
+ line_items: slice.lines.map((line) => ({ variant_id: line.externalVariantId, quantity: line.quantity, price: line.unitPrice / 100 })),
183
+ customer: { email: slice.customer.email, first_name: firstName ?? "", last_name: lastParts.join(" ") },
184
+ shipping_address: slice.customer.shippingAddress,
185
+ transactions: [{ kind: "sale", status: "success", amount: slice.grandTotal / 100 }],
186
+ } }),
187
+ });
188
+ if (!result.ok)
189
+ return result;
190
+ const id = String(result.value.data.order.id);
191
+ return Ok({ remoteOrderId: id, remoteUrl: `${apiBase(store, version)}/orders/${id}.json` });
192
+ },
193
+ async fetchOrderStatus(store, remoteId) {
194
+ const token = credentials(store);
195
+ if (!token)
196
+ return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required.", retriable: false });
197
+ const result = await request(fetchImpl, `${apiBase(store, version)}/orders/${encodeURIComponent(remoteId)}.json`, token);
198
+ return result.ok ? Ok(shopifyStatus(result.value.data.order)) : result;
199
+ },
200
+ async verifyWebhook(_store, request) {
201
+ const body = await request.text();
202
+ // Shopify signs every webhook for an app with the app CLIENT SECRET — there is no
203
+ // per-store/per-subscription secret (unlike WooCommerce). Verify against clientSecret.
204
+ if (!options.clientSecret) {
205
+ return Err({ code: "SHOPIFY_CLIENT_SECRET_MISSING", message: "Shopify clientSecret is required to verify webhooks." });
206
+ }
207
+ if (!validBase64Hmac(options.clientSecret, body, request.headers.get("x-shopify-hmac-sha256"))) {
208
+ return Err({ code: "INVALID_WEBHOOK_SIGNATURE", message: "Invalid Shopify webhook signature." });
209
+ }
210
+ try {
211
+ const data = JSON.parse(body);
212
+ const id = request.headers.get("x-shopify-event-id");
213
+ const type = request.headers.get("x-shopify-topic");
214
+ if (!id || !type)
215
+ return Err({ code: "INVALID_WEBHOOK", message: "Shopify webhook headers are incomplete." });
216
+ return Ok({ id, type, data });
217
+ }
218
+ catch {
219
+ return Err({ code: "INVALID_WEBHOOK", message: "Shopify webhook body must be valid JSON." });
220
+ }
221
+ },
222
+ async verifyAppWebhook(request) {
223
+ if (!options.clientSecret) {
224
+ return Err({ code: "SHOPIFY_CLIENT_SECRET_MISSING", message: "Shopify clientSecret is required to verify app webhooks.", retriable: false });
225
+ }
226
+ const body = await request.text();
227
+ if (!validBase64Hmac(options.clientSecret, body, request.headers.get("x-shopify-hmac-sha256"))) {
228
+ return Err({ code: "INVALID_APP_WEBHOOK_SIGNATURE", message: "Invalid Shopify app webhook signature.", retriable: false });
229
+ }
230
+ try {
231
+ const data = JSON.parse(body);
232
+ const payload = data;
233
+ const topic = request.headers.get("x-shopify-topic");
234
+ const shopDomain = typeof payload.shop_domain === "string" ? payload.shop_domain : "";
235
+ if (!topic)
236
+ return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify app webhook topic header is missing.", retriable: false });
237
+ return Ok({ topic, shopDomain, data });
238
+ }
239
+ catch {
240
+ return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify app webhook body must be valid JSON.", retriable: false });
241
+ }
242
+ },
243
+ async registerWebhooks(store, topics, callbackUrl) {
244
+ const token = credentials(store);
245
+ if (!token)
246
+ return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
247
+ for (const topic of topics) {
248
+ const result = await request(fetchImpl, `${apiBase(store, version)}/webhooks.json`, token, {
249
+ method: "POST",
250
+ headers: { "content-type": "application/json" },
251
+ body: JSON.stringify({ webhook: { topic, address: callbackUrl, format: "json" } }),
252
+ });
253
+ if (!result.ok)
254
+ return result;
255
+ }
256
+ return Ok({ registered: topics.length });
257
+ },
258
+ async refundExecute() { return Err({ code: "NOT_IMPLEMENTED", message: "Shopify refund execution is not implemented in this slice." }); },
259
+ });
260
+ }