@1st-flock/donations-embed-node 1.0.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.
@@ -0,0 +1,381 @@
1
+ import { D as DonationListResponse, a as Donation, R as RefundResponse, b as RecurringStatus, c as RecurringListResponse, d as RecurringCancelResponse } from './webhooks-DBoxlrQm.js';
2
+ export { e as DEFAULT_WEBHOOK_TOLERANCE_SECONDS, f as DonationCompletedEvent, g as DonationCreatedEvent, h as DonationCreatedEventObject, i as DonationEventDonor, j as DonationEventFundAllocation, k as DonationEventObject, l as DonationFailedEvent, m as DonationRefundedEvent, n as DonationRefundedEventObject, o as DonationStatus, E as EventPaymentMethod, F as FundAllocation, K as KeyFrozenEvent, p as KeyFrozenEventObject, q as KeyFrozenReason, P as PaymentMethodType, r as Recurring, s as RecurringActivatedEvent, t as RecurringCancelledEvent, u as RecurringCancelledEventObject, v as RecurringEventObject, w as RecurringInterval, x as RecurringPaymentFailedEvent, y as RecurringPaymentSucceededEvent, z as RefundRequest, S as VERSION, V as VerifyWebhookOptions, W as WEBHOOK_EVENT_TYPES, A as WebhookEnvelope, B as WebhookEnvelopeBase, C as WebhookEvent, G as WebhookEventType, H as isWebhookEvent, I as verifyWebhook } from './webhooks-DBoxlrQm.js';
3
+
4
+ /**
5
+ * Idempotency-key helper.
6
+ *
7
+ * The platform's idempotency contract: replaying a request with the same
8
+ * `Idempotency-Key` returns the original response without performing the
9
+ * side effect a second time. Keys are scoped per (`api_key`, `endpoint`)
10
+ * and persisted for 24 hours.
11
+ *
12
+ * This module exposes {@link idempotencyKey}, a tiny convenience wrapper
13
+ * that prefixes a fresh UUID4 with a use-case tag so observability tooling
14
+ * can group related retries (e.g. all `refund:*` keys belong to the
15
+ * refund flow). Callers MAY also supply their own keys directly.
16
+ */
17
+ /**
18
+ * Generate a fresh idempotency key tagged with a use-case prefix.
19
+ *
20
+ * The returned key has the form `"<usage>:<uuid4>"`, e.g.
21
+ * `"refund:1f2dab36-2a55-4f11-bdc8-2a2a4a95b001"`. When `usage` is
22
+ * omitted, returns a bare UUID4 with no prefix.
23
+ *
24
+ * @param usage - Optional short tag describing the operation
25
+ * (`"refund"`, `"cancel-recurring"`, `"replay-confirm"`). When
26
+ * supplied, must match `^[a-z0-9][a-z0-9_\-.]*$`; an oddly-shaped
27
+ * tag throws a `TypeError`.
28
+ * @returns A string suitable for the `Idempotency-Key` HTTP header.
29
+ */
30
+ declare function idempotencyKey(usage?: string): string;
31
+
32
+ /**
33
+ * Internal HTTP transport — typed errors, retry, and idempotency forwarding.
34
+ *
35
+ * The {@link HttpTransport} class wraps Node 18+'s native global `fetch`
36
+ * and applies the SDK's cross-cutting policies on every request:
37
+ *
38
+ * - Adds the `Authorization: Bearer <api_key>` header.
39
+ * - Adds a `User-Agent` header identifying the SDK + Node version so the
40
+ * platform can attribute traffic and warn customers running EOL
41
+ * versions.
42
+ * - Forwards an optional `Idempotency-Key` header.
43
+ * - Maps non-2xx responses to typed exceptions
44
+ * ({@link ApiError} and subclasses).
45
+ * - Retries 5xx responses with exponential backoff + jitter; honors the
46
+ * `Retry-After` header on `429` (no auto-retry — back-pressure is a
47
+ * caller-controlled concern).
48
+ *
49
+ * The transport is internal — public callers always interact through
50
+ * {@link Client} from `client.ts`.
51
+ */
52
+
53
+ /**
54
+ * Logger interface matching the subset of `console` we use. Allows
55
+ * callers to plug in pino / winston / a no-op logger without depending
56
+ * on a particular logging library.
57
+ */
58
+ interface Logger {
59
+ debug(message: string, ...args: unknown[]): void;
60
+ }
61
+ /**
62
+ * The portion of WHATWG `fetch` we rely on. Typed loosely so callers
63
+ * can inject a mock without bringing in `undici-types` if they don't
64
+ * need to.
65
+ */
66
+ type FetchLike = typeof globalThis.fetch;
67
+
68
+ /**
69
+ * Models for the synthetic-event endpoint `POST /v1/embed/webhooks/test`.
70
+ */
71
+ /**
72
+ * The synthetic-event endpoint accepts a subset of the full webhook event
73
+ * types; `key.frozen` is excluded because it is only emitted by the
74
+ * automatic-protection subsystem and cannot meaningfully be replayed on
75
+ * demand.
76
+ */
77
+ type TestableWebhookEventType = "donation.created" | "donation.completed" | "donation.failed" | "donation.refunded" | "recurring.activated" | "recurring.payment_succeeded" | "recurring.payment_failed" | "recurring.cancelled";
78
+ /** Body of `POST /v1/embed/webhooks/test`. */
79
+ interface WebhookTestRequest {
80
+ /** Which event type to fire as a synthetic delivery. */
81
+ event_type: TestableWebhookEventType;
82
+ }
83
+ /** Acknowledgment of a queued synthetic event. */
84
+ interface WebhookTestResponse {
85
+ /**
86
+ * ID of the synthetic event; matches the `Flock-Event-Id` header on
87
+ * delivery.
88
+ */
89
+ event_id: string;
90
+ queued: boolean;
91
+ }
92
+
93
+ /**
94
+ * `Client` — entry point for the Donations Embed Customer SDK.
95
+ *
96
+ * Every method maps to a documented endpoint under the `/v1/embed/` path
97
+ * prefix. All inputs and outputs are typed via the shapes in
98
+ * `models/`. Errors surface as typed exceptions from `errors.ts`.
99
+ *
100
+ * Example:
101
+ * ```ts
102
+ * import { Client } from "@1st-flock/donations-embed-node";
103
+ *
104
+ * const client = new Client({ apiKey: process.env.FLOCK_SECRET_KEY! });
105
+ * const page = await client.listDonations({ limit: 20 });
106
+ * for (const donation of page.donations) {
107
+ * console.log(donation.id, donation.gross_amount_cents);
108
+ * }
109
+ * ```
110
+ */
111
+
112
+ /** Constructor options for {@link Client}. */
113
+ interface ClientOptions {
114
+ /** Secret API key (`sk_live_*` or `sk_test_*`). */
115
+ apiKey: string;
116
+ /**
117
+ * API base URL. Defaults to `https://api.1stflock.com`; point at
118
+ * `https://api.sandbox.1stflock.com` to hit the sandbox environment.
119
+ */
120
+ baseUrl?: string;
121
+ /**
122
+ * Optional `fetch` implementation override. Defaults to the global
123
+ * `fetch` shipped in Node 18+. Useful for tests, custom retry/proxy
124
+ * stacks, or alternative runtimes.
125
+ */
126
+ fetch?: FetchLike;
127
+ /**
128
+ * Number of retries on retryable failures (5xx + transient network
129
+ * errors). The original attempt counts separately — `retries: 3`
130
+ * performs at most 4 requests. Defaults to 3.
131
+ */
132
+ retries?: number;
133
+ /** Per-request timeout in milliseconds. Defaults to 30000. */
134
+ timeout?: number;
135
+ /**
136
+ * Optional logger. Used at DEBUG for transient transport errors that
137
+ * trigger a retry. Defaults to a no-op.
138
+ */
139
+ logger?: Logger;
140
+ }
141
+ /** Optional inputs supported by `listDonations`. */
142
+ interface ListDonationsParams {
143
+ cursor?: string;
144
+ limit?: number;
145
+ fundId?: string;
146
+ donorEmail?: string;
147
+ }
148
+ /** Optional inputs supported by `refundDonation`. */
149
+ interface RefundDonationParams {
150
+ /**
151
+ * Refund amount in cents. Omit (or pass `null` / `undefined`) to
152
+ * refund the full donation. When supplied, must be >= 1.
153
+ */
154
+ amountCents?: number;
155
+ /** Optional internal note attached to the refund record. */
156
+ reason?: string;
157
+ }
158
+ /** Optional inputs supported by `listRecurring`. */
159
+ interface ListRecurringParams {
160
+ cursor?: string;
161
+ limit?: number;
162
+ status?: RecurringStatus;
163
+ }
164
+ /** Per-call options that can carry an idempotency key. */
165
+ interface IdempotentCallOptions {
166
+ idempotencyKey?: string;
167
+ }
168
+ /**
169
+ * `Client` — typed access to the Donations Embed Customer SDK endpoints.
170
+ */
171
+ declare class Client {
172
+ private readonly transport;
173
+ constructor(options: ClientOptions);
174
+ /**
175
+ * List donations, ordered `(created_at DESC, id DESC)`.
176
+ *
177
+ * @param params - Optional cursor / limit / fund / donor filters.
178
+ * @returns A page of donations plus an optional `next_cursor`.
179
+ */
180
+ listDonations(params?: ListDonationsParams): Promise<DonationListResponse>;
181
+ /**
182
+ * Fetch a single donation by ID.
183
+ *
184
+ * Cross-organization access collapses to `404` (raises
185
+ * {@link NotFoundError}).
186
+ */
187
+ getDonation(donationId: string): Promise<Donation>;
188
+ /**
189
+ * Refund a donation in full or part.
190
+ *
191
+ * @param donationId - The donation to refund.
192
+ * @param params - Optional amount + reason.
193
+ * @param options - Optional idempotency key (use
194
+ * {@link idempotencyKey} to generate one tagged with a use-case
195
+ * prefix).
196
+ * @returns The {@link RefundResponse} describing the issued refund.
197
+ * Idempotent replays return the original response without
198
+ * re-contacting the gateway.
199
+ */
200
+ refundDonation(donationId: string, params?: RefundDonationParams, options?: IdempotentCallOptions): Promise<RefundResponse>;
201
+ /**
202
+ * List recurring schedules, ordered `(created_at DESC, id DESC)`.
203
+ *
204
+ * @returns A page of recurring schedules plus an optional `next_cursor`.
205
+ */
206
+ listRecurring(params?: ListRecurringParams): Promise<RecurringListResponse>;
207
+ /**
208
+ * Cancel a recurring schedule.
209
+ *
210
+ * Idempotent: a second call against an already-cancelled schedule
211
+ * returns `already_cancelled: true` without re-emitting a webhook.
212
+ */
213
+ cancelRecurring(recurringId: string, options?: IdempotentCallOptions): Promise<RecurringCancelResponse>;
214
+ /**
215
+ * Queue a synthetic webhook event for delivery.
216
+ *
217
+ * The synthetic event's `data.object.synthetic` flag is set so
218
+ * downstream code can branch on it during integration testing.
219
+ *
220
+ * @param eventType - Which event type to fire. Defaults to
221
+ * `"donation.created"`.
222
+ */
223
+ testWebhook(eventType?: TestableWebhookEventType): Promise<WebhookTestResponse>;
224
+ }
225
+
226
+ /**
227
+ * Typed error hierarchy raised by the SDK.
228
+ *
229
+ * The base type is {@link ApiError}. All transport-level failures (4xx /
230
+ * 5xx) surface as concrete subclasses so caller code can branch on type
231
+ * rather than parsing status codes directly. Webhook verification has its
232
+ * own dedicated exceptions ({@link WebhookSignatureError},
233
+ * {@link WebhookTimestampError}) so middleware can return a single
234
+ * `401 Unauthorized` without leaking which check failed.
235
+ *
236
+ * Every exception captures the raw error code + message returned by the
237
+ * service when one is available, so callers can pivot on
238
+ * `error.code === "invalid_cursor"` without re-deserializing the body.
239
+ */
240
+ /** Base class for every exception raised by this SDK. */
241
+ declare class DonationsEmbedError extends Error {
242
+ constructor(message: string);
243
+ }
244
+ /** Optional structured init bag accepted by every {@link ApiError} subclass. */
245
+ interface ApiErrorInit {
246
+ /** Stable, machine-readable error identifier (e.g. `"invalid_cursor"`). */
247
+ code?: string | null;
248
+ /** Optional, error-specific extra data the service emitted. */
249
+ details?: Record<string, unknown> | null;
250
+ /** Server-issued correlation ID from the `x-request-id` response header. */
251
+ requestId?: string | null;
252
+ }
253
+ /**
254
+ * Raised when the API returns a non-2xx status code.
255
+ *
256
+ * Concrete subclasses below ({@link AuthError}, {@link NotFoundError},
257
+ * etc.) cover the common status codes; an `ApiError` instance is returned
258
+ * for any other non-2xx response.
259
+ */
260
+ declare class ApiError extends DonationsEmbedError {
261
+ readonly statusCode: number;
262
+ readonly code: string | null;
263
+ readonly message: string;
264
+ readonly details: Record<string, unknown> | null;
265
+ readonly requestId: string | null;
266
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
267
+ toString(): string;
268
+ }
269
+ /**
270
+ * Raised on a `401 Unauthorized` response.
271
+ *
272
+ * Common causes: revoked secret key, malformed bearer token, expired
273
+ * session, or the token was issued for a different environment (test vs.
274
+ * live) than the URL being called.
275
+ */
276
+ declare class AuthError extends ApiError {
277
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
278
+ }
279
+ /**
280
+ * Raised on a `403 Forbidden` response.
281
+ *
282
+ * Common causes: the secret key has been frozen by automatic protection,
283
+ * the caller's RBAC scope is insufficient, or the action is disabled for
284
+ * the organization.
285
+ */
286
+ declare class ForbiddenError extends ApiError {
287
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
288
+ }
289
+ /**
290
+ * Raised on a `404 Not Found` response.
291
+ *
292
+ * Note: cross-organization lookups collapse to `404` to avoid confirming
293
+ * that an object exists in another tenant.
294
+ */
295
+ declare class NotFoundError extends ApiError {
296
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
297
+ }
298
+ /**
299
+ * Raised on `400 Bad Request` or `422 Unprocessable Entity`.
300
+ *
301
+ * The originating request body failed schema validation. Inspect
302
+ * `details` for the offending field path (e.g.
303
+ * `{ loc: ["body", "amount_cents"] }`).
304
+ */
305
+ declare class ValidationError extends ApiError {
306
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
307
+ }
308
+ /**
309
+ * Raised on a `409 Conflict` response.
310
+ *
311
+ * Common causes: attempting to refund a donation that is already fully
312
+ * refunded, or cancelling a recurring schedule whose state forbids the
313
+ * transition.
314
+ */
315
+ declare class ConflictError extends ApiError {
316
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
317
+ }
318
+ /** Raised on a `410 Gone` response (terminal session error). */
319
+ declare class GoneError extends ApiError {
320
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
321
+ }
322
+ /**
323
+ * Raised on a `429 Too Many Requests` response.
324
+ *
325
+ * The caller should wait `retryAfterSeconds` before retrying. The SDK
326
+ * does not auto-retry rate-limited requests by default — back-pressure
327
+ * is a caller-controlled concern.
328
+ */
329
+ declare class RateLimitError extends ApiError {
330
+ readonly retryAfterSeconds: number | null;
331
+ constructor(statusCode: number, message: string, init?: ApiErrorInit & {
332
+ retryAfterSeconds?: number | null;
333
+ });
334
+ }
335
+ /**
336
+ * Raised on a `502 Bad Gateway` response.
337
+ *
338
+ * Indicates an upstream payment-processor failure. The original request
339
+ * is safe to retry — it has not been performed.
340
+ */
341
+ declare class BadGatewayError extends ApiError {
342
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
343
+ }
344
+ /** Raised on a `503 Service Unavailable` response. */
345
+ declare class ServiceUnavailableError extends ApiError {
346
+ constructor(statusCode: number, message: string, init?: ApiErrorInit);
347
+ }
348
+ /** Base class for webhook signature-verification failures. */
349
+ declare class WebhookError extends DonationsEmbedError {
350
+ constructor(message: string);
351
+ }
352
+ /**
353
+ * Raised when webhook signature verification fails.
354
+ *
355
+ * This may indicate a wrong shared secret, a tampered request body, or
356
+ * that the signature header was not produced by 1st Flock. Callers MUST
357
+ * return an HTTP 401 (or drop the request) without enqueueing the event.
358
+ */
359
+ declare class WebhookSignatureError extends WebhookError {
360
+ constructor(message: string);
361
+ }
362
+ /**
363
+ * Raised when the webhook timestamp is outside the 5-minute tolerance.
364
+ *
365
+ * This is a replay-prevention check; callers MUST treat it as a
366
+ * verification failure and return `401` without processing the event.
367
+ */
368
+ declare class WebhookTimestampError extends WebhookError {
369
+ constructor(message: string);
370
+ }
371
+ /**
372
+ * Raised when the signature header is structurally malformed.
373
+ *
374
+ * Examples: missing `t=` segment, no `v1=` segments, non-integer
375
+ * timestamp, etc. The request did not parse as a signed delivery.
376
+ */
377
+ declare class WebhookFormatError extends WebhookError {
378
+ constructor(message: string);
379
+ }
380
+
381
+ export { ApiError, type ApiErrorInit, AuthError, BadGatewayError, Client, type ClientOptions, ConflictError, Donation, DonationListResponse, DonationsEmbedError, type FetchLike, ForbiddenError, GoneError, type IdempotentCallOptions, type ListDonationsParams, type ListRecurringParams, type Logger, NotFoundError, RateLimitError, RecurringCancelResponse, RecurringListResponse, RecurringStatus, type RefundDonationParams, RefundResponse, ServiceUnavailableError, type TestableWebhookEventType, ValidationError, WebhookError, WebhookFormatError, WebhookSignatureError, type WebhookTestRequest, type WebhookTestResponse, WebhookTimestampError, idempotencyKey };