@aglyn/plugins-commerce 1.34.1 → 1.35.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.
Files changed (40) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/woo-connections-card.component.d.ts +52 -0
  3. package/src/lib/components/console/woo-connections-card.component.js +189 -0
  4. package/src/lib/components/console/woo-connections-card.component.js.map +1 -0
  5. package/src/lib/plugin.js +13 -1
  6. package/src/lib/plugin.js.map +1 -1
  7. package/src/lib/server/order-event-triggers.js +9 -0
  8. package/src/lib/server/order-event-triggers.js.map +1 -1
  9. package/src/lib/server/woo/woo-connections.d.ts +23 -0
  10. package/src/lib/server/woo/woo-connections.js +109 -0
  11. package/src/lib/server/woo/woo-connections.js.map +1 -0
  12. package/src/lib/server/woo/woo-context.d.ts +45 -0
  13. package/src/lib/server/woo/woo-context.js +36 -0
  14. package/src/lib/server/woo/woo-context.js.map +1 -0
  15. package/src/lib/server/woo/woo-ids.d.ts +45 -0
  16. package/src/lib/server/woo/woo-ids.js +141 -0
  17. package/src/lib/server/woo/woo-ids.js.map +1 -0
  18. package/src/lib/server/woo/woo-meta.d.ts +68 -0
  19. package/src/lib/server/woo/woo-meta.js +127 -0
  20. package/src/lib/server/woo/woo-meta.js.map +1 -0
  21. package/src/lib/server/woo/woo-orders.d.ts +136 -0
  22. package/src/lib/server/woo/woo-orders.js +378 -0
  23. package/src/lib/server/woo/woo-orders.js.map +1 -0
  24. package/src/lib/server/woo/woo-products.d.ts +19 -0
  25. package/src/lib/server/woo/woo-products.js +662 -0
  26. package/src/lib/server/woo/woo-products.js.map +1 -0
  27. package/src/lib/server/woo/woo-route.d.ts +49 -0
  28. package/src/lib/server/woo/woo-route.js +333 -0
  29. package/src/lib/server/woo/woo-route.js.map +1 -0
  30. package/src/lib/server/woo/woo-shapes.d.ts +421 -0
  31. package/src/lib/server/woo/woo-shapes.js +835 -0
  32. package/src/lib/server/woo/woo-shapes.js.map +1 -0
  33. package/src/lib/server/woo/woo-system.d.ts +35 -0
  34. package/src/lib/server/woo/woo-system.js +339 -0
  35. package/src/lib/server/woo/woo-system.js.map +1 -0
  36. package/src/lib/server/woo/woo-webhooks.d.ts +53 -0
  37. package/src/lib/server/woo/woo-webhooks.js +204 -0
  38. package/src/lib/server/woo/woo-webhooks.js.map +1 -0
  39. package/src/lib/server.js +15 -0
  40. package/src/lib/server.js.map +1 -1
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { PluginDomainEventEnvelope } from '@aglyn/aglyn/plugin-manager/plugin-domain-events';
18
+ import { fetchConfiguredPublicUrl } from '@aglyn/tenant-data-admin';
19
+ import { type StoredWebhook } from './woo-meta';
20
+ /** How long an app's receiver has to answer, as WooCommerce allows it. */
21
+ export declare const WOO_WEBHOOK_TIMEOUT_MS = 15000;
22
+ /** The WooCommerce topics one store event is delivered as. */
23
+ export declare function wooTopicsForEvent(event: string): string[];
24
+ /** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */
25
+ export declare function signWooWebhook(body: string, secret: string): string;
26
+ /** The headers WooCommerce sends with a delivery. */
27
+ export declare function wooWebhookHeaders(input: {
28
+ hook: Pick<StoredWebhook, 'id' | 'topic' | 'secret'>;
29
+ deliveryId: string;
30
+ source: string;
31
+ body: string;
32
+ }): Record<string, string>;
33
+ type Fetch = typeof fetchConfiguredPublicUrl;
34
+ /**
35
+ * The ping WooCommerce sends when a webhook is saved active: a form post of
36
+ * `webhook_id`, which some apps wait for before they count the hook as set
37
+ * up. Its answer is only logged.
38
+ */
39
+ export declare function pingWooWebhook(hook: StoredWebhook, source: string, fetchImpl?: Fetch): Promise<{
40
+ status: number | null;
41
+ error: string | null;
42
+ }>;
43
+ export interface WooWebhookDeps {
44
+ fetchImpl?: Fetch;
45
+ now?: () => number;
46
+ isLive?: (grantId: string, hostId: string) => Promise<boolean>;
47
+ }
48
+ /** The subscriber: delivers one store event to every live hook that takes it. */
49
+ export declare function deliverWooWebhooks(envelope: PluginDomainEventEnvelope, deps?: WooWebhookDeps): Promise<{
50
+ delivered: number;
51
+ failed: number;
52
+ }>;
53
+ export {};
@@ -0,0 +1,204 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /*==========================================
17
+ * WEBHOOKS, DELIVERED AS WOOCOMMERCE DELIVERS THEM.
18
+ *
19
+ * An app that links a store through its WooCommerce connector may register
20
+ * webhooks (`POST /wc/v3/webhooks`, `woo-system.ts`) rather than poll for
21
+ * orders. Commerce's own order events drive them, through the plugin event
22
+ * outbox like the merchant's order webhooks: a failed delivery throws, and
23
+ * the outbox retries it with its backoff; a hook that already took the event
24
+ * is not sent it again.
25
+ *
26
+ * - `order.paid` → `order.created` and `order.updated`. A store order
27
+ * exists for an app once it is paid: an unpaid checkout is never listed.
28
+ * - fulfilled, delivered, refunded, cancelled → `order.updated`.
29
+ *
30
+ * The body is the order exactly as `GET /wc/v3/orders/{id}` answers it. The
31
+ * headers are WooCommerce's: `X-WC-Webhook-Topic`, `-Resource`, `-Event`,
32
+ * `-ID`, `-Delivery-ID`, `-Source`, and `-Signature`, the base64 HMAC-SHA256
33
+ * of the body under the hook's secret. Each call goes through
34
+ * `fetchConfiguredPublicUrl` (https, public address, no redirect). A hook
35
+ * whose link has ended is skipped.
36
+ *=========================================*/ import { _ as _extends } from "@swc/helpers/_/_extends";
37
+ import { fetchConfiguredPublicUrl, firebaseAdmin, wooConnectionIsLive } from "@aglyn/tenant-data-admin";
38
+ import { PLUGIN_EVENT_MAX_ATTEMPTS } from "@aglyn/tenant-data-admin/server/plugin-event-outbox";
39
+ import { createHmac } from "node:crypto";
40
+ import { shapeStoreOrders } from "./woo-orders.js";
41
+ import { readWebhooks } from "./woo-meta.js";
42
+ import { WOO_REPORTED_VERSION, WP_REPORTED_VERSION } from "./woo-shapes.js";
43
+ /** How long an app's receiver has to answer, as WooCommerce allows it. */ export const WOO_WEBHOOK_TIMEOUT_MS = 15000;
44
+ const DELIVERY_LOG_TTL_MS = 30 * 86400000;
45
+ /** The WooCommerce topics one store event is delivered as. */ export function wooTopicsForEvent(event) {
46
+ if (event === 'order.paid') return [
47
+ 'order.created',
48
+ 'order.updated'
49
+ ];
50
+ if (event === 'order.fulfilled' || event === 'order.delivered' || event === 'order.refunded' || event === 'order.cancelled') {
51
+ return [
52
+ 'order.updated'
53
+ ];
54
+ }
55
+ return [];
56
+ }
57
+ /** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */ export function signWooWebhook(body, secret) {
58
+ return createHmac('sha256', secret).update(body, 'utf8').digest('base64');
59
+ }
60
+ /** The headers WooCommerce sends with a delivery. */ export function wooWebhookHeaders(input) {
61
+ const [resource, event] = input.hook.topic.split('.');
62
+ return {
63
+ 'content-type': 'application/json',
64
+ 'user-agent': `WooCommerce/${WOO_REPORTED_VERSION} Hookshot (WordPress/${WP_REPORTED_VERSION})`,
65
+ 'x-wc-webhook-source': input.source.endsWith('/') ? input.source : `${input.source}/`,
66
+ 'x-wc-webhook-topic': input.hook.topic,
67
+ 'x-wc-webhook-resource': resource != null ? resource : '',
68
+ 'x-wc-webhook-event': event != null ? event : '',
69
+ 'x-wc-webhook-signature': signWooWebhook(input.body, input.hook.secret),
70
+ 'x-wc-webhook-id': String(input.hook.id),
71
+ 'x-wc-webhook-delivery-id': input.deliveryId
72
+ };
73
+ }
74
+ /** One POST; `null` when it was taken (2xx), otherwise why not. Never throws. */ async function post(url, init, fetchImpl) {
75
+ try {
76
+ const result = await fetchImpl(url, {
77
+ method: 'POST',
78
+ headers: init.headers,
79
+ body: init.body,
80
+ signal: AbortSignal.timeout(WOO_WEBHOOK_TIMEOUT_MS)
81
+ });
82
+ if ('refusal' in result) return {
83
+ status: null,
84
+ error: `refused: ${result.refusal}`
85
+ };
86
+ return {
87
+ status: result.status,
88
+ error: result.status >= 200 && result.status < 300 ? null : `answered ${result.status}`
89
+ };
90
+ } catch (caught) {
91
+ var _ref;
92
+ return {
93
+ status: null,
94
+ error: String((_ref = caught == null ? void 0 : caught.name) != null ? _ref : 'network')
95
+ };
96
+ }
97
+ }
98
+ /**
99
+ * The ping WooCommerce sends when a webhook is saved active: a form post of
100
+ * `webhook_id`, which some apps wait for before they count the hook as set
101
+ * up. Its answer is only logged.
102
+ */ export async function pingWooWebhook(hook, source, fetchImpl = fetchConfiguredPublicUrl) {
103
+ const body = new URLSearchParams({
104
+ webhook_id: String(hook.id)
105
+ }).toString();
106
+ const headers = _extends({}, wooWebhookHeaders({
107
+ hook,
108
+ deliveryId: '0',
109
+ source,
110
+ body
111
+ }), {
112
+ 'content-type': 'application/x-www-form-urlencoded'
113
+ });
114
+ return post(hook.delivery_url, {
115
+ headers,
116
+ body
117
+ }, fetchImpl);
118
+ }
119
+ /** The subscriber: delivers one store event to every live hook that takes it. */ export async function deliverWooWebhooks(envelope, deps = {}) {
120
+ var _ref, _envelope_payload, _orderSnap_data, _deps_isLive, _deps_fetchImpl, _deps_now;
121
+ var _order;
122
+ const topics = wooTopicsForEvent(envelope.event);
123
+ if (!topics.length) return {
124
+ delivered: 0,
125
+ failed: 0
126
+ };
127
+ const firestore = firebaseAdmin.app().firestore();
128
+ const hooks = (await readWebhooks(firestore, envelope.hostId)).filter((hook)=>hook.status === 'active' && topics.includes(hook.topic));
129
+ if (!hooks.length) return {
130
+ delivered: 0,
131
+ failed: 0
132
+ };
133
+ const orderId = String((_ref = (_order = ((_envelope_payload = envelope.payload) != null ? _envelope_payload : {}).order) == null ? void 0 : _order.id) != null ? _ref : '');
134
+ if (!orderId) return {
135
+ delivered: 0,
136
+ failed: 0
137
+ };
138
+ const hostRef = firestore.collection('hosts').doc(envelope.hostId);
139
+ const orderSnap = await hostRef.collection('orders').doc(orderId).get();
140
+ if (!orderSnap.exists) return {
141
+ delivered: 0,
142
+ failed: 0
143
+ };
144
+ const [order] = await shapeStoreOrders(firestore, envelope.hostId, [
145
+ {
146
+ id: orderId,
147
+ data: (_orderSnap_data = orderSnap.data()) != null ? _orderSnap_data : {}
148
+ }
149
+ ]);
150
+ const body = JSON.stringify(order);
151
+ const isLive = (_deps_isLive = deps.isLive) != null ? _deps_isLive : (grantId, hostId)=>wooConnectionIsLive(grantId, hostId);
152
+ const fetchImpl = (_deps_fetchImpl = deps.fetchImpl) != null ? _deps_fetchImpl : fetchConfiguredPublicUrl;
153
+ const clock = (_deps_now = deps.now) != null ? _deps_now : Date.now;
154
+ const final = envelope.attempt >= PLUGIN_EVENT_MAX_ATTEMPTS;
155
+ const liveByGrant = new Map();
156
+ let delivered = 0;
157
+ let failed = 0;
158
+ for (const hook of hooks){
159
+ var _hook_source;
160
+ if (!liveByGrant.has(hook.grantId)) liveByGrant.set(hook.grantId, isLive(hook.grantId, envelope.hostId).catch(()=>false));
161
+ if (!await liveByGrant.get(hook.grantId)) continue;
162
+ const logRef = hostRef.collection('wooRequests').doc(`webhook.${envelope.id}.${hook.id}`.replace(/\//g, '_'));
163
+ if ((await logRef.get()).get('status') === 'delivered') {
164
+ delivered += 1;
165
+ continue;
166
+ }
167
+ const startedAt = clock();
168
+ const deliveryId = `${envelope.id}.${hook.id}`;
169
+ const result = await post(hook.delivery_url, {
170
+ headers: wooWebhookHeaders({
171
+ hook,
172
+ deliveryId,
173
+ source: (_hook_source = hook.source) != null ? _hook_source : '',
174
+ body
175
+ }),
176
+ body
177
+ }, fetchImpl);
178
+ const ok = result.error === null;
179
+ if (ok) delivered += 1;
180
+ else failed += 1;
181
+ await logRef.set({
182
+ kind: 'webhook',
183
+ topic: hook.topic,
184
+ webhookId: hook.id,
185
+ grantId: hook.grantId,
186
+ event: envelope.event,
187
+ orderId,
188
+ status: ok ? 'delivered' : final ? 'failed' : 'retrying',
189
+ httpStatus: result.status,
190
+ error: result.error,
191
+ attempt: envelope.attempt,
192
+ atMs: startedAt,
193
+ ms: Math.max(0, clock() - startedAt),
194
+ expiresAt: firebaseAdmin.firestore.Timestamp.fromMillis(startedAt + DELIVERY_LOG_TTL_MS)
195
+ }).catch(()=>undefined);
196
+ }
197
+ if (failed > 0 && !final) throw new Error(`${failed} WooCommerce webhook(s) did not take ${envelope.event}`);
198
+ return {
199
+ delivered,
200
+ failed
201
+ };
202
+ }
203
+
204
+ //# sourceMappingURL=woo-webhooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-webhooks.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WEBHOOKS, DELIVERED AS WOOCOMMERCE DELIVERS THEM.\n *\n * An app that links a store through its WooCommerce connector may register\n * webhooks (`POST /wc/v3/webhooks`, `woo-system.ts`) rather than poll for\n * orders. Commerce's own order events drive them, through the plugin event\n * outbox like the merchant's order webhooks: a failed delivery throws, and\n * the outbox retries it with its backoff; a hook that already took the event\n * is not sent it again.\n *\n * - `order.paid` → `order.created` and `order.updated`. A store order\n * exists for an app once it is paid: an unpaid checkout is never listed.\n * - fulfilled, delivered, refunded, cancelled → `order.updated`.\n *\n * The body is the order exactly as `GET /wc/v3/orders/{id}` answers it. The\n * headers are WooCommerce's: `X-WC-Webhook-Topic`, `-Resource`, `-Event`,\n * `-ID`, `-Delivery-ID`, `-Source`, and `-Signature`, the base64 HMAC-SHA256\n * of the body under the hook's secret. Each call goes through\n * `fetchConfiguredPublicUrl` (https, public address, no redirect). A hook\n * whose link has ended is skipped.\n *=========================================*/\n\nimport type { PluginDomainEventEnvelope } from '@aglyn/aglyn/plugin-manager/plugin-domain-events'\nimport { fetchConfiguredPublicUrl, firebaseAdmin, wooConnectionIsLive } from '@aglyn/tenant-data-admin'\nimport { PLUGIN_EVENT_MAX_ATTEMPTS } from '@aglyn/tenant-data-admin/server/plugin-event-outbox'\nimport { createHmac } from 'node:crypto'\nimport { shapeStoreOrders } from './woo-orders'\nimport { readWebhooks, type StoredWebhook } from './woo-meta'\nimport { WOO_REPORTED_VERSION, WP_REPORTED_VERSION } from './woo-shapes'\n\n/** How long an app's receiver has to answer, as WooCommerce allows it. */\nexport const WOO_WEBHOOK_TIMEOUT_MS = 15_000\nconst DELIVERY_LOG_TTL_MS = 30 * 86_400_000\n\n/** The WooCommerce topics one store event is delivered as. */\nexport function wooTopicsForEvent(event: string): string[] {\n if (event === 'order.paid') return ['order.created', 'order.updated']\n if (event === 'order.fulfilled' || event === 'order.delivered' || event === 'order.refunded' || event === 'order.cancelled') {\n return ['order.updated']\n }\n return []\n}\n\n/** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */\nexport function signWooWebhook(body: string, secret: string): string {\n return createHmac('sha256', secret).update(body, 'utf8').digest('base64')\n}\n\n/** The headers WooCommerce sends with a delivery. */\nexport function wooWebhookHeaders(input: {\n hook: Pick<StoredWebhook, 'id' | 'topic' | 'secret'>\n deliveryId: string\n source: string\n body: string\n}): Record<string, string> {\n const [resource, event] = input.hook.topic.split('.')\n return {\n 'content-type': 'application/json',\n 'user-agent': `WooCommerce/${WOO_REPORTED_VERSION} Hookshot (WordPress/${WP_REPORTED_VERSION})`,\n 'x-wc-webhook-source': input.source.endsWith('/') ? input.source : `${input.source}/`,\n 'x-wc-webhook-topic': input.hook.topic,\n 'x-wc-webhook-resource': resource ?? '',\n 'x-wc-webhook-event': event ?? '',\n 'x-wc-webhook-signature': signWooWebhook(input.body, input.hook.secret),\n 'x-wc-webhook-id': String(input.hook.id),\n 'x-wc-webhook-delivery-id': input.deliveryId,\n }\n}\n\ntype Fetch = typeof fetchConfiguredPublicUrl\n\n/** One POST; `null` when it was taken (2xx), otherwise why not. Never throws. */\nasync function post(url: string, init: { headers: Record<string, string>; body: string }, fetchImpl: Fetch): Promise<{ status: number | null; error: string | null }> {\n try {\n const result = await fetchImpl(url, { method: 'POST', headers: init.headers, body: init.body, signal: AbortSignal.timeout(WOO_WEBHOOK_TIMEOUT_MS) })\n if ('refusal' in result) return { status: null, error: `refused: ${result.refusal}` }\n return { status: result.status, error: result.status >= 200 && result.status < 300 ? null : `answered ${result.status}` }\n } catch (caught) {\n return { status: null, error: String((caught as Error)?.name ?? 'network') }\n }\n}\n\n/**\n * The ping WooCommerce sends when a webhook is saved active: a form post of\n * `webhook_id`, which some apps wait for before they count the hook as set\n * up. Its answer is only logged.\n */\nexport async function pingWooWebhook(hook: StoredWebhook, source: string, fetchImpl: Fetch = fetchConfiguredPublicUrl) {\n const body = new URLSearchParams({ webhook_id: String(hook.id) }).toString()\n const headers = { ...wooWebhookHeaders({ hook, deliveryId: '0', source, body }), 'content-type': 'application/x-www-form-urlencoded' }\n return post(hook.delivery_url, { headers, body }, fetchImpl)\n}\n\nexport interface WooWebhookDeps {\n fetchImpl?: Fetch\n now?: () => number\n isLive?: (grantId: string, hostId: string) => Promise<boolean>\n}\n\n/** The subscriber: delivers one store event to every live hook that takes it. */\nexport async function deliverWooWebhooks(envelope: PluginDomainEventEnvelope, deps: WooWebhookDeps = {}): Promise<{ delivered: number; failed: number }> {\n const topics = wooTopicsForEvent(envelope.event)\n if (!topics.length) return { delivered: 0, failed: 0 }\n const firestore = firebaseAdmin.app().firestore()\n const hooks = (await readWebhooks(firestore, envelope.hostId)).filter((hook) => hook.status === 'active' && topics.includes(hook.topic))\n if (!hooks.length) return { delivered: 0, failed: 0 }\n const orderId = String(((envelope.payload ?? {}) as { order?: { id?: unknown } }).order?.id ?? '')\n if (!orderId) return { delivered: 0, failed: 0 }\n const hostRef = firestore.collection('hosts').doc(envelope.hostId)\n const orderSnap = await hostRef.collection('orders').doc(orderId).get()\n if (!orderSnap.exists) return { delivered: 0, failed: 0 }\n const [order] = await shapeStoreOrders(firestore, envelope.hostId, [{ id: orderId, data: orderSnap.data() ?? {} }])\n const body = JSON.stringify(order)\n const isLive = deps.isLive ?? ((grantId: string, hostId: string) => wooConnectionIsLive(grantId, hostId))\n const fetchImpl = deps.fetchImpl ?? fetchConfiguredPublicUrl\n const clock = deps.now ?? Date.now\n const final = envelope.attempt >= PLUGIN_EVENT_MAX_ATTEMPTS\n const liveByGrant = new Map<string, Promise<boolean>>()\n let delivered = 0\n let failed = 0\n for (const hook of hooks) {\n if (!liveByGrant.has(hook.grantId)) liveByGrant.set(hook.grantId, isLive(hook.grantId, envelope.hostId).catch(() => false))\n if (!(await liveByGrant.get(hook.grantId))) continue\n const logRef = hostRef.collection('wooRequests').doc(`webhook.${envelope.id}.${hook.id}`.replace(/\\//g, '_'))\n if ((await logRef.get()).get('status') === 'delivered') {\n delivered += 1\n continue\n }\n const startedAt = clock()\n const deliveryId = `${envelope.id}.${hook.id}`\n const result = await post(hook.delivery_url, { headers: wooWebhookHeaders({ hook, deliveryId, source: hook.source ?? '', body }), body }, fetchImpl)\n const ok = result.error === null\n if (ok) delivered += 1\n else failed += 1\n await logRef\n .set({\n kind: 'webhook',\n topic: hook.topic,\n webhookId: hook.id,\n grantId: hook.grantId,\n event: envelope.event,\n orderId,\n status: ok ? 'delivered' : final ? 'failed' : 'retrying',\n httpStatus: result.status,\n error: result.error,\n attempt: envelope.attempt,\n atMs: startedAt,\n ms: Math.max(0, clock() - startedAt),\n expiresAt: firebaseAdmin.firestore.Timestamp.fromMillis(startedAt + DELIVERY_LOG_TTL_MS),\n })\n .catch(() => undefined)\n }\n if (failed > 0 && !final) throw new Error(`${failed} WooCommerce webhook(s) did not take ${envelope.event}`)\n return { delivered, failed }\n}\n"],"names":["fetchConfiguredPublicUrl","firebaseAdmin","wooConnectionIsLive","PLUGIN_EVENT_MAX_ATTEMPTS","createHmac","shapeStoreOrders","readWebhooks","WOO_REPORTED_VERSION","WP_REPORTED_VERSION","WOO_WEBHOOK_TIMEOUT_MS","DELIVERY_LOG_TTL_MS","wooTopicsForEvent","event","signWooWebhook","body","secret","update","digest","wooWebhookHeaders","input","resource","hook","topic","split","source","endsWith","String","id","deliveryId","post","url","init","fetchImpl","result","method","headers","signal","AbortSignal","timeout","status","error","refusal","caught","name","pingWooWebhook","URLSearchParams","webhook_id","toString","delivery_url","deliverWooWebhooks","envelope","deps","orderSnap","topics","length","delivered","failed","firestore","app","hooks","hostId","filter","includes","orderId","payload","order","hostRef","collection","doc","get","exists","data","JSON","stringify","isLive","grantId","clock","now","Date","final","attempt","liveByGrant","Map","has","set","catch","logRef","replace","startedAt","ok","kind","webhookId","httpStatus","atMs","ms","Math","max","expiresAt","Timestamp","fromMillis","undefined","Error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C;AAG3C,SAASA,wBAAwB,EAAEC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AACvG,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SAASC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C,SAAS9B,SAAS8B,OAAO;YACzBa,MAAML;YACNM,IAAIC,KAAKC,GAAG,CAAC,GAAGpB,UAAUY;YAC1BS,WAAWhG,cAAcwD,SAAS,CAACyC,SAAS,CAACC,UAAU,CAACX,YAAY9E;QACtE,GACC2E,KAAK,CAAC,IAAMe;IACjB;IACA,IAAI5C,SAAS,KAAK,CAACuB,OAAO,MAAM,IAAIsB,MAAM,GAAG7C,OAAO,qCAAqC,EAAEN,SAAStC,KAAK,EAAE;IAC3G,OAAO;QAAE2C;QAAWC;IAAO;AAC7B"}
package/src/lib/server.js CHANGED
@@ -756,6 +756,18 @@ export function registerCommerceConsoleApi() {
756
756
  }, {
757
757
  machine: true
758
758
  });
759
+ // A store that answers like WooCommerce, on its own domain: apps that link
760
+ // stores only through their WooCommerce connector (print-on-demand
761
+ // suppliers such as Tapstitch) link this store the same way. The tenant
762
+ // middleware sends `/wp-json/…` and `/wc-auth/…` here with the site's host
763
+ // label; the app's servers call with the link's own key, so it is a
764
+ // MACHINE's route like ShipStation's and asks every site gate itself once
765
+ // the key proves the site (`server/woo/woo-route.ts`).
766
+ registerPluginApiRoute('commerce/woo/:host', {
767
+ web: async (request, context)=>(await import("./server/woo/woo-route.js")).wooRoute(request, context)
768
+ }, {
769
+ machine: true
770
+ });
759
771
  // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post
760
772
  // each label bought for an order this store sent them, signed with the
761
773
  // merchant's own API secret, so it is a MACHINE's route like ShipStation's
@@ -768,6 +780,9 @@ export function registerCommerceConsoleApi() {
768
780
  // The ShipStation and ShippingEasy cards' connect, show, new password,
769
781
  // send open orders and disconnect.
770
782
  registerPluginApiRoute('commerce/shipping-connectors', async (req, res)=>(await import("./server/shipping-connectors.js")).shippingConnectorsHandler(req, res));
783
+ // The store's Connected apps card: apps linked through the WooCommerce
784
+ // connector, and ending one (`server/woo/woo-connections.ts`).
785
+ registerPluginApiRoute('commerce/woo-connections', async (req, res)=>(await import("./server/woo/woo-connections.js")).wooConnectionsHandler(req, res));
771
786
  // The store's sales as figure tables (AGL-2915), for the AI plugin's
772
787
  // insights to read by id rather than by reading orders. The console runs
773
788
  // insight jobs, so the console surface registers them.