@open-mercato/webhooks 0.6.7-develop.6862.1.c11a64ce0a → 0.6.7
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.js +0 -15
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.js.map +2 -2
- package/dist/modules/webhooks/api/inbound/[endpointId]/route.js +7 -152
- package/dist/modules/webhooks/api/inbound/[endpointId]/route.js.map +3 -3
- package/dist/modules/webhooks/backend/webhooks/[id]/page.js +1 -2
- package/dist/modules/webhooks/backend/webhooks/[id]/page.js.map +2 -2
- package/dist/modules/webhooks/backend/webhooks/page.js +1 -2
- package/dist/modules/webhooks/backend/webhooks/page.js.map +2 -2
- package/dist/modules/webhooks/data/entities.js +1 -101
- package/dist/modules/webhooks/data/entities.js.map +2 -2
- package/dist/modules/webhooks/encryption.js +0 -7
- package/dist/modules/webhooks/encryption.js.map +2 -2
- package/dist/modules/webhooks/events.js +0 -2
- package/dist/modules/webhooks/events.js.map +2 -2
- package/dist/modules/webhooks/lib/queue.js +0 -47
- package/dist/modules/webhooks/lib/queue.js.map +2 -2
- package/dist/modules/webhooks/widgets/injection/integration-deliveries/widget.client.js +1 -2
- package/dist/modules/webhooks/widgets/injection/integration-deliveries/widget.client.js.map +2 -2
- package/generated/entities.ids.generated.ts +1 -3
- package/generated/entity-fields-registry.ts +0 -28
- package/package.json +11 -12
- package/src/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.ts +0 -16
- package/src/modules/webhooks/api/inbound/[endpointId]/__tests__/route.test.ts +1 -99
- package/src/modules/webhooks/api/inbound/[endpointId]/route.ts +7 -178
- package/src/modules/webhooks/backend/webhooks/[id]/page.tsx +1 -2
- package/src/modules/webhooks/backend/webhooks/page.tsx +1 -2
- package/src/modules/webhooks/data/entities.ts +0 -84
- package/src/modules/webhooks/encryption.ts +0 -7
- package/src/modules/webhooks/events.ts +0 -2
- package/src/modules/webhooks/i18n/de.json +1 -1
- package/src/modules/webhooks/i18n/en.json +1 -1
- package/src/modules/webhooks/i18n/es.json +1 -1
- package/src/modules/webhooks/i18n/pl.json +1 -1
- package/src/modules/webhooks/lib/queue.ts +0 -60
- package/src/modules/webhooks/migrations/.snapshot-open-mercato.json +339 -908
- package/src/modules/webhooks/widgets/injection/integration-deliveries/widget.client.tsx +1 -2
- package/dist/modules/webhooks/extension-points.js +0 -15
- package/dist/modules/webhooks/extension-points.js.map +0 -7
- package/dist/modules/webhooks/generators.js +0 -57
- package/dist/modules/webhooks/generators.js.map +0 -7
- package/dist/modules/webhooks/lib/inbound-dispatch.js +0 -105
- package/dist/modules/webhooks/lib/inbound-dispatch.js.map +0 -7
- package/dist/modules/webhooks/lib/inbound-registry.js +0 -76
- package/dist/modules/webhooks/lib/inbound-registry.js.map +0 -7
- package/dist/modules/webhooks/lib/module-webhook-registry.js +0 -12
- package/dist/modules/webhooks/lib/module-webhook-registry.js.map +0 -7
- package/dist/modules/webhooks/migrations/Migration20260617141327_webhooks.js +0 -16
- package/dist/modules/webhooks/migrations/Migration20260617141327_webhooks.js.map +0 -7
- package/dist/modules/webhooks/workers/inbound-dispatch.js +0 -29
- package/dist/modules/webhooks/workers/inbound-dispatch.js.map +0 -7
- package/generated/entities/inbound_endpoint_config_entity/index.ts +0 -8
- package/generated/entities/webhook_ingestion_entity/index.ts +0 -16
- package/src/modules/webhooks/api/inbound/[endpointId]/__tests__/route.unify.test.ts +0 -149
- package/src/modules/webhooks/extension-points.ts +0 -12
- package/src/modules/webhooks/generators.ts +0 -57
- package/src/modules/webhooks/i18n/ko.json +0 -161
- package/src/modules/webhooks/lib/__tests__/inbound-dispatch.test.ts +0 -186
- package/src/modules/webhooks/lib/__tests__/inbound-registry.test.ts +0 -102
- package/src/modules/webhooks/lib/__tests__/module-webhook-registry.test.ts +0 -53
- package/src/modules/webhooks/lib/inbound-dispatch.ts +0 -147
- package/src/modules/webhooks/lib/inbound-registry.ts +0 -92
- package/src/modules/webhooks/lib/module-webhook-registry.ts +0 -33
- package/src/modules/webhooks/migrations/Migration20260617141327_webhooks.ts +0 -16
- package/src/modules/webhooks/workers/inbound-dispatch.ts +0 -31
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
-
import { extensionPoints } from '@open-mercato/webhooks/modules/webhooks/extension-points'
|
|
5
4
|
import Link from 'next/link'
|
|
6
5
|
import type { ColumnDef } from '@tanstack/react-table'
|
|
7
6
|
import type { InjectionWidgetComponentProps } from '@open-mercato/shared/modules/widgets/injection'
|
|
@@ -228,7 +227,7 @@ export default function IntegrationDeliveriesWidget(_props: InjectionWidgetCompo
|
|
|
228
227
|
</Button>
|
|
229
228
|
</div>
|
|
230
229
|
)}
|
|
231
|
-
perspective={{ tableId:
|
|
230
|
+
perspective={{ tableId: 'webhooks.integration-deliveries' }}
|
|
232
231
|
pagination={{
|
|
233
232
|
page,
|
|
234
233
|
pageSize: 20,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { dataTableExtensionHost, defineModuleExtensionPoints } from "@open-mercato/shared/modules/widgets/extension-points";
|
|
2
|
-
const extensionPoints = defineModuleExtensionPoints({
|
|
3
|
-
moduleId: "webhooks",
|
|
4
|
-
hosts: {
|
|
5
|
-
webhooksTable: dataTableExtensionHost({ tableId: "webhooks.list", source: "backend/webhooks/page.tsx" }),
|
|
6
|
-
deliveriesTable: dataTableExtensionHost({ tableId: "webhooks.deliveries", source: "backend/webhooks/[id]/page.tsx" }),
|
|
7
|
-
integrationDeliveriesTable: dataTableExtensionHost({ tableId: "webhooks.integration-deliveries", source: "widgets/injection/integration-deliveries/widget.client.tsx" })
|
|
8
|
-
}
|
|
9
|
-
});
|
|
10
|
-
var extension_points_default = extensionPoints;
|
|
11
|
-
export {
|
|
12
|
-
extension_points_default as default,
|
|
13
|
-
extensionPoints
|
|
14
|
-
};
|
|
15
|
-
//# sourceMappingURL=extension-points.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/modules/webhooks/extension-points.ts"],
|
|
4
|
-
"sourcesContent": ["import { dataTableExtensionHost, defineModuleExtensionPoints } from '@open-mercato/shared/modules/widgets/extension-points'\n\nexport const extensionPoints = defineModuleExtensionPoints({\n moduleId: 'webhooks',\n hosts: {\n webhooksTable: dataTableExtensionHost({ tableId: 'webhooks.list', source: 'backend/webhooks/page.tsx' }),\n deliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.deliveries', source: 'backend/webhooks/[id]/page.tsx' }),\n integrationDeliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.integration-deliveries', source: 'widgets/injection/integration-deliveries/widget.client.tsx' }),\n },\n})\n\nexport default extensionPoints\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,wBAAwB,mCAAmC;AAE7D,MAAM,kBAAkB,4BAA4B;AAAA,EACzD,UAAU;AAAA,EACV,OAAO;AAAA,IACL,eAAe,uBAAuB,EAAE,SAAS,iBAAiB,QAAQ,4BAA4B,CAAC;AAAA,IACvG,iBAAiB,uBAAuB,EAAE,SAAS,uBAAuB,QAAQ,iCAAiC,CAAC;AAAA,IACpH,4BAA4B,uBAAuB,EAAE,SAAS,mCAAmC,QAAQ,6DAA6D,CAAC;AAAA,EACzK;AACF,CAAC;AAED,IAAO,2BAAQ;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
function buildSourcesOutput({ importSection, entriesLiteral }) {
|
|
2
|
-
return `// AUTO-GENERATED by mercato generate registry
|
|
3
|
-
import type { WebhookSourceConfig } from '@open-mercato/shared/lib/webhooks'
|
|
4
|
-
${importSection ? `${importSection}
|
|
5
|
-
` : ""}type WebhookSourceModuleEntry = { moduleId: string; sources: WebhookSourceConfig[] }
|
|
6
|
-
|
|
7
|
-
export const webhookSourceEntries: WebhookSourceModuleEntry[] = [
|
|
8
|
-
${entriesLiteral ? ` ${entriesLiteral}
|
|
9
|
-
` : ""}]
|
|
10
|
-
`;
|
|
11
|
-
}
|
|
12
|
-
function buildHandlersOutput({ importSection, entriesLiteral }) {
|
|
13
|
-
return `// AUTO-GENERATED by mercato generate registry
|
|
14
|
-
import type { WebhookHandlerRegistryEntry } from '@open-mercato/shared/lib/webhooks'
|
|
15
|
-
${importSection ? `${importSection}
|
|
16
|
-
` : ""}type WebhookHandlerModuleEntry = { moduleId: string; handlers: WebhookHandlerRegistryEntry[] }
|
|
17
|
-
|
|
18
|
-
export const webhookHandlerEntries: WebhookHandlerModuleEntry[] = [
|
|
19
|
-
${entriesLiteral ? ` ${entriesLiteral}
|
|
20
|
-
` : ""}]
|
|
21
|
-
`;
|
|
22
|
-
}
|
|
23
|
-
const sourcesPlugin = {
|
|
24
|
-
id: "webhooks.sources",
|
|
25
|
-
conventionFile: "webhook-sources.ts",
|
|
26
|
-
importPrefix: "WEBHOOK_SOURCES",
|
|
27
|
-
configExpr: (importName, moduleId) => `{ moduleId: '${moduleId}', sources: ((${importName}.default ?? ${importName}.webhookSources ?? []) as WebhookSourceConfig[]) }`,
|
|
28
|
-
outputFileName: "webhook-sources.generated.ts",
|
|
29
|
-
buildOutput: buildSourcesOutput,
|
|
30
|
-
bootstrapRegistration: {
|
|
31
|
-
entriesExportName: "webhookSourceEntries",
|
|
32
|
-
registrationImports: [
|
|
33
|
-
`import { registerWebhookSourceEntries } from '@open-mercato/webhooks/modules/webhooks/lib/module-webhook-registry'`
|
|
34
|
-
],
|
|
35
|
-
buildCall: (name) => `registerWebhookSourceEntries(${name})`
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
const handlersPlugin = {
|
|
39
|
-
id: "webhooks.handlers",
|
|
40
|
-
conventionFile: "webhook-handlers.ts",
|
|
41
|
-
importPrefix: "WEBHOOK_HANDLERS",
|
|
42
|
-
configExpr: (importName, moduleId) => `{ moduleId: '${moduleId}', handlers: ((${importName}.default ?? ${importName}.webhookHandlers ?? []) as WebhookHandlerRegistryEntry[]) }`,
|
|
43
|
-
outputFileName: "webhook-handlers.generated.ts",
|
|
44
|
-
buildOutput: buildHandlersOutput,
|
|
45
|
-
bootstrapRegistration: {
|
|
46
|
-
entriesExportName: "webhookHandlerEntries",
|
|
47
|
-
registrationImports: [
|
|
48
|
-
`import { registerWebhookHandlerEntries } from '@open-mercato/webhooks/modules/webhooks/lib/module-webhook-registry'`
|
|
49
|
-
],
|
|
50
|
-
buildCall: (name) => `registerWebhookHandlerEntries(${name})`
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
const generatorPlugins = [sourcesPlugin, handlersPlugin];
|
|
54
|
-
export {
|
|
55
|
-
generatorPlugins
|
|
56
|
-
};
|
|
57
|
-
//# sourceMappingURL=generators.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/modules/webhooks/generators.ts"],
|
|
4
|
-
"sourcesContent": ["import type { GeneratorPlugin } from '@open-mercato/shared/modules/generators'\n\nfunction buildSourcesOutput({ importSection, entriesLiteral }: { importSection: string; entriesLiteral: string }): string {\n return `// AUTO-GENERATED by mercato generate registry\nimport type { WebhookSourceConfig } from '@open-mercato/shared/lib/webhooks'\n${importSection ? `${importSection}\\n` : ''}type WebhookSourceModuleEntry = { moduleId: string; sources: WebhookSourceConfig[] }\n\nexport const webhookSourceEntries: WebhookSourceModuleEntry[] = [\n${entriesLiteral ? ` ${entriesLiteral}\\n` : ''}]\n`\n}\n\nfunction buildHandlersOutput({ importSection, entriesLiteral }: { importSection: string; entriesLiteral: string }): string {\n return `// AUTO-GENERATED by mercato generate registry\nimport type { WebhookHandlerRegistryEntry } from '@open-mercato/shared/lib/webhooks'\n${importSection ? `${importSection}\\n` : ''}type WebhookHandlerModuleEntry = { moduleId: string; handlers: WebhookHandlerRegistryEntry[] }\n\nexport const webhookHandlerEntries: WebhookHandlerModuleEntry[] = [\n${entriesLiteral ? ` ${entriesLiteral}\\n` : ''}]\n`\n}\n\nconst sourcesPlugin: GeneratorPlugin = {\n id: 'webhooks.sources',\n conventionFile: 'webhook-sources.ts',\n importPrefix: 'WEBHOOK_SOURCES',\n configExpr: (importName: string, moduleId: string) =>\n `{ moduleId: '${moduleId}', sources: ((${importName}.default ?? ${importName}.webhookSources ?? []) as WebhookSourceConfig[]) }`,\n outputFileName: 'webhook-sources.generated.ts',\n buildOutput: buildSourcesOutput,\n bootstrapRegistration: {\n entriesExportName: 'webhookSourceEntries',\n registrationImports: [\n `import { registerWebhookSourceEntries } from '@open-mercato/webhooks/modules/webhooks/lib/module-webhook-registry'`,\n ],\n buildCall: (name: string) => `registerWebhookSourceEntries(${name})`,\n },\n}\n\nconst handlersPlugin: GeneratorPlugin = {\n id: 'webhooks.handlers',\n conventionFile: 'webhook-handlers.ts',\n importPrefix: 'WEBHOOK_HANDLERS',\n configExpr: (importName: string, moduleId: string) =>\n `{ moduleId: '${moduleId}', handlers: ((${importName}.default ?? ${importName}.webhookHandlers ?? []) as WebhookHandlerRegistryEntry[]) }`,\n outputFileName: 'webhook-handlers.generated.ts',\n buildOutput: buildHandlersOutput,\n bootstrapRegistration: {\n entriesExportName: 'webhookHandlerEntries',\n registrationImports: [\n `import { registerWebhookHandlerEntries } from '@open-mercato/webhooks/modules/webhooks/lib/module-webhook-registry'`,\n ],\n buildCall: (name: string) => `registerWebhookHandlerEntries(${name})`,\n },\n}\n\nexport const generatorPlugins: GeneratorPlugin[] = [sourcesPlugin, handlersPlugin]\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,mBAAmB,EAAE,eAAe,eAAe,GAA8D;AACxH,SAAO;AAAA;AAAA,EAEP,gBAAgB,GAAG,aAAa;AAAA,IAAO,EAAE;AAAA;AAAA;AAAA,EAGzC,iBAAiB,KAAK,cAAc;AAAA,IAAO,EAAE;AAAA;AAE/C;AAEA,SAAS,oBAAoB,EAAE,eAAe,eAAe,GAA8D;AACzH,SAAO;AAAA;AAAA,EAEP,gBAAgB,GAAG,aAAa;AAAA,IAAO,EAAE;AAAA;AAAA;AAAA,EAGzC,iBAAiB,KAAK,cAAc;AAAA,IAAO,EAAE;AAAA;AAE/C;AAEA,MAAM,gBAAiC;AAAA,EACrC,IAAI;AAAA,EACJ,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,YAAY,CAAC,YAAoB,aAC/B,gBAAgB,QAAQ,iBAAiB,UAAU,eAAe,UAAU;AAAA,EAC9E,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,uBAAuB;AAAA,IACrB,mBAAmB;AAAA,IACnB,qBAAqB;AAAA,MACnB;AAAA,IACF;AAAA,IACA,WAAW,CAAC,SAAiB,gCAAgC,IAAI;AAAA,EACnE;AACF;AAEA,MAAM,iBAAkC;AAAA,EACtC,IAAI;AAAA,EACJ,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,YAAY,CAAC,YAAoB,aAC/B,gBAAgB,QAAQ,kBAAkB,UAAU,eAAe,UAAU;AAAA,EAC/E,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,uBAAuB;AAAA,IACrB,mBAAmB;AAAA,IACnB,qBAAqB;AAAA,MACnB;AAAA,IACF;AAAA,IACA,WAAW,CAAC,SAAiB,iCAAiC,IAAI;AAAA,EACpE;AACF;AAEO,MAAM,mBAAsC,CAAC,eAAe,cAAc;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
2
|
-
import { WebhookIngestionEntity } from "../data/entities.js";
|
|
3
|
-
import { emitWebhooksEvent } from "../events.js";
|
|
4
|
-
import { resolveWebhookHandlers } from "./inbound-registry.js";
|
|
5
|
-
const MAX_HANDLER_RESULTS = 50;
|
|
6
|
-
const MAX_ERROR_MESSAGE_LENGTH = 1024;
|
|
7
|
-
function truncateError(message) {
|
|
8
|
-
return message.length > MAX_ERROR_MESSAGE_LENGTH ? `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}\u2026` : message;
|
|
9
|
-
}
|
|
10
|
-
function moduleOfHandler(handlerId) {
|
|
11
|
-
const separatorIndex = handlerId.indexOf(":");
|
|
12
|
-
return separatorIndex > 0 ? handlerId.slice(0, separatorIndex) : handlerId;
|
|
13
|
-
}
|
|
14
|
-
async function processInboundDispatchJob(em, job, ctx) {
|
|
15
|
-
const startedAtMs = Date.now();
|
|
16
|
-
const ingestion = await findOneWithDecryption(
|
|
17
|
-
em,
|
|
18
|
-
WebhookIngestionEntity,
|
|
19
|
-
{
|
|
20
|
-
id: job.ingestionId,
|
|
21
|
-
tenantId: job.tenantId,
|
|
22
|
-
organizationId: job.organizationId
|
|
23
|
-
},
|
|
24
|
-
{}
|
|
25
|
-
);
|
|
26
|
-
if (!ingestion || ingestion.status === "processed") return;
|
|
27
|
-
ingestion.status = "processing";
|
|
28
|
-
await em.flush();
|
|
29
|
-
const handlers = resolveWebhookHandlers(job.sourceKey, job.eventType);
|
|
30
|
-
const payload = {
|
|
31
|
-
data: ingestion.payload,
|
|
32
|
-
eventType: job.eventType,
|
|
33
|
-
sourceKey: job.sourceKey,
|
|
34
|
-
headers: ingestion.headers ?? {},
|
|
35
|
-
ingestionId: job.ingestionId,
|
|
36
|
-
tenantId: job.tenantId,
|
|
37
|
-
organizationId: job.organizationId
|
|
38
|
-
};
|
|
39
|
-
const previousResults = Array.isArray(ingestion.handlerResults) ? ingestion.handlerResults : [];
|
|
40
|
-
const alreadySucceeded = new Map(
|
|
41
|
-
previousResults.filter((result) => result?.status === "success").map((result) => [result.handlerId, result])
|
|
42
|
-
);
|
|
43
|
-
const results = [];
|
|
44
|
-
let failedCount = 0;
|
|
45
|
-
for (const entry of handlers) {
|
|
46
|
-
const previousSuccess = alreadySucceeded.get(entry.meta.id);
|
|
47
|
-
if (previousSuccess) {
|
|
48
|
-
results.push(previousSuccess);
|
|
49
|
-
continue;
|
|
50
|
-
}
|
|
51
|
-
const handlerStartedMs = Date.now();
|
|
52
|
-
const handlerStartedAt = new Date(handlerStartedMs).toISOString();
|
|
53
|
-
try {
|
|
54
|
-
const mod = await entry.handler();
|
|
55
|
-
await mod.default(payload, ctx);
|
|
56
|
-
results.push({
|
|
57
|
-
handlerId: entry.meta.id,
|
|
58
|
-
module: moduleOfHandler(entry.meta.id),
|
|
59
|
-
status: "success",
|
|
60
|
-
durationMs: Date.now() - handlerStartedMs,
|
|
61
|
-
startedAt: handlerStartedAt
|
|
62
|
-
});
|
|
63
|
-
} catch (error) {
|
|
64
|
-
failedCount += 1;
|
|
65
|
-
const message = truncateError(error instanceof Error ? error.message : String(error));
|
|
66
|
-
results.push({
|
|
67
|
-
handlerId: entry.meta.id,
|
|
68
|
-
module: moduleOfHandler(entry.meta.id),
|
|
69
|
-
status: "failed",
|
|
70
|
-
errorMessage: message,
|
|
71
|
-
durationMs: Date.now() - handlerStartedMs,
|
|
72
|
-
startedAt: handlerStartedAt
|
|
73
|
-
});
|
|
74
|
-
await emitWebhooksEvent("webhooks.inbound.handler_failed", {
|
|
75
|
-
ingestionId: job.ingestionId,
|
|
76
|
-
sourceKey: job.sourceKey,
|
|
77
|
-
eventType: job.eventType,
|
|
78
|
-
handlerId: entry.meta.id,
|
|
79
|
-
errorMessage: message,
|
|
80
|
-
tenantId: job.tenantId,
|
|
81
|
-
organizationId: job.organizationId
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
ingestion.handlerCount = handlers.length;
|
|
86
|
-
ingestion.handlerResults = results.slice(0, MAX_HANDLER_RESULTS);
|
|
87
|
-
ingestion.status = failedCount > 0 ? "failed" : "processed";
|
|
88
|
-
ingestion.processedAt = /* @__PURE__ */ new Date();
|
|
89
|
-
ingestion.durationMs = Date.now() - startedAtMs;
|
|
90
|
-
ingestion.errorMessage = failedCount > 0 ? `${failedCount}/${handlers.length} handlers failed` : null;
|
|
91
|
-
await em.flush();
|
|
92
|
-
await emitWebhooksEvent("webhooks.inbound.processed", {
|
|
93
|
-
ingestionId: job.ingestionId,
|
|
94
|
-
sourceKey: job.sourceKey,
|
|
95
|
-
eventType: job.eventType,
|
|
96
|
-
handlerCount: handlers.length,
|
|
97
|
-
failedCount,
|
|
98
|
-
tenantId: job.tenantId,
|
|
99
|
-
organizationId: job.organizationId
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
export {
|
|
103
|
-
processInboundDispatchJob
|
|
104
|
-
};
|
|
105
|
-
//# sourceMappingURL=inbound-dispatch.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/webhooks/lib/inbound-dispatch.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type {\n WebhookHandlerContext,\n WebhookHandlerPayload,\n WebhookHandlerResult,\n} from '@open-mercato/shared/lib/webhooks'\nimport { WebhookIngestionEntity } from '../data/entities'\nimport { emitWebhooksEvent } from '../events'\nimport { resolveWebhookHandlers } from './inbound-registry'\n\nconst MAX_HANDLER_RESULTS = 50\nconst MAX_ERROR_MESSAGE_LENGTH = 1024\n\nexport type InboundDispatchJob = {\n ingestionId: string\n sourceKey: string\n eventType: string\n tenantId: string\n organizationId: string\n}\n\nfunction truncateError(message: string): string {\n return message.length > MAX_ERROR_MESSAGE_LENGTH\n ? `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}\u2026`\n : message\n}\n\nfunction moduleOfHandler(handlerId: string): string {\n const separatorIndex = handlerId.indexOf(':')\n return separatorIndex > 0 ? handlerId.slice(0, separatorIndex) : handlerId\n}\n\n/**\n * Process a queued inbound-dispatch job: load the ingestion, run every matching\n * handler independently (a failing handler never blocks the others), record\n * per-handler results, and emit lifecycle events. The payload and headers are\n * read from the (decrypted) ingestion row rather than carried on the job, so the\n * queue never stores the raw webhook body. Idempotent \u2014 a job whose ingestion is\n * already `processed` returns early, and a retry after a partial failure re-runs\n * only the handlers that have not already succeeded.\n */\nexport async function processInboundDispatchJob(\n em: EntityManager,\n job: InboundDispatchJob,\n ctx: WebhookHandlerContext,\n): Promise<void> {\n const startedAtMs = Date.now()\n const ingestion = await findOneWithDecryption(\n em,\n WebhookIngestionEntity,\n {\n id: job.ingestionId,\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n },\n {},\n )\n\n if (!ingestion || ingestion.status === 'processed') return\n\n ingestion.status = 'processing'\n await em.flush()\n\n const handlers = resolveWebhookHandlers(job.sourceKey, job.eventType)\n const payload: WebhookHandlerPayload = {\n data: ingestion.payload,\n eventType: job.eventType,\n sourceKey: job.sourceKey,\n headers: ingestion.headers ?? {},\n ingestionId: job.ingestionId,\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n }\n\n const previousResults = Array.isArray(ingestion.handlerResults) ? ingestion.handlerResults : []\n const alreadySucceeded = new Map(\n previousResults\n .filter((result) => result?.status === 'success')\n .map((result) => [result.handlerId, result]),\n )\n\n const results: WebhookHandlerResult[] = []\n let failedCount = 0\n\n for (const entry of handlers) {\n const previousSuccess = alreadySucceeded.get(entry.meta.id)\n if (previousSuccess) {\n results.push(previousSuccess)\n continue\n }\n\n const handlerStartedMs = Date.now()\n const handlerStartedAt = new Date(handlerStartedMs).toISOString()\n try {\n const mod = await entry.handler()\n await mod.default(payload, ctx)\n results.push({\n handlerId: entry.meta.id,\n module: moduleOfHandler(entry.meta.id),\n status: 'success',\n durationMs: Date.now() - handlerStartedMs,\n startedAt: handlerStartedAt,\n })\n } catch (error) {\n failedCount += 1\n const message = truncateError(error instanceof Error ? error.message : String(error))\n results.push({\n handlerId: entry.meta.id,\n module: moduleOfHandler(entry.meta.id),\n status: 'failed',\n errorMessage: message,\n durationMs: Date.now() - handlerStartedMs,\n startedAt: handlerStartedAt,\n })\n await emitWebhooksEvent('webhooks.inbound.handler_failed', {\n ingestionId: job.ingestionId,\n sourceKey: job.sourceKey,\n eventType: job.eventType,\n handlerId: entry.meta.id,\n errorMessage: message,\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n })\n }\n }\n\n ingestion.handlerCount = handlers.length\n ingestion.handlerResults = results.slice(0, MAX_HANDLER_RESULTS)\n ingestion.status = failedCount > 0 ? 'failed' : 'processed'\n ingestion.processedAt = new Date()\n ingestion.durationMs = Date.now() - startedAtMs\n ingestion.errorMessage = failedCount > 0\n ? `${failedCount}/${handlers.length} handlers failed`\n : null\n await em.flush()\n\n await emitWebhooksEvent('webhooks.inbound.processed', {\n ingestionId: job.ingestionId,\n sourceKey: job.sourceKey,\n eventType: job.eventType,\n handlerCount: handlers.length,\n failedCount,\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n })\n}\n"],
|
|
5
|
-
"mappings": "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",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { matchWebhookEventPattern } from "@open-mercato/shared/lib/events/patterns";
|
|
2
|
-
const WEBHOOK_SOURCES_KEY = "__openMercatoWebhookSources__";
|
|
3
|
-
const WEBHOOK_HANDLERS_KEY = "__openMercatoWebhookHandlers__";
|
|
4
|
-
function getSourceRegistry() {
|
|
5
|
-
const globalState = globalThis;
|
|
6
|
-
if (!globalState[WEBHOOK_SOURCES_KEY]) {
|
|
7
|
-
globalState[WEBHOOK_SOURCES_KEY] = /* @__PURE__ */ new Map();
|
|
8
|
-
}
|
|
9
|
-
return globalState[WEBHOOK_SOURCES_KEY];
|
|
10
|
-
}
|
|
11
|
-
function getHandlerRegistry() {
|
|
12
|
-
const globalState = globalThis;
|
|
13
|
-
if (!globalState[WEBHOOK_HANDLERS_KEY]) {
|
|
14
|
-
globalState[WEBHOOK_HANDLERS_KEY] = [];
|
|
15
|
-
}
|
|
16
|
-
return globalState[WEBHOOK_HANDLERS_KEY];
|
|
17
|
-
}
|
|
18
|
-
function registerWebhookSource(config) {
|
|
19
|
-
const registry = getSourceRegistry();
|
|
20
|
-
registry.set(config.key, config);
|
|
21
|
-
return () => {
|
|
22
|
-
if (registry.get(config.key) === config) registry.delete(config.key);
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
function setWebhookSources(configs) {
|
|
26
|
-
const registry = getSourceRegistry();
|
|
27
|
-
registry.clear();
|
|
28
|
-
for (const config of configs) registry.set(config.key, config);
|
|
29
|
-
}
|
|
30
|
-
function getWebhookSource(sourceKey) {
|
|
31
|
-
return getSourceRegistry().get(sourceKey);
|
|
32
|
-
}
|
|
33
|
-
function listWebhookSources() {
|
|
34
|
-
return Array.from(getSourceRegistry().values());
|
|
35
|
-
}
|
|
36
|
-
function clearWebhookSources() {
|
|
37
|
-
getSourceRegistry().clear();
|
|
38
|
-
}
|
|
39
|
-
function registerWebhookHandler(entry) {
|
|
40
|
-
const registry = getHandlerRegistry();
|
|
41
|
-
registry.push(entry);
|
|
42
|
-
return () => {
|
|
43
|
-
const index = registry.indexOf(entry);
|
|
44
|
-
if (index >= 0) registry.splice(index, 1);
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
function setWebhookHandlers(entries) {
|
|
48
|
-
const registry = getHandlerRegistry();
|
|
49
|
-
registry.length = 0;
|
|
50
|
-
registry.push(...entries);
|
|
51
|
-
}
|
|
52
|
-
function listWebhookHandlers() {
|
|
53
|
-
return [...getHandlerRegistry()];
|
|
54
|
-
}
|
|
55
|
-
function clearWebhookHandlers() {
|
|
56
|
-
getHandlerRegistry().length = 0;
|
|
57
|
-
}
|
|
58
|
-
function resolveWebhookHandlers(sourceKey, eventType) {
|
|
59
|
-
return getHandlerRegistry().filter((entry) => {
|
|
60
|
-
if (entry.meta.source !== sourceKey) return false;
|
|
61
|
-
return matchWebhookEventPattern(eventType, entry.meta.event);
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
export {
|
|
65
|
-
clearWebhookHandlers,
|
|
66
|
-
clearWebhookSources,
|
|
67
|
-
getWebhookSource,
|
|
68
|
-
listWebhookHandlers,
|
|
69
|
-
listWebhookSources,
|
|
70
|
-
registerWebhookHandler,
|
|
71
|
-
registerWebhookSource,
|
|
72
|
-
resolveWebhookHandlers,
|
|
73
|
-
setWebhookHandlers,
|
|
74
|
-
setWebhookSources
|
|
75
|
-
};
|
|
76
|
-
//# sourceMappingURL=inbound-registry.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/webhooks/lib/inbound-registry.ts"],
|
|
4
|
-
"sourcesContent": ["import { matchWebhookEventPattern } from '@open-mercato/shared/lib/events/patterns'\nimport type {\n WebhookHandlerRegistryEntry,\n WebhookSourceConfig,\n} from '@open-mercato/shared/lib/webhooks'\n\nconst WEBHOOK_SOURCES_KEY = '__openMercatoWebhookSources__'\nconst WEBHOOK_HANDLERS_KEY = '__openMercatoWebhookHandlers__'\n\ntype GlobalState = typeof globalThis & {\n [WEBHOOK_SOURCES_KEY]?: Map<string, WebhookSourceConfig>\n [WEBHOOK_HANDLERS_KEY]?: WebhookHandlerRegistryEntry[]\n}\n\nfunction getSourceRegistry(): Map<string, WebhookSourceConfig> {\n const globalState = globalThis as GlobalState\n if (!globalState[WEBHOOK_SOURCES_KEY]) {\n globalState[WEBHOOK_SOURCES_KEY] = new Map<string, WebhookSourceConfig>()\n }\n return globalState[WEBHOOK_SOURCES_KEY]\n}\n\nfunction getHandlerRegistry(): WebhookHandlerRegistryEntry[] {\n const globalState = globalThis as GlobalState\n if (!globalState[WEBHOOK_HANDLERS_KEY]) {\n globalState[WEBHOOK_HANDLERS_KEY] = []\n }\n return globalState[WEBHOOK_HANDLERS_KEY]\n}\n\nexport function registerWebhookSource(config: WebhookSourceConfig): () => void {\n const registry = getSourceRegistry()\n registry.set(config.key, config)\n return () => {\n if (registry.get(config.key) === config) registry.delete(config.key)\n }\n}\n\nexport function setWebhookSources(configs: WebhookSourceConfig[]): void {\n const registry = getSourceRegistry()\n registry.clear()\n for (const config of configs) registry.set(config.key, config)\n}\n\nexport function getWebhookSource(sourceKey: string): WebhookSourceConfig | undefined {\n return getSourceRegistry().get(sourceKey)\n}\n\nexport function listWebhookSources(): WebhookSourceConfig[] {\n return Array.from(getSourceRegistry().values())\n}\n\nexport function clearWebhookSources(): void {\n getSourceRegistry().clear()\n}\n\nexport function registerWebhookHandler(entry: WebhookHandlerRegistryEntry): () => void {\n const registry = getHandlerRegistry()\n registry.push(entry)\n return () => {\n const index = registry.indexOf(entry)\n if (index >= 0) registry.splice(index, 1)\n }\n}\n\nexport function setWebhookHandlers(entries: WebhookHandlerRegistryEntry[]): void {\n const registry = getHandlerRegistry()\n registry.length = 0\n registry.push(...entries)\n}\n\nexport function listWebhookHandlers(): WebhookHandlerRegistryEntry[] {\n return [...getHandlerRegistry()]\n}\n\nexport function clearWebhookHandlers(): void {\n getHandlerRegistry().length = 0\n}\n\n/**\n * Resolve the handlers that match an inbound webhook's source key and event type.\n * Event matching reuses the outbound prefix-wildcard semantics (`*`, `payment_intent.*`).\n */\nexport function resolveWebhookHandlers(\n sourceKey: string,\n eventType: string,\n): WebhookHandlerRegistryEntry[] {\n return getHandlerRegistry().filter((entry) => {\n if (entry.meta.source !== sourceKey) return false\n return matchWebhookEventPattern(eventType, entry.meta.event)\n })\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gCAAgC;AAMzC,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAO7B,SAAS,oBAAsD;AAC7D,QAAM,cAAc;AACpB,MAAI,CAAC,YAAY,mBAAmB,GAAG;AACrC,gBAAY,mBAAmB,IAAI,oBAAI,IAAiC;AAAA,EAC1E;AACA,SAAO,YAAY,mBAAmB;AACxC;AAEA,SAAS,qBAAoD;AAC3D,QAAM,cAAc;AACpB,MAAI,CAAC,YAAY,oBAAoB,GAAG;AACtC,gBAAY,oBAAoB,IAAI,CAAC;AAAA,EACvC;AACA,SAAO,YAAY,oBAAoB;AACzC;AAEO,SAAS,sBAAsB,QAAyC;AAC7E,QAAM,WAAW,kBAAkB;AACnC,WAAS,IAAI,OAAO,KAAK,MAAM;AAC/B,SAAO,MAAM;AACX,QAAI,SAAS,IAAI,OAAO,GAAG,MAAM,OAAQ,UAAS,OAAO,OAAO,GAAG;AAAA,EACrE;AACF;AAEO,SAAS,kBAAkB,SAAsC;AACtE,QAAM,WAAW,kBAAkB;AACnC,WAAS,MAAM;AACf,aAAW,UAAU,QAAS,UAAS,IAAI,OAAO,KAAK,MAAM;AAC/D;AAEO,SAAS,iBAAiB,WAAoD;AACnF,SAAO,kBAAkB,EAAE,IAAI,SAAS;AAC1C;AAEO,SAAS,qBAA4C;AAC1D,SAAO,MAAM,KAAK,kBAAkB,EAAE,OAAO,CAAC;AAChD;AAEO,SAAS,sBAA4B;AAC1C,oBAAkB,EAAE,MAAM;AAC5B;AAEO,SAAS,uBAAuB,OAAgD;AACrF,QAAM,WAAW,mBAAmB;AACpC,WAAS,KAAK,KAAK;AACnB,SAAO,MAAM;AACX,UAAM,QAAQ,SAAS,QAAQ,KAAK;AACpC,QAAI,SAAS,EAAG,UAAS,OAAO,OAAO,CAAC;AAAA,EAC1C;AACF;AAEO,SAAS,mBAAmB,SAA8C;AAC/E,QAAM,WAAW,mBAAmB;AACpC,WAAS,SAAS;AAClB,WAAS,KAAK,GAAG,OAAO;AAC1B;AAEO,SAAS,sBAAqD;AACnE,SAAO,CAAC,GAAG,mBAAmB,CAAC;AACjC;AAEO,SAAS,uBAA6B;AAC3C,qBAAmB,EAAE,SAAS;AAChC;AAMO,SAAS,uBACd,WACA,WAC+B;AAC/B,SAAO,mBAAmB,EAAE,OAAO,CAAC,UAAU;AAC5C,QAAI,MAAM,KAAK,WAAW,UAAW,QAAO;AAC5C,WAAO,yBAAyB,WAAW,MAAM,KAAK,KAAK;AAAA,EAC7D,CAAC;AACH;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { setWebhookHandlers, setWebhookSources } from "./inbound-registry.js";
|
|
2
|
-
function registerWebhookSourceEntries(entries) {
|
|
3
|
-
setWebhookSources(entries.flatMap((entry) => entry.sources ?? []));
|
|
4
|
-
}
|
|
5
|
-
function registerWebhookHandlerEntries(entries) {
|
|
6
|
-
setWebhookHandlers(entries.flatMap((entry) => entry.handlers ?? []));
|
|
7
|
-
}
|
|
8
|
-
export {
|
|
9
|
-
registerWebhookHandlerEntries,
|
|
10
|
-
registerWebhookSourceEntries
|
|
11
|
-
};
|
|
12
|
-
//# sourceMappingURL=module-webhook-registry.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/webhooks/lib/module-webhook-registry.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n WebhookHandlerRegistryEntry,\n WebhookSourceConfig,\n} from '@open-mercato/shared/lib/webhooks'\nimport { setWebhookHandlers, setWebhookSources } from './inbound-registry'\n\nexport type WebhookSourceModuleEntry = {\n moduleId: string\n sources: WebhookSourceConfig[]\n}\n\nexport type WebhookHandlerModuleEntry = {\n moduleId: string\n handlers: WebhookHandlerRegistryEntry[]\n}\n\n/**\n * Bootstrap-time registration for module-declared webhook sources.\n * Driven by the `webhooks.sources` generator plugin via\n * `bootstrap-registrations.generated.ts` \u2014 modules contribute a\n * `webhook-sources.ts` and are wired here without bootstrap.ts edits.\n */\nexport function registerWebhookSourceEntries(entries: WebhookSourceModuleEntry[]): void {\n setWebhookSources(entries.flatMap((entry) => entry.sources ?? []))\n}\n\n/**\n * Bootstrap-time registration for module-declared webhook handlers.\n * Driven by the `webhooks.handlers` generator plugin.\n */\nexport function registerWebhookHandlerEntries(entries: WebhookHandlerModuleEntry[]): void {\n setWebhookHandlers(entries.flatMap((entry) => entry.handlers ?? []))\n}\n"],
|
|
5
|
-
"mappings": "AAIA,SAAS,oBAAoB,yBAAyB;AAkB/C,SAAS,6BAA6B,SAA2C;AACtF,oBAAkB,QAAQ,QAAQ,CAAC,UAAU,MAAM,WAAW,CAAC,CAAC,CAAC;AACnE;AAMO,SAAS,8BAA8B,SAA4C;AACxF,qBAAmB,QAAQ,QAAQ,CAAC,UAAU,MAAM,YAAY,CAAC,CAAC,CAAC;AACrE;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { Migration } from "@mikro-orm/migrations";
|
|
2
|
-
class Migration20260617141327_webhooks extends Migration {
|
|
3
|
-
up() {
|
|
4
|
-
this.addSql(`create table "webhook_inbound_configs" ("id" uuid not null default gen_random_uuid(), "source_key" text not null, "is_active" boolean not null default true, "integration_id" text null, "organization_id" uuid not null, "tenant_id" uuid not null, "created_at" timestamptz not null, "updated_at" timestamptz not null, primary key ("id"));`);
|
|
5
|
-
this.addSql(`create index "webhook_inbound_configs_source_key_is_active_index" on "webhook_inbound_configs" ("source_key", "is_active");`);
|
|
6
|
-
this.addSql(`alter table "webhook_inbound_configs" add constraint "webhook_inbound_configs_source_scope_unique" unique ("source_key", "organization_id", "tenant_id");`);
|
|
7
|
-
this.addSql(`create table "webhook_ingestions" ("id" uuid not null default gen_random_uuid(), "source_key" text not null, "event_type" text not null, "external_message_id" text null, "payload" jsonb not null, "headers" jsonb null, "status" text not null default 'received', "error_message" text null, "processed_at" timestamptz null, "handler_count" int not null default 0, "handler_results" jsonb null, "duration_ms" int null, "organization_id" uuid not null, "tenant_id" uuid not null, "created_at" timestamptz not null, "updated_at" timestamptz not null, primary key ("id"));`);
|
|
8
|
-
this.addSql(`create index "webhook_ingestions_external_message_id_index" on "webhook_ingestions" ("external_message_id");`);
|
|
9
|
-
this.addSql(`create index "webhook_ingestions_organization_id_tenant_id_created_at_index" on "webhook_ingestions" ("organization_id", "tenant_id", "created_at");`);
|
|
10
|
-
this.addSql(`create index "webhook_ingestions_source_key_status_created_at_index" on "webhook_ingestions" ("source_key", "status", "created_at");`);
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
export {
|
|
14
|
-
Migration20260617141327_webhooks
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=Migration20260617141327_webhooks.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/webhooks/migrations/Migration20260617141327_webhooks.ts"],
|
|
4
|
-
"sourcesContent": ["import { Migration } from '@mikro-orm/migrations';\n\nexport class Migration20260617141327_webhooks extends Migration {\n\n override up(): void | Promise<void> {\n this.addSql(`create table \"webhook_inbound_configs\" (\"id\" uuid not null default gen_random_uuid(), \"source_key\" text not null, \"is_active\" boolean not null default true, \"integration_id\" text null, \"organization_id\" uuid not null, \"tenant_id\" uuid not null, \"created_at\" timestamptz not null, \"updated_at\" timestamptz not null, primary key (\"id\"));`);\n this.addSql(`create index \"webhook_inbound_configs_source_key_is_active_index\" on \"webhook_inbound_configs\" (\"source_key\", \"is_active\");`);\n this.addSql(`alter table \"webhook_inbound_configs\" add constraint \"webhook_inbound_configs_source_scope_unique\" unique (\"source_key\", \"organization_id\", \"tenant_id\");`);\n\n this.addSql(`create table \"webhook_ingestions\" (\"id\" uuid not null default gen_random_uuid(), \"source_key\" text not null, \"event_type\" text not null, \"external_message_id\" text null, \"payload\" jsonb not null, \"headers\" jsonb null, \"status\" text not null default 'received', \"error_message\" text null, \"processed_at\" timestamptz null, \"handler_count\" int not null default 0, \"handler_results\" jsonb null, \"duration_ms\" int null, \"organization_id\" uuid not null, \"tenant_id\" uuid not null, \"created_at\" timestamptz not null, \"updated_at\" timestamptz not null, primary key (\"id\"));`);\n this.addSql(`create index \"webhook_ingestions_external_message_id_index\" on \"webhook_ingestions\" (\"external_message_id\");`);\n this.addSql(`create index \"webhook_ingestions_organization_id_tenant_id_created_at_index\" on \"webhook_ingestions\" (\"organization_id\", \"tenant_id\", \"created_at\");`);\n this.addSql(`create index \"webhook_ingestions_source_key_status_created_at_index\" on \"webhook_ingestions\" (\"source_key\", \"status\", \"created_at\");`);\n }\n\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAEnB,MAAM,yCAAyC,UAAU;AAAA,EAErD,KAA2B;AAClC,SAAK,OAAO,iVAAiV;AAC7V,SAAK,OAAO,6HAA6H;AACzI,SAAK,OAAO,2JAA2J;AAEvK,SAAK,OAAO,ujBAAujB;AACnkB,SAAK,OAAO,8GAA8G;AAC1H,SAAK,OAAO,sJAAsJ;AAClK,SAAK,OAAO,sIAAsI;AAAA,EACpJ;AAEF;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
2
|
-
import { processInboundDispatchJob } from "../lib/inbound-dispatch.js";
|
|
3
|
-
const logger = createLogger("webhooks");
|
|
4
|
-
const metadata = {
|
|
5
|
-
queue: "webhook-inbound-dispatch",
|
|
6
|
-
id: "webhooks:inbound-dispatch-worker",
|
|
7
|
-
concurrency: 5
|
|
8
|
-
};
|
|
9
|
-
async function handler(job, ctx) {
|
|
10
|
-
const em = ctx.resolve("em").fork();
|
|
11
|
-
try {
|
|
12
|
-
await processInboundDispatchJob(em, job.data, {
|
|
13
|
-
resolve: (name) => ctx.resolve(name)
|
|
14
|
-
});
|
|
15
|
-
} catch (error) {
|
|
16
|
-
logger.error("Inbound dispatch job processing failed", {
|
|
17
|
-
ingestionId: job.data.ingestionId,
|
|
18
|
-
sourceKey: job.data.sourceKey,
|
|
19
|
-
tenantId: job.data.tenantId,
|
|
20
|
-
err: error
|
|
21
|
-
});
|
|
22
|
-
throw error;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
export {
|
|
26
|
-
handler as default,
|
|
27
|
-
metadata
|
|
28
|
-
};
|
|
29
|
-
//# sourceMappingURL=inbound-dispatch.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/modules/webhooks/workers/inbound-dispatch.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { processInboundDispatchJob, type InboundDispatchJob } from '../lib/inbound-dispatch'\n\nconst logger = createLogger('webhooks')\n\nexport const metadata = {\n queue: 'webhook-inbound-dispatch',\n id: 'webhooks:inbound-dispatch-worker',\n concurrency: 5,\n}\n\nexport default async function handler(\n job: { data: InboundDispatchJob },\n ctx: { resolve: <T = unknown>(name: string) => T },\n) {\n const em = (ctx.resolve('em') as EntityManager).fork()\n try {\n await processInboundDispatchJob(em, job.data, {\n resolve: <T,>(name: string) => ctx.resolve(name) as T,\n })\n } catch (error) {\n logger.error('Inbound dispatch job processing failed', {\n ingestionId: job.data.ingestionId,\n sourceKey: job.data.sourceKey,\n tenantId: job.data.tenantId,\n err: error,\n })\n throw error\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,iCAA0D;AAEnE,MAAM,SAAS,aAAa,UAAU;AAE/B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAEA,eAAO,QACL,KACA,KACA;AACA,QAAM,KAAM,IAAI,QAAQ,IAAI,EAAoB,KAAK;AACrD,MAAI;AACF,UAAM,0BAA0B,IAAI,IAAI,MAAM;AAAA,MAC5C,SAAS,CAAK,SAAiB,IAAI,QAAQ,IAAI;AAAA,IACjD,CAAC;AAAA,EACH,SAAS,OAAO;AACd,WAAO,MAAM,0CAA0C;AAAA,MACrD,aAAa,IAAI,KAAK;AAAA,MACtB,WAAW,IAAI,KAAK;AAAA,MACpB,UAAU,IAAI,KAAK;AAAA,MACnB,KAAK;AAAA,IACP,CAAC;AACD,UAAM;AAAA,EACR;AACF;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export const id = "id";
|
|
2
|
-
export const source_key = "source_key";
|
|
3
|
-
export const is_active = "is_active";
|
|
4
|
-
export const integration_id = "integration_id";
|
|
5
|
-
export const organization_id = "organization_id";
|
|
6
|
-
export const tenant_id = "tenant_id";
|
|
7
|
-
export const created_at = "created_at";
|
|
8
|
-
export const updated_at = "updated_at";
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
export const id = "id";
|
|
2
|
-
export const source_key = "source_key";
|
|
3
|
-
export const event_type = "event_type";
|
|
4
|
-
export const external_message_id = "external_message_id";
|
|
5
|
-
export const payload = "payload";
|
|
6
|
-
export const headers = "headers";
|
|
7
|
-
export const status = "status";
|
|
8
|
-
export const error_message = "error_message";
|
|
9
|
-
export const processed_at = "processed_at";
|
|
10
|
-
export const handler_count = "handler_count";
|
|
11
|
-
export const handler_results = "handler_results";
|
|
12
|
-
export const duration_ms = "duration_ms";
|
|
13
|
-
export const organization_id = "organization_id";
|
|
14
|
-
export const tenant_id = "tenant_id";
|
|
15
|
-
export const created_at = "created_at";
|
|
16
|
-
export const updated_at = "updated_at";
|
|
@@ -1,149 +0,0 @@
|
|
|
1
|
-
import type { WebhookSourceConfig } from '@open-mercato/shared/lib/webhooks'
|
|
2
|
-
|
|
3
|
-
const enqueueInboundDispatch = jest.fn(async () => 'job-1')
|
|
4
|
-
const emitWebhooksEvent = jest.fn(async () => undefined)
|
|
5
|
-
const findWithDecryption = jest.fn()
|
|
6
|
-
const credentialsResolve = jest.fn(async () => ({ webhookSigningSecret: 'whsec' }))
|
|
7
|
-
|
|
8
|
-
const flush = jest.fn(async () => undefined)
|
|
9
|
-
const persist = jest.fn()
|
|
10
|
-
const em = {
|
|
11
|
-
fork: () => em,
|
|
12
|
-
create: (_entity: unknown, data: Record<string, unknown>) => ({ id: 'ing-1', ...data }),
|
|
13
|
-
persist,
|
|
14
|
-
flush,
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
18
|
-
createRequestContainer: async () => ({
|
|
19
|
-
resolve: (name: string) => {
|
|
20
|
-
if (name === 'em') return em
|
|
21
|
-
if (name === 'integrationCredentialsService') return { resolve: credentialsResolve }
|
|
22
|
-
throw new Error(`[internal] no mock for ${name}`)
|
|
23
|
-
},
|
|
24
|
-
}),
|
|
25
|
-
}))
|
|
26
|
-
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
27
|
-
resolveTranslations: async () => ({ translate: (_key: string, fallback: string) => fallback }),
|
|
28
|
-
}))
|
|
29
|
-
jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
|
|
30
|
-
findWithDecryption: (...args: unknown[]) => findWithDecryption(...args),
|
|
31
|
-
}))
|
|
32
|
-
jest.mock('../../../../events', () => ({
|
|
33
|
-
emitWebhooksEvent: (...args: unknown[]) => emitWebhooksEvent(...args),
|
|
34
|
-
}))
|
|
35
|
-
jest.mock('../../../../lib/queue', () => ({
|
|
36
|
-
enqueueInboundDispatch: (...args: unknown[]) => enqueueInboundDispatch(...args),
|
|
37
|
-
}))
|
|
38
|
-
|
|
39
|
-
import { POST } from '../route'
|
|
40
|
-
import { clearWebhookSources, registerWebhookSource } from '../../../../lib/inbound-registry'
|
|
41
|
-
|
|
42
|
-
function makeSource(overrides: Partial<WebhookSourceConfig> = {}): WebhookSourceConfig {
|
|
43
|
-
return {
|
|
44
|
-
key: 'stripe',
|
|
45
|
-
label: 'Stripe',
|
|
46
|
-
verifier: async () => true,
|
|
47
|
-
eventTypeExtractor: (body) => String((body as { type?: string }).type ?? ''),
|
|
48
|
-
messageIdExtractor: (body) => String((body as { id?: string }).id ?? ''),
|
|
49
|
-
...overrides,
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function postTo(
|
|
54
|
-
endpointId: string,
|
|
55
|
-
body = '{"type":"payment_intent.succeeded","id":"evt_1"}',
|
|
56
|
-
headers: Record<string, string> = {},
|
|
57
|
-
) {
|
|
58
|
-
const request = new Request(`http://localhost/api/webhooks/inbound/${endpointId}`, {
|
|
59
|
-
method: 'POST',
|
|
60
|
-
body,
|
|
61
|
-
headers: { 'content-type': 'application/json', ...headers },
|
|
62
|
-
})
|
|
63
|
-
return POST(request, { params: Promise.resolve({ endpointId }) })
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
beforeEach(() => {
|
|
67
|
-
clearWebhookSources()
|
|
68
|
-
enqueueInboundDispatch.mockClear()
|
|
69
|
-
emitWebhooksEvent.mockClear()
|
|
70
|
-
persist.mockClear()
|
|
71
|
-
flush.mockReset()
|
|
72
|
-
flush.mockResolvedValue(undefined)
|
|
73
|
-
findWithDecryption.mockReset()
|
|
74
|
-
findWithDecryption.mockResolvedValue([{ organizationId: 'o1', tenantId: 't1', sourceKey: 'stripe', isActive: true }])
|
|
75
|
-
credentialsResolve.mockClear()
|
|
76
|
-
})
|
|
77
|
-
|
|
78
|
-
it('returns 404 when neither a source nor an adapter matches the segment', async () => {
|
|
79
|
-
const res = await postTo('totally-unknown')
|
|
80
|
-
expect(res.status).toBe(404)
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
it('accepts a valid source webhook: records ingestion, enqueues dispatch, emits received', async () => {
|
|
84
|
-
registerWebhookSource(makeSource({ verifier: async () => true }))
|
|
85
|
-
const res = await postTo('stripe')
|
|
86
|
-
expect(res.status).toBe(200)
|
|
87
|
-
await expect(res.json()).resolves.toEqual({ ok: true })
|
|
88
|
-
expect(enqueueInboundDispatch).toHaveBeenCalledWith(
|
|
89
|
-
expect.objectContaining({ ingestionId: 'ing-1', sourceKey: 'stripe', eventType: 'payment_intent.succeeded', tenantId: 't1', organizationId: 'o1' }),
|
|
90
|
-
)
|
|
91
|
-
expect(emitWebhooksEvent).toHaveBeenCalledWith(
|
|
92
|
-
'webhooks.inbound.received',
|
|
93
|
-
expect.objectContaining({ endpointId: 'stripe', eventType: 'payment_intent.succeeded' }),
|
|
94
|
-
{ persistent: true },
|
|
95
|
-
)
|
|
96
|
-
})
|
|
97
|
-
|
|
98
|
-
it('rejects a stale source webhook before signature verification or persistence', async () => {
|
|
99
|
-
const verifier = jest.fn(async () => true)
|
|
100
|
-
registerWebhookSource(makeSource({ verifier }))
|
|
101
|
-
|
|
102
|
-
const res = await postTo('stripe', undefined, { 'webhook-timestamp': '1' })
|
|
103
|
-
|
|
104
|
-
expect(res.status).toBe(400)
|
|
105
|
-
await expect(res.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
|
|
106
|
-
expect(verifier).not.toHaveBeenCalled()
|
|
107
|
-
expect(findWithDecryption).not.toHaveBeenCalled()
|
|
108
|
-
expect(persist).not.toHaveBeenCalled()
|
|
109
|
-
expect(flush).not.toHaveBeenCalled()
|
|
110
|
-
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
111
|
-
expect(emitWebhooksEvent).not.toHaveBeenCalled()
|
|
112
|
-
})
|
|
113
|
-
|
|
114
|
-
it('rejects an oversized source webhook before verification or persistence', async () => {
|
|
115
|
-
const verifier = jest.fn(async () => true)
|
|
116
|
-
registerWebhookSource(makeSource({ verifier }))
|
|
117
|
-
const request = new Request('http://localhost/api/webhooks/inbound/stripe', {
|
|
118
|
-
method: 'POST',
|
|
119
|
-
body: '{}',
|
|
120
|
-
headers: {
|
|
121
|
-
'content-length': String(1024 * 1024 + 1),
|
|
122
|
-
'content-type': 'application/json',
|
|
123
|
-
},
|
|
124
|
-
})
|
|
125
|
-
|
|
126
|
-
const response = await POST(request, { params: Promise.resolve({ endpointId: 'stripe' }) })
|
|
127
|
-
|
|
128
|
-
expect(response.status).toBe(413)
|
|
129
|
-
expect(verifier).not.toHaveBeenCalled()
|
|
130
|
-
expect(findWithDecryption).not.toHaveBeenCalled()
|
|
131
|
-
expect(persist).not.toHaveBeenCalled()
|
|
132
|
-
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
133
|
-
})
|
|
134
|
-
|
|
135
|
-
it('rejects with 401 when no candidate scope verifies', async () => {
|
|
136
|
-
registerWebhookSource(makeSource({ verifier: async () => false }))
|
|
137
|
-
const res = await postTo('stripe')
|
|
138
|
-
expect(res.status).toBe(401)
|
|
139
|
-
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
140
|
-
})
|
|
141
|
-
|
|
142
|
-
it('returns duplicate when the receipt unique constraint is violated', async () => {
|
|
143
|
-
registerWebhookSource(makeSource())
|
|
144
|
-
flush.mockRejectedValueOnce({ code: '23505' })
|
|
145
|
-
const res = await postTo('stripe')
|
|
146
|
-
expect(res.status).toBe(200)
|
|
147
|
-
await expect(res.json()).resolves.toEqual({ ok: true, duplicate: true })
|
|
148
|
-
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
149
|
-
})
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { dataTableExtensionHost, defineModuleExtensionPoints } from '@open-mercato/shared/modules/widgets/extension-points'
|
|
2
|
-
|
|
3
|
-
export const extensionPoints = defineModuleExtensionPoints({
|
|
4
|
-
moduleId: 'webhooks',
|
|
5
|
-
hosts: {
|
|
6
|
-
webhooksTable: dataTableExtensionHost({ tableId: 'webhooks.list', source: 'backend/webhooks/page.tsx' }),
|
|
7
|
-
deliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.deliveries', source: 'backend/webhooks/[id]/page.tsx' }),
|
|
8
|
-
integrationDeliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.integration-deliveries', source: 'widgets/injection/integration-deliveries/widget.client.tsx' }),
|
|
9
|
-
},
|
|
10
|
-
})
|
|
11
|
-
|
|
12
|
-
export default extensionPoints
|