@open-wa/integration-webhook 5.0.0-alpha.7 → 5.0.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.md +2 -2
- package/README.md +5 -5
- package/dist/index.d.mts +80 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +249 -31
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -6
- package/.turbo/turbo-build.log +0 -30
- package/.turbo/turbo-lint.log +0 -0
- package/CHANGELOG.md +0 -61
- package/src/config.ts +0 -43
- package/src/deliverer.ts +0 -81
- package/src/index.ts +0 -7
- package/src/plugin.ts +0 -76
- package/tsconfig.json +0 -9
package/LICENSE.md
CHANGED
|
@@ -55,9 +55,9 @@ Licensor hereby grants permission by this license ("License"), free of charge,
|
|
|
55
55
|
4. Compliance with Human Rights Laws and Human Rights Principles:
|
|
56
56
|
|
|
57
57
|
a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
|
|
58
|
-
|
|
58
|
+
|
|
59
59
|
b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
|
|
60
|
-
|
|
60
|
+
|
|
61
61
|
c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles.
|
|
62
62
|
|
|
63
63
|
5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
|
package/README.md
CHANGED
|
@@ -8,13 +8,13 @@ Part of the [@open-wa v5 monorepo](https://github.com/open-wa/wa-automate-nodejs
|
|
|
8
8
|
|
|
9
9
|
`@open-wa/integration-webhook` forwards public open-wa events to an external URL with HTTP `POST`. It supports event filtering, custom headers, request timeouts, retry with exponential backoff, and concurrent delivery through a queue.
|
|
10
10
|
|
|
11
|
-
Use this integration
|
|
11
|
+
Use this integration to send open-wa runtime events to another service without direct open-wa integration.
|
|
12
12
|
|
|
13
13
|
## Configuration
|
|
14
14
|
|
|
15
15
|
The plugin config is validated by the plugin SDK schema in `src/plugin.ts`.
|
|
16
16
|
|
|
17
|
-
| Field |
|
|
17
|
+
| Field | Necessary | Source-visible behavior |
|
|
18
18
|
| --- | --- | --- |
|
|
19
19
|
| `url` | Yes | Target URL for webhook delivery. Must be a URL. |
|
|
20
20
|
| `events` | No | `all` or an array of event names. Defaults to `all`. Non-matching events are skipped. |
|
|
@@ -45,7 +45,7 @@ The payload shape is defined by `WebhookPayload` in `src/config.ts` and produced
|
|
|
45
45
|
- `WebhookDeliverer` posts JSON with native `fetch` and aborts requests with `AbortController` when the timeout elapses.
|
|
46
46
|
- Non-2xx responses throw an error and enter the retry path.
|
|
47
47
|
- Retry delay is `retryDelay * 2 ** attempt` until the configured retry count is exhausted.
|
|
48
|
-
-
|
|
48
|
+
- The deliverer logs failed deliveries after all attempts. The final retry path does not throw the error again.
|
|
49
49
|
- On `dispose`, the plugin waits for the queue to become idle and logs that the queue drained.
|
|
50
50
|
|
|
51
51
|
## Exports
|
|
@@ -63,8 +63,8 @@ The payload shape is defined by `WebhookPayload` in `src/config.ts` and produced
|
|
|
63
63
|
|
|
64
64
|
## Documentation
|
|
65
65
|
|
|
66
|
-
See the [docs site](https://
|
|
66
|
+
See the [docs site](https://openwa.dev).
|
|
67
67
|
|
|
68
68
|
## License
|
|
69
69
|
|
|
70
|
-
[H-DNH
|
|
70
|
+
[H-DNH 1.1](https://github.com/open-wa/wa-automate-nodejs/blob/master/LICENSE.md) - Hippocratic + Do Not Harm
|
package/dist/index.d.mts
CHANGED
|
@@ -1,25 +1,42 @@
|
|
|
1
|
-
import * as _$_open_wa_plugin_sdk0 from "@open-wa/plugin-sdk";
|
|
2
1
|
import { z } from "@open-wa/plugin-sdk";
|
|
3
|
-
|
|
2
|
+
import { Context, Layer } from "effect";
|
|
3
|
+
import { RuntimeObservabilityShape } from "@open-wa/runtime-core";
|
|
4
4
|
//#region src/plugin.d.ts
|
|
5
5
|
declare const configSchema: z.ZodObject<{
|
|
6
6
|
url: z.ZodString;
|
|
7
7
|
events: z.ZodDefault<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodLiteral<"all">]>>;
|
|
8
8
|
concurrency: z.ZodDefault<z.ZodNumber>;
|
|
9
|
+
queueCapacity: z.ZodDefault<z.ZodNumber>;
|
|
10
|
+
overload: z.ZodDefault<z.ZodEnum<{
|
|
11
|
+
backpressure: "backpressure";
|
|
12
|
+
dropping: "dropping";
|
|
13
|
+
}>>;
|
|
9
14
|
retries: z.ZodDefault<z.ZodNumber>;
|
|
10
15
|
retryDelay: z.ZodDefault<z.ZodNumber>;
|
|
11
|
-
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.
|
|
16
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
12
17
|
timeout: z.ZodDefault<z.ZodNumber>;
|
|
18
|
+
durability: z.ZodOptional<z.ZodObject<{
|
|
19
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
20
|
+
path: z.ZodDefault<z.ZodString>;
|
|
21
|
+
replayLimit: z.ZodDefault<z.ZodNumber>;
|
|
22
|
+
}, z.core.$strip>>;
|
|
13
23
|
}, z.core.$strip>;
|
|
14
24
|
type WebhookPluginConfig = z.infer<typeof configSchema>;
|
|
15
|
-
declare const _default:
|
|
25
|
+
declare const _default: import("@open-wa/plugin-sdk").Plugin<{
|
|
16
26
|
url: string;
|
|
17
27
|
events: "all" | string[];
|
|
18
28
|
concurrency: number;
|
|
29
|
+
queueCapacity: number;
|
|
30
|
+
overload: "backpressure" | "dropping";
|
|
19
31
|
retries: number;
|
|
20
32
|
retryDelay: number;
|
|
33
|
+
headers?: Record<string, string> | undefined;
|
|
21
34
|
timeout: number;
|
|
22
|
-
|
|
35
|
+
durability?: {
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
path: string;
|
|
38
|
+
replayLimit: number;
|
|
39
|
+
} | undefined;
|
|
23
40
|
}>;
|
|
24
41
|
//#endregion
|
|
25
42
|
//#region src/config.d.ts
|
|
@@ -27,10 +44,17 @@ interface WebhookConfig {
|
|
|
27
44
|
url: string;
|
|
28
45
|
events?: string[] | 'all';
|
|
29
46
|
concurrency?: number;
|
|
47
|
+
queueCapacity?: number;
|
|
48
|
+
overload?: 'backpressure' | 'dropping';
|
|
30
49
|
retries?: number;
|
|
31
50
|
retryDelay?: number;
|
|
32
51
|
headers?: Record<string, string>;
|
|
33
52
|
timeout?: number;
|
|
53
|
+
durability?: {
|
|
54
|
+
enabled: boolean;
|
|
55
|
+
path?: string;
|
|
56
|
+
replayLimit?: number;
|
|
57
|
+
};
|
|
34
58
|
}
|
|
35
59
|
interface Webhook {
|
|
36
60
|
id: string;
|
|
@@ -45,6 +69,7 @@ interface WebhookPayload {
|
|
|
45
69
|
event: string;
|
|
46
70
|
payload: unknown;
|
|
47
71
|
timestamp: number;
|
|
72
|
+
idempotencyKey?: string;
|
|
48
73
|
}
|
|
49
74
|
//#endregion
|
|
50
75
|
//#region ../../packages/logger/dist/index.d.cts
|
|
@@ -68,8 +93,7 @@ interface LogContext {
|
|
|
68
93
|
}
|
|
69
94
|
//#endregion
|
|
70
95
|
//#region src/core/levels.d.ts
|
|
71
|
-
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
72
|
-
//#region src/core/logger.d.ts
|
|
96
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
73
97
|
interface LoggerInterface {
|
|
74
98
|
debug(message: string, meta?: LogContext): void;
|
|
75
99
|
info(message: string, meta?: LogContext): void;
|
|
@@ -84,23 +108,67 @@ interface LoggerInterface {
|
|
|
84
108
|
withContext(context: LogContext): LoggerInterface;
|
|
85
109
|
setLevel(level: LogLevel): void;
|
|
86
110
|
}
|
|
87
|
-
type Logger = LoggerInterface;
|
|
88
|
-
//#region src/security/rules.d.ts
|
|
111
|
+
type Logger = LoggerInterface;
|
|
89
112
|
//#endregion
|
|
90
113
|
//#region src/deliverer.d.ts
|
|
91
|
-
declare class WebhookDeliverer {
|
|
114
|
+
export declare class WebhookDeliverer {
|
|
92
115
|
private readonly config;
|
|
93
116
|
private readonly logger;
|
|
94
117
|
private readonly queue;
|
|
95
118
|
private readonly retries;
|
|
96
119
|
private readonly retryDelay;
|
|
97
120
|
private readonly timeout;
|
|
98
|
-
|
|
121
|
+
private readonly store?;
|
|
122
|
+
private readonly ready;
|
|
123
|
+
private readonly inFlight;
|
|
124
|
+
private readonly background;
|
|
125
|
+
private readonly lifecycle;
|
|
126
|
+
private readonly observability;
|
|
127
|
+
private closing;
|
|
128
|
+
constructor(config: WebhookConfig, logger: Pick<Logger, 'debug' | 'warn' | 'error'>, observability?: RuntimeObservabilityShape);
|
|
99
129
|
deliver(payload: WebhookPayload): Promise<void>;
|
|
130
|
+
private schedule;
|
|
100
131
|
private sendWithRetry;
|
|
101
132
|
private sleep;
|
|
102
133
|
waitForIdle(): Promise<void>;
|
|
134
|
+
close(): Promise<void>;
|
|
135
|
+
metrics(): Promise<Readonly<Record<string, number>>>;
|
|
136
|
+
private replayPending;
|
|
103
137
|
}
|
|
104
138
|
//#endregion
|
|
105
|
-
|
|
139
|
+
//#region src/durable-store.d.ts
|
|
140
|
+
interface StoredWebhookDelivery {
|
|
141
|
+
readonly id: string;
|
|
142
|
+
readonly payload: WebhookPayload;
|
|
143
|
+
readonly attempts: number;
|
|
144
|
+
readonly nextAttemptAt: number;
|
|
145
|
+
readonly status: 'pending' | 'delivered' | 'dead_letter';
|
|
146
|
+
}
|
|
147
|
+
interface WebhookDeliveryStore {
|
|
148
|
+
enqueue(payload: WebhookPayload): StoredWebhookDelivery;
|
|
149
|
+
pending(limit?: number): StoredWebhookDelivery[];
|
|
150
|
+
markAttempt(id: string, error: string, nextAttemptAt: number): void;
|
|
151
|
+
markDelivered(id: string): void;
|
|
152
|
+
markDeadLetter(id: string, error: string): void;
|
|
153
|
+
close(): void;
|
|
154
|
+
}
|
|
155
|
+
export declare class SqliteWebhookDeliveryStore implements WebhookDeliveryStore {
|
|
156
|
+
private readonly database;
|
|
157
|
+
constructor(path: string);
|
|
158
|
+
enqueue(payload: WebhookPayload): StoredWebhookDelivery;
|
|
159
|
+
pending(limit?: number): StoredWebhookDelivery[];
|
|
160
|
+
markAttempt(id: string, error: string, nextAttemptAt: number): void;
|
|
161
|
+
markDelivered(id: string): void;
|
|
162
|
+
markDeadLetter(id: string, error: string): void;
|
|
163
|
+
close(): void;
|
|
164
|
+
private get;
|
|
165
|
+
private decode;
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/service.d.ts
|
|
169
|
+
export declare const WebhookDelivererService: Context.Service<WebhookDeliverer, WebhookDeliverer>;
|
|
170
|
+
export declare const webhookDelivererTestLayer: (deliverer: WebhookDeliverer) => Layer.Layer<WebhookDeliverer, never, never>;
|
|
171
|
+
export declare const webhookDelivererLayer: (config: WebhookConfig, logger: Pick<Logger, 'debug' | 'warn' | 'error'>) => Layer.Layer<WebhookDeliverer, never, never>;
|
|
172
|
+
//#endregion
|
|
173
|
+
export { type StoredWebhookDelivery, type Webhook, type WebhookConfig, type WebhookDeliveryStore, type WebhookPayload, type WebhookPluginConfig, _default as default, _default as webhookPlugin };
|
|
106
174
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/plugin.ts","../src/config.ts","../../../packages/logger/dist/index.d.cts","../src/deliverer.ts","../src/durable-store.ts","../src/service.ts"],"mappings":";;;;cAUM,cAAY,EAAA;;;;;;;;;;;;;;;;;;GAiChB,EAAA,KAAA;KAEU,sBAAsB,EAAE,aAAa;;;;;;;;;;;;;;;;;;;UCxChC;EAEf;EAGA;EAGA;EAGA;EAGA;EAGA;EAGA;EAGA,UAAU;EAGV;EAGA;IACE;IACA;IACA;;;UAIa;EACf;EACA;EACA;EACA,UAAU;EACV;;UAGe;EACf;EACA;EACA;EACA;EACA;EAEA;;;;;;UCqBQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;GACC;;;;KAiBE;UAMK;EACR,MAAM,iBAAiB,OAAO;EAC9B,KAAK,iBAAiB,OAAO;EAC7B,KAAK,iBAAiB,OAAO;EAC7B,MAAM,iBAAiB,OAAO;IAC5B;;EAEF,MAAM,iBAAiB,OAAO;IAC5B;;EAEF,MAAM,SAAS,aAAa;EAC5B,YAAY,SAAS,aAAa;EAClC,SAAS,OAAO;;KAKb,SAAS;;;qBChHD;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;UACT;EAER,YACE,QAAQ,eACR,QAAQ,KAAK,qCACb,gBAAe;EAqBX,QAAQ,SAAS,iBAAiB;UAQ1B;UAgBA;UA2DN;EAmBF,eAAe;EAKf,SAAS;EAUT,WAAW,QAAQ,SAAS;UAIpB;;;;UC7KC;WACN;WACA,SAAS;WACT;WACA;WACA;;UAGM;EACf,QAAQ,SAAS,iBAAiB;EAClC,QAAQ,iBAAiB;EACzB,YAAY,YAAY,eAAe;EACvC,cAAc;EACd,eAAe,YAAY;EAC3B;;qBAgBW,sCAAsC;mBAChC;EAEjB,YAAY;EAqBZ,QAAQ,SAAS,iBAAiB;EAWlC,QAAQ,iBAAe;EAkBvB,YAAY,YAAY,eAAe;EAQvC,cAAc;EAQd,eAAe,YAAY;EAQ3B;UAIQ;UAQA;;;;qBCxHG,yBAAuB,QAAA,QAAA,kBAAA;qBAGvB,4BAAyB,WAAe,qBAAgB,MAAA,MAAA;qBAGxD,wBAAqB,QACxB,eAAa,QACb,KAAK,wCAAmC,MAAA,MAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,31 +1,160 @@
|
|
|
1
1
|
import { createPlugin, z } from "@open-wa/plugin-sdk";
|
|
2
|
-
import
|
|
2
|
+
import { Context, Effect, Layer, ManagedRuntime } from "effect";
|
|
3
|
+
import { ScopedTaskQueue, makeInMemoryObservability, queueMetricsObserver } from "@open-wa/runtime-core";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { mkdirSync } from "node:fs";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import { DatabaseSync } from "node:sqlite";
|
|
8
|
+
//#region src/durable-store.ts
|
|
9
|
+
const deliveryId = (payload) => createHash("sha256").update(payload.idempotencyKey ?? JSON.stringify(payload)).digest("hex");
|
|
10
|
+
var SqliteWebhookDeliveryStore = class {
|
|
11
|
+
constructor(path) {
|
|
12
|
+
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
|
|
13
|
+
this.database = new DatabaseSync(path);
|
|
14
|
+
this.database.exec(`
|
|
15
|
+
PRAGMA journal_mode = WAL;
|
|
16
|
+
PRAGMA synchronous = FULL;
|
|
17
|
+
CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
|
18
|
+
id TEXT PRIMARY KEY,
|
|
19
|
+
payload TEXT NOT NULL,
|
|
20
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
21
|
+
next_attempt_at INTEGER NOT NULL,
|
|
22
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
23
|
+
last_error TEXT,
|
|
24
|
+
created_at INTEGER NOT NULL,
|
|
25
|
+
updated_at INTEGER NOT NULL
|
|
26
|
+
);
|
|
27
|
+
CREATE INDEX IF NOT EXISTS webhook_deliveries_pending
|
|
28
|
+
ON webhook_deliveries(status, next_attempt_at);
|
|
29
|
+
`);
|
|
30
|
+
}
|
|
31
|
+
enqueue(payload) {
|
|
32
|
+
const id = deliveryId(payload);
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
this.database.prepare(`
|
|
35
|
+
INSERT OR IGNORE INTO webhook_deliveries
|
|
36
|
+
(id, payload, attempts, next_attempt_at, status, created_at, updated_at)
|
|
37
|
+
VALUES (?, ?, 0, ?, 'pending', ?, ?)
|
|
38
|
+
`).run(id, JSON.stringify(payload), now, now, now);
|
|
39
|
+
return this.get(id);
|
|
40
|
+
}
|
|
41
|
+
pending(limit = 1e3) {
|
|
42
|
+
return this.database.prepare(`
|
|
43
|
+
SELECT id, payload, attempts, next_attempt_at, status
|
|
44
|
+
FROM webhook_deliveries
|
|
45
|
+
WHERE status = 'pending'
|
|
46
|
+
ORDER BY next_attempt_at ASC, created_at ASC
|
|
47
|
+
LIMIT ?
|
|
48
|
+
`).all(limit).flatMap((row) => {
|
|
49
|
+
try {
|
|
50
|
+
return [this.decode(row)];
|
|
51
|
+
} catch (error) {
|
|
52
|
+
this.markDeadLetter(row.id, `decode failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
53
|
+
return [];
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
markAttempt(id, error, nextAttemptAt) {
|
|
58
|
+
this.database.prepare(`
|
|
59
|
+
UPDATE webhook_deliveries
|
|
60
|
+
SET attempts = attempts + 1, next_attempt_at = ?, last_error = ?, updated_at = ?
|
|
61
|
+
WHERE id = ? AND status = 'pending'
|
|
62
|
+
`).run(nextAttemptAt, error, Date.now(), id);
|
|
63
|
+
}
|
|
64
|
+
markDelivered(id) {
|
|
65
|
+
this.database.prepare(`
|
|
66
|
+
UPDATE webhook_deliveries
|
|
67
|
+
SET status = 'delivered', last_error = NULL, updated_at = ?
|
|
68
|
+
WHERE id = ?
|
|
69
|
+
`).run(Date.now(), id);
|
|
70
|
+
}
|
|
71
|
+
markDeadLetter(id, error) {
|
|
72
|
+
this.database.prepare(`
|
|
73
|
+
UPDATE webhook_deliveries
|
|
74
|
+
SET status = 'dead_letter', last_error = ?, updated_at = ?
|
|
75
|
+
WHERE id = ?
|
|
76
|
+
`).run(error, Date.now(), id);
|
|
77
|
+
}
|
|
78
|
+
close() {
|
|
79
|
+
this.database.close();
|
|
80
|
+
}
|
|
81
|
+
get(id) {
|
|
82
|
+
const row = this.database.prepare(`
|
|
83
|
+
SELECT id, payload, attempts, next_attempt_at, status
|
|
84
|
+
FROM webhook_deliveries WHERE id = ?
|
|
85
|
+
`).get(id);
|
|
86
|
+
return row ? this.decode(row) : void 0;
|
|
87
|
+
}
|
|
88
|
+
decode(row) {
|
|
89
|
+
return {
|
|
90
|
+
id: row.id,
|
|
91
|
+
payload: JSON.parse(row.payload),
|
|
92
|
+
attempts: row.attempts,
|
|
93
|
+
nextAttemptAt: row.next_attempt_at,
|
|
94
|
+
status: row.status
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
3
99
|
//#region src/deliverer.ts
|
|
4
100
|
/**
|
|
5
101
|
* Webhook Deliverer — uses native fetch instead of axios.
|
|
6
|
-
* Supports exponential backoff retry
|
|
102
|
+
* Supports exponential backoff retry on a bounded, scoped Effect queue.
|
|
7
103
|
*/
|
|
8
104
|
var WebhookDeliverer = class {
|
|
9
|
-
constructor(config, logger) {
|
|
105
|
+
constructor(config, logger, observability = makeInMemoryObservability()) {
|
|
106
|
+
this.inFlight = /* @__PURE__ */ new Set();
|
|
107
|
+
this.background = /* @__PURE__ */ new Set();
|
|
108
|
+
this.lifecycle = new AbortController();
|
|
109
|
+
this.closing = false;
|
|
10
110
|
this.config = config;
|
|
11
111
|
this.logger = logger;
|
|
12
112
|
this.retries = config.retries ?? 3;
|
|
13
113
|
this.retryDelay = config.retryDelay ?? 1e3;
|
|
14
114
|
this.timeout = config.timeout ?? 3e4;
|
|
15
|
-
this.
|
|
115
|
+
this.observability = observability;
|
|
116
|
+
this.queue = ScopedTaskQueue.make({
|
|
117
|
+
name: "webhook.delivery",
|
|
118
|
+
concurrency: config.concurrency ?? 10,
|
|
119
|
+
capacity: config.queueCapacity ?? 1e3,
|
|
120
|
+
overload: config.overload ?? "backpressure",
|
|
121
|
+
observe: queueMetricsObserver(observability)
|
|
122
|
+
});
|
|
123
|
+
this.store = config.durability?.enabled ? new SqliteWebhookDeliveryStore(config.durability.path ?? ".openwa/webhook-deliveries.sqlite") : void 0;
|
|
124
|
+
this.ready = this.replayPending();
|
|
16
125
|
}
|
|
17
126
|
async deliver(payload) {
|
|
18
|
-
await this.
|
|
127
|
+
await this.ready;
|
|
128
|
+
if (this.closing) throw new Error("Webhook deliverer is closed");
|
|
129
|
+
const stored = this.store?.enqueue(payload);
|
|
130
|
+
if (stored?.status === "delivered" || stored && this.inFlight.has(stored.id)) return;
|
|
131
|
+
await this.schedule(payload, stored);
|
|
19
132
|
}
|
|
20
|
-
async
|
|
133
|
+
async schedule(payload, stored) {
|
|
134
|
+
if (stored) this.inFlight.add(stored.id);
|
|
135
|
+
try {
|
|
136
|
+
await (await this.queue).submit(async () => {
|
|
137
|
+
const delay = Math.max(0, (stored?.nextAttemptAt ?? 0) - Date.now());
|
|
138
|
+
if (delay > 0) await this.sleep(delay);
|
|
139
|
+
await this.sendWithRetry(payload, stored?.attempts ?? 0, stored?.id);
|
|
140
|
+
}, `${payload.webhookId}.${payload.event}`);
|
|
141
|
+
} finally {
|
|
142
|
+
if (stored) this.inFlight.delete(stored.id);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async sendWithRetry(payload, attempt = 0, deliveryId) {
|
|
21
146
|
try {
|
|
22
147
|
const controller = new AbortController();
|
|
23
148
|
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
149
|
+
const abortFromLifecycle = () => controller.abort(this.lifecycle.signal.reason);
|
|
24
150
|
try {
|
|
151
|
+
if (this.lifecycle.signal.aborted) abortFromLifecycle();
|
|
152
|
+
else this.lifecycle.signal.addEventListener("abort", abortFromLifecycle, { once: true });
|
|
25
153
|
const response = await fetch(this.config.url, {
|
|
26
154
|
method: "POST",
|
|
27
155
|
headers: {
|
|
28
156
|
"Content-Type": "application/json",
|
|
157
|
+
...deliveryId ? { "Idempotency-Key": deliveryId } : {},
|
|
29
158
|
...this.config.headers
|
|
30
159
|
},
|
|
31
160
|
body: JSON.stringify(payload),
|
|
@@ -33,27 +162,120 @@ var WebhookDeliverer = class {
|
|
|
33
162
|
});
|
|
34
163
|
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
35
164
|
this.logger.debug(`Webhook delivered: ${payload.event} to ${this.config.url}`);
|
|
165
|
+
if (deliveryId) this.store?.markDelivered(deliveryId);
|
|
36
166
|
} finally {
|
|
37
167
|
clearTimeout(timeoutId);
|
|
168
|
+
this.lifecycle.signal.removeEventListener("abort", abortFromLifecycle);
|
|
38
169
|
}
|
|
39
170
|
} catch (error) {
|
|
171
|
+
if (this.closing || this.lifecycle.signal.aborted) throw error;
|
|
40
172
|
const errMessage = error instanceof Error ? error.message : String(error);
|
|
41
173
|
if (attempt < this.retries) {
|
|
42
174
|
const delay = this.retryDelay * Math.pow(2, attempt);
|
|
43
175
|
this.logger.warn(`Webhook delivery failed (attempt ${attempt + 1}/${this.retries + 1}), retrying in ${delay}ms: ${errMessage}`);
|
|
176
|
+
Effect.runSync(this.observability.increment("retry_decisions", 1, {
|
|
177
|
+
component: "webhook",
|
|
178
|
+
attempt: attempt + 1
|
|
179
|
+
}));
|
|
180
|
+
if (deliveryId) this.store?.markAttempt(deliveryId, errMessage, Date.now() + delay);
|
|
44
181
|
await this.sleep(delay);
|
|
45
|
-
return this.sendWithRetry(payload, attempt + 1);
|
|
182
|
+
return this.sendWithRetry(payload, attempt + 1, deliveryId);
|
|
46
183
|
}
|
|
47
184
|
this.logger.error(`Webhook delivery failed after ${this.retries + 1} attempts: ${errMessage}`);
|
|
185
|
+
Effect.runSync(this.observability.recordCause("webhook.delivery", error, { component: "webhook" }));
|
|
186
|
+
if (deliveryId) this.store?.markDeadLetter(deliveryId, errMessage);
|
|
187
|
+
throw error;
|
|
48
188
|
}
|
|
49
189
|
}
|
|
50
190
|
sleep(ms) {
|
|
51
|
-
return new Promise((resolve) =>
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
const signal = this.lifecycle.signal;
|
|
193
|
+
if (signal.aborted) {
|
|
194
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("Webhook deliverer closed"));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const onAbort = () => {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("Webhook deliverer closed"));
|
|
200
|
+
};
|
|
201
|
+
const timer = setTimeout(() => {
|
|
202
|
+
signal.removeEventListener("abort", onAbort);
|
|
203
|
+
resolve();
|
|
204
|
+
}, ms);
|
|
205
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
206
|
+
});
|
|
52
207
|
}
|
|
53
208
|
async waitForIdle() {
|
|
54
|
-
await this.
|
|
209
|
+
await this.ready;
|
|
210
|
+
await (await this.queue).waitForIdle();
|
|
211
|
+
}
|
|
212
|
+
async close() {
|
|
213
|
+
if (this.closing) return;
|
|
214
|
+
this.closing = true;
|
|
215
|
+
this.lifecycle.abort(/* @__PURE__ */ new Error("Webhook deliverer closed"));
|
|
216
|
+
await this.ready;
|
|
217
|
+
await (await this.queue).close();
|
|
218
|
+
await Promise.allSettled(this.background);
|
|
219
|
+
this.store?.close();
|
|
220
|
+
}
|
|
221
|
+
async metrics() {
|
|
222
|
+
return Effect.runPromise(this.observability.snapshot);
|
|
223
|
+
}
|
|
224
|
+
async replayPending() {
|
|
225
|
+
if (!this.store) return;
|
|
226
|
+
await this.queue;
|
|
227
|
+
if (this.closing) return;
|
|
228
|
+
const pending = this.store.pending(this.config.durability?.replayLimit ?? 1e3);
|
|
229
|
+
for (const delivery of pending) {
|
|
230
|
+
const replay = this.schedule(delivery.payload, delivery).catch((error) => {
|
|
231
|
+
if (!this.closing) this.logger.error(`Durable webhook replay failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
232
|
+
});
|
|
233
|
+
this.background.add(replay);
|
|
234
|
+
replay.finally(() => this.background.delete(replay));
|
|
235
|
+
}
|
|
55
236
|
}
|
|
56
237
|
};
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region src/service.ts
|
|
240
|
+
const WebhookDelivererService = Context.Service("@open-wa/integration-webhook/WebhookDeliverer");
|
|
241
|
+
const webhookDelivererTestLayer = (deliverer) => Layer.succeed(WebhookDelivererService, deliverer);
|
|
242
|
+
const webhookDelivererLayer = (config, logger) => Layer.effect(WebhookDelivererService, Effect.acquireRelease(Effect.sync(() => new WebhookDeliverer(config, logger)), (deliverer) => Effect.promise(async () => {
|
|
243
|
+
await deliverer.waitForIdle();
|
|
244
|
+
await deliverer.close();
|
|
245
|
+
})));
|
|
246
|
+
//#endregion
|
|
247
|
+
//#region src/plugin.ts
|
|
248
|
+
/**
|
|
249
|
+
* Webhook Integration Plugin
|
|
250
|
+
*
|
|
251
|
+
* Forwards public WA events to an external URL via HTTP POST.
|
|
252
|
+
* Supports event filtering, retry with exponential backoff, and concurrent delivery.
|
|
253
|
+
*/
|
|
254
|
+
const configSchema = z.object({
|
|
255
|
+
/** Target URL for webhook delivery */
|
|
256
|
+
url: z.string().url(),
|
|
257
|
+
/** Which events to forward. Use 'all' to forward everything. */
|
|
258
|
+
events: z.union([z.array(z.string()), z.literal("all")]).default("all"),
|
|
259
|
+
/** Max concurrent deliveries */
|
|
260
|
+
concurrency: z.number().int().positive().default(10),
|
|
261
|
+
/** Maximum deliveries waiting in memory */
|
|
262
|
+
queueCapacity: z.number().int().positive().default(1e3),
|
|
263
|
+
/** Full-queue behavior */
|
|
264
|
+
overload: z.enum(["backpressure", "dropping"]).default("backpressure"),
|
|
265
|
+
/** Number of retry attempts */
|
|
266
|
+
retries: z.number().int().min(0).default(3),
|
|
267
|
+
/** Base retry delay in ms */
|
|
268
|
+
retryDelay: z.number().int().positive().default(1e3),
|
|
269
|
+
/** Additional headers */
|
|
270
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
271
|
+
/** Request timeout in ms */
|
|
272
|
+
timeout: z.number().int().positive().default(3e4),
|
|
273
|
+
durability: z.object({
|
|
274
|
+
enabled: z.boolean().default(false),
|
|
275
|
+
path: z.string().default(".openwa/webhook-deliveries.sqlite"),
|
|
276
|
+
replayLimit: z.number().int().positive().default(1e3)
|
|
277
|
+
}).optional()
|
|
278
|
+
});
|
|
57
279
|
var plugin_default = createPlugin({
|
|
58
280
|
meta: {
|
|
59
281
|
name: "webhook",
|
|
@@ -61,39 +283,35 @@ var plugin_default = createPlugin({
|
|
|
61
283
|
description: "Forward WhatsApp events to an external URL via HTTP POST",
|
|
62
284
|
author: "Mohammed Shah <@smashah>"
|
|
63
285
|
},
|
|
64
|
-
configSchema
|
|
65
|
-
url: z.string().url(),
|
|
66
|
-
events: z.union([z.array(z.string()), z.literal("all")]).default("all"),
|
|
67
|
-
concurrency: z.number().int().positive().default(10),
|
|
68
|
-
retries: z.number().int().min(0).default(3),
|
|
69
|
-
retryDelay: z.number().int().positive().default(1e3),
|
|
70
|
-
headers: z.record(z.string()).optional(),
|
|
71
|
-
timeout: z.number().int().positive().default(3e4)
|
|
72
|
-
}),
|
|
286
|
+
configSchema,
|
|
73
287
|
init: async ({ config, logger, sessionId }) => {
|
|
74
288
|
const webhookId = crypto.randomUUID();
|
|
75
|
-
const
|
|
289
|
+
const runtime = ManagedRuntime.make(webhookDelivererLayer(config, logger));
|
|
290
|
+
const deliverer = await runtime.runPromise(WebhookDelivererService);
|
|
76
291
|
const allowedEvents = config.events === "all" ? null : new Set(config.events);
|
|
77
292
|
logger.info(`Webhook configured: ${config.url} (${config.events === "all" ? "all events" : `${config.events.length} events`})`);
|
|
78
293
|
return {
|
|
79
|
-
event:
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
294
|
+
event: ({ event, payload }) => runtime.runPromise(Effect.tryPromise({
|
|
295
|
+
try: async () => {
|
|
296
|
+
if (allowedEvents && !allowedEvents.has(event)) return;
|
|
297
|
+
await deliverer.deliver({
|
|
298
|
+
webhookId,
|
|
299
|
+
sessionId,
|
|
300
|
+
event,
|
|
301
|
+
payload,
|
|
302
|
+
timestamp: Date.now()
|
|
303
|
+
});
|
|
304
|
+
},
|
|
305
|
+
catch: (cause) => cause
|
|
306
|
+
})),
|
|
89
307
|
dispose: async () => {
|
|
90
|
-
await
|
|
308
|
+
await runtime.dispose();
|
|
91
309
|
logger.info("Webhook deliverer queue drained");
|
|
92
310
|
}
|
|
93
311
|
};
|
|
94
312
|
}
|
|
95
313
|
});
|
|
96
314
|
//#endregion
|
|
97
|
-
export { WebhookDeliverer, plugin_default as default, plugin_default as webhookPlugin };
|
|
315
|
+
export { SqliteWebhookDeliveryStore, WebhookDeliverer, WebhookDelivererService, plugin_default as default, plugin_default as webhookPlugin, webhookDelivererLayer, webhookDelivererTestLayer };
|
|
98
316
|
|
|
99
317
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/deliverer.ts","../src/plugin.ts"],"sourcesContent":["import PQueue from 'p-queue';\nimport type { Logger } from '@open-wa/logger';\nimport type { WebhookConfig, WebhookPayload } from './config.js';\n\n/**\n * Webhook Deliverer — uses native fetch instead of axios.\n * Supports exponential backoff retry and concurrent delivery via PQueue.\n */\nexport class WebhookDeliverer {\n private readonly config: WebhookConfig;\n private readonly logger: Logger;\n private readonly queue: PQueue;\n private readonly retries: number;\n private readonly retryDelay: number;\n private readonly timeout: number;\n\n constructor(config: WebhookConfig, logger: Logger) {\n this.config = config;\n this.logger = logger;\n this.retries = config.retries ?? 3;\n this.retryDelay = config.retryDelay ?? 1000;\n this.timeout = config.timeout ?? 30_000;\n this.queue = new PQueue({\n concurrency: config.concurrency ?? 10,\n });\n }\n\n async deliver(payload: WebhookPayload): Promise<void> {\n await this.queue.add(() => this.sendWithRetry(payload));\n }\n\n private async sendWithRetry(payload: WebhookPayload, attempt = 0): Promise<void> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.config.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.config.headers,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n this.logger.debug(`Webhook delivered: ${payload.event} to ${this.config.url}`);\n } finally {\n clearTimeout(timeoutId);\n }\n } catch (error) {\n const errMessage = error instanceof Error ? error.message : String(error);\n\n if (attempt < this.retries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n this.logger.warn(\n `Webhook delivery failed (attempt ${attempt + 1}/${this.retries + 1}), retrying in ${delay}ms: ${errMessage}`\n );\n await this.sleep(delay);\n return this.sendWithRetry(payload, attempt + 1);\n }\n\n this.logger.error(\n `Webhook delivery failed after ${this.retries + 1} attempts: ${errMessage}`\n );\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n async waitForIdle(): Promise<void> {\n await this.queue.onIdle();\n }\n}\n","/**\n * Webhook Integration Plugin\n *\n * Forwards public WA events to an external URL via HTTP POST.\n * Supports event filtering, retry with exponential backoff, and concurrent delivery.\n */\nimport { createPlugin, z } from '@open-wa/plugin-sdk';\nimport { WebhookDeliverer } from './deliverer.js';\n\nconst configSchema = z.object({\n /** Target URL for webhook delivery */\n url: z.string().url(),\n\n /** Which events to forward. Use 'all' to forward everything. */\n events: z.union([z.array(z.string()), z.literal('all')]).default('all'),\n\n /** Max concurrent deliveries */\n concurrency: z.number().int().positive().default(10),\n\n /** Number of retry attempts */\n retries: z.number().int().min(0).default(3),\n\n /** Base retry delay in ms */\n retryDelay: z.number().int().positive().default(1000),\n\n /** Additional headers */\n headers: z.record(z.string()).optional(),\n\n /** Request timeout in ms */\n timeout: z.number().int().positive().default(30_000),\n});\n\nexport type WebhookPluginConfig = z.infer<typeof configSchema>;\n\nexport default createPlugin({\n meta: {\n name: 'webhook',\n version: '5.0.0-alpha.1',\n description: 'Forward WhatsApp events to an external URL via HTTP POST',\n author: 'Mohammed Shah <@smashah>',\n },\n\n configSchema,\n\n init: async ({ config, logger, sessionId }) => {\n const webhookId = crypto.randomUUID();\n const deliverer = new WebhookDeliverer(config, logger);\n\n const allowedEvents = config.events === 'all'\n ? null\n : new Set(config.events);\n\n logger.info(`Webhook configured: ${config.url} (${config.events === 'all' ? 'all events' : `${(config.events as string[]).length} events`})`);\n\n return {\n event: async ({ event, payload }) => {\n if (allowedEvents && !allowedEvents.has(event)) {\n return;\n }\n\n await deliverer.deliver({\n webhookId,\n sessionId,\n event,\n payload,\n timestamp: Date.now(),\n });\n },\n\n dispose: async () => {\n await deliverer.waitForIdle();\n logger.info('Webhook deliverer queue drained');\n },\n };\n },\n});\n"],"mappings":";;;;;;;AAQA,IAAa,mBAAb,MAA8B;CAQ5B,YAAY,QAAuB,QAAgB;AACjD,OAAK,SAAS;AACd,OAAK,SAAS;AACd,OAAK,UAAU,OAAO,WAAW;AACjC,OAAK,aAAa,OAAO,cAAc;AACvC,OAAK,UAAU,OAAO,WAAW;AACjC,OAAK,QAAQ,IAAI,OAAO,EACtB,aAAa,OAAO,eAAe,IACpC,CAAC;;CAGJ,MAAM,QAAQ,SAAwC;AACpD,QAAM,KAAK,MAAM,UAAU,KAAK,cAAc,QAAQ,CAAC;;CAGzD,MAAc,cAAc,SAAyB,UAAU,GAAkB;AAC/E,MAAI;GACF,MAAM,aAAa,IAAI,iBAAiB;GACxC,MAAM,YAAY,iBAAiB,WAAW,OAAO,EAAE,KAAK,QAAQ;AAEpE,OAAI;IACF,MAAM,WAAW,MAAM,MAAM,KAAK,OAAO,KAAK;KAC5C,QAAQ;KACR,SAAS;MACP,gBAAgB;MAChB,GAAG,KAAK,OAAO;MAChB;KACD,MAAM,KAAK,UAAU,QAAQ;KAC7B,QAAQ,WAAW;KACpB,CAAC;AAEF,QAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,QAAQ,SAAS,OAAO,IAAI,SAAS,aAAa;AAGpE,SAAK,OAAO,MAAM,sBAAsB,QAAQ,MAAM,MAAM,KAAK,OAAO,MAAM;aACtE;AACR,iBAAa,UAAU;;WAElB,OAAO;GACd,MAAM,aAAa,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AAEzE,OAAI,UAAU,KAAK,SAAS;IAC1B,MAAM,QAAQ,KAAK,aAAa,KAAK,IAAI,GAAG,QAAQ;AACpD,SAAK,OAAO,KACV,oCAAoC,UAAU,EAAE,GAAG,KAAK,UAAU,EAAE,iBAAiB,M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AAO,OAAO,EAAE,OAAO,cAAc;AACnC,QAAI,iBAAiB,CAAC,cAAc,IAAI,MAAM,CAC5C;AAGF,UAAM,UAAU,QAAQ;KACtB;KACA;KACA;KACA;KACA,WAAW,KAAK,KAAK;KACtB,CAAC;;GAGJ,SAAS,YAAY;AACnB,UAAM,UAAU,aAAa;AAC7B,WAAO,KAAK,kCAAkC;;GAEjD;;CAEJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/durable-store.ts","../src/deliverer.ts","../src/service.ts","../src/plugin.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\nimport type { WebhookPayload } from './config';\n\nexport interface StoredWebhookDelivery {\n readonly id: string;\n readonly payload: WebhookPayload;\n readonly attempts: number;\n readonly nextAttemptAt: number;\n readonly status: 'pending' | 'delivered' | 'dead_letter';\n}\n\nexport interface WebhookDeliveryStore {\n enqueue(payload: WebhookPayload): StoredWebhookDelivery;\n pending(limit?: number): StoredWebhookDelivery[];\n markAttempt(id: string, error: string, nextAttemptAt: number): void;\n markDelivered(id: string): void;\n markDeadLetter(id: string, error: string): void;\n close(): void;\n}\n\ninterface DeliveryRow {\n id: string;\n payload: string;\n attempts: number;\n next_attempt_at: number;\n status: StoredWebhookDelivery['status'];\n}\n\nconst deliveryId = (payload: WebhookPayload): string =>\n createHash('sha256')\n .update(payload.idempotencyKey ?? JSON.stringify(payload))\n .digest('hex');\n\nexport class SqliteWebhookDeliveryStore implements WebhookDeliveryStore {\n private readonly database: DatabaseSync;\n\n constructor(path: string) {\n if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });\n this.database = new DatabaseSync(path);\n this.database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n CREATE TABLE IF NOT EXISTS webhook_deliveries (\n id TEXT PRIMARY KEY,\n payload TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n next_attempt_at INTEGER NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n last_error TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS webhook_deliveries_pending\n ON webhook_deliveries(status, next_attempt_at);\n `);\n }\n\n enqueue(payload: WebhookPayload): StoredWebhookDelivery {\n const id = deliveryId(payload);\n const now = Date.now();\n this.database.prepare(`\n INSERT OR IGNORE INTO webhook_deliveries\n (id, payload, attempts, next_attempt_at, status, created_at, updated_at)\n VALUES (?, ?, 0, ?, 'pending', ?, ?)\n `).run(id, JSON.stringify(payload), now, now, now);\n return this.get(id)!;\n }\n\n pending(limit = 1000): StoredWebhookDelivery[] {\n const rows = this.database.prepare(`\n SELECT id, payload, attempts, next_attempt_at, status\n FROM webhook_deliveries\n WHERE status = 'pending'\n ORDER BY next_attempt_at ASC, created_at ASC\n LIMIT ?\n `).all(limit) as unknown as DeliveryRow[];\n return rows.flatMap((row) => {\n try {\n return [this.decode(row)];\n } catch (error) {\n this.markDeadLetter(row.id, `decode failed: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n });\n }\n\n markAttempt(id: string, error: string, nextAttemptAt: number): void {\n this.database.prepare(`\n UPDATE webhook_deliveries\n SET attempts = attempts + 1, next_attempt_at = ?, last_error = ?, updated_at = ?\n WHERE id = ? AND status = 'pending'\n `).run(nextAttemptAt, error, Date.now(), id);\n }\n\n markDelivered(id: string): void {\n this.database.prepare(`\n UPDATE webhook_deliveries\n SET status = 'delivered', last_error = NULL, updated_at = ?\n WHERE id = ?\n `).run(Date.now(), id);\n }\n\n markDeadLetter(id: string, error: string): void {\n this.database.prepare(`\n UPDATE webhook_deliveries\n SET status = 'dead_letter', last_error = ?, updated_at = ?\n WHERE id = ?\n `).run(error, Date.now(), id);\n }\n\n close(): void {\n this.database.close();\n }\n\n private get(id: string): StoredWebhookDelivery | undefined {\n const row = this.database.prepare(`\n SELECT id, payload, attempts, next_attempt_at, status\n FROM webhook_deliveries WHERE id = ?\n `).get(id) as unknown as DeliveryRow | undefined;\n return row ? this.decode(row) : undefined;\n }\n\n private decode(row: DeliveryRow): StoredWebhookDelivery {\n return {\n id: row.id,\n payload: JSON.parse(row.payload) as WebhookPayload,\n attempts: row.attempts,\n nextAttemptAt: row.next_attempt_at,\n status: row.status,\n };\n }\n}\n","import type { Logger } from '@open-wa/logger';\nimport {\n makeInMemoryObservability,\n queueMetricsObserver,\n ScopedTaskQueue,\n type RuntimeObservabilityShape,\n} from '@open-wa/runtime-core';\nimport { Effect } from 'effect';\nimport type { WebhookConfig, WebhookPayload } from './config';\nimport {\n SqliteWebhookDeliveryStore,\n type StoredWebhookDelivery,\n type WebhookDeliveryStore,\n} from './durable-store';\n\n/**\n * Webhook Deliverer — uses native fetch instead of axios.\n * Supports exponential backoff retry on a bounded, scoped Effect queue.\n */\nexport class WebhookDeliverer {\n private readonly config: WebhookConfig;\n private readonly logger: Pick<Logger, 'debug' | 'warn' | 'error'>;\n private readonly queue: Promise<ScopedTaskQueue>;\n private readonly retries: number;\n private readonly retryDelay: number;\n private readonly timeout: number;\n private readonly store?: WebhookDeliveryStore;\n private readonly ready: Promise<void>;\n private readonly inFlight = new Set<string>();\n private readonly background = new Set<Promise<void>>();\n private readonly lifecycle = new AbortController();\n private readonly observability: RuntimeObservabilityShape;\n private closing = false;\n\n constructor(\n config: WebhookConfig,\n logger: Pick<Logger, 'debug' | 'warn' | 'error'>,\n observability: RuntimeObservabilityShape = makeInMemoryObservability(),\n ) {\n this.config = config;\n this.logger = logger;\n this.retries = config.retries ?? 3;\n this.retryDelay = config.retryDelay ?? 1000;\n this.timeout = config.timeout ?? 30_000;\n this.observability = observability;\n this.queue = ScopedTaskQueue.make({\n name: 'webhook.delivery',\n concurrency: config.concurrency ?? 10,\n capacity: config.queueCapacity ?? 1000,\n overload: config.overload ?? 'backpressure',\n observe: queueMetricsObserver(observability),\n });\n this.store = config.durability?.enabled\n ? new SqliteWebhookDeliveryStore(config.durability.path ?? '.openwa/webhook-deliveries.sqlite')\n : undefined;\n this.ready = this.replayPending();\n }\n\n async deliver(payload: WebhookPayload): Promise<void> {\n await this.ready;\n if (this.closing) throw new Error('Webhook deliverer is closed');\n const stored = this.store?.enqueue(payload);\n if (stored?.status === 'delivered' || (stored && this.inFlight.has(stored.id))) return;\n await this.schedule(payload, stored);\n }\n\n private async schedule(payload: WebhookPayload, stored?: StoredWebhookDelivery): Promise<void> {\n if (stored) this.inFlight.add(stored.id);\n try {\n await (await this.queue).submit(\n async () => {\n const delay = Math.max(0, (stored?.nextAttemptAt ?? 0) - Date.now());\n if (delay > 0) await this.sleep(delay);\n await this.sendWithRetry(payload, stored?.attempts ?? 0, stored?.id);\n },\n `${payload.webhookId}.${payload.event}`,\n );\n } finally {\n if (stored) this.inFlight.delete(stored.id);\n }\n }\n\n private async sendWithRetry(payload: WebhookPayload, attempt = 0, deliveryId?: string): Promise<void> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n const abortFromLifecycle = () => controller.abort(this.lifecycle.signal.reason);\n\n try {\n if (this.lifecycle.signal.aborted) abortFromLifecycle();\n else this.lifecycle.signal.addEventListener('abort', abortFromLifecycle, { once: true });\n const response = await fetch(this.config.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(deliveryId ? { 'Idempotency-Key': deliveryId } : {}),\n ...this.config.headers,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n this.logger.debug(`Webhook delivered: ${payload.event} to ${this.config.url}`);\n if (deliveryId) this.store?.markDelivered(deliveryId);\n } finally {\n clearTimeout(timeoutId);\n this.lifecycle.signal.removeEventListener('abort', abortFromLifecycle);\n }\n } catch (error) {\n if (this.closing || this.lifecycle.signal.aborted) throw error;\n const errMessage = error instanceof Error ? error.message : String(error);\n\n if (attempt < this.retries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n this.logger.warn(\n `Webhook delivery failed (attempt ${attempt + 1}/${this.retries + 1}), retrying in ${delay}ms: ${errMessage}`\n );\n Effect.runSync(this.observability.increment('retry_decisions', 1, {\n component: 'webhook',\n attempt: attempt + 1,\n }));\n if (deliveryId) this.store?.markAttempt(deliveryId, errMessage, Date.now() + delay);\n await this.sleep(delay);\n return this.sendWithRetry(payload, attempt + 1, deliveryId);\n }\n\n this.logger.error(\n `Webhook delivery failed after ${this.retries + 1} attempts: ${errMessage}`\n );\n Effect.runSync(this.observability.recordCause('webhook.delivery', error, {\n component: 'webhook',\n }));\n if (deliveryId) this.store?.markDeadLetter(deliveryId, errMessage);\n throw error;\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const signal = this.lifecycle.signal;\n if (signal.aborted) {\n reject(signal.reason ?? new Error('Webhook deliverer closed'));\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason ?? new Error('Webhook deliverer closed'));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n async waitForIdle(): Promise<void> {\n await this.ready;\n await (await this.queue).waitForIdle();\n }\n\n async close(): Promise<void> {\n if (this.closing) return;\n this.closing = true;\n this.lifecycle.abort(new Error('Webhook deliverer closed'));\n await this.ready;\n await (await this.queue).close();\n await Promise.allSettled(this.background);\n this.store?.close();\n }\n\n async metrics(): Promise<Readonly<Record<string, number>>> {\n return Effect.runPromise(this.observability.snapshot);\n }\n\n private async replayPending(): Promise<void> {\n if (!this.store) return;\n await this.queue;\n if (this.closing) return;\n const pending = this.store.pending(this.config.durability?.replayLimit ?? 1000);\n for (const delivery of pending) {\n const replay = this.schedule(delivery.payload, delivery).catch((error) => {\n if (!this.closing) {\n this.logger.error(\n `Durable webhook replay failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n this.background.add(replay);\n void replay.finally(() => this.background.delete(replay));\n }\n }\n}\n","import type { Logger } from '@open-wa/logger';\nimport { Context, Effect, Layer } from 'effect';\nimport type { WebhookConfig } from './config';\nimport { WebhookDeliverer } from './deliverer';\n\nexport const WebhookDelivererService =\n Context.Service<WebhookDeliverer>('@open-wa/integration-webhook/WebhookDeliverer');\n\nexport const webhookDelivererTestLayer = (deliverer: WebhookDeliverer) =>\n Layer.succeed(WebhookDelivererService, deliverer);\n\nexport const webhookDelivererLayer = (\n config: WebhookConfig,\n logger: Pick<Logger, 'debug' | 'warn' | 'error'>,\n) => Layer.effect(\n WebhookDelivererService,\n Effect.acquireRelease(\n Effect.sync(() => new WebhookDeliverer(config, logger)),\n (deliverer) => Effect.promise(async () => {\n await deliverer.waitForIdle();\n await deliverer.close();\n }),\n ),\n);\n","/**\n * Webhook Integration Plugin\n *\n * Forwards public WA events to an external URL via HTTP POST.\n * Supports event filtering, retry with exponential backoff, and concurrent delivery.\n */\nimport { createPlugin, z } from '@open-wa/plugin-sdk';\nimport { Effect, ManagedRuntime } from 'effect';\nimport { WebhookDelivererService, webhookDelivererLayer } from './service';\n\nconst configSchema = z.object({\n /** Target URL for webhook delivery */\n url: z.string().url(),\n\n /** Which events to forward. Use 'all' to forward everything. */\n events: z.union([z.array(z.string()), z.literal('all')]).default('all'),\n\n /** Max concurrent deliveries */\n concurrency: z.number().int().positive().default(10),\n\n /** Maximum deliveries waiting in memory */\n queueCapacity: z.number().int().positive().default(1000),\n\n /** Full-queue behavior */\n overload: z.enum(['backpressure', 'dropping']).default('backpressure'),\n\n /** Number of retry attempts */\n retries: z.number().int().min(0).default(3),\n\n /** Base retry delay in ms */\n retryDelay: z.number().int().positive().default(1000),\n\n /** Additional headers */\n headers: z.record(z.string(), z.string()).optional(),\n\n /** Request timeout in ms */\n timeout: z.number().int().positive().default(30_000),\n\n durability: z.object({\n enabled: z.boolean().default(false),\n path: z.string().default('.openwa/webhook-deliveries.sqlite'),\n replayLimit: z.number().int().positive().default(1000),\n }).optional(),\n});\n\nexport type WebhookPluginConfig = z.infer<typeof configSchema>;\n\nexport default createPlugin({\n meta: {\n name: 'webhook',\n version: '5.0.0-alpha.1',\n description: 'Forward WhatsApp events to an external URL via HTTP POST',\n author: 'Mohammed Shah <@smashah>',\n },\n\n configSchema,\n\n init: async ({ config, logger, sessionId }) => {\n const webhookId = crypto.randomUUID();\n const runtime = ManagedRuntime.make(webhookDelivererLayer(config, logger));\n const deliverer = await runtime.runPromise(WebhookDelivererService);\n\n const allowedEvents = config.events === 'all'\n ? null\n : new Set(config.events);\n\n logger.info(`Webhook configured: ${config.url} (${config.events === 'all' ? 'all events' : `${(config.events as string[]).length} events`})`);\n\n return {\n event: ({ event, payload }) => runtime.runPromise(Effect.tryPromise({\n try: async () => {\n if (allowedEvents && !allowedEvents.has(event)) return;\n await deliverer.deliver({\n webhookId,\n sessionId,\n event,\n payload,\n timestamp: Date.now(),\n });\n },\n catch: (cause) => cause,\n })),\n\n dispose: async () => {\n await runtime.dispose();\n logger.info('Webhook deliverer queue drained');\n },\n };\n },\n});\n"],"mappings":";;;;;;;;AA+BA,MAAM,cAAc,YAClB,WAAW,QAAQ,CAAC,CACjB,OAAO,QAAQ,kBAAkB,KAAK,UAAU,OAAO,CAAC,CAAC,CACzD,OAAO,KAAK;AAEjB,IAAa,6BAAb,MAAwE;CAGtE,YAAY,MAAc;EACxB,IAAI,SAAS,YAAY,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EACrE,KAAK,WAAW,IAAI,aAAa,IAAI;EACrC,KAAK,SAAS,KAAK;;;;;;;;;;;;;;;KAelB;CACH;CAEA,QAAQ,SAAgD;EACtD,MAAM,KAAK,WAAW,OAAO;EAC7B,MAAM,MAAM,KAAK,IAAI;EACrB,KAAK,SAAS,QAAQ;;;;KAIrB,CAAC,CAAC,IAAI,IAAI,KAAK,UAAU,OAAO,GAAG,KAAK,KAAK,GAAG;EACjD,OAAO,KAAK,IAAI,EAAE;CACpB;CAEA,QA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iCAAiC;GAC/C;EACF;CACF;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-wa/integration-webhook",
|
|
3
|
-
"version": "5.0.0
|
|
3
|
+
"version": "5.0.0",
|
|
4
4
|
"description": "Webhook delivery integration plugin for open-wa",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -10,13 +10,15 @@
|
|
|
10
10
|
}
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"
|
|
14
|
-
"@open-wa/
|
|
13
|
+
"@open-wa/plugin-sdk": "5.0.0",
|
|
14
|
+
"@open-wa/runtime-core": "5.0.0",
|
|
15
|
+
"effect": "4.0.0-beta.100"
|
|
15
16
|
},
|
|
16
17
|
"devDependencies": {
|
|
17
|
-
"@
|
|
18
|
-
"
|
|
19
|
-
"
|
|
18
|
+
"@open-wa/logger": "5.0.0",
|
|
19
|
+
"@types/node": "^26.6.3",
|
|
20
|
+
"typescript": "^7.0.2",
|
|
21
|
+
"vitest": "5.0.2"
|
|
20
22
|
},
|
|
21
23
|
"publishConfig": {
|
|
22
24
|
"access": "public"
|
|
@@ -25,9 +27,15 @@
|
|
|
25
27
|
"type": "git",
|
|
26
28
|
"url": "https://github.com/open-wa/wa-automate-nodejs.git"
|
|
27
29
|
},
|
|
30
|
+
"license": "SEE LICENSE IN LICENSE.md",
|
|
31
|
+
"files": [
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
28
34
|
"scripts": {
|
|
29
35
|
"build": "tsdown src/index.ts --format esm --dts",
|
|
30
36
|
"dev": "tsdown src/index.ts --format esm --dts --watch",
|
|
37
|
+
"test": "vitest run",
|
|
38
|
+
"typecheck": "tsc --noEmit",
|
|
31
39
|
"lint": "oxlint src",
|
|
32
40
|
"clean": "rimraf dist"
|
|
33
41
|
}
|
package/.turbo/turbo-build.log
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
> @open-wa/integration-webhook@5.0.0-alpha.7 build /Users/Mohammed/projects/tools/wa/integrations/webhook
|
|
3
|
-
> tsdown src/index.ts --format esm --dts
|
|
4
|
-
|
|
5
|
-
ℹ tsdown v0.21.7 powered by rolldown v1.0.0-rc.12
|
|
6
|
-
ℹ entry: src/index.ts
|
|
7
|
-
ℹ tsconfig: tsconfig.json
|
|
8
|
-
ℹ Build start
|
|
9
|
-
ℹ Cleaning 4 files
|
|
10
|
-
ℹ dist/index.mjs 3.41 kB │ gzip: 1.44 kB
|
|
11
|
-
ℹ dist/index.mjs.map 7.13 kB │ gzip: 2.62 kB
|
|
12
|
-
ℹ dist/index.d.mts.map 6.17 kB │ gzip: 2.42 kB
|
|
13
|
-
ℹ dist/index.d.mts 3.13 kB │ gzip: 1.02 kB
|
|
14
|
-
ℹ 4 files, total: 19.83 kB
|
|
15
|
-
../../node_modules/winston/index.d.ts (6:247) [33m[IMPORT_IS_UNDEFINED] Warning:[0m Import `AbstractConfigSetLevels` will always be undefined because there is no matching export in '../../node_modules/winston/lib/winston/config/index.d.ts'
|
|
16
|
-
- in ../../node_modules/winston/index.d.ts at 487..517
|
|
17
|
-
|
|
18
|
-
../../node_modules/winston/index.d.ts (6:358) [33m[IMPORT_IS_UNDEFINED] Warning:[0m Import `AbstractConfigSetLevels` will always be undefined because there is no matching export in '../../node_modules/winston/lib/winston/config/index.d.ts'
|
|
19
|
-
- in ../../node_modules/winston/index.d.ts at 598..628
|
|
20
|
-
|
|
21
|
-
../../node_modules/winston/index.d.ts (6:977) [33m[IMPORT_IS_UNDEFINED] Warning:[0m Import `AbstractConfigSetColors` will always be undefined because there is no matching export in '../../node_modules/winston/lib/winston/config/index.d.ts'
|
|
22
|
-
- in ../../node_modules/winston/index.d.ts at 1217..1247
|
|
23
|
-
|
|
24
|
-
[33m[PLUGIN_TIMINGS] Warning:[0m Your build spent significant time in plugins. Here is a breakdown:
|
|
25
|
-
- rolldown-plugin-dts:generate (44%)
|
|
26
|
-
- rolldown-plugin-dts:fake-js (29%)
|
|
27
|
-
- rolldown-plugin-dts:resolver (26%)
|
|
28
|
-
See https://rolldown.rs/options/checks#plugintimings for more details.
|
|
29
|
-
|
|
30
|
-
✔ Build complete in 4307ms
|
package/.turbo/turbo-lint.log
DELETED
|
File without changes
|
package/CHANGELOG.md
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
# @open-wa/integration-webhook
|
|
2
|
-
|
|
3
|
-
## 5.0.0-alpha.7
|
|
4
|
-
|
|
5
|
-
### Patch Changes
|
|
6
|
-
|
|
7
|
-
- Updated dependencies []:
|
|
8
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.7
|
|
9
|
-
|
|
10
|
-
## 5.0.0-alpha.6
|
|
11
|
-
|
|
12
|
-
### Patch Changes
|
|
13
|
-
|
|
14
|
-
- Updated dependencies []:
|
|
15
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.6
|
|
16
|
-
|
|
17
|
-
## 5.0.0-alpha.5
|
|
18
|
-
|
|
19
|
-
### Patch Changes
|
|
20
|
-
|
|
21
|
-
- Updated dependencies []:
|
|
22
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.5
|
|
23
|
-
|
|
24
|
-
## 5.0.0-alpha.4
|
|
25
|
-
|
|
26
|
-
### Patch Changes
|
|
27
|
-
|
|
28
|
-
- Updated dependencies []:
|
|
29
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.4
|
|
30
|
-
|
|
31
|
-
## 5.0.0-alpha.3
|
|
32
|
-
|
|
33
|
-
### Patch Changes
|
|
34
|
-
|
|
35
|
-
- Updated dependencies []:
|
|
36
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.3
|
|
37
|
-
|
|
38
|
-
## 5.0.0-alpha.2
|
|
39
|
-
|
|
40
|
-
### Patch Changes
|
|
41
|
-
|
|
42
|
-
- Updated dependencies []:
|
|
43
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.2
|
|
44
|
-
|
|
45
|
-
## 5.0.0-alpha.3
|
|
46
|
-
|
|
47
|
-
### Minor Changes
|
|
48
|
-
|
|
49
|
-
- Dry run minor bump
|
|
50
|
-
|
|
51
|
-
### Patch Changes
|
|
52
|
-
|
|
53
|
-
- Updated dependencies []:
|
|
54
|
-
- @open-wa/plugin-sdk@5.0.0-alpha.2
|
|
55
|
-
|
|
56
|
-
## 5.0.0-alpha.2
|
|
57
|
-
|
|
58
|
-
### Patch Changes
|
|
59
|
-
|
|
60
|
-
- Updated dependencies []:
|
|
61
|
-
- @open-wa/plugin-sdk@5.0.1-alpha.2
|
package/src/config.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Webhook configuration types.
|
|
3
|
-
* No longer depends on AxiosRequestConfig — uses native fetch options.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
export interface WebhookConfig {
|
|
7
|
-
/** Target URL for webhook delivery */
|
|
8
|
-
url: string;
|
|
9
|
-
|
|
10
|
-
/** Which events to forward. 'all' or an array of event names. */
|
|
11
|
-
events?: string[] | 'all';
|
|
12
|
-
|
|
13
|
-
/** Max concurrent deliveries (default: 10) */
|
|
14
|
-
concurrency?: number;
|
|
15
|
-
|
|
16
|
-
/** Number of retry attempts (default: 3) */
|
|
17
|
-
retries?: number;
|
|
18
|
-
|
|
19
|
-
/** Base retry delay in ms, exponentially backed off (default: 1000) */
|
|
20
|
-
retryDelay?: number;
|
|
21
|
-
|
|
22
|
-
/** Additional headers to send with each webhook request */
|
|
23
|
-
headers?: Record<string, string>;
|
|
24
|
-
|
|
25
|
-
/** Request timeout in ms (default: 30000) */
|
|
26
|
-
timeout?: number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export interface Webhook {
|
|
30
|
-
id: string;
|
|
31
|
-
url: string;
|
|
32
|
-
events: string[];
|
|
33
|
-
headers?: Record<string, string>;
|
|
34
|
-
createdAt: number;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export interface WebhookPayload {
|
|
38
|
-
webhookId: string;
|
|
39
|
-
sessionId: string;
|
|
40
|
-
event: string;
|
|
41
|
-
payload: unknown;
|
|
42
|
-
timestamp: number;
|
|
43
|
-
}
|
package/src/deliverer.ts
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import PQueue from 'p-queue';
|
|
2
|
-
import type { Logger } from '@open-wa/logger';
|
|
3
|
-
import type { WebhookConfig, WebhookPayload } from './config.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Webhook Deliverer — uses native fetch instead of axios.
|
|
7
|
-
* Supports exponential backoff retry and concurrent delivery via PQueue.
|
|
8
|
-
*/
|
|
9
|
-
export class WebhookDeliverer {
|
|
10
|
-
private readonly config: WebhookConfig;
|
|
11
|
-
private readonly logger: Logger;
|
|
12
|
-
private readonly queue: PQueue;
|
|
13
|
-
private readonly retries: number;
|
|
14
|
-
private readonly retryDelay: number;
|
|
15
|
-
private readonly timeout: number;
|
|
16
|
-
|
|
17
|
-
constructor(config: WebhookConfig, logger: Logger) {
|
|
18
|
-
this.config = config;
|
|
19
|
-
this.logger = logger;
|
|
20
|
-
this.retries = config.retries ?? 3;
|
|
21
|
-
this.retryDelay = config.retryDelay ?? 1000;
|
|
22
|
-
this.timeout = config.timeout ?? 30_000;
|
|
23
|
-
this.queue = new PQueue({
|
|
24
|
-
concurrency: config.concurrency ?? 10,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
async deliver(payload: WebhookPayload): Promise<void> {
|
|
29
|
-
await this.queue.add(() => this.sendWithRetry(payload));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
private async sendWithRetry(payload: WebhookPayload, attempt = 0): Promise<void> {
|
|
33
|
-
try {
|
|
34
|
-
const controller = new AbortController();
|
|
35
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
36
|
-
|
|
37
|
-
try {
|
|
38
|
-
const response = await fetch(this.config.url, {
|
|
39
|
-
method: 'POST',
|
|
40
|
-
headers: {
|
|
41
|
-
'Content-Type': 'application/json',
|
|
42
|
-
...this.config.headers,
|
|
43
|
-
},
|
|
44
|
-
body: JSON.stringify(payload),
|
|
45
|
-
signal: controller.signal,
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
if (!response.ok) {
|
|
49
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
this.logger.debug(`Webhook delivered: ${payload.event} to ${this.config.url}`);
|
|
53
|
-
} finally {
|
|
54
|
-
clearTimeout(timeoutId);
|
|
55
|
-
}
|
|
56
|
-
} catch (error) {
|
|
57
|
-
const errMessage = error instanceof Error ? error.message : String(error);
|
|
58
|
-
|
|
59
|
-
if (attempt < this.retries) {
|
|
60
|
-
const delay = this.retryDelay * Math.pow(2, attempt);
|
|
61
|
-
this.logger.warn(
|
|
62
|
-
`Webhook delivery failed (attempt ${attempt + 1}/${this.retries + 1}), retrying in ${delay}ms: ${errMessage}`
|
|
63
|
-
);
|
|
64
|
-
await this.sleep(delay);
|
|
65
|
-
return this.sendWithRetry(payload, attempt + 1);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
this.logger.error(
|
|
69
|
-
`Webhook delivery failed after ${this.retries + 1} attempts: ${errMessage}`
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
private sleep(ms: number): Promise<void> {
|
|
75
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async waitForIdle(): Promise<void> {
|
|
79
|
-
await this.queue.onIdle();
|
|
80
|
-
}
|
|
81
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
// Default export is the plugin itself (for config-driven loading)
|
|
2
|
-
export { default, default as webhookPlugin } from './plugin.js';
|
|
3
|
-
export type { WebhookPluginConfig } from './plugin.js';
|
|
4
|
-
|
|
5
|
-
// Named exports for direct usage
|
|
6
|
-
export type { WebhookConfig, Webhook, WebhookPayload } from './config.js';
|
|
7
|
-
export { WebhookDeliverer } from './deliverer.js';
|
package/src/plugin.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Webhook Integration Plugin
|
|
3
|
-
*
|
|
4
|
-
* Forwards public WA events to an external URL via HTTP POST.
|
|
5
|
-
* Supports event filtering, retry with exponential backoff, and concurrent delivery.
|
|
6
|
-
*/
|
|
7
|
-
import { createPlugin, z } from '@open-wa/plugin-sdk';
|
|
8
|
-
import { WebhookDeliverer } from './deliverer.js';
|
|
9
|
-
|
|
10
|
-
const configSchema = z.object({
|
|
11
|
-
/** Target URL for webhook delivery */
|
|
12
|
-
url: z.string().url(),
|
|
13
|
-
|
|
14
|
-
/** Which events to forward. Use 'all' to forward everything. */
|
|
15
|
-
events: z.union([z.array(z.string()), z.literal('all')]).default('all'),
|
|
16
|
-
|
|
17
|
-
/** Max concurrent deliveries */
|
|
18
|
-
concurrency: z.number().int().positive().default(10),
|
|
19
|
-
|
|
20
|
-
/** Number of retry attempts */
|
|
21
|
-
retries: z.number().int().min(0).default(3),
|
|
22
|
-
|
|
23
|
-
/** Base retry delay in ms */
|
|
24
|
-
retryDelay: z.number().int().positive().default(1000),
|
|
25
|
-
|
|
26
|
-
/** Additional headers */
|
|
27
|
-
headers: z.record(z.string()).optional(),
|
|
28
|
-
|
|
29
|
-
/** Request timeout in ms */
|
|
30
|
-
timeout: z.number().int().positive().default(30_000),
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
export type WebhookPluginConfig = z.infer<typeof configSchema>;
|
|
34
|
-
|
|
35
|
-
export default createPlugin({
|
|
36
|
-
meta: {
|
|
37
|
-
name: 'webhook',
|
|
38
|
-
version: '5.0.0-alpha.1',
|
|
39
|
-
description: 'Forward WhatsApp events to an external URL via HTTP POST',
|
|
40
|
-
author: 'Mohammed Shah <@smashah>',
|
|
41
|
-
},
|
|
42
|
-
|
|
43
|
-
configSchema,
|
|
44
|
-
|
|
45
|
-
init: async ({ config, logger, sessionId }) => {
|
|
46
|
-
const webhookId = crypto.randomUUID();
|
|
47
|
-
const deliverer = new WebhookDeliverer(config, logger);
|
|
48
|
-
|
|
49
|
-
const allowedEvents = config.events === 'all'
|
|
50
|
-
? null
|
|
51
|
-
: new Set(config.events);
|
|
52
|
-
|
|
53
|
-
logger.info(`Webhook configured: ${config.url} (${config.events === 'all' ? 'all events' : `${(config.events as string[]).length} events`})`);
|
|
54
|
-
|
|
55
|
-
return {
|
|
56
|
-
event: async ({ event, payload }) => {
|
|
57
|
-
if (allowedEvents && !allowedEvents.has(event)) {
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
await deliverer.deliver({
|
|
62
|
-
webhookId,
|
|
63
|
-
sessionId,
|
|
64
|
-
event,
|
|
65
|
-
payload,
|
|
66
|
-
timestamp: Date.now(),
|
|
67
|
-
});
|
|
68
|
-
},
|
|
69
|
-
|
|
70
|
-
dispose: async () => {
|
|
71
|
-
await deliverer.waitForIdle();
|
|
72
|
-
logger.info('Webhook deliverer queue drained');
|
|
73
|
-
},
|
|
74
|
-
};
|
|
75
|
-
},
|
|
76
|
-
});
|