@botozap/sdk 0.7.0 → 0.9.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/dist/index.js CHANGED
@@ -39,16 +39,28 @@ function assertAudioPricing(value) {
39
39
  var BotoZapError = class extends Error {
40
40
  code;
41
41
  status;
42
+ outcome;
43
+ retry;
42
44
  /** Headers da resposta HTTP. Ausente em erros sem resposta (status 0). */
43
45
  headers;
44
- constructor(code, message, status, headers) {
46
+ constructor(code, message, status, headers, details) {
45
47
  super(message);
46
48
  this.name = "BotoZapError";
47
49
  this.code = code;
48
50
  this.status = status;
49
51
  this.headers = headers;
52
+ this.outcome = details?.outcome;
53
+ this.retry = details?.retry;
50
54
  }
51
55
  };
56
+ var PLAN_ERROR_CODES = [
57
+ "plan_restricted",
58
+ "free_form_limit_reached",
59
+ "free_number_cap"
60
+ ];
61
+ function isPlanError(error) {
62
+ return error instanceof BotoZapError && PLAN_ERROR_CODES.includes(error.code);
63
+ }
52
64
 
53
65
  // src/resources/ai/upload.ts
54
66
  var receipts = /* @__PURE__ */ new WeakMap();
@@ -3813,6 +3825,7 @@ var AI_OPERATIONS = [
3813
3825
  ];
3814
3826
 
3815
3827
  // src/resources/ai/types.ts
3828
+ var AI_CREDENTIAL_PROVIDERS = ["openai", "anthropic"];
3816
3829
  var AI_PURPOSES = [
3817
3830
  "default",
3818
3831
  "agent_turn",
@@ -3936,7 +3949,7 @@ var AiCredentialsResource = class {
3936
3949
  get(input) {
3937
3950
  return request(this.client, AI_OPERATIONS[11], input);
3938
3951
  }
3939
- /** Cria credencial própria no Vault; a resposta nunca contém a chave. */
3952
+ /** Cria credencial própria no Vault; a resposta nunca contém a chave. Só `AI_CREDENTIAL_PROVIDERS` (openai/anthropic); os demais: 422 `provider_not_enabled`. */
3940
3953
  create(input) {
3941
3954
  return request(this.client, AI_OPERATIONS[12], input);
3942
3955
  }
@@ -5080,8 +5093,9 @@ var Messages = class {
5080
5093
  }
5081
5094
  client;
5082
5095
  /** Envia uma mensagem de texto. */
5083
- async send(params) {
5096
+ async send(params, options = {}) {
5084
5097
  const result = await this.client.requestObject("POST", "/messages", {
5098
+ idempotencyKey: options.idempotencyKey,
5085
5099
  body: {
5086
5100
  to: params.to,
5087
5101
  type: "text",
@@ -5092,8 +5106,9 @@ var Messages = class {
5092
5106
  return assertSendResult(result);
5093
5107
  }
5094
5108
  /** Envia uma mensagem usando um template aprovado. */
5095
- async sendTemplate(params) {
5109
+ async sendTemplate(params, options = {}) {
5096
5110
  const result = await this.client.requestObject("POST", "/messages", {
5111
+ idempotencyKey: options.idempotencyKey,
5097
5112
  body: {
5098
5113
  to: params.to,
5099
5114
  type: "template",
@@ -5104,7 +5119,7 @@ var Messages = class {
5104
5119
  return assertSendResult(result);
5105
5120
  }
5106
5121
  /** Envia mídia por URL pública. */
5107
- async sendMedia(params) {
5122
+ async sendMedia(params, options = {}) {
5108
5123
  const media = { link: params.link };
5109
5124
  if ("caption" in params && params.caption !== void 0) {
5110
5125
  media.caption = params.caption;
@@ -5113,6 +5128,7 @@ var Messages = class {
5113
5128
  media.filename = params.filename;
5114
5129
  }
5115
5130
  const result = await this.client.requestObject("POST", "/messages", {
5131
+ idempotencyKey: options.idempotencyKey,
5116
5132
  body: {
5117
5133
  to: params.to,
5118
5134
  from: params.from,
@@ -5122,6 +5138,47 @@ var Messages = class {
5122
5138
  });
5123
5139
  return assertSendResult(result);
5124
5140
  }
5141
+ /**
5142
+ * Envia botões de resposta, lista ou botão de link (WhatsApp; mensagem livre,
5143
+ * exige janela de 24h aberta).
5144
+ */
5145
+ async sendInteractive(params, options = {}) {
5146
+ return postMessage(
5147
+ this.client,
5148
+ { to: params.to, from: params.from, type: "interactive", interactive: params.interactive },
5149
+ options
5150
+ );
5151
+ }
5152
+ /** Envia uma localização (WhatsApp; mensagem livre). */
5153
+ async sendLocation(params, options = {}) {
5154
+ const location = {
5155
+ latitude: params.latitude,
5156
+ longitude: params.longitude
5157
+ };
5158
+ if (params.name !== void 0) location.name = params.name;
5159
+ if (params.address !== void 0) location.address = params.address;
5160
+ return postMessage(
5161
+ this.client,
5162
+ { to: params.to, from: params.from, type: "location", location },
5163
+ options
5164
+ );
5165
+ }
5166
+ /**
5167
+ * Reage a uma mensagem recebida (WhatsApp). `emoji: ""` retira a reação.
5168
+ * O retorno traz `reaction` com o alvo e a ação.
5169
+ */
5170
+ async sendReaction(params, options = {}) {
5171
+ return postMessage(
5172
+ this.client,
5173
+ {
5174
+ to: params.to,
5175
+ from: params.from,
5176
+ type: "reaction",
5177
+ reaction: { message_id: params.message_id, emoji: params.emoji }
5178
+ },
5179
+ options
5180
+ );
5181
+ }
5125
5182
  /** Lista as mensagens da conta (paginação por cursor). */
5126
5183
  list(params = {}) {
5127
5184
  return this.client.requestCursorList("GET", "/messages", {
@@ -5129,6 +5186,7 @@ var Messages = class {
5129
5186
  limit: params.limit,
5130
5187
  after: params.after,
5131
5188
  before: params.before,
5189
+ sort: params.sort,
5132
5190
  phone_number_id: params.phone_number_id,
5133
5191
  conversation_id: params.conversation_id,
5134
5192
  direction: params.direction,
@@ -5146,6 +5204,13 @@ var Messages = class {
5146
5204
  );
5147
5205
  }
5148
5206
  };
5207
+ async function postMessage(client, body, options) {
5208
+ const result = await client.requestObject("POST", "/messages", {
5209
+ idempotencyKey: options.idempotencyKey,
5210
+ body
5211
+ });
5212
+ return assertSendResult(result);
5213
+ }
5149
5214
  function assertSendResult(value) {
5150
5215
  if (typeof value.wamid !== "string" || typeof value.to !== "string" || typeof value.status !== "string" || value.id !== null && typeof value.id !== "string") {
5151
5216
  throw new BotoZapError(
@@ -5200,7 +5265,12 @@ var Customers = class {
5200
5265
  { query: { page: params.page, per_page: params.per_page } }
5201
5266
  );
5202
5267
  }
5203
- /** Cria um link de setup sob um cliente. */
5268
+ /**
5269
+ * Cria um link de setup sob um cliente (expira em 30 dias). Envie a `url`
5270
+ * devolvida ao Cliente; veja em {@link CreateSetupLinkParams} como funcionam
5271
+ * os redirecionamentos. URL de redirecionamento inválida lança
5272
+ * `BotoZapError` com `code: "invalid_redirect_url"` (422).
5273
+ */
5204
5274
  createSetupLink(customerId, params = {}) {
5205
5275
  return this.client.requestItem(
5206
5276
  "POST",
@@ -5431,7 +5501,7 @@ var Conversations = class {
5431
5501
  * A leitura e o envio usam a mesma chave; o POST /messages revalida Conta,
5432
5502
  * ambiente, identidade, janela, quota e billing antes de chamar a Meta.
5433
5503
  */
5434
- async reply(id, params) {
5504
+ async reply(id, params, options = {}) {
5435
5505
  const conversation = await this.get(id);
5436
5506
  const from = conversation.phone_number_id;
5437
5507
  if (typeof from !== "string" || !from.trim()) {
@@ -5450,7 +5520,7 @@ var Conversations = class {
5450
5520
  422
5451
5521
  );
5452
5522
  }
5453
- return this.client.messages.send({ to, text: params.text, from });
5523
+ return this.client.messages.send({ to, text: params.text, from }, options);
5454
5524
  }
5455
5525
  update(id, params) {
5456
5526
  return this.client.requestItem(
@@ -5563,10 +5633,19 @@ var PhoneNumbers = class {
5563
5633
  `/phone_numbers/${enc6(id)}`
5564
5634
  );
5565
5635
  }
5566
- // NOTA: `update` foi removido de propósito. A rota PATCH /v1/phone_numbers/:id
5567
- // responde SEMPRE 422 `no_updatable_fields` — o schema atual só tem campos de
5568
- // identidade e campos sincronizados da Meta, nenhum editável por aqui. Expor o
5569
- // método só entregaria uma chamada garantidamente quebrada.
5636
+ /**
5637
+ * Atualiza o nome local (`label`) do Número. É o único campo editável:
5638
+ * identidade e dados sincronizados da Meta (`display_phone_number`,
5639
+ * `verified_name`, `quality_rating`) não mudam por aqui. `{id}` aceita o
5640
+ * UUID interno ou o `phone_number_id` da Meta.
5641
+ */
5642
+ update(id, params) {
5643
+ return this.client.requestItem(
5644
+ "PATCH",
5645
+ `/phone_numbers/${enc6(id)}`,
5646
+ { body: { label: params.label } }
5647
+ );
5648
+ }
5570
5649
  /** Remove um número. Responde 204 (sem corpo). */
5571
5650
  delete(id) {
5572
5651
  return this.client.request("DELETE", `/phone_numbers/${enc6(id)}`);
@@ -5642,6 +5721,28 @@ var Events = class {
5642
5721
  }
5643
5722
  };
5644
5723
 
5724
+ // src/resources/usage.ts
5725
+ var Usage = class {
5726
+ constructor(client) {
5727
+ this.client = client;
5728
+ }
5729
+ client;
5730
+ /**
5731
+ * Custo da Meta por dia, categoria e tipo, lido da Pricing Analytics
5732
+ * sincronizada uma vez por dia por WABA. Scope `customers:read`; o sandbox
5733
+ * fica de fora. Intervalo grande demais responde 422 `range_too_large`.
5734
+ */
5735
+ metaCosts(params = {}) {
5736
+ return this.client.requestItem("GET", "/usage/meta-costs", {
5737
+ query: {
5738
+ customer_id: params.customer_id,
5739
+ from: params.from,
5740
+ to: params.to
5741
+ }
5742
+ });
5743
+ }
5744
+ };
5745
+
5645
5746
  // src/resources/read-only.ts
5646
5747
  var Users = class {
5647
5748
  constructor(client) {
@@ -5696,6 +5797,18 @@ var WebhookDeliveries = class {
5696
5797
  }
5697
5798
  };
5698
5799
 
5800
+ // src/resources/me.ts
5801
+ var MeResource = class {
5802
+ constructor(client) {
5803
+ this.client = client;
5804
+ }
5805
+ client;
5806
+ /** Retorna a Conta, o ambiente e os scopes efetivos da chave. */
5807
+ get() {
5808
+ return this.client.requestItem("GET", "/me");
5809
+ }
5810
+ };
5811
+
5699
5812
  // src/client.ts
5700
5813
  var DEFAULT_BASE_URL = "https://botozap.com.br/api/v1";
5701
5814
  var BotoZap = class {
@@ -5720,17 +5833,19 @@ var BotoZap = class {
5720
5833
  radar;
5721
5834
  media;
5722
5835
  events;
5836
+ usage;
5723
5837
  users;
5724
5838
  apiLogs;
5725
5839
  webhookDeliveries;
5726
- apiKey;
5840
+ me;
5841
+ credential;
5727
5842
  baseUrl;
5728
5843
  fetchImpl;
5729
5844
  constructor(options) {
5730
- if (!options || !options.apiKey) {
5731
- throw new Error("BotoZap: apiKey \xE9 obrigat\xF3rio.");
5845
+ if (!options || Boolean(options.apiKey) === Boolean(options.accessToken)) {
5846
+ throw new Error("BotoZap: informe apenas apiKey ou accessToken.");
5732
5847
  }
5733
- this.apiKey = options.apiKey;
5848
+ this.credential = options.accessToken ?? options.apiKey;
5734
5849
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
5735
5850
  const resolvedFetch = options.fetch ?? globalThis.fetch;
5736
5851
  if (typeof resolvedFetch !== "function") {
@@ -5760,9 +5875,11 @@ var BotoZap = class {
5760
5875
  this.phoneNumbers = new PhoneNumbers(this);
5761
5876
  this.media = new Media(this);
5762
5877
  this.events = new Events(this);
5878
+ this.usage = new Usage(this);
5763
5879
  this.users = new Users(this);
5764
5880
  this.apiLogs = new ApiLogs(this);
5765
5881
  this.webhookDeliveries = new WebhookDeliveries(this);
5882
+ this.me = new MeResource(this);
5766
5883
  }
5767
5884
  /** PUT de artefato em URL assinada, sem token BotoZap nem cookies. Não segue redirecionamentos. */
5768
5885
  async putArtifact(url, contentType, file) {
@@ -5804,12 +5921,16 @@ var BotoZap = class {
5804
5921
  if (value !== void 0) url.searchParams.set(key, String(value));
5805
5922
  }
5806
5923
  }
5924
+ const credential = typeof this.credential === "function" ? await this.credential() : this.credential;
5925
+ if (!credential || /[\s,]/.test(credential)) {
5926
+ throw new BotoZapError("invalid_credential", "Credencial Bearer inv\xE1lida.", 401);
5927
+ }
5807
5928
  let res;
5808
5929
  try {
5809
5930
  res = await this.fetchImpl(url.toString(), {
5810
5931
  method,
5811
5932
  headers: {
5812
- Authorization: `Bearer ${this.apiKey}`,
5933
+ Authorization: `Bearer ${credential}`,
5813
5934
  ...opts.body instanceof FormData ? {} : { "Content-Type": "application/json" },
5814
5935
  Accept: "application/json",
5815
5936
  ...opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : {}
@@ -5818,6 +5939,7 @@ var BotoZap = class {
5818
5939
  signal: opts.signal
5819
5940
  });
5820
5941
  } catch (cause) {
5942
+ if (cause instanceof BotoZapError) throw cause;
5821
5943
  const detail = cause instanceof Error ? cause.message : String(cause);
5822
5944
  throw new BotoZapError(
5823
5945
  "network_error",
@@ -5838,7 +5960,11 @@ var BotoZap = class {
5838
5960
  envelope?.error?.code ?? "http_error",
5839
5961
  envelope?.error?.message ?? `HTTP ${res.status}`,
5840
5962
  res.status,
5841
- headers
5963
+ headers,
5964
+ {
5965
+ outcome: envelope?.error?.outcome === "rejected" || envelope?.error?.outcome === "accepted" || envelope?.error?.outcome === "unknown" ? envelope.error.outcome : void 0,
5966
+ retry: envelope?.error?.retry === "backoff" || envelope?.error?.retry === "after_correction" || envelope?.error?.retry === "reconcile_first" || envelope?.error?.retry === "unknown" ? envelope.error.retry : void 0
5967
+ }
5842
5968
  );
5843
5969
  }
5844
5970
  return data;
@@ -5902,8 +6028,18 @@ function safeJson(text) {
5902
6028
  return text;
5903
6029
  }
5904
6030
  }
6031
+
6032
+ // src/types.ts
6033
+ var WEBHOOK_CATEGORIES = [
6034
+ "messages",
6035
+ "statuses",
6036
+ "crm",
6037
+ "account",
6038
+ "app_messages"
6039
+ ];
5905
6040
  export {
5906
6041
  AI_CONFIGURABLE_PURPOSES,
6042
+ AI_CREDENTIAL_PROVIDERS,
5907
6043
  AI_OPERATIONS,
5908
6044
  AI_PURPOSES,
5909
6045
  AgendaConfiguration,
@@ -5940,7 +6076,10 @@ export {
5940
6076
  CrmResource,
5941
6077
  Inbox,
5942
6078
  Journeys,
6079
+ PLAN_ERROR_CODES,
5943
6080
  Radar,
5944
- SavedReplies
6081
+ SavedReplies,
6082
+ WEBHOOK_CATEGORIES,
6083
+ isPlanError
5945
6084
  };
5946
6085
  //# sourceMappingURL=index.js.map