@open-apime/sdk 0.2.2

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.
@@ -0,0 +1,512 @@
1
+ import { A as ApimeError } from './index-37ITjlwO.cjs';
2
+ export { a as ApiError, b as AuthenticationError, C as ConfigurationError, c as ConflictError, d as ConnectionError, I as InvalidRequestError, e as InvalidSignatureError, N as NotFoundError, P as PermissionError, R as RateLimitError, S as SessionUnavailableError, T as TimeoutError, U as UnprocessableError, f as constructEvent, v as verifyWebhookSignature } from './index-37ITjlwO.cjs';
3
+ import { Instance, QrCode, EventLogEntry, InstanceInfo, Profile, SentMessage } from './types/index.cjs';
4
+ export { C as ChatPresencePayload, a as ContactReachoutLockedPayload, b as ContactUpdatePayload, D as DisconnectedPayload, M as MessageButton, c as MessagePayload, P as PresencePayload, R as ReceiptPayload, d as RestrictionLiftedPayload, T as TemporaryBanPayload, W as WebhookEnvelope, e as WebhookEvent, f as WebhookEventType } from './events-BV5UVoFu.cjs';
5
+
6
+ /**
7
+ * The apime has three credentials and they do not overlap: 46 routes only
8
+ * accept an instance token, 13 only accept a user one. Typing the credential
9
+ * lets the compiler refuse the wrong call, instead of the caller finding out
10
+ * with a 403 in production.
11
+ */
12
+ /** Session token from POST /auth/login. Expires. */
13
+ interface UserJwtAuth {
14
+ readonly type: "userJwt";
15
+ readonly token: string;
16
+ }
17
+ /** Integration token an admin creates. Does not expire. */
18
+ interface ApiTokenAuth {
19
+ readonly type: "apiToken";
20
+ readonly token: string;
21
+ }
22
+ /**
23
+ * Scoped to a single instance, so the id travels with the credential and the
24
+ * caller never has to repeat it on every call.
25
+ */
26
+ interface InstanceTokenAuth {
27
+ readonly type: "instanceToken";
28
+ readonly token: string;
29
+ readonly instanceId: string;
30
+ }
31
+ type Auth = UserJwtAuth | ApiTokenAuth | InstanceTokenAuth;
32
+ /** The two credentials that identify a user, as opposed to a single instance. */
33
+ type UserAuth = UserJwtAuth | ApiTokenAuth;
34
+ type AuthKind = Auth["type"];
35
+
36
+ /** What the SDK knows about a request when it reports it. */
37
+ interface RequestInfo {
38
+ method: string;
39
+ /** Templated path, with ids replaced, so it groups in the error tracker. */
40
+ route: string;
41
+ /** Real path, with ids. Useful to reproduce the call. */
42
+ path: string;
43
+ instanceId: string | undefined;
44
+ attempt: number;
45
+ idempotencyKey: string | undefined;
46
+ }
47
+ interface SuccessInfo extends RequestInfo {
48
+ status: number;
49
+ durationMs: number;
50
+ }
51
+ interface FailureInfo extends RequestInfo {
52
+ status: number | undefined;
53
+ durationMs: number;
54
+ error: ApimeError;
55
+ /** True when the client is about to try again. */
56
+ willRetry: boolean;
57
+ }
58
+ /**
59
+ * Where the host app plugs its own observability. The SDK reports, and stays
60
+ * out of the decision: a library that imports Sentry forces it on everyone and
61
+ * pins a version the app may not want.
62
+ *
63
+ * Wiring these to the app's own logger is what makes reporting automatic for
64
+ * every call, instead of each call site remembering to try/catch.
65
+ */
66
+ interface Observer {
67
+ onRequest?: (info: RequestInfo) => void;
68
+ onSuccess?: (info: SuccessInfo) => void;
69
+ /**
70
+ * Fires on every failed attempt, including the ones that will be retried.
71
+ * Check `willRetry` to report only what actually failed for good.
72
+ */
73
+ onError?: (info: FailureInfo) => void;
74
+ onRetry?: (info: FailureInfo & {
75
+ delayMs: number;
76
+ }) => void;
77
+ }
78
+
79
+ /** True when the app has an initialized Sentry. Absent means every report is a no-op. */
80
+ declare function hasSentry(): boolean;
81
+
82
+ interface RequestOptions {
83
+ timeoutMs?: number;
84
+ maxRetries?: number;
85
+ signal?: AbortSignal;
86
+ /** Extra headers for this call. */
87
+ headers?: Record<string, string>;
88
+ /**
89
+ * Makes a repeated send safe: the apime replays the first result instead of
90
+ * sending the message again. Required for a send to be retried at all.
91
+ */
92
+ idempotencyKey?: string;
93
+ }
94
+ interface HttpClientOptions {
95
+ baseUrl: string;
96
+ auth: Auth;
97
+ timeoutMs?: number;
98
+ maxRetries?: number;
99
+ fetch?: typeof globalThis.fetch;
100
+ /** Appended to the User-Agent, to identify the calling app in the apime logs. */
101
+ appName?: string;
102
+ /** Where the app plugs its logger or error tracker. See Observer. */
103
+ observer?: Observer;
104
+ /**
105
+ * With no observer, definitive failures still reach the Sentry the app
106
+ * already runs, found through its global client. No Sentry means no-op.
107
+ * Set false to silence it.
108
+ */
109
+ autoReport?: boolean;
110
+ }
111
+ interface SendArgs {
112
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
113
+ path: string;
114
+ query?: Record<string, string | number | undefined>;
115
+ body?: unknown;
116
+ options?: RequestOptions;
117
+ }
118
+ declare class HttpClient {
119
+ private readonly baseUrl;
120
+ private readonly auth;
121
+ private readonly timeoutMs;
122
+ private readonly maxRetries;
123
+ private readonly fetchImpl;
124
+ private readonly userAgent;
125
+ private readonly observer;
126
+ private readonly autoReport;
127
+ private readonly instanceId;
128
+ constructor(options: HttpClientOptions);
129
+ private info;
130
+ request<T>(args: SendArgs): Promise<T>;
131
+ /**
132
+ * A write is only retried when the caller passed an idempotency key: without
133
+ * it a retried send can deliver the same WhatsApp message twice. The one
134
+ * exception is 503, which the apime returns before touching WhatsApp.
135
+ */
136
+ private mayRetry;
137
+ private writeIsSafe;
138
+ private attempt;
139
+ }
140
+
141
+ interface CreateInstanceInput {
142
+ name: string;
143
+ webhook_url?: string;
144
+ webhook_secret?: string;
145
+ }
146
+ interface UpdateInstanceInput {
147
+ name: string;
148
+ webhook_url?: string | null;
149
+ webhook_secret?: string | null;
150
+ }
151
+ /**
152
+ * Routes that only a user credential reaches. An instance token gets a 403 here,
153
+ * so these live on the user client alone.
154
+ */
155
+ declare class InstancesResource {
156
+ private readonly http;
157
+ constructor(http: HttpClient);
158
+ list(options?: RequestOptions): Promise<Instance[]>;
159
+ create(input: CreateInstanceInput, options?: RequestOptions): Promise<Instance>;
160
+ get(instanceId: string, options?: RequestOptions): Promise<Instance>;
161
+ update(instanceId: string, input: UpdateInstanceInput, options?: RequestOptions): Promise<Instance>;
162
+ delete(instanceId: string, options?: RequestOptions): Promise<void>;
163
+ rotateToken(instanceId: string, options?: RequestOptions): Promise<{
164
+ token: string;
165
+ }>;
166
+ getQrCode(instanceId: string, options?: RequestOptions): Promise<QrCode>;
167
+ disconnect(instanceId: string, options?: RequestOptions): Promise<{
168
+ message: string;
169
+ }>;
170
+ listEvents(instanceId: string, query?: {
171
+ limit?: number;
172
+ }, options?: RequestOptions): Promise<EventLogEntry[]>;
173
+ }
174
+ /**
175
+ * The same family seen from an instance token: the id comes from the credential
176
+ * and the routes are the ones that demand it.
177
+ */
178
+ declare class ScopedInstanceResource {
179
+ private readonly http;
180
+ private readonly instanceId;
181
+ constructor(http: HttpClient, instanceId: string);
182
+ get(options?: RequestOptions): Promise<Instance>;
183
+ /** Only reachable with an instance token; a user token gets a 403. */
184
+ info(options?: RequestOptions): Promise<InstanceInfo>;
185
+ getQrCode(options?: RequestOptions): Promise<QrCode>;
186
+ disconnect(options?: RequestOptions): Promise<{
187
+ message: string;
188
+ }>;
189
+ listEvents(query?: {
190
+ limit?: number;
191
+ }, options?: RequestOptions): Promise<EventLogEntry[]>;
192
+ getProfile(jid: string, options?: RequestOptions): Promise<Profile>;
193
+ getBusinessProfile(jid: string, options?: RequestOptions): Promise<Profile>;
194
+ getProfilePicture(jid: string, options?: RequestOptions): Promise<{
195
+ url?: string;
196
+ }>;
197
+ }
198
+
199
+ /** Fields every send accepts to quote another message. */
200
+ interface QuoteInput {
201
+ /** Id of the quoted message. */
202
+ quoted?: string;
203
+ quotedParticipant?: string;
204
+ quotedText?: string;
205
+ quotedFromMe?: boolean;
206
+ }
207
+ /** Marks the incoming message as read in the same call that answers it. */
208
+ interface MarkReadInput {
209
+ markReadMessageId?: string;
210
+ markReadSender?: string;
211
+ }
212
+ interface SendTextInput extends QuoteInput, MarkReadInput {
213
+ to: string;
214
+ text: string;
215
+ mentionedJids?: string[];
216
+ }
217
+ interface SendMediaInput extends QuoteInput, MarkReadInput {
218
+ to: string;
219
+ type: "image" | "video";
220
+ /** Bytes of the file. The SDK does not read from disk. */
221
+ file: Blob | File;
222
+ filename?: string;
223
+ caption?: string;
224
+ }
225
+ interface SendAudioInput extends QuoteInput, MarkReadInput {
226
+ to: string;
227
+ file: Blob | File;
228
+ filename?: string;
229
+ /** true sends it as a voice note instead of an attachment. */
230
+ ptt?: boolean;
231
+ seconds?: number;
232
+ }
233
+ interface SendDocumentInput extends QuoteInput, MarkReadInput {
234
+ to: string;
235
+ file: Blob | File;
236
+ /** Name the recipient sees. */
237
+ filename?: string;
238
+ caption?: string;
239
+ }
240
+ interface ContactEntry {
241
+ displayName: string;
242
+ vcard?: string;
243
+ }
244
+ interface SendContactInput extends QuoteInput {
245
+ to: string;
246
+ displayName: string;
247
+ vcard?: string;
248
+ contacts?: ContactEntry[];
249
+ mentionedJids?: string[];
250
+ }
251
+ interface SendLocationInput extends QuoteInput {
252
+ to: string;
253
+ latitude: number;
254
+ longitude: number;
255
+ name?: string;
256
+ address?: string;
257
+ }
258
+ /**
259
+ * Sending is the one place where a retry can be seen by the customer, so every
260
+ * method takes an idempotency key through `options`. Without it the client
261
+ * refuses to retry a failed send.
262
+ */
263
+ declare class MessagesResource {
264
+ private readonly http;
265
+ private readonly instanceId;
266
+ constructor(http: HttpClient, instanceId: string);
267
+ private get base();
268
+ sendText(input: SendTextInput, options?: RequestOptions): Promise<SentMessage>;
269
+ sendMedia(input: SendMediaInput, options?: RequestOptions): Promise<SentMessage>;
270
+ sendAudio(input: SendAudioInput, options?: RequestOptions): Promise<SentMessage>;
271
+ sendDocument(input: SendDocumentInput, options?: RequestOptions): Promise<SentMessage>;
272
+ sendContact(input: SendContactInput, options?: RequestOptions): Promise<SentMessage>;
273
+ sendLocation(input: SendLocationInput, options?: RequestOptions): Promise<SentMessage>;
274
+ /** Generic enqueue, for a type the SDK does not model yet. */
275
+ enqueue(input: {
276
+ to: string;
277
+ type: string;
278
+ payload: string;
279
+ }, options?: RequestOptions): Promise<SentMessage>;
280
+ list(options?: RequestOptions): Promise<SentMessage[]>;
281
+ }
282
+
283
+ interface ApiToken {
284
+ id: string;
285
+ name: string;
286
+ expiresAt?: string;
287
+ createdAt?: string;
288
+ /** Only present on creation: the apime never returns it again. */
289
+ token?: string;
290
+ }
291
+ declare class TokensResource {
292
+ private readonly http;
293
+ constructor(http: HttpClient);
294
+ list(options?: RequestOptions): Promise<ApiToken[]>;
295
+ create(input: {
296
+ name: string;
297
+ expiresAt?: string;
298
+ }, options?: RequestOptions): Promise<ApiToken>;
299
+ delete(tokenId: string, options?: RequestOptions): Promise<void>;
300
+ }
301
+
302
+ interface User {
303
+ id: string;
304
+ email: string;
305
+ role?: string;
306
+ createdAt?: string;
307
+ }
308
+ /** Every route here also demands role admin, checked against the database. */
309
+ declare class UsersResource {
310
+ private readonly http;
311
+ constructor(http: HttpClient);
312
+ list(options?: RequestOptions): Promise<User[]>;
313
+ create(input: {
314
+ email: string;
315
+ password: string;
316
+ role?: string;
317
+ }, options?: RequestOptions): Promise<User>;
318
+ updatePassword(userId: string, password: string, options?: RequestOptions): Promise<unknown>;
319
+ rotateApiToken(userId: string, options?: RequestOptions): Promise<{
320
+ token: string;
321
+ }>;
322
+ delete(userId: string, options?: RequestOptions): Promise<void>;
323
+ }
324
+
325
+ interface CheckNumberResult {
326
+ valid?: boolean;
327
+ jid?: string;
328
+ [key: string]: unknown;
329
+ }
330
+ interface GroupParticipant {
331
+ jid: string;
332
+ isAdmin?: boolean;
333
+ isSuperAdmin?: boolean;
334
+ }
335
+ interface GroupInfo {
336
+ jid: string;
337
+ name?: string;
338
+ topic?: string;
339
+ participants?: GroupParticipant[];
340
+ [key: string]: unknown;
341
+ }
342
+ type PresenceState = "composing" | "paused" | "available" | "unavailable";
343
+ type ParticipantAction = "add" | "remove" | "promote" | "demote";
344
+ type JoinRequestAction = "approve" | "reject";
345
+ /**
346
+ * Every route here demands the instance token: the apime answers 403 to a user
347
+ * credential, so this resource only hangs off the instance client.
348
+ */
349
+ declare class WhatsAppResource {
350
+ private readonly http;
351
+ private readonly instanceId;
352
+ readonly groups: GroupsResource;
353
+ readonly newsletters: NewslettersResource;
354
+ constructor(http: HttpClient, instanceId: string);
355
+ private get base();
356
+ checkNumber(phone: string, options?: RequestOptions): Promise<CheckNumberResult>;
357
+ /** `to` is optional: without it the presence is global, not per chat. */
358
+ setPresence(input: {
359
+ state: PresenceState;
360
+ to?: string;
361
+ }, options?: RequestOptions): Promise<unknown>;
362
+ listContacts(options?: RequestOptions): Promise<unknown>;
363
+ getContact(jid: string, options?: RequestOptions): Promise<unknown>;
364
+ getUserInfo(jid: string, options?: RequestOptions): Promise<unknown>;
365
+ /** `sender` is required in groups, to identify whose message it is. */
366
+ markRead(input: {
367
+ chat: string;
368
+ message_id: string;
369
+ sender?: string;
370
+ played?: boolean;
371
+ }, options?: RequestOptions): Promise<unknown>;
372
+ deleteMessage(input: {
373
+ chat: string;
374
+ message_id: string;
375
+ sender?: string;
376
+ }, options?: RequestOptions): Promise<unknown>;
377
+ editMessage(input: {
378
+ chat: string;
379
+ message_id: string;
380
+ text: string;
381
+ }, options?: RequestOptions): Promise<unknown>;
382
+ /** An empty `emoji` removes the reaction. */
383
+ react(input: {
384
+ chat: string;
385
+ message_id: string;
386
+ emoji?: string;
387
+ sender?: string;
388
+ from_me?: boolean;
389
+ }, options?: RequestOptions): Promise<unknown>;
390
+ getPrivacySettings(options?: RequestOptions): Promise<unknown>;
391
+ setPrivacySetting(input: {
392
+ name: string;
393
+ value: string;
394
+ }, options?: RequestOptions): Promise<unknown>;
395
+ getStatusPrivacy(options?: RequestOptions): Promise<unknown>;
396
+ getChatSettings(chat: string, options?: RequestOptions): Promise<unknown>;
397
+ /** `muted_until` as null unmutes. */
398
+ setChatSettings(chat: string, input: {
399
+ muted_until?: string | null;
400
+ pinned?: boolean;
401
+ archived?: boolean;
402
+ }, options?: RequestOptions): Promise<unknown>;
403
+ setStatusMessage(message: string, options?: RequestOptions): Promise<unknown>;
404
+ /** `seconds` as 0 turns disappearing messages off. */
405
+ setDefaultDisappearingTimer(seconds: number, options?: RequestOptions): Promise<unknown>;
406
+ uploadMedia(input: {
407
+ media_type: "image" | "video" | "audio" | "document";
408
+ data_base64: string;
409
+ }, options?: RequestOptions): Promise<unknown>;
410
+ /** `revoke` invalidates the previous link and issues another. */
411
+ getContactQrLink(query?: {
412
+ revoke?: boolean;
413
+ }, options?: RequestOptions): Promise<unknown>;
414
+ resolveContactQrLink(code: string, options?: RequestOptions): Promise<unknown>;
415
+ resolveBusinessMessageLink(code: string, options?: RequestOptions): Promise<unknown>;
416
+ }
417
+ declare class GroupsResource {
418
+ private readonly http;
419
+ private readonly instanceId;
420
+ constructor(http: HttpClient, instanceId: string);
421
+ private get base();
422
+ list(options?: RequestOptions): Promise<GroupInfo[]>;
423
+ create(input: {
424
+ name: string;
425
+ participants?: string[];
426
+ }, options?: RequestOptions): Promise<GroupInfo>;
427
+ get(group: string, options?: RequestOptions): Promise<GroupInfo>;
428
+ getInviteLink(group: string, options?: RequestOptions): Promise<{
429
+ link?: string;
430
+ }>;
431
+ resolveInvite(link: string, options?: RequestOptions): Promise<GroupInfo>;
432
+ join(link: string, options?: RequestOptions): Promise<unknown>;
433
+ leave(group: string, options?: RequestOptions): Promise<unknown>;
434
+ updateParticipants(group: string, input: {
435
+ action: ParticipantAction;
436
+ participants: string[];
437
+ }, options?: RequestOptions): Promise<unknown>;
438
+ listJoinRequests(group: string, options?: RequestOptions): Promise<unknown>;
439
+ updateJoinRequests(group: string, input: {
440
+ action: JoinRequestAction;
441
+ participants: string[];
442
+ }, options?: RequestOptions): Promise<unknown>;
443
+ }
444
+ declare class NewslettersResource {
445
+ private readonly http;
446
+ private readonly instanceId;
447
+ constructor(http: HttpClient, instanceId: string);
448
+ private base;
449
+ subscribeLiveUpdates(jid: string, options?: RequestOptions): Promise<unknown>;
450
+ markViewed(jid: string, serverIds: string[], options?: RequestOptions): Promise<unknown>;
451
+ react(jid: string, input: {
452
+ server_id: string;
453
+ reaction?: string;
454
+ message_id?: string;
455
+ }, options?: RequestOptions): Promise<unknown>;
456
+ getMessageUpdates(jid: string, options?: RequestOptions): Promise<unknown>;
457
+ }
458
+
459
+ interface ClientOptions {
460
+ baseUrl: string;
461
+ timeoutMs?: number;
462
+ maxRetries?: number;
463
+ fetch?: typeof globalThis.fetch;
464
+ appName?: string;
465
+ /**
466
+ * Reports every request, failure and retry to the app's own logger or error
467
+ * tracker. Nothing is reported without it: the SDK does not pick a vendor.
468
+ */
469
+ observer?: Observer;
470
+ /**
471
+ * Sem `observer`, a falha definitiva ainda vai para o Sentry que o app já
472
+ * roda, achado pelo cliente global. Sem Sentry, não faz nada. `false` cala.
473
+ */
474
+ autoReport?: boolean;
475
+ }
476
+ interface Credentials {
477
+ token: string;
478
+ }
479
+ /**
480
+ * Two clients instead of one, because the apime splits its routes by credential
481
+ * and a single class would offer methods that always answer 403. Which one you
482
+ * build decides what the compiler lets you call.
483
+ */
484
+ declare class ApimeUserClient {
485
+ readonly instances: InstancesResource;
486
+ /** Requires the user to have role admin; other users get a 403. */
487
+ readonly users: UsersResource;
488
+ readonly tokens: TokensResource;
489
+ private readonly http;
490
+ constructor(auth: UserJwtAuth | ApiTokenAuth, options: ClientOptions);
491
+ /** Escape hatch for a route the SDK does not cover yet. */
492
+ request<T>(args: Parameters<HttpClient["request"]>[0]): Promise<T>;
493
+ }
494
+ declare class ApimeInstanceClient {
495
+ readonly instanceId: string;
496
+ readonly instance: ScopedInstanceResource;
497
+ readonly messages: MessagesResource;
498
+ readonly whatsapp: WhatsAppResource;
499
+ private readonly http;
500
+ constructor(auth: InstanceTokenAuth, options: ClientOptions);
501
+ request<T>(args: Parameters<HttpClient["request"]>[0]): Promise<T>;
502
+ }
503
+ /** Entry point. The factory you pick is the credential you have. */
504
+ declare const Apime: {
505
+ withUserJwt(token: string, options: ClientOptions): ApimeUserClient;
506
+ withApiToken(token: string, options: ClientOptions): ApimeUserClient;
507
+ withInstanceToken(credentials: Credentials & {
508
+ instanceId: string;
509
+ }, options: ClientOptions): ApimeInstanceClient;
510
+ };
511
+
512
+ export { type ApiToken, type ApiTokenAuth, Apime, ApimeError, ApimeInstanceClient, ApimeUserClient, type Auth, type AuthKind, type CheckNumberResult, type ClientOptions, type ContactEntry, type CreateInstanceInput, EventLogEntry, type FailureInfo, type GroupInfo, type GroupParticipant, Instance, InstanceInfo, type InstanceTokenAuth, type JoinRequestAction, type MarkReadInput, type Observer, type ParticipantAction, type PresenceState, Profile, QrCode, type QuoteInput, type RequestInfo, type RequestOptions, type SendAudioInput, type SendContactInput, type SendDocumentInput, type SendLocationInput, type SendMediaInput, type SendTextInput, SentMessage, type SuccessInfo, type UpdateInstanceInput, type User, type UserAuth, type UserJwtAuth, hasSentry };