UNPKG

@agnostack/next-shopify

Version:

Please contact agnoStack via info@agnostack.com for any questions

110 lines 6.39 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleWebhookEvent = void 0; const verifyd_1 = require("@agnostack/verifyd"); const utils_1 = require("../../utils"); const shared_1 = require("../../../shared"); // NOTE: typically handling: "/api/webhooks/event" or "/api/webhooks/event/{appId}" or "/api/webhooks/event?appId={appId}" const handleWebhookEvent = (serverRuntimeConfig, data) => { const { ORIGIN_SAFELIST, WEBHOOK_TOPIC_BLOCKLIST } = serverRuntimeConfig; const _a = data !== null && data !== void 0 ? data : {}, { returnResponse = true } = _a, config = __rest(_a, ["returnResponse"]); return (req, res, data) => __awaiter(void 0, void 0, void 0, function* () { var _b; const handleResponse = (body, statusCode = 200) => { if (returnResponse) { return res.status(statusCode).json(body); } return { statusCode, body }; }; try { const _c = (_b = req.headers) !== null && _b !== void 0 ? _b : {}, { 'x-shop-domain': shopDomain, 'x-shopify-shop-domain': shopifyShopDomain, 'x-shopify-shop': shop = shopifyShopDomain !== null && shopifyShopDomain !== void 0 ? shopifyShopDomain : shopDomain } = _c, _headers = __rest(_c, ['x-shop-domain', 'x-shopify-shop-domain', 'x-shopify-shop']); if ((0, shared_1.stringEmpty)(shop)) { return handleResponse({ handler: 'webhook', error: 'Missing shop' }); } if (!(0, shared_1.matchHostname)(shop, ORIGIN_SAFELIST)) { return handleResponse({ handler: 'webhook', error: 'Shop is not safelisted' }); } const { shopify } = yield (0, utils_1.getShopifyHelpers)(serverRuntimeConfig, { shop }); // TODO: explore getVerificationHelpers? const rawBody = yield (0, verifyd_1.ensureRawBody)(req); const _d = (serverRuntimeConfig.SHOPIFY_RUN_MODE === 'cli') ? { valid: true, topic: _headers['x-shopify-topic'], domain: _headers['x-shopify-shop-domain'] || shop, webhookId: _headers['x-shopify-webhook-id'], apiVersion: _headers['x-shopify-api-version'], } : (yield shopify.webhooks.validate({ rawBody, rawRequest: req, rawResponse: res, })), { valid } = _d, message = __rest(_d, ["valid"]); if (!valid) { console.warn('Unable to validate webhook', message); return handleResponse({ handler: 'webhook', error: 'Unable to validate webhook', message }); } try { const { topic, domain, webhookId, apiVersion } = message; const eventType = (0, shared_1.convertEventTopic)(topic); const eventShop = domain || shop; if (!shared_1.API_WEBHOOK_TOPICS_IMMUTABLE.includes(eventType) && ((0, shared_1.stringEmpty)(eventShop) || ((WEBHOOK_TOPIC_BLOCKLIST === 'ALL') || (0, shared_1.splitCommas)(WEBHOOK_TOPIC_BLOCKLIST).includes(eventShop)))) { return handleResponse({ handler: 'webhook', message: 'blocked' }); } const eventBody = (0, shared_1.safeParse)(rawBody); // NOTE: this callback signature matches the built in callback option PLUS data const topicHandlePromises = (0, shared_1.ensureArray)(config === null || config === void 0 ? void 0 : config[eventType]).map((handler) => (handler === null || handler === void 0 ? void 0 : handler({ apiVersion, webhookId, eventType, topic, data, shop: eventShop, body: eventBody, }))); const registrationHandlePromises = shopify.webhooks.getHandlers(topic).reduce((_registrationHandlePromises, handler) => { if (!handler.callback) { return _registrationHandlePromises; } return [ ..._registrationHandlePromises, // NOTE: this callback signature matches the built in callback option PLUS data handler.callback(topic, domain || shop, eventBody, webhookId, apiVersion, data) ]; }, []); yield Promise.all([...topicHandlePromises, ...registrationHandlePromises]); return handleResponse({ handler: 'webhook', message: 'success' }); } catch (error) { console.error('Error handling webhook promises', error); return handleResponse({ handler: 'webhook', error: error === null || error === void 0 ? void 0 : error.message }); } } catch (error) { console.error('Error handling webhook', error); return handleResponse({ handler: 'webhook', error: 'Error handling webhook' }); } }); }; exports.handleWebhookEvent = handleWebhookEvent; //# sourceMappingURL=webhook.js.map