@sockethub/platform-whatsapp 0.0.0-stage → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # `@sockethub/platform-whatsapp`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Outgoing text messages through the WhatsApp Business Cloud API. This is a
4
+ stateless, authenticated platform: set credentials, then send. No connect action
5
+ or webhook endpoint is needed. Incoming messages and recipient discovery are
6
+ external.
7
+
8
+ ## Setup
9
+
10
+ The Sockethub CLI bundles this platform. For a custom server installation, install
11
+ `@sockethub/platform-whatsapp` and include it in your config's `platforms` list
12
+ alongside the other platforms you use. Node.js >= 20.19 and Redis >= 6 are required.
13
+
14
+ Create a Meta developer app with the WhatsApp use case and register a business
15
+ phone number. Use a system-user or temporary access token with
16
+ `whatsapp_business_messaging`. The actor ID is the **phone number ID** shown in
17
+ the app's WhatsApp API setup (not the phone number itself); the target ID is the
18
+ recipient's phone number in international format, for example `+15551234567`.
19
+
20
+ This implementation sends as a WhatsApp Business number through Meta's Cloud
21
+ API, not as a personal WhatsApp account. Obtain tokens outside Sockethub.
22
+
23
+ ## Usage
24
+
25
+ This server-side JavaScript example uses runtime environment variables. In a
26
+ browser, obtain credentials through your application's secure runtime flow.
27
+ Choose a supported Graph API version enabled for your Meta app explicitly.
28
+
29
+ ```javascript
30
+ import SockethubClient from '@sockethub/client';
31
+
32
+ const sc = await SockethubClient.connect('http://localhost:10550');
33
+ await sc.ready();
34
+ const actor = { id: process.env.WHATSAPP_PHONE_NUMBER_ID, type: 'person' };
35
+
36
+ sc.socket.emit('credentials', {
37
+ '@context': sc.contextFor('whatsapp'),
38
+ type: 'credentials',
39
+ actor,
40
+ object: {
41
+ type: 'credentials',
42
+ token: process.env.META_ACCESS_TOKEN,
43
+ apiVersion: process.env.META_API_VERSION
44
+ }
45
+ }, (ack) => {
46
+ if (ack?.error) {
47
+ console.error(ack.error);
48
+ return;
49
+ }
50
+ sc.socket.emit('message', {
51
+ '@context': sc.contextFor('whatsapp'),
52
+ type: 'send',
53
+ actor,
54
+ target: { id: '+15551234567', type: 'person' },
55
+ object: { type: 'message', content: 'Hello from Sockethub!' }
56
+ }, (result) => {
57
+ if (result?.error) {
58
+ console.error(result.error);
59
+ return;
60
+ }
61
+ // A successful send returns the original activity with object.id set to
62
+ // the WhatsApp message ID (wamid). This confirms API acceptance, not
63
+ // delivery or reading.
64
+ console.log(result.object?.id);
65
+ });
66
+ });
67
+ ```
68
+
69
+ ## Limits and failures
70
+
71
+ - Text only, up to 4096 characters per message. Link previews are off.
72
+ - Free-form text is only accepted within 24 hours of the recipient's last
73
+ message to your number. Sockethub does not track incoming messages or
74
+ calculate eligibility; Meta enforces its policies. Template messages, which
75
+ are required to start a conversation, are not supported.
76
+ - Meta error code `131047` returns the stable marker
77
+ `meta:messaging-window-closed` followed by the original diagnostic details,
78
+ matching the Messenger and Instagram platforms.
79
+ - Meta failures return the HTTP status, error code, and error message.
80
+ Requests time out after 15 seconds. There are no platform-level retries:
81
+ after a network timeout, delivery is unknown, so retrying may duplicate a send.
82
+ - No inbound messages, delivery/read receipts, templates, media, interactive
83
+ messages, or webhook hosting.
84
+
85
+ API contract references:
86
+
87
+ - [Send messages](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages)
88
+ - [Error codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes)
@@ -0,0 +1,160 @@
1
+ import type { ActivityStream, CredentialsObject, PlatformCallback, PlatformInterface, PlatformSession, StatelessPlatformConfig } from "@sockethub/schemas";
2
+ export interface WhatsAppCredentials extends CredentialsObject {
3
+ object: {
4
+ type: "credentials";
5
+ token: string;
6
+ apiVersion: string;
7
+ };
8
+ }
9
+ export default class WhatsApp implements PlatformInterface {
10
+ private readonly log;
11
+ config: StatelessPlatformConfig;
12
+ constructor(session: PlatformSession);
13
+ get schema(): {
14
+ name: string;
15
+ version: string;
16
+ contextUrl: string;
17
+ contextVersion: string;
18
+ schemaVersion: string;
19
+ messages: {
20
+ required: string[];
21
+ properties: {
22
+ type: {
23
+ enum: string[];
24
+ };
25
+ actor: {
26
+ type: string;
27
+ required: string[];
28
+ additionalProperties: boolean;
29
+ properties: {
30
+ id: {
31
+ type: string;
32
+ pattern: string;
33
+ maxLength: number;
34
+ };
35
+ type: {
36
+ const: string;
37
+ };
38
+ };
39
+ };
40
+ target: {
41
+ type: string;
42
+ required: string[];
43
+ additionalProperties: boolean;
44
+ properties: {
45
+ id: {
46
+ type: string;
47
+ pattern: string;
48
+ };
49
+ type: {
50
+ const: string;
51
+ };
52
+ };
53
+ };
54
+ object: {
55
+ type: string;
56
+ required: string[];
57
+ additionalProperties: boolean;
58
+ properties: {
59
+ type: {
60
+ const: string;
61
+ };
62
+ content: {
63
+ type: string;
64
+ minLength: number;
65
+ maxLength: number;
66
+ };
67
+ };
68
+ };
69
+ };
70
+ };
71
+ credentials: {
72
+ required: string[];
73
+ properties: {
74
+ object: {
75
+ type: string;
76
+ required: string[];
77
+ additionalProperties: boolean;
78
+ properties: {
79
+ type: {
80
+ const: string;
81
+ };
82
+ token: {
83
+ type: string;
84
+ minLength: number;
85
+ maxLength: number;
86
+ pattern: string;
87
+ };
88
+ apiVersion: {
89
+ type: string;
90
+ pattern: string;
91
+ };
92
+ };
93
+ };
94
+ };
95
+ };
96
+ responses: {
97
+ type: string;
98
+ required: string[];
99
+ properties: {
100
+ "@context": {
101
+ type: string;
102
+ items: {
103
+ type: string;
104
+ };
105
+ };
106
+ type: {
107
+ const: string;
108
+ };
109
+ actor: {
110
+ type: string;
111
+ required: string[];
112
+ additionalProperties: boolean;
113
+ properties: {
114
+ id: {
115
+ type: string;
116
+ pattern: string;
117
+ maxLength: number;
118
+ };
119
+ type: {
120
+ const: string;
121
+ };
122
+ };
123
+ };
124
+ target: {
125
+ type: string;
126
+ required: string[];
127
+ additionalProperties: boolean;
128
+ properties: {
129
+ id: {
130
+ type: string;
131
+ pattern: string;
132
+ };
133
+ type: {
134
+ const: string;
135
+ };
136
+ };
137
+ };
138
+ object: {
139
+ type: string;
140
+ required: string[];
141
+ properties: {
142
+ type: {
143
+ const: string;
144
+ };
145
+ id: {
146
+ type: string;
147
+ minLength: number;
148
+ };
149
+ content: {
150
+ type: string;
151
+ };
152
+ };
153
+ };
154
+ };
155
+ };
156
+ };
157
+ isInitialized(): boolean;
158
+ cleanup(done: PlatformCallback): void;
159
+ send(job: ActivityStream, credentials: WhatsAppCredentials, done: PlatformCallback): Promise<void>;
160
+ }
package/dist/index.js ADDED
@@ -0,0 +1,212 @@
1
+ // package.json
2
+ var package_default = {
3
+ name: "@sockethub/platform-whatsapp",
4
+ description: "Outgoing text messages through the WhatsApp Business Cloud API",
5
+ version: "1.0.0-beta.3",
6
+ type: "module",
7
+ private: false,
8
+ license: "LGPL-3.0+",
9
+ publishConfig: {
10
+ access: "public"
11
+ },
12
+ main: "./dist/index.js",
13
+ types: "./dist/index.d.ts",
14
+ exports: {
15
+ ".": {
16
+ types: "./dist/index.d.ts",
17
+ import: "./dist/index.js",
18
+ default: "./dist/index.js"
19
+ }
20
+ },
21
+ files: [
22
+ "dist/"
23
+ ],
24
+ engines: {
25
+ node: ">=20.19"
26
+ },
27
+ scripts: {
28
+ build: "bun build src/index.ts --outdir dist --target node --format esm --sourcemap=external",
29
+ clean: "rm -rf dist",
30
+ "clean:deps": "rm -rf node_modules",
31
+ test: "bun test src/"
32
+ },
33
+ dependencies: {
34
+ "@sockethub/schemas": "^3.0.0-beta.3"
35
+ },
36
+ devDependencies: {
37
+ "@types/bun": "latest"
38
+ },
39
+ peerDependencies: {
40
+ "@sockethub/server": "^5.0.0-beta.3"
41
+ },
42
+ peerDependenciesMeta: {
43
+ "@sockethub/server": {
44
+ optional: true
45
+ }
46
+ },
47
+ gitHead: "bc04522d60d1e2fa1b3098b339897de62c3b0549"
48
+ };
49
+
50
+ // src/schema.ts
51
+ var actor = {
52
+ type: "object",
53
+ required: ["id", "type"],
54
+ additionalProperties: false,
55
+ properties: {
56
+ id: { type: "string", pattern: "^[0-9]+$", maxLength: 128 },
57
+ type: { const: "person" }
58
+ }
59
+ };
60
+ var target = {
61
+ type: "object",
62
+ required: ["id", "type"],
63
+ additionalProperties: false,
64
+ properties: {
65
+ id: { type: "string", pattern: "^\\+?[1-9][0-9]{6,14}$" },
66
+ type: { const: "person" }
67
+ }
68
+ };
69
+ var PlatformWhatsAppSchema = {
70
+ name: "whatsapp",
71
+ version: package_default.version,
72
+ contextUrl: "https://sockethub.org/ns/context/platform/whatsapp/v1.jsonld",
73
+ contextVersion: "1",
74
+ schemaVersion: "1",
75
+ messages: {
76
+ required: ["type", "actor", "target", "object"],
77
+ properties: {
78
+ type: { enum: ["send"] },
79
+ actor,
80
+ target,
81
+ object: {
82
+ type: "object",
83
+ required: ["type", "content"],
84
+ additionalProperties: false,
85
+ properties: {
86
+ type: { const: "message" },
87
+ content: { type: "string", minLength: 1, maxLength: 4096 }
88
+ }
89
+ }
90
+ }
91
+ },
92
+ credentials: {
93
+ required: ["object"],
94
+ properties: {
95
+ object: {
96
+ type: "object",
97
+ required: ["type", "token", "apiVersion"],
98
+ additionalProperties: false,
99
+ properties: {
100
+ type: { const: "credentials" },
101
+ token: {
102
+ type: "string",
103
+ minLength: 1,
104
+ maxLength: 8192,
105
+ pattern: "^[^\\r\\n]+$"
106
+ },
107
+ apiVersion: {
108
+ type: "string",
109
+ pattern: "^v[0-9]{1,3}\\.[0-9]{1,2}$"
110
+ }
111
+ }
112
+ }
113
+ }
114
+ },
115
+ responses: {
116
+ type: "object",
117
+ required: ["@context", "type", "actor", "target", "object"],
118
+ properties: {
119
+ "@context": { type: "array", items: { type: "string" } },
120
+ type: { const: "send" },
121
+ actor,
122
+ target,
123
+ object: {
124
+ type: "object",
125
+ required: ["type", "id", "content"],
126
+ properties: {
127
+ type: { const: "message" },
128
+ id: { type: "string", minLength: 1 },
129
+ content: { type: "string" }
130
+ }
131
+ }
132
+ }
133
+ }
134
+ };
135
+
136
+ // src/index.ts
137
+ class WhatsApp {
138
+ log;
139
+ config = {
140
+ persist: false,
141
+ requireCredentials: ["send"]
142
+ };
143
+ constructor(session) {
144
+ this.log = session.log;
145
+ }
146
+ get schema() {
147
+ return PlatformWhatsAppSchema;
148
+ }
149
+ isInitialized() {
150
+ return true;
151
+ }
152
+ cleanup(done) {
153
+ done();
154
+ }
155
+ async send(job, credentials, done) {
156
+ const { token, apiVersion } = credentials.object;
157
+ let result;
158
+ try {
159
+ const response = await fetch(`https://graph.facebook.com/${apiVersion}/${encodeURIComponent(job.actor.id)}/messages`, {
160
+ method: "POST",
161
+ redirect: "error",
162
+ headers: {
163
+ authorization: `Bearer ${token}`,
164
+ "content-type": "application/json"
165
+ },
166
+ body: JSON.stringify({
167
+ messaging_product: "whatsapp",
168
+ recipient_type: "individual",
169
+ to: job.target.id,
170
+ type: "text",
171
+ text: { body: job.object.content, preview_url: false }
172
+ }),
173
+ signal: AbortSignal.timeout(15000)
174
+ });
175
+ const data = await response.json();
176
+ if (!data || typeof data !== "object") {
177
+ throw new Error("whatsapp: invalid API response");
178
+ }
179
+ if ("error" in data || !response.ok) {
180
+ const error = "error" in data ? data.error : undefined;
181
+ let detail = `HTTP ${response.status}`;
182
+ if (error && typeof error === "object") {
183
+ if ("code" in error && typeof error.code === "number") {
184
+ detail += `, code ${error.code}`;
185
+ }
186
+ if ("message" in error && typeof error.message === "string") {
187
+ detail += `: ${error.message.split(token).join("[redacted]")}`;
188
+ }
189
+ }
190
+ const windowClosed = error && typeof error === "object" && "code" in error && error.code === 131047;
191
+ const reason = windowClosed ? "meta:messaging-window-closed" : "whatsapp: send rejected";
192
+ throw new Error(`${reason} (${detail})`);
193
+ }
194
+ const id = "messages" in data && Array.isArray(data.messages) && data.messages[0] && typeof data.messages[0] === "object" && "id" in data.messages[0] ? data.messages[0].id : undefined;
195
+ if (typeof id !== "string" || !id) {
196
+ throw new Error("whatsapp: API response missing message id");
197
+ }
198
+ result = { ...job, object: { ...job.object, id } };
199
+ } catch (error) {
200
+ const failure = error instanceof Error && (error.message.startsWith("whatsapp:") || error.message.startsWith("meta:messaging-window-closed")) ? new Error(error.message.split(token).join("[redacted]")) : new Error("whatsapp: send failed (network error, timeout, or invalid JSON); delivery is unknown");
201
+ this.log.warn(`send failed for actor ${job.actor.id} on whatsapp`);
202
+ done(failure);
203
+ return;
204
+ }
205
+ done(null, result);
206
+ }
207
+ }
208
+ export {
209
+ WhatsApp as default
210
+ };
211
+
212
+ //# debugId=645C91CA9AEA149964756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/schema.ts", "../src/index.ts"],
4
+ "sourcesContent": [
5
+ "import packageJson from \"../package.json\" with { type: \"json\" };\n\n// actor: WhatsApp Business phone number ID (Meta-assigned, numeric).\nconst actor = {\n type: \"object\",\n required: [\"id\", \"type\"],\n additionalProperties: false,\n properties: {\n id: { type: \"string\", pattern: \"^[0-9]+$\", maxLength: 128 },\n type: { const: \"person\" },\n },\n};\n\n// target: recipient phone number in international format (E.164 digits).\nconst target = {\n type: \"object\",\n required: [\"id\", \"type\"],\n additionalProperties: false,\n properties: {\n id: { type: \"string\", pattern: \"^\\\\+?[1-9][0-9]{6,14}$\" },\n type: { const: \"person\" },\n },\n};\n\nexport const PlatformWhatsAppSchema = {\n name: \"whatsapp\",\n version: packageJson.version,\n contextUrl: \"https://sockethub.org/ns/context/platform/whatsapp/v1.jsonld\",\n contextVersion: \"1\",\n schemaVersion: \"1\",\n messages: {\n required: [\"type\", \"actor\", \"target\", \"object\"],\n properties: {\n type: { enum: [\"send\"] },\n actor,\n target,\n object: {\n type: \"object\",\n required: [\"type\", \"content\"],\n additionalProperties: false,\n properties: {\n type: { const: \"message\" },\n content: { type: \"string\", minLength: 1, maxLength: 4096 },\n },\n },\n },\n },\n credentials: {\n required: [\"object\"],\n properties: {\n object: {\n type: \"object\",\n required: [\"type\", \"token\", \"apiVersion\"],\n additionalProperties: false,\n properties: {\n type: { const: \"credentials\" },\n token: {\n type: \"string\",\n minLength: 1,\n maxLength: 8192,\n pattern: \"^[^\\\\r\\\\n]+$\",\n },\n apiVersion: {\n type: \"string\",\n pattern: \"^v[0-9]{1,3}\\\\.[0-9]{1,2}$\",\n },\n },\n },\n },\n },\n responses: {\n type: \"object\",\n required: [\"@context\", \"type\", \"actor\", \"target\", \"object\"],\n properties: {\n \"@context\": { type: \"array\", items: { type: \"string\" } },\n type: { const: \"send\" },\n actor,\n target,\n object: {\n type: \"object\",\n required: [\"type\", \"id\", \"content\"],\n properties: {\n type: { const: \"message\" },\n id: { type: \"string\", minLength: 1 },\n content: { type: \"string\" },\n },\n },\n },\n },\n};\n",
6
+ "import type {\n ActivityStream,\n CredentialsObject,\n Logger,\n PlatformCallback,\n PlatformInterface,\n PlatformSession,\n StatelessPlatformConfig,\n} from \"@sockethub/schemas\";\nimport { PlatformWhatsAppSchema } from \"./schema.js\";\n\nexport interface WhatsAppCredentials extends CredentialsObject {\n object: { type: \"credentials\"; token: string; apiVersion: string };\n}\n\nexport default class WhatsApp implements PlatformInterface {\n private readonly log: Logger;\n config: StatelessPlatformConfig = {\n persist: false,\n requireCredentials: [\"send\"],\n };\n\n constructor(session: PlatformSession) {\n this.log = session.log;\n }\n\n get schema() {\n return PlatformWhatsAppSchema;\n }\n\n isInitialized(): boolean {\n return true;\n }\n\n cleanup(done: PlatformCallback): void {\n done();\n }\n\n async send(\n job: ActivityStream,\n credentials: WhatsAppCredentials,\n done: PlatformCallback,\n ): Promise<void> {\n const { token, apiVersion } = credentials.object;\n let result: ActivityStream;\n try {\n const response = await fetch(\n `https://graph.facebook.com/${apiVersion}/${encodeURIComponent(job.actor.id)}/messages`,\n {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n authorization: `Bearer ${token}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to: job.target.id,\n type: \"text\",\n text: { body: job.object.content, preview_url: false },\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n const data: unknown = await response.json();\n if (!data || typeof data !== \"object\") {\n throw new Error(\"whatsapp: invalid API response\");\n }\n if (\"error\" in data || !response.ok) {\n const error = \"error\" in data ? data.error : undefined;\n let detail = `HTTP ${response.status}`;\n if (error && typeof error === \"object\") {\n if (\"code\" in error && typeof error.code === \"number\") {\n detail += `, code ${error.code}`;\n }\n if (\n \"message\" in error &&\n typeof error.message === \"string\"\n ) {\n detail += `: ${error.message.split(token).join(\"[redacted]\")}`;\n }\n }\n // 131047: more than 24 hours since the recipient last messaged.\n const windowClosed =\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === 131047;\n const reason = windowClosed\n ? \"meta:messaging-window-closed\"\n : \"whatsapp: send rejected\";\n throw new Error(`${reason} (${detail})`);\n }\n const id =\n \"messages\" in data &&\n Array.isArray(data.messages) &&\n data.messages[0] &&\n typeof data.messages[0] === \"object\" &&\n \"id\" in data.messages[0]\n ? data.messages[0].id\n : undefined;\n if (typeof id !== \"string\" || !id) {\n throw new Error(\"whatsapp: API response missing message id\");\n }\n result = { ...job, object: { ...job.object, id } };\n } catch (error) {\n // Network errors may contain request details; never expose tokens.\n const failure =\n error instanceof Error &&\n (error.message.startsWith(\"whatsapp:\") ||\n error.message.startsWith(\"meta:messaging-window-closed\"))\n ? new Error(error.message.split(token).join(\"[redacted]\"))\n : new Error(\n \"whatsapp: send failed (network error, timeout, or invalid JSON); delivery is unknown\",\n );\n this.log.warn(`send failed for actor ${job.actor.id} on whatsapp`);\n done(failure);\n return;\n }\n done(null, result);\n }\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM,QAAQ;AAAA,EACV,MAAM;AAAA,EACN,UAAU,CAAC,MAAM,MAAM;AAAA,EACvB,sBAAsB;AAAA,EACtB,YAAY;AAAA,IACR,IAAI,EAAE,MAAM,UAAU,SAAS,YAAY,WAAW,IAAI;AAAA,IAC1D,MAAM,EAAE,OAAO,SAAS;AAAA,EAC5B;AACJ;AAGA,IAAM,SAAS;AAAA,EACX,MAAM;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8BAA8B,KACrD,IAAI,MAAM,MAAM,QAAQ,MAAM,KAAK,EAAE,KAAK,YAAY,CAAC,IACvD,IAAI,MACA,sFACJ;AAAA,MACV,KAAK,IAAI,KAAK,yBAAyB,IAAI,MAAM,gBAAgB;AAAA,MACjE,KAAK,OAAO;AAAA,MACZ;AAAA;AAAA,IAEJ,KAAK,MAAM,MAAM;AAAA;AAEzB;",
9
+ "debugId": "645C91CA9AEA149964756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,144 @@
1
+ export declare const PlatformWhatsAppSchema: {
2
+ name: string;
3
+ version: string;
4
+ contextUrl: string;
5
+ contextVersion: string;
6
+ schemaVersion: string;
7
+ messages: {
8
+ required: string[];
9
+ properties: {
10
+ type: {
11
+ enum: string[];
12
+ };
13
+ actor: {
14
+ type: string;
15
+ required: string[];
16
+ additionalProperties: boolean;
17
+ properties: {
18
+ id: {
19
+ type: string;
20
+ pattern: string;
21
+ maxLength: number;
22
+ };
23
+ type: {
24
+ const: string;
25
+ };
26
+ };
27
+ };
28
+ target: {
29
+ type: string;
30
+ required: string[];
31
+ additionalProperties: boolean;
32
+ properties: {
33
+ id: {
34
+ type: string;
35
+ pattern: string;
36
+ };
37
+ type: {
38
+ const: string;
39
+ };
40
+ };
41
+ };
42
+ object: {
43
+ type: string;
44
+ required: string[];
45
+ additionalProperties: boolean;
46
+ properties: {
47
+ type: {
48
+ const: string;
49
+ };
50
+ content: {
51
+ type: string;
52
+ minLength: number;
53
+ maxLength: number;
54
+ };
55
+ };
56
+ };
57
+ };
58
+ };
59
+ credentials: {
60
+ required: string[];
61
+ properties: {
62
+ object: {
63
+ type: string;
64
+ required: string[];
65
+ additionalProperties: boolean;
66
+ properties: {
67
+ type: {
68
+ const: string;
69
+ };
70
+ token: {
71
+ type: string;
72
+ minLength: number;
73
+ maxLength: number;
74
+ pattern: string;
75
+ };
76
+ apiVersion: {
77
+ type: string;
78
+ pattern: string;
79
+ };
80
+ };
81
+ };
82
+ };
83
+ };
84
+ responses: {
85
+ type: string;
86
+ required: string[];
87
+ properties: {
88
+ "@context": {
89
+ type: string;
90
+ items: {
91
+ type: string;
92
+ };
93
+ };
94
+ type: {
95
+ const: string;
96
+ };
97
+ actor: {
98
+ type: string;
99
+ required: string[];
100
+ additionalProperties: boolean;
101
+ properties: {
102
+ id: {
103
+ type: string;
104
+ pattern: string;
105
+ maxLength: number;
106
+ };
107
+ type: {
108
+ const: string;
109
+ };
110
+ };
111
+ };
112
+ target: {
113
+ type: string;
114
+ required: string[];
115
+ additionalProperties: boolean;
116
+ properties: {
117
+ id: {
118
+ type: string;
119
+ pattern: string;
120
+ };
121
+ type: {
122
+ const: string;
123
+ };
124
+ };
125
+ };
126
+ object: {
127
+ type: string;
128
+ required: string[];
129
+ properties: {
130
+ type: {
131
+ const: string;
132
+ };
133
+ id: {
134
+ type: string;
135
+ minLength: number;
136
+ };
137
+ content: {
138
+ type: string;
139
+ };
140
+ };
141
+ };
142
+ };
143
+ };
144
+ };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@sockethub/platform-whatsapp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Outgoing text messages through the WhatsApp Business Cloud API",
4
+ "version": "1.0.0-beta.3",
5
+ "type": "module",
6
+ "private": false,
7
+ "license": "LGPL-3.0+",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist/"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20.19"
25
+ },
26
+ "scripts": {
27
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --sourcemap=external",
28
+ "clean": "rm -rf dist",
29
+ "clean:deps": "rm -rf node_modules",
30
+ "test": "bun test src/"
31
+ },
32
+ "dependencies": {
33
+ "@sockethub/schemas": "^3.0.0-beta.3"
34
+ },
35
+ "devDependencies": {
36
+ "@types/bun": "latest"
37
+ },
38
+ "peerDependencies": {
39
+ "@sockethub/server": "^5.0.0-beta.3"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@sockethub/server": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "gitHead": "603d4edd90e1f0f0b70c4ab759be5f70b24020ea"
47
+ }