@effect/chat-whatsapp 0.0.0 → 4.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +61 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/WhatsAppChat.d.ts +373 -0
  88. package/dist/WhatsAppChat.d.ts.map +1 -0
  89. package/dist/WhatsAppChat.js +388 -0
  90. package/dist/WhatsAppChat.js.map +1 -0
  91. package/dist/WhatsAppGraphApi.d.ts +90 -0
  92. package/dist/WhatsAppGraphApi.d.ts.map +1 -0
  93. package/dist/WhatsAppGraphApi.js +97 -0
  94. package/dist/WhatsAppGraphApi.js.map +1 -0
  95. package/dist/WhatsAppUpdate.d.ts +168 -0
  96. package/dist/WhatsAppUpdate.d.ts.map +1 -0
  97. package/dist/WhatsAppUpdate.js +103 -0
  98. package/dist/WhatsAppUpdate.js.map +1 -0
  99. package/dist/index.d.ts +20 -0
  100. package/dist/index.d.ts.map +1 -0
  101. package/dist/index.js +21 -0
  102. package/dist/index.js.map +1 -0
  103. package/dist/internal/actions.d.ts +2 -0
  104. package/dist/internal/actions.d.ts.map +1 -0
  105. package/dist/internal/actions.js +224 -0
  106. package/dist/internal/actions.js.map +1 -0
  107. package/dist/internal/adapter.d.ts +2 -0
  108. package/dist/internal/adapter.d.ts.map +1 -0
  109. package/dist/internal/adapter.js +330 -0
  110. package/dist/internal/adapter.js.map +1 -0
  111. package/dist/internal/address.d.ts +2 -0
  112. package/dist/internal/address.d.ts.map +1 -0
  113. package/dist/internal/address.js +36 -0
  114. package/dist/internal/address.js.map +1 -0
  115. package/dist/internal/errors.d.ts +2 -0
  116. package/dist/internal/errors.d.ts.map +1 -0
  117. package/dist/internal/errors.js +93 -0
  118. package/dist/internal/errors.js.map +1 -0
  119. package/dist/internal/normalize.d.ts +2 -0
  120. package/dist/internal/normalize.d.ts.map +1 -0
  121. package/dist/internal/normalize.js +292 -0
  122. package/dist/internal/normalize.js.map +1 -0
  123. package/dist/internal/options.d.ts +2 -0
  124. package/dist/internal/options.d.ts.map +1 -0
  125. package/dist/internal/options.js +10 -0
  126. package/dist/internal/options.js.map +1 -0
  127. package/dist/internal/text.d.ts +11 -0
  128. package/dist/internal/text.d.ts.map +1 -0
  129. package/dist/internal/text.js +485 -0
  130. package/dist/internal/text.js.map +1 -0
  131. package/dist/internal/webhook.d.ts +2 -0
  132. package/dist/internal/webhook.d.ts.map +1 -0
  133. package/dist/internal/webhook.js +150 -0
  134. package/dist/internal/webhook.js.map +1 -0
  135. package/package.json +61 -1
  136. package/src/WhatsAppChat.ts +505 -0
  137. package/src/WhatsAppGraphApi.ts +147 -0
  138. package/src/WhatsAppUpdate.ts +142 -0
  139. package/src/index.ts +24 -0
  140. package/src/internal/actions.ts +220 -0
  141. package/src/internal/adapter.ts +284 -0
  142. package/src/internal/address.ts +41 -0
  143. package/src/internal/errors.ts +102 -0
  144. package/src/internal/normalize.ts +250 -0
  145. package/src/internal/options.ts +13 -0
  146. package/src/internal/text.ts +495 -0
  147. package/src/internal/webhook.ts +216 -0
@@ -0,0 +1,284 @@
1
+ import { type ChatAdapter, checkMessageLength, type Descriptor, type File, type Posted } from "effect/chat/ChatAdapter"
2
+ import {
3
+ type ChatError,
4
+ type ChatErrorReason,
5
+ fileRefused,
6
+ InvalidRequest,
7
+ TooLarge,
8
+ Unsupported
9
+ } from "effect/chat/ChatError"
10
+ import type { ChatThread } from "effect/chat/ChatThread"
11
+ import * as DateTime from "effect/DateTime"
12
+ import * as Duration from "effect/Duration"
13
+ import * as Effect from "effect/Effect"
14
+ import type * as HttpClient from "effect/http/HttpClient"
15
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
16
+ import * as Option from "effect/Option"
17
+ import * as Redacted from "effect/Redacted"
18
+ import type * as Schema from "effect/Schema"
19
+ import * as Stream from "effect/Stream"
20
+ import type { Template } from "../WhatsAppChat.ts"
21
+ import type { WhatsAppGraphApi } from "../WhatsAppGraphApi.ts"
22
+ import * as Actions from "./actions.ts"
23
+ import * as Address from "./address.ts"
24
+ import * as Errors from "./errors.ts"
25
+ import { isObject, type JsonObject, string } from "./normalize.ts"
26
+ import { CurrentPostOptions } from "./options.ts"
27
+ import * as Text from "./text.ts"
28
+
29
+ /** @internal */
30
+ export const descriptor: Descriptor = {
31
+ platform: Address.platform,
32
+ capabilities: new Set(["replyTo", "files", "download", "getThread", "opener", "buttons", "selects"]),
33
+ measure: (markdown, actions) => Text.measure(markdown) + Actions.measure(actions ?? []),
34
+ limits: {
35
+ messageLength: Text.messageLength,
36
+ filesPerMessage: 1,
37
+ uploadBytes: 100 * 1024 * 1024,
38
+ minWriteInterval: Duration.seconds(6),
39
+ ...Actions.limits
40
+ }
41
+ }
42
+
43
+ type MediaType = "image" | "video" | "audio" | "document"
44
+
45
+ const megabytes = (n: number) => n * 1024 * 1024
46
+
47
+ const image = { type: "image", maxBytes: megabytes(5) } as const
48
+ const video = { type: "video", maxBytes: megabytes(16) } as const
49
+ const audio = { type: "audio", maxBytes: megabytes(16) } as const
50
+ const doc = { type: "document", maxBytes: megabytes(100) } as const
51
+
52
+ /** Meta's supported media, by MIME type, with the largest upload of each. */
53
+ const mediaTypes: Record<string, { readonly type: MediaType; readonly maxBytes: number }> = {
54
+ "image/jpeg": image,
55
+ "image/png": image,
56
+ "video/mp4": video,
57
+ "video/3gpp": video,
58
+ "audio/aac": audio,
59
+ "audio/amr": audio,
60
+ "audio/mpeg": audio,
61
+ "audio/mp4": audio,
62
+ "audio/ogg": audio,
63
+ "text/plain": doc,
64
+ "application/pdf": doc,
65
+ "application/msword": doc,
66
+ "application/vnd.ms-excel": doc,
67
+ "application/vnd.ms-powerpoint": doc,
68
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": doc,
69
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": doc,
70
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": doc
71
+ }
72
+
73
+ /** The MIME type a file is uploaded as: without parameters, and `text/markdown` as `text/plain`. @internal */
74
+ export const uploadType = (contentType: string): string => {
75
+ const base = contentType.split(";")[0].trim().toLowerCase()
76
+ return base === "text/markdown" ? "text/plain" : base
77
+ }
78
+
79
+ const refused = new TooLarge({ subject: "files", detail: fileRefused })
80
+
81
+ /** @internal */
82
+ export const make = (options: {
83
+ readonly graph: WhatsAppGraphApi["Service"]
84
+ readonly http: HttpClient.HttpClient
85
+ readonly accessToken: Redacted.Redacted
86
+ readonly phoneNumberId: string
87
+ readonly messagingAccountId?: string | undefined
88
+ }) => {
89
+ const { graph, phoneNumberId } = options
90
+ const account = options.messagingAccountId === undefined ? {} : { messaging_account_id: options.messagingAccountId }
91
+
92
+ const fail = (op: string, reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
93
+
94
+ const withOp = (op: string) => (error: ChatError) => Errors.chatError(op, error.reason)
95
+
96
+ const unsupported = (op: string, capability: Unsupported["capability"]) => fail(op, new Unsupported({ capability }))
97
+
98
+ /** The user of a thread this adapter can write to. */
99
+ const resolve = (op: string, thread: ChatThread): Effect.Effect<string, ChatError> => {
100
+ const parts = Address.parts(thread)
101
+ if (Option.isNone(parts)) return fail(op, new InvalidRequest({ detail: "invalid_thread" }))
102
+ if (parts.value.kind === "group") return fail(op, new InvalidRequest({ detail: "group_unsupported" }))
103
+ if (parts.value.phoneNumberId !== phoneNumberId) {
104
+ return fail(op, new InvalidRequest({ detail: "other_phone_number" }))
105
+ }
106
+ return Effect.succeed(parts.value.id)
107
+ }
108
+
109
+ const recipient = (user: string) => Address.isBsuid(user) ? { recipient: user } : { to: user }
110
+
111
+ const send = Effect.fnUntraced(function*(op: string, thread: ChatThread, user: string, message: JsonObject) {
112
+ const answer = yield* graph.call(`${phoneNumberId}/messages`, {
113
+ body: { messaging_product: "whatsapp", recipient_type: "individual", ...account, ...recipient(user), ...message },
114
+ write: true
115
+ }).pipe(Effect.mapError(withOp(op)))
116
+ const messages = isObject(answer) && Array.isArray(answer.messages) ? answer.messages : []
117
+ const id = string(messages[0], "id")
118
+ if (id === undefined) return yield* fail(op, Errors.invalidResponse(true, "missing_message_id"))
119
+ const timestamp = yield* DateTime.now
120
+ return { id, thread, timestamp } satisfies Posted
121
+ })
122
+
123
+ /** The checks on a file, before anything is sent: its media type, or the refusal. */
124
+ const checkFile = (
125
+ files: ReadonlyArray<File>,
126
+ caption: string,
127
+ plan: Actions.Plan
128
+ ): ChatErrorReason | { readonly file: File; readonly mime: string; readonly type: MediaType } => {
129
+ if (files.length > 1) return refused
130
+ const file = files[0]
131
+ const mime = uploadType(file.contentType)
132
+ const media = Object.hasOwn(mediaTypes, mime) ? mediaTypes[mime] : undefined
133
+ if (media === undefined || file.content.length > media.maxBytes) return refused
134
+ if (plan.kind === "list") return refused
135
+ if (media.type === "audio" && (caption.trim() !== "" || plan.kind !== "none")) return refused
136
+ if (caption.length > Text.shortBodyLength) return refused
137
+ return { file, mime, type: media.type }
138
+ }
139
+
140
+ const upload = (op: string, file: File, mime: string): Effect.Effect<string, ChatError> => {
141
+ const form = new FormData()
142
+ form.append("messaging_product", "whatsapp")
143
+ form.append("type", mime)
144
+ form.append("file", new Blob([file.content as Uint8Array<ArrayBuffer>], { type: mime }), file.name)
145
+ return graph.call(`${phoneNumberId}/media`, { form }).pipe(
146
+ // Meta refusing the file itself is a file refusal: nothing was sent, so the text can go without it.
147
+ Effect.mapError((error) =>
148
+ Errors.chatError(
149
+ op,
150
+ error.reason._tag === "TooLarge" || error.reason._tag === "InvalidRequest"
151
+ ? new TooLarge({ subject: "files", detail: fileRefused, cause: error.reason })
152
+ : error.reason
153
+ )
154
+ ),
155
+ Effect.flatMap((answer) => {
156
+ const id = string(answer, "id")
157
+ return id === undefined ? fail(op, Errors.invalidResponse(false, "missing_media_id")) : Effect.succeed(id)
158
+ })
159
+ )
160
+ }
161
+
162
+ const post: ChatAdapter["post"] = Effect.fnUntraced(function*(thread, content) {
163
+ const op = "post"
164
+ const user = yield* resolve(op, thread)
165
+ const actions = content.actions ?? []
166
+ const postOptions = yield* CurrentPostOptions
167
+ const plan = Actions.plan(actions, postOptions)
168
+ if (!("kind" in plan)) return yield* fail(op, plan)
169
+ yield* checkMessageLength(descriptor, op, content.markdown, actions)
170
+ const text = Actions.body(Text.render(content.markdown), actions)
171
+ const files = content.files ?? []
172
+ const context = content.replyTo === undefined ? {} : { context: { message_id: content.replyTo.messageId } }
173
+ let header: JsonObject | undefined
174
+ if (files.length > 0) {
175
+ const checked = checkFile(files, text, plan)
176
+ if (!("file" in checked)) return yield* fail(op, checked)
177
+ const { file, mime, type } = checked
178
+ const id = yield* upload(op, file, mime)
179
+ const media: JsonObject = type === "document" ? { id, filename: file.name } : { id }
180
+ if (plan.interactive === undefined) {
181
+ const caption = type === "audio" || text.trim() === "" ? {} : { caption: text }
182
+ return yield* send(op, thread, user, { ...context, type, [type]: { ...media, ...caption } })
183
+ }
184
+ header = { type, [type]: media }
185
+ }
186
+ if (plan.interactive !== undefined) {
187
+ return yield* send(op, thread, user, {
188
+ ...context,
189
+ type: "interactive",
190
+ interactive: {
191
+ type: plan.interactive.type,
192
+ ...(header === undefined ? {} : { header }),
193
+ body: { text },
194
+ action: plan.interactive.action as Schema.Json
195
+ }
196
+ })
197
+ }
198
+ if (text.trim() === "") return yield* fail(op, new InvalidRequest({ detail: "empty_message" }))
199
+ return yield* send(op, thread, user, {
200
+ ...context,
201
+ type: "text",
202
+ text: { body: text, preview_url: postOptions.linkPreview === true }
203
+ })
204
+ })
205
+
206
+ const download: ChatAdapter["download"] = (thread, attachment, { maxBytes }) =>
207
+ Stream.unwrap(Effect.gen(function*() {
208
+ const op = "download"
209
+ yield* resolve(op, thread)
210
+ const tooLarge = Errors.chatError(op, new TooLarge({ subject: "files", detail: "max_bytes" }))
211
+ if (attachment.size !== undefined && attachment.size > maxBytes) return yield* Effect.fail(tooLarge)
212
+ const answer = yield* graph.call(encodeURIComponent(attachment.id), {
213
+ params: { phone_number_id: phoneNumberId }
214
+ }).pipe(Effect.mapError(withOp(op)))
215
+ const info = isObject(answer) ? answer : undefined
216
+ const url = string(info, "url")
217
+ if (url === undefined) return yield* fail(op, Errors.invalidResponse(false, "missing_url"))
218
+ const size = info?.file_size
219
+ if (typeof size === "number" && size > maxBytes) return yield* Effect.fail(tooLarge)
220
+ const response = yield* options.http.execute(
221
+ HttpClientRequest.get(url).pipe(HttpClientRequest.bearerToken(Redacted.value(options.accessToken)))
222
+ ).pipe(Effect.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag, error))))
223
+ if (response.status < 200 || response.status >= 300) {
224
+ return yield* fail(op, Errors.reasonForStatus(response.status, { write: false }))
225
+ }
226
+ let received = 0
227
+ return response.stream.pipe(
228
+ Stream.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag, error))),
229
+ Stream.mapEffect((chunk) => {
230
+ received += chunk.length
231
+ return received > maxBytes ? Effect.fail(tooLarge) : Effect.succeed(chunk)
232
+ })
233
+ )
234
+ }))
235
+
236
+ const adapter: ChatAdapter = {
237
+ descriptor,
238
+ post,
239
+ edit: () => unsupported("edit", "edit"),
240
+ delete: () => unsupported("delete", "delete"),
241
+ fetchMessage: () => unsupported("fetchMessage", "fetchMessage"),
242
+ history: () => Stream.fail(Errors.chatError("history", new Unsupported({ capability: "history" }))),
243
+ download,
244
+ startThread: () => unsupported("startThread", "startThread"),
245
+ getThread: (thread) =>
246
+ Effect.map(resolve("getThread", thread), (user) => ({
247
+ thread,
248
+ kind: "direct" as const,
249
+ raw: { phoneNumberId, user }
250
+ })),
251
+ opener: (thread) => Effect.as(resolve("opener", thread), Option.none()),
252
+ getUser: () => unsupported("getUser", "getUser"),
253
+ followUp: () => unsupported("followUp", "commands")
254
+ }
255
+
256
+ const sendTemplate = (thread: ChatThread, template: Template): Effect.Effect<Posted, ChatError> =>
257
+ Effect.flatMap(resolve("sendTemplate", thread), (user) =>
258
+ send("sendTemplate", thread, user, {
259
+ type: "template",
260
+ template: {
261
+ name: template.name,
262
+ language: { code: template.language },
263
+ ...(template.components === undefined ? {} : { components: template.components })
264
+ }
265
+ }))
266
+
267
+ const markRead = (
268
+ thread: ChatThread,
269
+ messageId: string,
270
+ markOptions?: { readonly typing?: boolean | undefined }
271
+ ): Effect.Effect<void, ChatError> =>
272
+ Effect.flatMap(resolve("markRead", thread), () =>
273
+ graph.call(`${phoneNumberId}/messages`, {
274
+ body: {
275
+ messaging_product: "whatsapp",
276
+ status: "read",
277
+ message_id: messageId,
278
+ ...(markOptions?.typing === true ? { typing_indicator: { type: "text" } } : {})
279
+ },
280
+ write: true
281
+ }).pipe(Effect.mapError(withOp("markRead")), Effect.asVoid))
282
+
283
+ return { adapter, sendTemplate, markRead }
284
+ }
@@ -0,0 +1,41 @@
1
+ import * as ChatThread from "effect/chat/ChatThread"
2
+ import * as Option from "effect/Option"
3
+
4
+ /** @internal */
5
+ export const platform = "whatsapp"
6
+
7
+ /** @internal */
8
+ export interface Parts {
9
+ readonly phoneNumberId: string
10
+ readonly kind: "user" | "group"
11
+ readonly id: string
12
+ }
13
+
14
+ const digits = /^\d+$/
15
+
16
+ /**
17
+ * A business-scoped user id, such as `US.13491208655302741918`, or a parent
18
+ * one, such as `US.ENT.11815799212886844830`. The grammar is read from
19
+ * examples, not from a specification.
20
+ *
21
+ * @internal
22
+ */
23
+ export const isBsuid = (id: string): boolean => /^[A-Z]{2}(?:\.[A-Z0-9]+)+$/.test(id)
24
+
25
+ /** A phone number in digits, or a BSUID. @internal */
26
+ export const isUser = (id: string): boolean => digits.test(id) || isBsuid(id)
27
+
28
+ /** @internal */
29
+ export const thread = (parts: Parts): ChatThread.ChatThread =>
30
+ ChatThread.make(platform, `${parts.phoneNumberId}/${parts.kind === "user" ? "u" : "g"}/${parts.id}`)
31
+
32
+ /** @internal */
33
+ export const parts = (address: ChatThread.ChatThread): Option.Option<Parts> => {
34
+ if (address.platform !== platform) return Option.none()
35
+ const segments = address.id.split("/")
36
+ if (segments.length !== 3 || !digits.test(segments[0]) || segments[2].length === 0) return Option.none()
37
+ const [phoneNumberId, kind, id] = segments
38
+ if (kind === "u") return isUser(id) ? Option.some({ phoneNumberId, kind: "user", id }) : Option.none()
39
+ if (kind === "g") return Option.some({ phoneNumberId, kind: "group", id })
40
+ return Option.none()
41
+ }
@@ -0,0 +1,102 @@
1
+ import {
2
+ ChatError,
3
+ type ChatErrorReason,
4
+ Forbidden,
5
+ InvalidRequest,
6
+ InvalidResponse,
7
+ NotFound,
8
+ PlatformUnavailable,
9
+ RateLimited,
10
+ TooLarge,
11
+ Transport,
12
+ Unauthenticated,
13
+ Unknown
14
+ } from "effect/chat/ChatError"
15
+ import { isObject } from "effect/Predicate"
16
+ import { platform } from "./address.ts"
17
+
18
+ /** The detail of a send refused outside the 24 hour window, Graph error 131047. @internal */
19
+ export const outsideWindow = "graph_131047"
20
+
21
+ const unauthenticated = new Set([0, 102, 190])
22
+
23
+ const forbidden = new Set([
24
+ 3,
25
+ 10,
26
+ 368,
27
+ 131030,
28
+ 131031,
29
+ 131042,
30
+ 131045,
31
+ 131047,
32
+ 131049,
33
+ 131050,
34
+ 133010
35
+ ])
36
+
37
+ const rateLimited = new Set([4, 17, 32, 613, 80007, 130429, 131048, 131056])
38
+
39
+ const unavailable = new Set([1, 2, 131000, 131016])
40
+
41
+ /** An error a Graph answer carries, in an `error` field or in a status's `errors`. @internal */
42
+ export interface GraphError {
43
+ readonly code: number
44
+ readonly subcode?: number | undefined
45
+ }
46
+
47
+ /** The Graph error in an answer's body, if it has one. @internal */
48
+ export const graphError = (body: unknown): GraphError | undefined => {
49
+ const error = isObject(body) && isObject(body.error) ? body.error : body
50
+ if (!isObject(error) || typeof error.code !== "number") return undefined
51
+ return { code: error.code, ...(typeof error.error_subcode === "number" ? { subcode: error.error_subcode } : {}) }
52
+ }
53
+
54
+ /**
55
+ * Maps a Graph error code to a reason. `detail` is `graph_{code}`, which
56
+ * holds no message text or ids. The Graph error itself is the `cause`.
57
+ *
58
+ * @internal
59
+ */
60
+ export const reasonForGraphError = (
61
+ error: GraphError,
62
+ options: { readonly write: boolean; readonly cause?: unknown }
63
+ ): ChatErrorReason => {
64
+ const fields = { detail: `graph_${error.code}`, ...(options.cause === undefined ? {} : { cause: options.cause }) }
65
+ if (rateLimited.has(error.code)) return new RateLimited(fields)
66
+ if (unauthenticated.has(error.code)) return new Unauthenticated(fields)
67
+ if (forbidden.has(error.code) || (error.code >= 200 && error.code < 300)) return new Forbidden(fields)
68
+ if (unavailable.has(error.code)) {
69
+ return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", ...fields })
70
+ }
71
+ if (error.code === 100 && error.subcode === 33) return new NotFound(fields)
72
+ if (error.code === 131053) return new TooLarge({ subject: "files", ...fields })
73
+ return new InvalidRequest(fields)
74
+ }
75
+
76
+ /** @internal */
77
+ export const reasonForStatus = (
78
+ status: number,
79
+ options: { readonly write: boolean; readonly cause?: unknown }
80
+ ): ChatErrorReason => {
81
+ const fields = { detail: `http_${status}`, ...(options.cause === undefined ? {} : { cause: options.cause }) }
82
+ if (status === 429) return new RateLimited(fields)
83
+ if (status >= 500) return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", ...fields })
84
+ if (status === 401) return new Unauthenticated(fields)
85
+ if (status === 403) return new Forbidden(fields)
86
+ if (status === 404) return new NotFound(fields)
87
+ if (status === 413) return new TooLarge(fields)
88
+ return new InvalidRequest(fields)
89
+ }
90
+
91
+ /** A request that failed before an answer came. A write may have landed. @internal */
92
+ export const transport = (write: boolean, detail: string, cause?: unknown): ChatErrorReason =>
93
+ new Transport({ retry: write ? "uncertain" : "retry", detail, ...(cause === undefined ? {} : { cause }) })
94
+
95
+ /** An answer the adapter cannot read. A write may have landed. @internal */
96
+ export const invalidResponse = (write: boolean, detail: string, cause?: unknown): ChatErrorReason => {
97
+ const fields = { detail, ...(cause === undefined ? {} : { cause }) }
98
+ return write ? new Unknown(fields) : new InvalidResponse(fields)
99
+ }
100
+
101
+ /** @internal */
102
+ export const chatError = (op: string, reason: ChatErrorReason): ChatError => new ChatError({ platform, op, reason })
@@ -0,0 +1,250 @@
1
+ import type { Attachment, ChatMessage } from "effect/chat/ChatMessage"
2
+ import type { ChatThread } from "effect/chat/ChatThread"
3
+ import * as DateTime from "effect/DateTime"
4
+ import * as Predicate from "effect/Predicate"
5
+ import type * as Schema from "effect/Schema"
6
+ import type { Inbound } from "../WhatsAppChat.ts"
7
+ import type * as Update from "../WhatsAppUpdate.ts"
8
+ import { parseWireId } from "./actions.ts"
9
+ import * as Address from "./address.ts"
10
+ import { reasonForGraphError } from "./errors.ts"
11
+
12
+ type Json = Schema.Json
13
+
14
+ /** @internal */
15
+ export type JsonObject = { readonly [key: string]: Json }
16
+
17
+ /** A phone number without its formatting: Meta may show `display_phone_number` with `+`, spaces or dashes. */
18
+ const digits = (phone: string) => phone.replace(/\D/g, "")
19
+
20
+ /** @internal */
21
+ export const isObject = (u: unknown): u is JsonObject => Predicate.isObject(u)
22
+
23
+ /** A non-empty string field of `value`, when `value` is an object. @internal */
24
+ export const string = (value: unknown, key: string): string | undefined => {
25
+ const field = isObject(value) ? value[key] : undefined
26
+ return typeof field === "string" && field.length > 0 ? field : undefined
27
+ }
28
+
29
+ const object = (value: unknown, key: string): JsonObject | undefined => {
30
+ const field = isObject(value) ? value[key] : undefined
31
+ return isObject(field) ? field : undefined
32
+ }
33
+
34
+ const array = (value: Json | undefined): ReadonlyArray<Json> => Array.isArray(value) ? value : []
35
+
36
+ const timestamp = (value: string | undefined) => {
37
+ const seconds = Number(value)
38
+ return value !== undefined && Number.isFinite(seconds) ? DateTime.makeUnsafe(seconds * 1000) : undefined
39
+ }
40
+
41
+ const media = ["image", "video", "audio", "document", "sticker"] as const
42
+
43
+ /** Whether a message is from a group, which the adapter does not support yet. @internal */
44
+ export const isGroupMessage = (message: Json): boolean =>
45
+ isObject(message) && (message.group_id !== undefined || string(object(message, "context"), "group_id") !== undefined)
46
+
47
+ /** The messages of a delivery that are from groups. @internal */
48
+ export const groupMessages = (envelope: unknown): number => {
49
+ let count = 0
50
+ if (!isObject(envelope)) return count
51
+ for (const entry of array(envelope.entry)) {
52
+ for (const change of array(isObject(entry) ? entry.changes : undefined)) {
53
+ const value = object(change, "value")
54
+ for (const message of array(value?.messages)) if (isGroupMessage(message)) count++
55
+ for (const status of array(value?.statuses)) if (isObject(status) && status.recipient_type === "group") count++
56
+ }
57
+ }
58
+ return count
59
+ }
60
+
61
+ /** A changed phone number or BSUID, addressed by the user's new id. */
62
+ const fromSystem = (
63
+ value: JsonObject,
64
+ metadata: JsonObject,
65
+ phoneNumberId: string,
66
+ message: JsonObject,
67
+ id: string,
68
+ at: DateTime.Utc | undefined
69
+ ): ReadonlyArray<Inbound> => {
70
+ const system = object(message, "system")
71
+ const change = string(system, "type")
72
+ if (change !== "user_changed_number" && change !== "user_changed_user_id") return []
73
+ const userId = string(system, "user_id")
74
+ const phone = string(system, "wa_id")
75
+ const next = userId ?? phone
76
+ if (next === undefined || !Address.isUser(next)) return []
77
+ const previousUserId = string(system, "previous_user_id")
78
+ const previousPhone = string(message, "from")
79
+ return [{
80
+ _tag: "UserIdChanged",
81
+ thread: Address.thread({ phoneNumberId, kind: "user", id: next }),
82
+ id,
83
+ change,
84
+ ...(userId === undefined ? {} : { userId }),
85
+ ...(previousUserId === undefined ? {} : { previousUserId }),
86
+ ...(phone === undefined ? {} : { phone }),
87
+ ...(previousPhone === undefined ? {} : { previousPhone }),
88
+ ...(at === undefined ? {} : { timestamp: at }),
89
+ raw: { metadata, contacts: array(value.contacts).filter(isObject), messages: [message] }
90
+ }]
91
+ }
92
+
93
+ const fromMessage = (
94
+ value: JsonObject,
95
+ metadata: JsonObject,
96
+ phoneNumberId: string,
97
+ message: Json
98
+ ): ReadonlyArray<Inbound> => {
99
+ if (!isObject(message) || isGroupMessage(message)) return []
100
+ const id = string(message, "id")
101
+ const at = timestamp(string(message, "timestamp"))
102
+ const type = string(message, "type")
103
+ // A changed BSUID can arrive with no sender at all: the new id is only in `system`.
104
+ if (type === "system") return id === undefined ? [] : fromSystem(value, metadata, phoneNumberId, message, id, at)
105
+ const contacts = array(value.contacts).filter(isObject)
106
+ const from = string(message, "from")
107
+ const fromUserId = string(message, "from_user_id")
108
+ const contact =
109
+ contacts.find((contact) =>
110
+ (fromUserId !== undefined && contact.user_id === fromUserId) || (from !== undefined && contact.wa_id === from)
111
+ ) ?? contacts[0]
112
+ const user = fromUserId ?? string(contact, "user_id") ?? from
113
+ if (id === undefined || user === undefined || !Address.isUser(user)) return []
114
+ const thread = Address.thread({ phoneNumberId, kind: "user", id: user })
115
+ const raw: Json = { metadata, contacts: contact === undefined ? [] : [contact], messages: [message] }
116
+ switch (type) {
117
+ case "reaction": {
118
+ const reaction = object(message, "reaction")
119
+ const emoji = string(reaction, "emoji")
120
+ const messageId = string(reaction, "message_id")
121
+ // An empty emoji is a removed reaction, which is dropped.
122
+ if (emoji === undefined || messageId === undefined) return []
123
+ return [{
124
+ _tag: "ReactionAdded",
125
+ thread,
126
+ messageId,
127
+ userId: user,
128
+ emoji,
129
+ ...(at === undefined ? {} : { timestamp: at }),
130
+ raw
131
+ }]
132
+ }
133
+ case "interactive": {
134
+ const interactive = object(message, "interactive")
135
+ const reply = object(interactive, "button_reply") ?? object(interactive, "list_reply")
136
+ const wire = string(reply, "id")
137
+ const parsed = wire === undefined ? undefined : parseWireId(wire)
138
+ const messageId = string(object(message, "context"), "id")
139
+ if (parsed === undefined || messageId === undefined) return []
140
+ const origin = { thread, messageId, userId: user, raw }
141
+ return parsed.kind === "select"
142
+ ? [{ _tag: "SelectChanged", id: parsed.id, value: parsed.value, ...origin }]
143
+ : [{
144
+ _tag: "ButtonClicked",
145
+ id: parsed.id,
146
+ ...(parsed.value === undefined ? {} : { value: parsed.value }),
147
+ ...origin
148
+ }]
149
+ }
150
+ case "unsupported":
151
+ case "request_welcome":
152
+ return []
153
+ }
154
+ const attachments: Array<Attachment> = []
155
+ let text = string(object(message, "text"), "body") ?? string(object(message, "button"), "text") ?? ""
156
+ for (const kind of media) {
157
+ const item = object(message, kind)
158
+ const mediaId = string(item, "id")
159
+ if (mediaId === undefined) continue
160
+ const name = string(item, "filename")
161
+ const contentType = string(item, "mime_type")
162
+ attachments.push({
163
+ id: mediaId,
164
+ ...(name === undefined ? {} : { name }),
165
+ ...(contentType === undefined ? {} : { contentType })
166
+ })
167
+ text = string(item, "caption") ?? text
168
+ }
169
+ const context = object(message, "context")
170
+ const replyId = string(context, "id")
171
+ const quoted = string(context, "from")
172
+ const name = string(object(contact, "profile"), "name")
173
+ const chatMessage: ChatMessage = {
174
+ id,
175
+ thread,
176
+ author: { id: user, ...(name === undefined ? {} : { name }), isBot: false, isSelf: false },
177
+ text,
178
+ mentions: [],
179
+ ...(replyId === undefined ? {} : {
180
+ replyTo: {
181
+ messageId: replyId,
182
+ ...(quoted === undefined
183
+ ? {}
184
+ : { isSelf: digits(quoted) === digits(string(metadata, "display_phone_number") ?? "") })
185
+ }
186
+ }),
187
+ attachments,
188
+ timestamp: at ?? DateTime.makeUnsafe(0),
189
+ raw: message
190
+ }
191
+ return [{ _tag: "MessageCreated", thread, kind: "direct", message: chatMessage, raw }]
192
+ }
193
+
194
+ const statuses = new Set(["sent", "delivered", "read", "failed"])
195
+
196
+ const fromStatus = (metadata: JsonObject, phoneNumberId: string, status: Json): ReadonlyArray<Inbound> => {
197
+ if (!isObject(status) || status.recipient_type === "group") return []
198
+ const messageId = string(status, "id")
199
+ const value = string(status, "status")
200
+ const phone = string(status, "recipient_id")
201
+ const userId = string(status, "recipient_user_id")
202
+ const user = userId ?? phone
203
+ if (messageId === undefined || value === undefined || !statuses.has(value) || user === undefined) return []
204
+ if (!Address.isUser(user)) return []
205
+ const thread: ChatThread = Address.thread({ phoneNumberId, kind: "user", id: user })
206
+ const raw: Json = { metadata, statuses: [status] }
207
+ const at = timestamp(string(status, "timestamp"))
208
+ const error = array(status.errors).find(isObject)
209
+ const code = error?.code
210
+ const out: Array<Inbound> = [{
211
+ _tag: "Status",
212
+ thread,
213
+ messageId,
214
+ status: value as Update.Status["status"],
215
+ ...(at === undefined ? {} : { timestamp: at }),
216
+ ...(value === "failed" && typeof code === "number"
217
+ ? { reason: reasonForGraphError({ code }, { write: false, cause: error }) }
218
+ : {}),
219
+ ...(phone === undefined ? {} : { phone }),
220
+ ...(userId === undefined ? {} : { userId }),
221
+ raw
222
+ }]
223
+ if (value !== "failed" && phone !== undefined && userId !== undefined) {
224
+ out.push({ _tag: "Alias", thread, phone, userId, messageId, status: value as Update.Alias["status"], raw })
225
+ }
226
+ return out
227
+ }
228
+
229
+ /** @internal */
230
+ export const normalize = (envelope: unknown, context: { readonly phoneNumberId: string }): ReadonlyArray<Inbound> => {
231
+ const out: Array<Inbound> = []
232
+ if (!isObject(envelope) || envelope.object !== "whatsapp_business_account") return out
233
+ for (const entry of array(envelope.entry)) {
234
+ for (const change of array(isObject(entry) ? entry.changes : undefined)) {
235
+ if (!isObject(change) || change.field !== "messages") continue
236
+ const value = object(change, "value")
237
+ const metadata = object(value, "metadata")
238
+ if (
239
+ value === undefined || metadata === undefined || string(metadata, "phone_number_id") !== context.phoneNumberId
240
+ ) {
241
+ continue
242
+ }
243
+ for (const message of array(value.messages)) {
244
+ out.push(...fromMessage(value, metadata, context.phoneNumberId, message))
245
+ }
246
+ for (const status of array(value.statuses)) out.push(...fromStatus(metadata, context.phoneNumberId, status))
247
+ }
248
+ }
249
+ return out
250
+ }