@geekapps/billing-fastify 0.13.0 → 0.16.1

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/README.md CHANGED
@@ -47,7 +47,20 @@ const client = new BillingClient({
47
47
  await client.customers.create({ name: "...", email: "..." });
48
48
  ```
49
49
 
50
- O `mode` (dev/prod) é configurado uma única vez ao instanciar o cliente — nenhum método individual precisa recebê-lo novamente.
50
+ O `mode` (dev/prod) é configurado uma única vez ao instanciar o cliente e vale para todas as chamadas (default: `"prod"`).
51
+
52
+ ### Override de modo por chamada
53
+
54
+ Todo método aceita, no último parâmetro, `{ mode }` para sobrescrever o modo geral só naquela chamada — útil para testar algo novo em dev com o app inteiro em prod:
55
+
56
+ ```ts
57
+ await client.charges.create({ customer_id, amount: 5000, method: "PIX" }, { mode: "dev" });
58
+ await client.customers.list({}, { mode: "dev" });
59
+
60
+ // várias chamadas seguidas no mesmo modo
61
+ const dev = client.withMode("dev");
62
+ await dev.items.list();
63
+ ```
51
64
 
52
65
  ## Cobrança avulsa simples (sempre cartão)
53
66
 
package/dist/index.d.ts CHANGED
@@ -12,14 +12,30 @@ interface HttpClientOptions {
12
12
  */
13
13
  mode?: string | (() => string | Promise<string>);
14
14
  }
15
+ /** Opções por chamada — sobrescrevem a configuração geral do cliente só naquela requisição. */
16
+ interface RequestOptions {
17
+ /**
18
+ * Override do ambiente (dev/prod) apenas para esta chamada. Ex.: app inteiro em "prod"
19
+ * e uma cobrança de teste com `charges.create(input, { mode: "dev" })`.
20
+ */
21
+ mode?: "dev" | "prod" | (string & {});
22
+ }
15
23
  declare class HttpClient {
16
24
  private readonly baseUrl;
17
25
  private readonly token;
18
26
  private readonly organizationId?;
19
27
  private readonly mode;
28
+ private readonly options;
20
29
  constructor(options: HttpClientOptions);
30
+ /**
31
+ * Cliente com as mesmas credenciais e o modo sobrescrito por `opts.mode` — sem override,
32
+ * devolve a própria instância (modo geral).
33
+ */
34
+ with(opts?: RequestOptions): HttpClient;
21
35
  private resolveToken;
22
36
  private resolveOrgId;
37
+ /** Modo efetivo desta instância (geral ou sobrescrito via `with`). */
38
+ currentMode(): Promise<string>;
23
39
  private resolveMode;
24
40
  request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>;
25
41
  get<T>(path: string): Promise<T>;
@@ -131,9 +147,23 @@ interface CustomerInput {
131
147
  address_state?: string;
132
148
  address_postal_code?: string;
133
149
  address_country?: string;
134
- /** Para CNPJ, completa com os dados da Receita Federal os campos não informados. Default: true. */
150
+ /**
151
+ * Para CNPJ, razão social e endereço vêm sempre da Receita Federal (o que for enviado é
152
+ * ignorado). Default: true.
153
+ */
135
154
  autofill?: boolean;
155
+ /**
156
+ * Obrigatório (`true`) quando a Receita não pôde ser consultada e os dados da empresa
157
+ * foram informados à mão: aceite da declaração de que as informações são verdadeiras e de
158
+ * que quem as forneceu responde por elas. Sem isso a API responde 422
159
+ * `{ code: "manual_declaration_required", declaration }`.
160
+ */
161
+ manual_declaration?: boolean;
136
162
  }
163
+ /**
164
+ * Em empresa verificada (`registry_synced_at` preenchido), razão social e endereço não podem
165
+ * ser alterados (409) — use `customers.refreshRegistry(id)`.
166
+ */
137
167
  type CustomerUpdateInput = Partial<Omit<CustomerInput, "autofill" | "external_ref">> & {
138
168
  /** `null` remove a referência. */
139
169
  external_ref?: string | null;
@@ -164,6 +194,11 @@ interface Customer {
164
194
  /** Pessoa física: "***" quando presente. Empresa: completo. */
165
195
  address_line2: string | null;
166
196
  address_district: string | null;
197
+ /** Empresa: data da última sincronização de razão social/endereço com a Receita Federal
198
+ * (null = não verificada, dados declarados manualmente). */
199
+ registry_synced_at?: string | null;
200
+ /** Empresa não verificada: quando a declaração de veracidade foi aceita. */
201
+ registry_declared_at?: string | null;
167
202
  address_city: string | null;
168
203
  address_state: string | null;
169
204
  /** Mascarado, mantém só o prefixo (ex: "01310***"). */
@@ -215,8 +250,11 @@ interface CreateBillingPlanInput {
215
250
  * criar um plano avulso, sem página pública, usado no fluxo simplificado de
216
251
  * checkout/confirmação (`checkoutPlan`/`confirmPlanSubscription`). */
217
252
  plan_page_id?: string;
218
- /** Item de catálogo (BillingItem) do qual nome/preço são copiados na criação. */
219
- item_id: string;
253
+ /**
254
+ * Item de catálogo (BillingItem) do qual nome/preço são copiados na criação. Opcional:
255
+ * sem ele, informe `name` e `amount` — o plano é manual e um item é criado para ele.
256
+ */
257
+ item_id?: string;
220
258
  name?: string;
221
259
  description?: string;
222
260
  amount?: number;
@@ -314,6 +352,8 @@ interface CompanyTaxIdData {
314
352
  legal_nature: string | null;
315
353
  email: string | null;
316
354
  phone: string | null;
355
+ /** Inscrição estadual (quando a fonte informa). */
356
+ state_registration: string | null;
317
357
  address_line1: string | null;
318
358
  address_number: string | null;
319
359
  address_line2: string | null;
@@ -322,6 +362,8 @@ interface CompanyTaxIdData {
322
362
  address_state: string | null;
323
363
  address_postal_code: string | null;
324
364
  address_country: string;
365
+ /** Base que respondeu: "minhareceita" | "brasilapi" | "cnpja" | "cnpjws" | "receitaws". */
366
+ source: string;
325
367
  }
326
368
  interface TaxIdLookupResult {
327
369
  tax_id: string;
@@ -603,20 +645,30 @@ interface CreateOrderResult {
603
645
  payment_ref: string;
604
646
  stripe_publishable_key: string | null;
605
647
  }
648
+ interface CepLookupResult {
649
+ postal_code: string;
650
+ address_line1: string | null;
651
+ address_district: string | null;
652
+ address_city: string;
653
+ address_state: string;
654
+ address_country: "BR";
655
+ /** Base que respondeu: "viacep" | "brasilapi" | "opencep" | "awesomeapi" | "apicep". */
656
+ source: string;
657
+ }
606
658
 
607
659
  declare class ChargesResource {
608
660
  private readonly http;
609
661
  constructor(http: HttpClient);
610
662
  list(params?: {
611
663
  installment_group_id?: string;
612
- }): Promise<Charge[]>;
664
+ }, opts?: RequestOptions): Promise<Charge[]>;
613
665
  /**
614
666
  * Cria uma cobrança (PIX, boleto ou cartão). A geração de fato acontece de forma
615
667
  * assíncrona no backend — a resposta volta com a charge em PENDING, sem os campos
616
668
  * do método (QR code, boleto, etc) ainda preenchidos. Use `get`/`getStatus` para
617
669
  * acompanhar até que estejam prontos.
618
670
  */
619
- create(input: CreateChargeInput): Promise<CreateChargeResult>;
671
+ create(input: CreateChargeInput, opts?: RequestOptions): Promise<CreateChargeResult>;
620
672
  /**
621
673
  * Cobrança avulsa simples, sempre em cartão — cobra direto no cartão padrão já
622
674
  * salvo do cliente (sem fricção nenhuma). Se ele ainda não tiver um cartão salvo,
@@ -630,16 +682,16 @@ declare class ChargesResource {
630
682
  * }
631
683
  * ```
632
684
  */
633
- charge(customerId: string, amountCents: number, options?: Omit<QuickChargeInput, "customer_id" | "amount">): Promise<QuickChargeResult>;
634
- get(id: string): Promise<Charge>;
635
- getStatus(id: string): Promise<{
685
+ charge(customerId: string, amountCents: number, options?: Omit<QuickChargeInput, "customer_id" | "amount">, opts?: RequestOptions): Promise<QuickChargeResult>;
686
+ get(id: string, opts?: RequestOptions): Promise<Charge>;
687
+ getStatus(id: string, opts?: RequestOptions): Promise<{
636
688
  status: Charge["status"];
637
689
  }>;
638
- cancel(id: string): Promise<Charge>;
639
- refund(id: string): Promise<Charge>;
690
+ cancel(id: string, opts?: RequestOptions): Promise<Charge>;
691
+ refund(id: string, opts?: RequestOptions): Promise<Charge>;
640
692
  }
641
693
 
642
- interface WaitUntilPaidOptions {
694
+ interface WaitUntilPaidOptions extends RequestOptions {
643
695
  /** Intervalo entre tentativas, em ms. Default: 2000. */
644
696
  intervalMs?: number;
645
697
  /** Tempo máximo de espera antes de desistir, em ms. Default: 5 minutos. */
@@ -651,7 +703,7 @@ declare class CheckoutResource {
651
703
  /** Consulta o status atual de uma cobrança/checkout pelo `checkout_token` retornado
652
704
  * por `plans.checkout()` (ou qualquer outro fluxo de cobrança do SDK). Sincroniza com
653
705
  * o provedor de pagamento sob o capô quando ainda está PENDING. */
654
- getStatus(checkoutToken: string): Promise<CheckoutStatusResult>;
706
+ getStatus(checkoutToken: string, opts?: RequestOptions): Promise<CheckoutStatusResult>;
655
707
  /**
656
708
  * Faz polling de `getStatus` até o pagamento ser confirmado (ou falhar/expirar) — é
657
709
  * a forma recomendada de confirmar, depois de redirecionar o cliente para a
@@ -666,11 +718,11 @@ declare class CheckoutResource {
666
718
  declare class CouponsResource {
667
719
  private readonly http;
668
720
  constructor(http: HttpClient);
669
- list(): Promise<Coupon[]>;
721
+ list(opts?: RequestOptions): Promise<Coupon[]>;
670
722
  /** `idOrCode` aceita tanto o id interno (`coupon.id`) quanto o `code` legível que você
671
723
  * escolheu na criação (ex: `"BEMVINDO20"`) — normalmente é mais prático guardar/usar o
672
724
  * `code`, já que é você quem o define e é o que aparece para o cliente final. */
673
- get(idOrCode: string): Promise<Coupon>;
725
+ get(idOrCode: string, opts?: RequestOptions): Promise<Coupon>;
674
726
  /**
675
727
  * Cria um cupom de desconto — o `code` é o que o cliente final informa no checkout
676
728
  * (`plans.checkout(planId, { coupon_code })`).
@@ -685,33 +737,35 @@ declare class CouponsResource {
685
737
  * });
686
738
  * ```
687
739
  */
688
- create(input: CreateCouponInput): Promise<Coupon>;
740
+ create(input: CreateCouponInput, opts?: RequestOptions): Promise<Coupon>;
689
741
  /** Só permite editar limites/validade/ativação — o desconto em si (type/value/duration)
690
742
  * de um cupom já criado é imutável; crie um novo código para mudar o valor do desconto.
691
743
  * `idOrCode` aceita id interno ou `code` (ver `get`). */
692
744
  update(idOrCode: string, input: Partial<Pick<CreateCouponInput, "max_redemptions" | "expires_at">> & {
693
745
  active?: boolean;
694
- }): Promise<Coupon>;
746
+ }, opts?: RequestOptions): Promise<Coupon>;
695
747
  /** Desativa o cupom (soft-delete) — códigos já resgatados continuam no histórico.
696
748
  * `idOrCode` aceita id interno ou `code` (ver `get`). */
697
- remove(idOrCode: string): Promise<void>;
749
+ remove(idOrCode: string, opts?: RequestOptions): Promise<void>;
698
750
  }
699
751
 
700
752
  declare class CustomersResource {
701
753
  private readonly http;
702
754
  constructor(http: HttpClient);
703
755
  /** Lista clientes — opcionalmente filtrando por `external_ref`, `tax_id` ou `customer_type`. */
704
- list(filters?: CustomerListFilters): Promise<Customer[]>;
756
+ list(filters?: CustomerListFilters, opts?: RequestOptions): Promise<Customer[]>;
705
757
  /**
706
758
  * Busca o cliente de cobrança pela referência do seu app (ex: `"company:456"`). Use ao
707
759
  * trocar de conta (pessoal ↔ empresa) para operar nos cartões da conta ativa.
708
760
  */
709
- findByExternalRef(externalRef: string): Promise<Customer | null>;
761
+ findByExternalRef(externalRef: string, opts?: RequestOptions): Promise<Customer | null>;
710
762
  /**
711
763
  * Valida um CPF/CNPJ e, para CNPJ, retorna razão social, nome fantasia e endereço da
712
764
  * Receita Federal — use para pré-preencher o cadastro assim que o usuário digitar.
765
+ * Consulta em cascata (Minha Receita → BrasilAPI → CNPJá → CNPJ.ws → ReceitaWS); 404
766
+ * quando nenhuma base encontra o CNPJ, 502 quando todas falham.
713
767
  */
714
- lookupTaxId(taxId: string): Promise<TaxIdLookupResult>;
768
+ lookupTaxId(taxId: string, opts?: RequestOptions): Promise<TaxIdLookupResult>;
715
769
  /**
716
770
  * Cria um cliente pessoa física (CPF) ou empresa (CNPJ). Para CNPJ, os campos não
717
771
  * informados (razão social, endereço...) são completados com os dados da Receita.
@@ -721,15 +775,27 @@ declare class CustomersResource {
721
775
  * await client.customers.create({ tax_id: "11.222.333/0001-81", email: "fin@acme.com", external_ref: "company:456" });
722
776
  * ```
723
777
  */
724
- create(input: CustomerInput): Promise<Customer>;
725
- get(id: string): Promise<Customer>;
778
+ /**
779
+ * Busca o endereço de um CEP (ViaCEP → BrasilAPI → OpenCEP → AwesomeAPI → ApiCEP, em
780
+ * cascata). 404 quando nenhuma base conhece o CEP, 502 quando todas falham.
781
+ */
782
+ lookupCep(cep: string, opts?: RequestOptions): Promise<CepLookupResult>;
783
+ /**
784
+ * Ressincroniza razão social, nome fantasia e endereço de um cliente empresa com o
785
+ * registro atual da Receita Federal — único jeito de alterar esses campos.
786
+ */
787
+ refreshRegistry(id: string, opts?: RequestOptions): Promise<Customer & {
788
+ registry_source: string;
789
+ }>;
790
+ create(input: CustomerInput, opts?: RequestOptions): Promise<Customer>;
791
+ get(id: string, opts?: RequestOptions): Promise<Customer>;
726
792
  /** Atualiza dados de cobrança do cliente (nome, e-mail, endereço, CPF/CNPJ, razão social...). */
727
- update(id: string, input: CustomerUpdateInput): Promise<Customer>;
793
+ update(id: string, input: CustomerUpdateInput, opts?: RequestOptions): Promise<Customer>;
728
794
  /**
729
795
  * Lista os métodos de pagamento salvos do cliente — nunca expõe o número completo do
730
796
  * cartão, só os 4 últimos dígitos, bandeira e validade.
731
797
  */
732
- listPaymentMethods(id: string): Promise<PaymentMethodSummary[]>;
798
+ listPaymentMethods(id: string, opts?: RequestOptions): Promise<PaymentMethodSummary[]>;
733
799
  /**
734
800
  * Cria um SetupIntent para o cliente cadastrar um novo cartão — use o `clientSecret`
735
801
  * retornado com Stripe.js/Elements no frontend do seu app para coletar e confirmar o
@@ -740,11 +806,11 @@ declare class CustomersResource {
740
806
  * // no frontend: stripe.confirmCardSetup(clientSecret, { payment_method: {...} })
741
807
  * ```
742
808
  */
743
- createPaymentMethodSetupIntent(id: string): Promise<PaymentMethodSetupIntent>;
809
+ createPaymentMethodSetupIntent(id: string, opts?: RequestOptions): Promise<PaymentMethodSetupIntent>;
744
810
  /** Define um método de pagamento salvo como o padrão do cliente (usado em cobranças off-session). */
745
- setDefaultPaymentMethod(id: string, paymentMethodId: string): Promise<void>;
811
+ setDefaultPaymentMethod(id: string, paymentMethodId: string, opts?: RequestOptions): Promise<void>;
746
812
  /** Remove um método de pagamento salvo do cliente. */
747
- deletePaymentMethod(id: string, paymentMethodId: string): Promise<void>;
813
+ deletePaymentMethod(id: string, paymentMethodId: string, opts?: RequestOptions): Promise<void>;
748
814
  }
749
815
 
750
816
  interface ItemInput {
@@ -756,10 +822,10 @@ interface ItemInput {
756
822
  declare class ItemsResource {
757
823
  private readonly http;
758
824
  constructor(http: HttpClient);
759
- list(): Promise<BillingItem[]>;
760
- create(input: ItemInput): Promise<BillingItem>;
761
- get(id: string): Promise<BillingItem>;
762
- update(id: string, input: Partial<ItemInput>): Promise<BillingItem>;
825
+ list(opts?: RequestOptions): Promise<BillingItem[]>;
826
+ create(input: ItemInput, opts?: RequestOptions): Promise<BillingItem>;
827
+ get(id: string, opts?: RequestOptions): Promise<BillingItem>;
828
+ update(id: string, input: Partial<ItemInput>, opts?: RequestOptions): Promise<BillingItem>;
763
829
  }
764
830
 
765
831
  declare class OrdersResource {
@@ -771,27 +837,27 @@ declare class OrdersResource {
771
837
  * confirmar via Stripe Elements — as parcelas seguintes são cobradas
772
838
  * automaticamente pelo backend no cartão salvo.
773
839
  */
774
- create(input: CreateOrderInput): Promise<CreateOrderResult>;
775
- list(): Promise<unknown[]>;
776
- get(id: string): Promise<unknown>;
840
+ create(input: CreateOrderInput, opts?: RequestOptions): Promise<CreateOrderResult>;
841
+ list(opts?: RequestOptions): Promise<unknown[]>;
842
+ get(id: string, opts?: RequestOptions): Promise<unknown>;
777
843
  }
778
844
 
779
845
  declare class PlansResource {
780
846
  private readonly http;
781
847
  constructor(http: HttpClient);
782
- list(): Promise<BillingPlanSummary[]>;
783
- get(id: string): Promise<BillingPlanSummary>;
784
- create(input: CreateBillingPlanInput): Promise<BillingPlanSummary>;
848
+ list(opts?: RequestOptions): Promise<BillingPlanSummary[]>;
849
+ get(id: string, opts?: RequestOptions): Promise<BillingPlanSummary>;
850
+ create(input: CreateBillingPlanInput, opts?: RequestOptions): Promise<BillingPlanSummary>;
785
851
  update(id: string, input: Partial<CreateBillingPlanInput> & {
786
852
  active?: boolean;
787
- }): Promise<BillingPlanSummary>;
853
+ }, opts?: RequestOptions): Promise<BillingPlanSummary>;
788
854
  /** Não há hard-delete de planos (assinaturas existentes ainda referenciam) — para
789
855
  * remover um plano do catálogo público, arquive-o. */
790
- archive(id: string): Promise<BillingPlanSummary>;
856
+ archive(id: string, opts?: RequestOptions): Promise<BillingPlanSummary>;
791
857
  /** Vincula um plano avulso a uma página de planos existente (mesma org). */
792
- attachToPage(planId: string, pageId: string): Promise<BillingPlanSummary>;
858
+ attachToPage(planId: string, pageId: string, opts?: RequestOptions): Promise<BillingPlanSummary>;
793
859
  /** Desvincula um plano da sua página, tornando-o avulso (sem página pública). */
794
- detachFromPage(planId: string): Promise<BillingPlanSummary>;
860
+ detachFromPage(planId: string, opts?: RequestOptions): Promise<BillingPlanSummary>;
795
861
  /**
796
862
  * Fluxo simplificado de assinatura para um `Customer` já cadastrado na sua org
797
863
  * (autenticado, sem formulário de nome/e-mail): cria a assinatura + cobrança inicial e
@@ -810,15 +876,15 @@ declare class PlansResource {
810
876
  * }
811
877
  * ```
812
878
  */
813
- checkoutPlan(planId: string, customerId: string, input?: CheckoutForCustomerInput): Promise<CheckoutForCustomerResult>;
879
+ checkoutPlan(planId: string, customerId: string, input?: CheckoutForCustomerInput, opts?: RequestOptions): Promise<CheckoutForCustomerResult>;
814
880
  /** Verifica se um `Customer` tem uma assinatura ativa deste plano (a mais recente),
815
881
  * contraparte de `checkoutPlan` no fluxo simplificado autenticado. */
816
- confirmPlanSubscription(planId: string, customerId: string): Promise<PlanSubscriptionStatusResult>;
882
+ confirmPlanSubscription(planId: string, customerId: string, opts?: RequestOptions): Promise<PlanSubscriptionStatusResult>;
817
883
  /** Lista os planos ativos de uma org pelo slug público — página fixa legada, sem
818
884
  * suporte a múltiplas páginas. Prefira `getPublicPage` para orgs com várias páginas. */
819
- listPublic(orgSlug: string): Promise<ListPublicPlansResult>;
885
+ listPublic(orgSlug: string, opts?: RequestOptions): Promise<ListPublicPlansResult>;
820
886
  /** Busca uma página de planos pública específica pelo slug da org + slug da página. */
821
- getPublicPage(orgSlug: string, pageSlug: string): Promise<GetPublicPlanPageResult>;
887
+ getPublicPage(orgSlug: string, pageSlug: string, opts?: RequestOptions): Promise<GetPublicPlanPageResult>;
822
888
  /**
823
889
  * Inicia a assinatura de um plano para um cliente final: cria (ou reaproveita) o
824
890
  * `Customer` pelo e-mail, cria a `Subscription` e retorna uma URL de checkout hospedada
@@ -841,14 +907,14 @@ declare class PlansResource {
841
907
  * Não requer autenticação — pode ser chamado a partir do backend do dev sem token de
842
908
  * service account, ou do próprio SDK server-side usando qualquer token válido.
843
909
  */
844
- checkout(planId: string, input: PlanCheckoutInput): Promise<PlanCheckoutResult>;
910
+ checkout(planId: string, input: PlanCheckoutInput, opts?: RequestOptions): Promise<PlanCheckoutResult>;
845
911
  }
846
912
 
847
913
  declare class SubscriptionsResource {
848
914
  private readonly http;
849
915
  constructor(http: HttpClient);
850
916
  /** Requer autenticação (service account) — lista todas as assinaturas da sua org. */
851
- list(): Promise<Subscription[]>;
917
+ list(opts?: RequestOptions): Promise<Subscription[]>;
852
918
  /**
853
919
  * Fluxo legado de assinatura por `BillingItem` avulso (sem `BillingPlan`) — requer
854
920
  * autenticação (service account) e que `customer_id`/`item_id` já existam na sua org.
@@ -860,9 +926,9 @@ declare class SubscriptionsResource {
860
926
  * });
861
927
  * ```
862
928
  */
863
- create(input: CreateSubscriptionInput): Promise<CreateSubscriptionResult>;
929
+ create(input: CreateSubscriptionInput, opts?: RequestOptions): Promise<CreateSubscriptionResult>;
864
930
  /** Requer autenticação (service account). */
865
- get(id: string): Promise<Subscription>;
931
+ get(id: string, opts?: RequestOptions): Promise<Subscription>;
866
932
  /**
867
933
  * Cancela uma assinatura — requer autenticação (service account). Cancela no provedor
868
934
  * (Stripe) quando aplicável, marca cobranças pendentes como CANCELLED, e notifica o
@@ -876,7 +942,7 @@ declare class SubscriptionsResource {
876
942
  * await client.subscriptions.cancel(subId, { policy: "END_OF_PERIOD" });
877
943
  * ```
878
944
  */
879
- cancel(id: string, input: CancelSubscriptionInput): Promise<Subscription>;
945
+ cancel(id: string, input: CancelSubscriptionInput, opts?: RequestOptions): Promise<Subscription>;
880
946
  /**
881
947
  * Reverte um cancelamento agendado (cancel_at_period_end) — requer autenticação
882
948
  * (service account). Só se aplica enquanto a assinatura ainda está ACTIVE com o
@@ -884,7 +950,7 @@ declare class SubscriptionsResource {
884
950
  * uma vez CANCELLED de fato, a Subscription já foi encerrada no Stripe e não há o que
885
951
  * reverter — chame `cancel`/checkout novamente para recomeçar.
886
952
  */
887
- resume(id: string): Promise<Subscription>;
953
+ resume(id: string, opts?: RequestOptions): Promise<Subscription>;
888
954
  /**
889
955
  * Calcula o preview de uma troca de plano (não muta nada) — requer autenticação
890
956
  * (service account). Use para mostrar ao dono da org o valor devido/estimado antes de
@@ -896,7 +962,7 @@ declare class SubscriptionsResource {
896
962
  * });
897
963
  * ```
898
964
  */
899
- previewPlanSwap(id: string, input: SwapPlanInput): Promise<SwapPlanPreviewResult>;
965
+ previewPlanSwap(id: string, input: SwapPlanInput, opts?: RequestOptions): Promise<SwapPlanPreviewResult>;
900
966
  /**
901
967
  * Executa a troca de plano/item de uma assinatura já existente (upgrade/downgrade de
902
968
  * tier) — requer autenticação (service account). Executa a troca diretamente, sem
@@ -929,7 +995,7 @@ declare class SubscriptionsResource {
929
995
  * }
930
996
  * ```
931
997
  */
932
- swapPlan(id: string, input: SwapPlanInput): Promise<SwapPlanResult>;
998
+ swapPlan(id: string, input: SwapPlanInput, opts?: RequestOptions): Promise<SwapPlanResult>;
933
999
  /**
934
1000
  * Cancela uma troca de plano ainda pendente (aguardando confirmação de pagamento ou
935
1001
  * renovação — `policy: "AT_RENEWAL"` ou upgrade IMMEDIATE com proration nativa) — requer
@@ -942,7 +1008,7 @@ declare class SubscriptionsResource {
942
1008
  * await client.subscriptions.cancelPendingPlanSwap(subId);
943
1009
  * ```
944
1010
  */
945
- cancelPendingPlanSwap(id: string): Promise<Subscription>;
1011
+ cancelPendingPlanSwap(id: string, opts?: RequestOptions): Promise<Subscription>;
946
1012
  /**
947
1013
  * Verifica se uma assinatura está ativa e qual item ela cobre, usando o
948
1014
  * `management_token` retornado por `plans.checkout()` — rota pública, sem
@@ -956,7 +1022,7 @@ declare class SubscriptionsResource {
956
1022
  * }
957
1023
  * ```
958
1024
  */
959
- checkByToken(managementToken: string): Promise<SubscriptionStatusResult>;
1025
+ checkByToken(managementToken: string, opts?: RequestOptions): Promise<SubscriptionStatusResult>;
960
1026
  }
961
1027
 
962
1028
  type OutboundWebhookEventType = "SUBSCRIPTION_CREATED" | "SUBSCRIPTION_ACTIVATED" | "SUBSCRIPTION_RENEWED" | "SUBSCRIPTION_PLAN_SWAPPED" | "SUBSCRIPTION_PAST_DUE" | "SUBSCRIPTION_CANCELLED" | "SUBSCRIPTION_CANCEL_SCHEDULE" | "SUBSCRIPTION_RESUMED" | "CHARGE_PAID" | "CHARGE_FAILED" | "CHARGE_EXPIRED" | "CHARGE_REFUNDED";
@@ -1084,7 +1150,7 @@ declare class WebhooksResource {
1084
1150
  private readonly http;
1085
1151
  constructor(http: HttpClient);
1086
1152
  /** Lista os webhooks outbound cadastrados na sua org (secret sempre mascarado). */
1087
- list(): Promise<WebhookEndpointSummary[]>;
1153
+ list(opts?: RequestOptions): Promise<WebhookEndpointSummary[]>;
1088
1154
  /**
1089
1155
  * Registra um webhook outbound — idempotente por (org, url): chamar de novo com a
1090
1156
  * mesma URL apenas atualiza os `eventTypes`, sem criar duplicata. Guarde o `secret`
@@ -1092,14 +1158,14 @@ declare class WebhooksResource {
1092
1158
  * `X-Geekapps-Signature` nas entregas recebidas. Passe `secret` para definir o seu
1093
1159
  * próprio signing secret; se omitido, um valor aleatório é gerado automaticamente.
1094
1160
  */
1095
- register(input: WebhookEndpointInput): Promise<WebhookEndpointSummary>;
1161
+ register(input: WebhookEndpointInput, opts?: RequestOptions): Promise<WebhookEndpointSummary>;
1096
1162
  /** Edita um webhook existente — URL, eventos assinados e/ou status ativo/inativo. */
1097
1163
  update(id: string, input: Partial<WebhookEndpointInput> & {
1098
1164
  active?: boolean;
1099
- }): Promise<WebhookEndpointSummary>;
1165
+ }, opts?: RequestOptions): Promise<WebhookEndpointSummary>;
1100
1166
  /** Gera um novo secret e substitui o atual — a versão antiga deixa de validar imediatamente. */
1101
- rotateSecret(id: string): Promise<WebhookEndpointSummary>;
1102
- remove(id: string): Promise<void>;
1167
+ rotateSecret(id: string, opts?: RequestOptions): Promise<WebhookEndpointSummary>;
1168
+ remove(id: string, opts?: RequestOptions): Promise<void>;
1103
1169
  }
1104
1170
 
1105
1171
  interface BillingClientOptions extends Omit<HttpClientOptions, "baseUrl"> {
@@ -1116,7 +1182,24 @@ declare class BillingClient {
1116
1182
  readonly plans: PlansResource;
1117
1183
  readonly subscriptions: SubscriptionsResource;
1118
1184
  readonly webhooks: WebhooksResource;
1185
+ private readonly options;
1186
+ /**
1187
+ * O `mode` passado aqui é o modo geral (default "prod"). Qualquer método aceita um
1188
+ * override por chamada no último parâmetro — ex.: `charges.create(input, { mode: "dev" })`
1189
+ * — ou use `withMode("dev")` para um bloco inteiro de chamadas.
1190
+ */
1119
1191
  constructor(options: HttpClientOptions);
1192
+ /**
1193
+ * Cópia do cliente com outro modo (mesmas credenciais) — útil para várias chamadas
1194
+ * seguidas em dev sem repetir `{ mode: "dev" }` em cada uma.
1195
+ *
1196
+ * ```ts
1197
+ * const dev = billing.withMode("dev");
1198
+ * const customer = await dev.customers.create({ ... });
1199
+ * await dev.charges.create({ customer_id: customer.id, ... });
1200
+ * ```
1201
+ */
1202
+ withMode(mode: NonNullable<RequestOptions["mode"]>): BillingClient;
1120
1203
  }
1121
1204
 
1122
1205
  declare class BillingApiError extends Error {
@@ -1189,4 +1272,4 @@ type ExpirationUnit = "seconds" | "minutes" | "hours" | "days";
1189
1272
  */
1190
1273
  declare function expiresIn(value: number, unit: ExpirationUnit): number;
1191
1274
 
1192
- export { type AppliedDiscount, BillingApiError, BillingClient, type BillingClientOptions, type BillingItem, type BillingPeriod, type BillingPlanSummary, type BillingPluginOptions, type BillingRecurringInterval, type BillingRecurringStatus, type BillingSubscriptionCancelReason, type CancelSubscriptionInput, type CancellationPolicy, type Charge, type ChargeEventData, type ChargeStatus, ChargesResource, type CheckoutForCustomerInput, type CheckoutForCustomerResult, CheckoutResource, type CheckoutSessionStatus, type CheckoutStatusResult, type CompanyTaxIdData, type Coupon, type CouponDuration, type CouponType, CouponsResource, type CreateBillingPlanInput, type CreateChargeInput, type CreateChargeResult, type CreateCouponInput, type CreateOrderInput, type CreateOrderResult, type CreateSubscriptionInput, type CreateSubscriptionResult, type Customer, type CustomerInput, type CustomerListFilters, type CustomerType, type CustomerUpdateInput, CustomersResource, type ExpirationUnit, type GetPublicPlanPageResult, HttpClient, type HttpClientOptions, type ItemInput, ItemsResource, type ListPublicPlansResult, OrdersResource, type OutboundWebhookEventType, type PaymentMethod, type PaymentMethodSetupIntent, type PaymentMethodSummary, type PlanCheckoutCustomerInput, type PlanCheckoutInput, type PlanCheckoutResult, type PlanSubscriptionStatusResult, PlansResource, type ProrationPolicy, type PublicBillingPlan, type PublicOrganization, type PublicPlanBranding, type QuickChargeInput, type QuickChargeResult, type ServiceAccountOptions, ServiceAccountTokenProvider, type Subscription, type SubscriptionItemSummary, type SubscriptionPlanSummary, type SubscriptionStatusResult, SubscriptionsResource, type SwapMode, type SwapPlanInput, type SwapPlanPreviewResult, type SwapPlanResult, type SwapPolicy, type TaxIdLookupResult, type TokenResolver, type WaitUntilPaidOptions, type WebhookEndpointInput, type WebhookEndpointSummary, type WebhookEvent, WebhooksResource, _default as billingPlugin, createServiceAccountToken, expiresIn };
1275
+ export { type AppliedDiscount, BillingApiError, BillingClient, type BillingClientOptions, type BillingItem, type BillingPeriod, type BillingPlanSummary, type BillingPluginOptions, type BillingRecurringInterval, type BillingRecurringStatus, type BillingSubscriptionCancelReason, type CancelSubscriptionInput, type CancellationPolicy, type CepLookupResult, type Charge, type ChargeEventData, type ChargeStatus, ChargesResource, type CheckoutForCustomerInput, type CheckoutForCustomerResult, CheckoutResource, type CheckoutSessionStatus, type CheckoutStatusResult, type CompanyTaxIdData, type Coupon, type CouponDuration, type CouponType, CouponsResource, type CreateBillingPlanInput, type CreateChargeInput, type CreateChargeResult, type CreateCouponInput, type CreateOrderInput, type CreateOrderResult, type CreateSubscriptionInput, type CreateSubscriptionResult, type Customer, type CustomerInput, type CustomerListFilters, type CustomerType, type CustomerUpdateInput, CustomersResource, type ExpirationUnit, type GetPublicPlanPageResult, HttpClient, type HttpClientOptions, type ItemInput, ItemsResource, type ListPublicPlansResult, OrdersResource, type OutboundWebhookEventType, type PaymentMethod, type PaymentMethodSetupIntent, type PaymentMethodSummary, type PlanCheckoutCustomerInput, type PlanCheckoutInput, type PlanCheckoutResult, type PlanSubscriptionStatusResult, PlansResource, type ProrationPolicy, type PublicBillingPlan, type PublicOrganization, type PublicPlanBranding, type QuickChargeInput, type QuickChargeResult, type RequestOptions, type ServiceAccountOptions, ServiceAccountTokenProvider, type Subscription, type SubscriptionItemSummary, type SubscriptionPlanSummary, type SubscriptionStatusResult, SubscriptionsResource, type SwapMode, type SwapPlanInput, type SwapPlanPreviewResult, type SwapPlanResult, type SwapPolicy, type TaxIdLookupResult, type TokenResolver, type WaitUntilPaidOptions, type WebhookEndpointInput, type WebhookEndpointSummary, type WebhookEvent, WebhooksResource, _default as billingPlugin, createServiceAccountToken, expiresIn };