bulkit 0.1.0 → 0.2.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/README.md +58 -5
- package/dist/index.cjs +30 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +373 -301
- package/dist/index.d.ts +373 -301
- package/dist/index.js +30 -8
- package/dist/index.js.map +1 -1
- package/package.json +17 -2
package/README.md
CHANGED
|
@@ -1,16 +1,51 @@
|
|
|
1
1
|
# Bulkit Node.js SDK
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/bulkit)
|
|
4
|
-
[](https://docs.bulkit.io/docs?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)
|
|
5
|
+
[](./LICENSE)
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
**Schedule and publish to X, LinkedIn, Instagram, Facebook, Threads, TikTok, YouTube, Pinterest,
|
|
8
|
+
Reddit, Bluesky and Vimeo from your own code.**
|
|
8
9
|
|
|
10
|
+
[Bulkit](https://bulkit.io?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk) is a social
|
|
11
|
+
media scheduler built for developers and AI agents. Write a post once, tailor it per network,
|
|
12
|
+
and Bulkit handles each platform's limits, media rules, threads and retries. This package is the
|
|
13
|
+
official TypeScript / JavaScript client for its API.
|
|
14
|
+
|
|
15
|
+
**[Start your 14-day free trial →](https://app.bulkit.io/register?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)**
|
|
16
|
+
· [Get an API key](#get-your-api-key) ·
|
|
17
|
+
[Documentation](https://docs.bulkit.io/docs?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)
|
|
18
|
+
|
|
19
|
+
- One call posts to many networks, with a different text for each one
|
|
20
|
+
- Threads, images and video, scheduling, comments, and webhooks
|
|
9
21
|
- Fully typed, generated from the Bulkit OpenAPI spec
|
|
10
22
|
- Zero runtime dependencies, ESM and CommonJS
|
|
11
23
|
- Retries with backoff, timeouts, and automatic idempotency keys on every write
|
|
12
|
-
|
|
13
|
-
|
|
24
|
+
|
|
25
|
+
## Get your API key
|
|
26
|
+
|
|
27
|
+
You need a Bulkit account and an API key before the SDK can do anything. It takes a few minutes:
|
|
28
|
+
|
|
29
|
+
1. **Create an account.** [Sign up for Bulkit](https://app.bulkit.io/register?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk).
|
|
30
|
+
Every plan starts with a 14-day free trial.
|
|
31
|
+
2. **Connect your social accounts.** Bulkit publishes through your own platform apps (your X
|
|
32
|
+
app, your LinkedIn app, and so on). Add them and connect your accounts in the app. The
|
|
33
|
+
[workspace setup guide](https://docs.bulkit.io/docs/setup?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)
|
|
34
|
+
walks you through each network.
|
|
35
|
+
3. **Create a key.** In the app, open **Developers → API & Webhooks** and click **Create key**.
|
|
36
|
+
Copy it straight away, because it is only shown once.
|
|
37
|
+
|
|
38
|
+
Put the key in an environment variable, never in your code:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
# .env
|
|
42
|
+
BULKIT_API_KEY=bk_test_xxxxxxxxxxxxxxxx
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
> **Start with a test key.** A `bk_test_…` key checks and saves your requests exactly like a
|
|
46
|
+
> live key, but never publishes to a real account and is never billed. Switch to a `bk_live_…`
|
|
47
|
+
> key when you are ready to go live. See [Create an API key](https://docs.bulkit.io/docs/api-keys?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)
|
|
48
|
+
> for details.
|
|
14
49
|
|
|
15
50
|
## Installation
|
|
16
51
|
|
|
@@ -94,6 +129,15 @@ const video = await bulkit.media.uploadMultipart(await openAsBlob('launch.mp4'),
|
|
|
94
129
|
fileName: 'launch.mp4',
|
|
95
130
|
mimeType: 'video/mp4',
|
|
96
131
|
});
|
|
132
|
+
|
|
133
|
+
// The media library is paged like every other list, newest first.
|
|
134
|
+
for await (const item of bulkit.media.list()) {
|
|
135
|
+
console.log(item.id);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Or take a single page:
|
|
139
|
+
const page = await bulkit.media.list({ limit: 20 });
|
|
140
|
+
console.log(page.data.length, page.nextCursor);
|
|
97
141
|
```
|
|
98
142
|
|
|
99
143
|
## Webhooks
|
|
@@ -214,6 +258,15 @@ Your API key is a secret. The client refuses to run in a browser unless you opt
|
|
|
214
258
|
This package follows [SemVer](https://semver.org). The API version (`/public/v1`) is fixed per
|
|
215
259
|
major version of the SDK.
|
|
216
260
|
|
|
261
|
+
## Learn more
|
|
262
|
+
|
|
263
|
+
- [Bulkit documentation](https://docs.bulkit.io/docs?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk): guides, platform rules and the full API reference
|
|
264
|
+
- [Connect an AI agent (MCP)](https://docs.bulkit.io/docs/guides/mcp?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk): let Claude, Cursor and other agents post through Bulkit
|
|
265
|
+
- [Supported networks](https://bulkit.io/channels?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)
|
|
266
|
+
- Questions? Email [support@bulkit.io](mailto:support@bulkit.io) or find us on [X](https://x.com/bulkitio)
|
|
267
|
+
|
|
268
|
+
**New to Bulkit? [Start your 14-day free trial →](https://app.bulkit.io/register?utm_source=npm&utm_medium=readme&utm_campaign=node_sdk)**
|
|
269
|
+
|
|
217
270
|
## Contributing
|
|
218
271
|
|
|
219
272
|
See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
package/dist/index.cjs
CHANGED
|
@@ -207,8 +207,9 @@ var CursorPage = class CursorPage {
|
|
|
207
207
|
response;
|
|
208
208
|
#fetchPage;
|
|
209
209
|
constructor(body, response, fetchPage) {
|
|
210
|
+
if (!Array.isArray(body?.data)) throw new BulkitError(`Expected a paged response ({ data, nextCursor }) from ${response.url || "the API"}, but got something else. The server may be running an older API version.`);
|
|
210
211
|
this.data = body.data;
|
|
211
|
-
this.nextCursor = body.nextCursor;
|
|
212
|
+
this.nextCursor = body.nextCursor ?? null;
|
|
212
213
|
this.response = response;
|
|
213
214
|
this.#fetchPage = fetchPage;
|
|
214
215
|
}
|
|
@@ -315,9 +316,16 @@ var Channels = class extends APIResource {
|
|
|
315
316
|
//#region src/resources/media.ts
|
|
316
317
|
var Media = class extends APIResource {
|
|
317
318
|
uploads = new MediaUploads(this._client);
|
|
318
|
-
/**
|
|
319
|
-
|
|
320
|
-
|
|
319
|
+
/**
|
|
320
|
+
* The workspace's media library, newest first. Await it for one page, or iterate it
|
|
321
|
+
* for every file:
|
|
322
|
+
*
|
|
323
|
+
* ```ts
|
|
324
|
+
* for await (const item of bulkit.media.list()) { ... }
|
|
325
|
+
* ```
|
|
326
|
+
*/
|
|
327
|
+
list(params, options) {
|
|
328
|
+
return this._client.getPage("/media", params, options);
|
|
321
329
|
}
|
|
322
330
|
/**
|
|
323
331
|
* Upload a file in one request: images up to 10 MB, video and PDFs up to 100 MB,
|
|
@@ -334,6 +342,9 @@ var Media = class extends APIResource {
|
|
|
334
342
|
/**
|
|
335
343
|
* Upload a large video through an upload session: start it, PUT every part to its
|
|
336
344
|
* signed URL, then complete it. The session is aborted if any step fails.
|
|
345
|
+
*
|
|
346
|
+
* An `idempotencyKey` passed here is split per step (`<key>:start`, `<key>:complete`),
|
|
347
|
+
* since the API holds a key to one route. Keep it under 246 characters so both fit.
|
|
337
348
|
*/
|
|
338
349
|
async uploadMultipart(file, params = {}, options) {
|
|
339
350
|
const blob = toBlob(file, params.mimeType);
|
|
@@ -345,16 +356,19 @@ var Media = class extends APIResource {
|
|
|
345
356
|
fileName,
|
|
346
357
|
mimeType,
|
|
347
358
|
size: blob.size
|
|
348
|
-
}, options);
|
|
359
|
+
}, stepOptions(options, "start"));
|
|
349
360
|
const concurrency = Math.max(1, Math.min(params.concurrency ?? 4, 100));
|
|
350
361
|
try {
|
|
351
362
|
const partNumbers = Array.from({ length: session.partCount }, (_, i) => i + 1);
|
|
352
363
|
for (let i = 0; i < partNumbers.length; i += concurrency) {
|
|
353
364
|
const batch = partNumbers.slice(i, i + concurrency);
|
|
354
|
-
const parts = await this.uploads.signParts(session.id, { partNumbers: batch },
|
|
365
|
+
const parts = await this.uploads.signParts(session.id, { partNumbers: batch }, {
|
|
366
|
+
...options,
|
|
367
|
+
idempotencyKey: void 0
|
|
368
|
+
});
|
|
355
369
|
await Promise.all(parts.map((part) => this.#putPart(blob, session, part, options?.signal)));
|
|
356
370
|
}
|
|
357
|
-
return await this.uploads.complete(session.id, options);
|
|
371
|
+
return await this.uploads.complete(session.id, stepOptions(options, "complete"));
|
|
358
372
|
} catch (error) {
|
|
359
373
|
await this.uploads.abort(session.id).catch(() => void 0);
|
|
360
374
|
throw error;
|
|
@@ -397,6 +411,14 @@ function toBlob(file, type) {
|
|
|
397
411
|
const bytes = file instanceof ArrayBuffer ? new Uint8Array(file) : new Uint8Array(file.buffer, file.byteOffset, file.byteLength).slice();
|
|
398
412
|
return new Blob([bytes], type ? { type } : {});
|
|
399
413
|
}
|
|
414
|
+
/** The caller's key for one step of a multi-request call, or the options untouched. */
|
|
415
|
+
function stepOptions(options, step) {
|
|
416
|
+
if (!options?.idempotencyKey) return options;
|
|
417
|
+
return {
|
|
418
|
+
...options,
|
|
419
|
+
idempotencyKey: `${options.idempotencyKey}:${step}`
|
|
420
|
+
};
|
|
421
|
+
}
|
|
400
422
|
//#endregion
|
|
401
423
|
//#region src/resources/platforms.ts
|
|
402
424
|
var Platforms = class extends APIResource {
|
|
@@ -629,7 +651,7 @@ var Webhooks = class extends APIResource {
|
|
|
629
651
|
};
|
|
630
652
|
//#endregion
|
|
631
653
|
//#region src/version.ts
|
|
632
|
-
const VERSION = "0.
|
|
654
|
+
const VERSION = "0.2.0";
|
|
633
655
|
//#endregion
|
|
634
656
|
//#region src/client.ts
|
|
635
657
|
const DEFAULT_BASE_URL = "https://api.bulkit.io";
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/core/api-promise.ts","../src/core/errors.ts","../src/core/pagination.ts","../src/core/utils.ts","../src/core/resource.ts","../src/resources/channels.ts","../src/resources/media.ts","../src/resources/platforms.ts","../src/resources/posts.ts","../src/resources/stats.ts","../src/resources/tags.ts","../src/resources/usage.ts","../src/webhooks.ts","../src/resources/webhooks.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["export interface APIResponse<T> {\n data: T;\n response: Response;\n /** The `x-request-id` of the response. Quote it when contacting support. */\n requestId: string | null;\n /** Requests per minute allowed for this key, from `X-RateLimit-*` headers. */\n rateLimit: RateLimitInfo;\n}\n\nexport interface RateLimitInfo {\n limit: number | null;\n remaining: number | null;\n /** Seconds until the window refills. */\n reset: number | null;\n}\n\n/**\n * A `Promise` of the parsed response body that can also hand back the raw `Response`:\n *\n * ```ts\n * const post = await client.posts.retrieve('pst_123');\n * const { data, requestId, rateLimit } = await client.posts.retrieve('pst_123').withResponse();\n * ```\n */\nexport class APIPromise<T> extends Promise<T> {\n readonly #responsePromise: Promise<APIResponse<T>>;\n\n constructor(responsePromise: Promise<APIResponse<T>>) {\n // `Promise` subclasses must accept an executor; resolution is driven by `responsePromise`.\n super((resolve) => resolve(null as T));\n this.#responsePromise = responsePromise;\n }\n\n /** Resolves to the body together with the raw response and its metadata. */\n withResponse(): Promise<APIResponse<T>> {\n return this.#responsePromise;\n }\n\n #parsed?: Promise<T>;\n #parse(): Promise<T> {\n this.#parsed ??= this.#responsePromise.then((r) => r.data);\n return this.#parsed;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: an APIPromise is deliberately a thenable.\n override then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.#parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult> {\n return this.#parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#parse().finally(onfinally);\n }\n\n // Derived promises (from `.then`) should be plain Promises, not APIPromises.\n static override get [Symbol.species]() {\n return Promise;\n }\n}\n\nexport function rateLimitFrom(headers: Headers): RateLimitInfo {\n const num = (name: string) => {\n const raw = headers.get(name);\n const value = raw === null ? Number.NaN : Number(raw);\n return Number.isFinite(value) ? value : null;\n };\n return {\n limit: num('x-ratelimit-limit'),\n remaining: num('x-ratelimit-remaining'),\n reset: num('x-ratelimit-reset'),\n };\n}\n","import type { components } from '../generated/openapi';\n\nexport type ErrorBody = components['schemas']['ErrorDetail'];\nexport type FieldError = components['schemas']['FieldError'];\n/**\n * Error codes documented today. New ones may be added without notice,\n * so the type stays open to any string.\n */\nexport type ErrorCode = ErrorBody['code'] | (string & {});\n\n/** Base class for every error this SDK throws. `instanceof BulkitError` catches them all. */\nexport class BulkitError extends Error {\n override name = 'BulkitError';\n}\n\n/**\n * The API answered with a non-2xx status.\n *\n * Branch on `code` (stable within v1) rather than `message` (prose, may change).\n * New codes can appear at any time, so always keep a fallback branch.\n */\nexport class APIError extends BulkitError {\n override name = 'APIError';\n\n /** HTTP status code. */\n readonly status: number;\n /** Machine-readable error code, e.g. `content_too_long`. */\n readonly code: ErrorCode | undefined;\n /** Path into the request body (or the header name) that caused the failure. */\n readonly field: string | undefined;\n /** Every field-level failure when schema validation rejected more than one. */\n readonly details: FieldError[] | undefined;\n /** Quote this when contacting support: it is what Bulkit searches on. */\n readonly requestId: string | undefined;\n readonly headers: Headers;\n /** The parsed `error` object exactly as the API sent it. */\n readonly error: ErrorBody | undefined;\n\n constructor(status: number, error: ErrorBody | undefined, message: string, headers: Headers) {\n super(message);\n this.status = status;\n this.error = error;\n this.code = error?.code;\n this.field = error?.field ?? undefined;\n this.details = error?.details ?? undefined;\n this.requestId = error?.requestId ?? headers.get('x-request-id') ?? undefined;\n this.headers = headers;\n }\n\n /** @internal */\n static from(status: number, body: unknown, headers: Headers): APIError {\n const error = extractError(body);\n const message = error?.message ?? `Request failed with status ${status}`;\n const ErrorClass = errorClassFor(status);\n return new ErrorClass(status, error, message, headers);\n }\n}\n\n/** 400 — the request was malformed or failed schema validation. */\nexport class BadRequestError extends APIError {\n override name = 'BadRequestError';\n}\n\n/** 401 — the API key is missing, malformed, revoked or unknown. */\nexport class AuthenticationError extends APIError {\n override name = 'AuthenticationError';\n}\n\n/**\n * 402 — the plan's allowance for this period is spent.\n *\n * This is NOT a rate limit: retrying will never succeed until the period resets.\n * `client.usage.retrieve()` has the numbers and `periodEnd`. The SDK never retries it.\n */\nexport class QuotaExceededError extends APIError {\n override name = 'QuotaExceededError';\n}\n\n/** 403 — the key lacks the scope for this call (e.g. a read-only key attempting a write). */\nexport class PermissionDeniedError extends APIError {\n override name = 'PermissionDeniedError';\n}\n\n/** 404 — the resource does not exist in this workspace. */\nexport class NotFoundError extends APIError {\n override name = 'NotFoundError';\n}\n\n/** 409 — the resource is in a state that does not allow this, or a request with the same idempotency key is still running. */\nexport class ConflictError extends APIError {\n override name = 'ConflictError';\n}\n\n/** 413 — the request body or uploaded file is too large. */\nexport class PayloadTooLargeError extends APIError {\n override name = 'PayloadTooLargeError';\n}\n\n/** 415 — the uploaded file's type is not accepted. */\nexport class UnsupportedMediaTypeError extends APIError {\n override name = 'UnsupportedMediaTypeError';\n}\n\n/** 422 — well-formed but refused, e.g. a platform rule or an idempotency key reused with a different body. */\nexport class UnprocessableEntityError extends APIError {\n override name = 'UnprocessableEntityError';\n}\n\n/** 429 — too many requests. Retried automatically, honouring `Retry-After`. */\nexport class RateLimitError extends APIError {\n override name = 'RateLimitError';\n\n /** Seconds the API asked us to wait before retrying, if it said. */\n get retryAfter(): number | undefined {\n const value = Number(this.headers.get('retry-after'));\n return Number.isFinite(value) && value >= 0 ? value : undefined;\n }\n}\n\n/** 5xx — a fault on Bulkit's side or an unreachable dependency. */\nexport class InternalServerError extends APIError {\n override name = 'InternalServerError';\n}\n\n/** The request never got an HTTP response (DNS, TLS, connection reset, …). */\nexport class APIConnectionError extends BulkitError {\n override name = 'APIConnectionError';\n\n constructor(message = 'Connection error.', options?: { cause?: unknown }) {\n super(message, options);\n }\n}\n\n/** The request exceeded the configured `timeout`. */\nexport class APIConnectionTimeoutError extends APIConnectionError {\n override name = 'APIConnectionTimeoutError';\n\n constructor(message = 'Request timed out.') {\n super(message);\n }\n}\n\n/** The caller aborted the request through its `AbortSignal`. */\nexport class APIUserAbortError extends BulkitError {\n override name = 'APIUserAbortError';\n\n constructor(message = 'Request was aborted.') {\n super(message);\n }\n}\n\n/** A webhook delivery failed signature or timestamp verification. Respond 400 and drop it. */\nexport class WebhookVerificationError extends BulkitError {\n override name = 'WebhookVerificationError';\n}\n\nfunction errorClassFor(status: number): typeof APIError {\n switch (status) {\n case 400:\n return BadRequestError;\n case 401:\n return AuthenticationError;\n case 402:\n return QuotaExceededError;\n case 403:\n return PermissionDeniedError;\n case 404:\n return NotFoundError;\n case 409:\n return ConflictError;\n case 413:\n return PayloadTooLargeError;\n case 415:\n return UnsupportedMediaTypeError;\n case 422:\n return UnprocessableEntityError;\n case 429:\n return RateLimitError;\n default:\n return status >= 500 ? InternalServerError : APIError;\n }\n}\n\nfunction extractError(body: unknown): ErrorBody | undefined {\n if (body && typeof body === 'object' && 'error' in body) {\n const error = (body as { error: unknown }).error;\n if (error && typeof error === 'object' && 'code' in error) return error as ErrorBody;\n }\n return undefined;\n}\n","import { APIPromise, type APIResponse } from './api-promise';\n\ninterface CursorPageBody<T> {\n data: T[];\n nextCursor: string | null;\n}\n\ntype FetchPage<T> = (cursor: string | undefined) => Promise<APIResponse<CursorPageBody<T>>>;\n\n/**\n * One page of a cursor-paginated list.\n *\n * Iterate it with `for await` to walk every item across every page, or page\n * manually with `hasNextPage()` / `getNextPage()`.\n */\nexport class CursorPage<T> implements AsyncIterable<T> {\n readonly data: T[];\n /** Opaque. Pass it back as `cursor`; never parse or construct one. */\n readonly nextCursor: string | null;\n readonly response: Response;\n readonly #fetchPage: FetchPage<T>;\n\n constructor(body: CursorPageBody<T>, response: Response, fetchPage: FetchPage<T>) {\n this.data = body.data;\n this.nextCursor = body.nextCursor;\n this.response = response;\n this.#fetchPage = fetchPage;\n }\n\n /** A null `nextCursor` — not an empty `data` — is the end of the list. */\n hasNextPage(): boolean {\n return this.nextCursor !== null;\n }\n\n async getNextPage(): Promise<CursorPage<T>> {\n if (this.nextCursor === null) {\n throw new Error('No next page; check `hasNextPage()` before calling `getNextPage()`.');\n }\n const { data, response } = await this.#fetchPage(this.nextCursor);\n return new CursorPage(data, response, this.#fetchPage);\n }\n\n /** Yields this page and every page after it. */\n async *iterPages(): AsyncGenerator<CursorPage<T>> {\n let page: CursorPage<T> = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n for await (const page of this.iterPages()) {\n yield* page.data;\n }\n }\n}\n\n/**\n * Resolves to the first `CursorPage`, and is also directly async-iterable over every item:\n *\n * ```ts\n * for await (const post of client.posts.list({ status: 'scheduled' })) { ... }\n * ```\n */\nexport class PagePromise<T> extends APIPromise<CursorPage<T>> implements AsyncIterable<T> {\n constructor(fetchPage: FetchPage<T>, firstCursor?: string) {\n super(\n fetchPage(firstCursor).then((res) => ({\n ...res,\n data: new CursorPage(res.data, res.response, fetchPage),\n })),\n );\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n const page = await this;\n yield* page;\n }\n}\n","export type QueryValue = string | number | boolean | null | undefined;\nexport type Query = Record<string, QueryValue | QueryValue[]>;\n\n/** Reads an environment variable on runtimes that have `process`, and nothing on those that do not. */\nexport function readEnv(name: string): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n const value = env?.[name]?.trim();\n return value ? value : undefined;\n}\n\n/** Tagged template that URI-encodes every interpolated path segment. */\nexport function path(strings: TemplateStringsArray, ...params: string[]): string {\n return strings.reduce((acc, part, i) => {\n const param = params[i];\n if (param === undefined) return acc + part;\n if (param === '') throw new TypeError('Path parameters must not be empty.');\n return acc + part + encodeURIComponent(param);\n }, '');\n}\n\nexport function buildQuery(query: Query | undefined): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function uuid(): string {\n return globalThis.crypto.randomUUID();\n}\n\nexport function isBrowser(): boolean {\n return (\n typeof (globalThis as { window?: unknown }).window !== 'undefined' &&\n typeof (globalThis as { document?: unknown }).document !== 'undefined'\n );\n}\n","import type { Bulkit } from '../client';\n\nexport abstract class APIResource {\n protected readonly _client: Bulkit;\n\n constructor(client: Bulkit) {\n this._client = client;\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type { Channel, ChannelCapabilities, OptionChoices, OptionChoicesParams } from '../types';\n\nexport class Channels extends APIResource {\n /** Every channel this workspace can post to. Call this before composing a post. */\n list(options?: RequestOptions): APIPromise<Channel[]> {\n return this._client.get('/channels', undefined, options);\n }\n\n /** Account-level rules for one channel (privacy levels, required flair, …), read live from the platform. */\n capabilities(channelId: string, options?: RequestOptions): APIPromise<ChannelCapabilities> {\n return this._client.get(path`/channels/${channelId}/capabilities`, undefined, options);\n }\n\n /**\n * Search the values of a `search`-type option, such as Instagram's `location_id`.\n * Pass `q` to turn a name into values, or `value` to turn a stored value back into its label.\n */\n optionChoices(\n channelId: string,\n key: string,\n params?: OptionChoicesParams,\n options?: RequestOptions,\n ): APIPromise<OptionChoices> {\n return this._client.get(path`/channels/${channelId}/options/${key}/choices`, params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIConnectionError } from '../core/errors';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type { MediaItem, MediaUpload, MediaUploadPart, MediaUploadStartParams } from '../types';\n\n/**\n * Anything that holds a file's bytes. In Node, `await fs.openAsBlob(filePath)` gives you a\n * `Blob` without reading the whole file into memory.\n */\nexport type Uploadable = Blob | ArrayBuffer | ArrayBufferView;\n\nexport interface MediaUploadParams {\n /** Required unless `file` is a `File`, which carries its own name. */\n fileName?: string | undefined;\n /** Defaults to the `Blob`'s own type. */\n mimeType?: string | undefined;\n}\n\nexport interface MultipartUploadParams extends MediaUploadParams {\n /** How many parts to upload at once. Default 4. */\n concurrency?: number | undefined;\n}\n\nexport class Media extends APIResource {\n readonly uploads: MediaUploads = new MediaUploads(this._client);\n\n /** The workspace's media library. */\n list(options?: RequestOptions): APIPromise<MediaItem[]> {\n return this._client.get('/media', undefined, options);\n }\n\n /**\n * Upload a file in one request: images up to 10 MB, video and PDFs up to 100 MB,\n * subtitles up to 5 MB. For larger video, use `uploadMultipart()`.\n */\n upload(\n file: Uploadable,\n params: MediaUploadParams = {},\n options?: RequestOptions,\n ): APIPromise<MediaItem> {\n const blob = toBlob(file, params.mimeType);\n const fileName = params.fileName ?? (file instanceof File ? file.name : undefined);\n if (!fileName) throw new TypeError('`fileName` is required unless `file` is a File.');\n\n const form = new FormData();\n form.append('file', blob, fileName);\n return this._client.post('/media', form, options);\n }\n\n /**\n * Upload a large video through an upload session: start it, PUT every part to its\n * signed URL, then complete it. The session is aborted if any step fails.\n */\n async uploadMultipart(\n file: Uploadable,\n params: MultipartUploadParams = {},\n options?: RequestOptions,\n ): Promise<MediaItem> {\n const blob = toBlob(file, params.mimeType);\n const fileName = params.fileName ?? (file instanceof File ? file.name : undefined);\n const mimeType = params.mimeType ?? blob.type;\n if (!fileName) throw new TypeError('`fileName` is required unless `file` is a File.');\n if (!mimeType) throw new TypeError('`mimeType` is required when the Blob has no type.');\n\n const session = await this.uploads.start({ fileName, mimeType, size: blob.size }, options);\n const concurrency = Math.max(1, Math.min(params.concurrency ?? 4, 100));\n\n try {\n const partNumbers = Array.from({ length: session.partCount }, (_, i) => i + 1);\n // Signed URLs expire after an hour, so sign each batch just before uploading it.\n for (let i = 0; i < partNumbers.length; i += concurrency) {\n const batch = partNumbers.slice(i, i + concurrency);\n const parts = await this.uploads.signParts(session.id, { partNumbers: batch }, options);\n await Promise.all(parts.map((part) => this.#putPart(blob, session, part, options?.signal)));\n }\n return await this.uploads.complete(session.id, options);\n } catch (error) {\n await this.uploads.abort(session.id).catch(() => undefined);\n throw error;\n }\n }\n\n /** Delete a file from the media library. */\n delete(mediaId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/media/${mediaId}`, options);\n }\n\n async #putPart(\n blob: Blob,\n session: MediaUpload,\n part: MediaUploadPart,\n signal: AbortSignal | undefined,\n ): Promise<void> {\n const start = (part.partNumber - 1) * session.partSize;\n const body = blob.slice(start, start + session.partSize);\n // Presigned storage URL: no API key, raw bytes as the body.\n const response = await this._client.fetchExternal(part.url, { method: 'PUT', body, signal });\n if (!response.ok) {\n throw new APIConnectionError(\n `Uploading part ${part.partNumber} failed with status ${response.status}.`,\n );\n }\n }\n}\n\n/** Low-level upload-session calls. `media.uploadMultipart()` drives them for you. */\nexport class MediaUploads extends APIResource {\n start(params: MediaUploadStartParams, options?: RequestOptions): APIPromise<MediaUpload> {\n return this._client.post('/media/uploads', params, options);\n }\n\n /** Signed PUT URLs for up to 100 parts. Valid for an hour, so ask as you go. */\n signParts(\n uploadId: string,\n params: { partNumbers: number[] },\n options?: RequestOptions,\n ): APIPromise<MediaUploadPart[]> {\n return this._client.post(path`/media/uploads/${uploadId}/parts`, params, options);\n }\n\n /** Finish the session. Returns the new media item, whose `id` goes in `mediaIds`. */\n complete(uploadId: string, options?: RequestOptions): APIPromise<MediaItem> {\n return this._client.post(path`/media/uploads/${uploadId}/complete`, undefined, options);\n }\n\n abort(uploadId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/media/uploads/${uploadId}`, options);\n }\n}\n\nfunction toBlob(file: Uploadable, type: string | undefined): Blob {\n if (file instanceof Blob) return type && type !== file.type ? new Blob([file], { type }) : file;\n // Copy into a fresh ArrayBuffer: a view may sit on a SharedArrayBuffer, which Blob rejects.\n const bytes =\n file instanceof ArrayBuffer\n ? new Uint8Array(file)\n : new Uint8Array(file.buffer, file.byteOffset, file.byteLength).slice();\n return new Blob([bytes as Uint8Array<ArrayBuffer>], type ? { type } : {});\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Platform } from '../types';\n\nexport class Platforms extends APIResource {\n /**\n * Live per-platform rules: character counts, attachments, thread length, accepted\n * media types. Read these instead of hard-coding them — they change.\n */\n list(options?: RequestOptions): APIPromise<Platform[]> {\n return this._client.get('/platforms', undefined, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport type { PagePromise } from '../core/pagination';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type {\n Comment,\n CommentListParams,\n CommentReply,\n CommentReplyParams,\n Post,\n PostCreateParams,\n PostListParams,\n PostMetrics,\n PostReviseParams,\n RetractResult,\n ReviseResult,\n} from '../types';\n\nexport class Posts extends APIResource {\n readonly comments: Comments = new Comments(this._client);\n\n /**\n * Create one submission targeting one or more channels.\n *\n * Call this ONCE with several `channels`, not once per channel. With `intent: 'now'`\n * it returns as soon as the work is queued (`status: 'publishing'`); the outcome\n * arrives later via webhooks or `retrieve()`.\n */\n create(params: PostCreateParams, options?: RequestOptions): APIPromise<Post> {\n return this._client.post('/posts', params, options);\n }\n\n retrieve(postId: string, options?: RequestOptions): APIPromise<Post> {\n return this._client.get(path`/posts/${postId}`, undefined, options);\n }\n\n /**\n * Submissions, newest first. Await it for one page, or iterate it for every post:\n *\n * ```ts\n * for await (const post of bulkit.posts.list({ status: 'failed' })) { ... }\n * ```\n */\n list(params?: PostListParams, options?: RequestOptions): PagePromise<Post> {\n return this._client.getPage('/posts', params, options);\n }\n\n /** Replace an unpublished submission. Once it has published, use `revise()`. */\n update(postId: string, params: PostCreateParams, options?: RequestOptions): APIPromise<Post> {\n return this._client.put(path`/posts/${postId}`, params, options);\n }\n\n /**\n * Remove Bulkit's record of a submission. Published copies stay LIVE on the\n * platforms — use `retract()` to take them down.\n */\n delete(postId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/posts/${postId}`, options);\n }\n\n /**\n * Publish now, or retry a failed / partially published submission. Channels that\n * already published are skipped. Asynchronous, like `intent: 'now'`.\n */\n publish(postId: string, options?: RequestOptions): APIPromise<Post> {\n return this._client.post(path`/posts/${postId}/publish`, undefined, options);\n }\n\n /**\n * PERMANENTLY delete the published copies from their platforms, with their likes and\n * replies. Not every channel can be retracted: always read `remaining`.\n */\n retract(postId: string, options?: RequestOptions): APIPromise<RetractResult> {\n return this._client.post(path`/posts/${postId}/retract`, undefined, options);\n }\n\n /** Rewrite live copy in place, where the platform allows it (`limits.remoteEdit`). */\n revise(\n postId: string,\n params: PostReviseParams,\n options?: RequestOptions,\n ): APIPromise<ReviseResult> {\n return this._client.post(path`/posts/${postId}/revise`, params, options);\n }\n\n metrics(postId: string, options?: RequestOptions): APIPromise<PostMetrics> {\n return this._client.get(path`/posts/${postId}/metrics`, undefined, options);\n }\n}\n\nexport class Comments extends APIResource {\n /** Comments on one channel's copy of a post, read live from the platform. */\n list(postId: string, params: CommentListParams, options?: RequestOptions): PagePromise<Comment> {\n return this._client.getPage(path`/posts/${postId}/comments`, params, options);\n }\n\n /** Reply publicly to a comment. The reply is visible the moment this returns. */\n reply(\n postId: string,\n commentId: string,\n params: CommentReplyParams,\n options?: RequestOptions,\n ): APIPromise<CommentReply> {\n return this._client.post(path`/posts/${postId}/comments/${commentId}/replies`, params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Stats as StatsData, StatsInsights, StatsInsightsParams, StatsParams } from '../types';\n\nexport class Stats extends APIResource {\n /** Analytics counted from the posts themselves. Can go down when posts are deleted. */\n retrieve(params: StatsParams, options?: RequestOptions): APIPromise<StatsData> {\n return this._client.get('/stats', params, options);\n }\n\n /** When, where and in what format the workspace's posts perform best. */\n insights(params: StatsInsightsParams, options?: RequestOptions): APIPromise<StatsInsights> {\n return this._client.get('/stats/insights', params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Tag } from '../types';\n\nexport class Tags extends APIResource {\n /** The workspace's own labels for submissions. Never published, unlike hashtags. */\n list(options?: RequestOptions): APIPromise<Tag[]> {\n return this._client.get('/tags', undefined, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Usage as UsageData } from '../types';\n\nexport class Usage extends APIResource {\n /**\n * The billing meter for the current period. The only endpoint that predicts a\n * `QuotaExceededError` — do not use `stats` for that.\n */\n retrieve(options?: RequestOptions): APIPromise<UsageData> {\n return this._client.get('/usage', undefined, options);\n }\n}\n","import { WebhookVerificationError } from './core/errors';\nimport type { WebhookEvent } from './types';\n\nexport const SIGNATURE_HEADER = 'x-bulkit-signature';\nconst DEFAULT_TOLERANCE_SECONDS = 300;\n\n/** Fetch `Headers`, or the plain object Node / Express / Fastify give you. */\nexport type HeadersLike = Headers | Record<string, string | string[] | undefined>;\n\nexport interface VerifyWebhookOptions {\n /** The endpoint's signing secret (`whsec_…`), returned when it was created or rolled. */\n secret: string;\n /** Reject deliveries signed more than this many seconds from now. Default 300. */\n toleranceSeconds?: number | undefined;\n /** @internal For tests. */\n now?: (() => number) | undefined;\n}\n\n/**\n * Verify a webhook delivery and return the parsed event.\n *\n * `payload` MUST be the raw request body exactly as received — not `JSON.stringify(req.body)`,\n * whose key order and whitespace differ and so produce a different signature.\n *\n * ```ts\n * app.post('/webhooks/bulkit', express.raw({ type: 'application/json' }), async (req, res) => {\n * const event = await verifyWebhook(req.body, req.headers, { secret });\n * res.sendStatus(200);\n * });\n * ```\n *\n * @throws {WebhookVerificationError} if the signature or timestamp does not check out.\n */\nexport async function verifyWebhook(\n payload: string | Uint8Array,\n headers: HeadersLike,\n options: VerifyWebhookOptions,\n): Promise<WebhookEvent> {\n const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);\n const header = getHeader(headers, SIGNATURE_HEADER);\n if (!header) throw new WebhookVerificationError(`Missing ${SIGNATURE_HEADER} header.`);\n\n const { timestamp, signatures } = parseSignatureHeader(header);\n const now = Math.floor((options.now?.() ?? Date.now()) / 1000);\n const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookVerificationError('Webhook timestamp is outside the tolerance window.');\n }\n\n const expected = await sign(options.secret, `${timestamp}.${body}`);\n if (!signatures.some((candidate) => timingSafeEqual(expected, candidate))) {\n throw new WebhookVerificationError('Webhook signature does not match.');\n }\n\n try {\n return JSON.parse(body) as WebhookEvent;\n } catch {\n throw new WebhookVerificationError('Webhook body is not valid JSON.');\n }\n}\n\n/** Compute the `x-bulkit-signature` header value for a payload. Useful for testing your receiver. */\nexport async function signWebhookPayload(\n payload: string,\n secret: string,\n timestamp: number = Math.floor(Date.now() / 1000),\n): Promise<string> {\n return `t=${timestamp},v1=${await sign(secret, `${timestamp}.${payload}`)}`;\n}\n\nasync function sign(secret: string, message: string): Promise<string> {\n const encoder = new TextEncoder();\n const key = await globalThis.crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const digest = await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction parseSignatureHeader(header: string): { timestamp: number; signatures: string[] } {\n let timestamp = Number.NaN;\n const signatures: string[] = [];\n for (const part of header.split(',')) {\n const [key, value] = part.trim().split('=', 2);\n if (key === 't') timestamp = Number(value);\n else if (key === 'v1' && value) signatures.push(value);\n }\n if (!Number.isInteger(timestamp) || signatures.length === 0) {\n throw new WebhookVerificationError(`Malformed ${SIGNATURE_HEADER} header.`);\n }\n return { timestamp, signatures };\n}\n\n/** Constant-time string comparison, so timing does not leak how much of a guess was right. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\nfunction getHeader(headers: HeadersLike, name: string): string | undefined {\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n const key = Object.keys(headers).find((k) => k.toLowerCase() === name);\n const value = key === undefined ? undefined : headers[key];\n return Array.isArray(value) ? value[0] : value;\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport type { PagePromise } from '../core/pagination';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type {\n IssuedWebhookEndpoint,\n WebhookCreateParams,\n WebhookDelivery,\n WebhookDeliveryListParams,\n WebhookEndpoint,\n WebhookEvent,\n WebhookTestResult,\n WebhookUpdateParams,\n} from '../types';\nimport { type HeadersLike, type VerifyWebhookOptions, verifyWebhook } from '../webhooks';\n\nexport class Webhooks extends APIResource {\n /**\n * Register an endpoint. The response carries the signing `secret` — store it now;\n * no other call returns it.\n */\n create(params: WebhookCreateParams, options?: RequestOptions): APIPromise<IssuedWebhookEndpoint> {\n return this._client.post('/webhooks', params, options);\n }\n\n retrieve(webhookId: string, options?: RequestOptions): APIPromise<WebhookEndpoint> {\n return this._client.get(path`/webhooks/${webhookId}`, undefined, options);\n }\n\n list(options?: RequestOptions): APIPromise<WebhookEndpoint[]> {\n return this._client.get('/webhooks', undefined, options);\n }\n\n /** Update an endpoint. Setting `enabled: true` also clears its failure streak. */\n update(\n webhookId: string,\n params: WebhookUpdateParams,\n options?: RequestOptions,\n ): APIPromise<WebhookEndpoint> {\n return this._client.put(path`/webhooks/${webhookId}`, params, options);\n }\n\n delete(webhookId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/webhooks/${webhookId}`, options);\n }\n\n /** Every delivery attempt to this endpoint, newest first. */\n deliveries(\n webhookId: string,\n params?: WebhookDeliveryListParams,\n options?: RequestOptions,\n ): PagePromise<WebhookDelivery> {\n return this._client.getPage(path`/webhooks/${webhookId}/deliveries`, params, options);\n }\n\n /** Issue a new signing secret. The old one stops working immediately. */\n rollSecret(webhookId: string, options?: RequestOptions): APIPromise<IssuedWebhookEndpoint> {\n return this._client.post(path`/webhooks/${webhookId}/roll-secret`, undefined, options);\n }\n\n /** Send a signed `webhook.test` event now. Works with test keys, which emit no real events. */\n test(webhookId: string, options?: RequestOptions): APIPromise<WebhookTestResult> {\n return this._client.post(path`/webhooks/${webhookId}/test`, undefined, options);\n }\n\n /**\n * Verify a delivery's signature and parse it. Same as the standalone `verifyWebhook()`,\n * which needs no API key — prefer that in a receiver that makes no API calls.\n */\n unwrap(\n payload: string | Uint8Array,\n headers: HeadersLike,\n options: VerifyWebhookOptions,\n ): Promise<WebhookEvent> {\n return verifyWebhook(payload, headers, options);\n }\n}\n","export const VERSION = '0.1.0';\n","import { APIPromise, type APIResponse, rateLimitFrom } from './core/api-promise';\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIError,\n APIUserAbortError,\n BulkitError,\n RateLimitError,\n} from './core/errors';\nimport { PagePromise } from './core/pagination';\nimport { buildQuery, isBrowser, type Query, readEnv, sleep, uuid } from './core/utils';\nimport { Channels } from './resources/channels';\nimport { Media } from './resources/media';\nimport { Platforms } from './resources/platforms';\nimport { Posts } from './resources/posts';\nimport { Stats } from './resources/stats';\nimport { Tags } from './resources/tags';\nimport { Usage } from './resources/usage';\nimport { Webhooks } from './resources/webhooks';\nimport { VERSION } from './version';\n\nconst DEFAULT_BASE_URL = 'https://api.bulkit.io';\nconst API_PREFIX = '/public/v1';\nconst DEFAULT_TIMEOUT_MS = 60_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst INITIAL_RETRY_DELAY_MS = 500;\nconst MAX_RETRY_DELAY_MS = 8_000;\n\nexport type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\nexport interface ClientOptions {\n /** Your API key (`bk_live_…` or `bk_test_…`). Defaults to `process.env.BULKIT_API_KEY`. */\n apiKey?: string | undefined;\n /**\n * Scheme and host to send requests to. Only change this to route through a proxy or a mock\n * server. Defaults to `process.env.BULKIT_BASE_URL`, then `https://api.bulkit.io`.\n */\n baseURL?: string | undefined;\n /** Per-attempt timeout in milliseconds. Default 60 000. */\n timeout?: number | undefined;\n /** How many times to retry a retryable failure. Default 2. */\n maxRetries?: number | undefined;\n /** Headers sent with every request. */\n defaultHeaders?: Record<string, string> | undefined;\n /** A `fetch` implementation to use instead of the global one (proxies, testing, …). */\n fetch?: Fetch | undefined;\n /**\n * Your API key is a secret: shipping it to a browser hands it to every visitor.\n * Set this only if you understand that, e.g. for an internal tool.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n}\n\nexport interface RequestOptions {\n /**\n * Sent as `Idempotency-Key` on writes. The SDK generates one per call by default and\n * reuses it across its own retries; pass your own to make retries safe across processes.\n */\n idempotencyKey?: string | undefined;\n timeout?: number | undefined;\n maxRetries?: number | undefined;\n signal?: AbortSignal | undefined;\n headers?: Record<string, string> | undefined;\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\ninterface FinalRequest extends RequestOptions {\n method: Method;\n path: string;\n query?: Query | undefined;\n body?: unknown;\n}\n\n/**\n * The Bulkit API client.\n *\n * ```ts\n * import { Bulkit } from 'bulkit';\n *\n * const bulkit = new Bulkit(); // reads BULKIT_API_KEY\n * const channels = await bulkit.channels.list();\n * ```\n */\nexport class Bulkit {\n readonly channels: Channels = new Channels(this);\n readonly platforms: Platforms = new Platforms(this);\n readonly posts: Posts = new Posts(this);\n readonly media: Media = new Media(this);\n readonly tags: Tags = new Tags(this);\n readonly stats: Stats = new Stats(this);\n readonly usage: Usage = new Usage(this);\n readonly webhooks: Webhooks = new Webhooks(this);\n\n readonly baseURL: string;\n readonly timeout: number;\n readonly maxRetries: number;\n readonly #apiKey: string;\n readonly #fetch: Fetch;\n readonly #defaultHeaders: Record<string, string>;\n\n constructor(options: ClientOptions = {}) {\n const apiKey = options.apiKey ?? readEnv('BULKIT_API_KEY');\n if (!apiKey) {\n throw new BulkitError(\n 'Missing API key. Pass `apiKey` to `new Bulkit()` or set the BULKIT_API_KEY environment variable.',\n );\n }\n if (isBrowser() && !options.dangerouslyAllowBrowser) {\n throw new BulkitError(\n 'Running in a browser would expose your secret API key to every visitor. ' +\n 'Call Bulkit from your server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.',\n );\n }\n\n const baseURL = options.baseURL ?? readEnv('BULKIT_BASE_URL') ?? DEFAULT_BASE_URL;\n this.baseURL = baseURL.replace(/\\/+$/, '');\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.#apiKey = apiKey;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#defaultHeaders = options.defaultHeaders ?? {};\n }\n\n /** `true` for a `bk_test_…` key: validates like live, but publishes nothing and bills nothing. */\n get isTestMode(): boolean {\n return this.#apiKey.startsWith('bk_test_');\n }\n\n get<T>(path: string, query?: Query, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'GET', path, query, ...options });\n }\n\n post<T>(path: string, body?: unknown, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'POST', path, body, ...options });\n }\n\n put<T>(path: string, body?: unknown, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'PUT', path, body, ...options });\n }\n\n delete<T = void>(path: string, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'DELETE', path, ...options });\n }\n\n /** @internal */\n getPage<T>(path: string, query: Query | undefined, options?: RequestOptions): PagePromise<T> {\n return new PagePromise<T>((cursor) =>\n this.request<{ data: T[]; nextCursor: string | null }>({\n method: 'GET',\n path,\n query: cursor ? { ...query, cursor } : query,\n ...options,\n }).withResponse(),\n );\n }\n\n /** @internal Fetch a non-API URL (e.g. a presigned upload URL) without credentials. */\n fetchExternal(url: string, init: RequestInit): Promise<Response> {\n return this.#fetch(url, init);\n }\n\n /** Sends a request, retrying what is safe to retry. Prefer the resource methods. */\n request<T>(req: FinalRequest): APIPromise<T> {\n return new APIPromise(this.#send<T>(req));\n }\n\n async #send<T>(req: FinalRequest): Promise<APIResponse<T>> {\n const maxRetries = req.maxRetries ?? this.maxRetries;\n const isWrite = req.method === 'POST' || req.method === 'PUT';\n // One key per logical call, reused across retries — that is what makes a retry safe.\n const idempotencyKey = isWrite ? (req.idempotencyKey ?? uuid()) : undefined;\n const url = this.baseURL + API_PREFIX + req.path + buildQuery(req.query);\n\n for (let attempt = 0; ; attempt++) {\n const retriesLeft = maxRetries - attempt;\n let response: Response;\n try {\n response = await this.#fetchWithTimeout(url, req, idempotencyKey);\n } catch (error) {\n if (error instanceof APIUserAbortError || retriesLeft <= 0) throw error;\n await sleep(retryDelay(attempt));\n continue;\n }\n\n if (response.ok) {\n return {\n data: await parseBody<T>(response),\n response,\n requestId: response.headers.get('x-request-id'),\n rateLimit: rateLimitFrom(response.headers),\n };\n }\n\n const body = await parseBody<unknown>(response).catch(() => undefined);\n const error = APIError.from(response.status, body, response.headers);\n if (retriesLeft <= 0 || !shouldRetry(error, req.method)) throw error;\n await sleep(retryDelay(attempt, error));\n }\n }\n\n async #fetchWithTimeout(\n url: string,\n req: FinalRequest,\n idempotencyKey: string | undefined,\n ): Promise<Response> {\n const timeout = req.timeout ?? this.timeout;\n const timeoutSignal = AbortSignal.timeout(timeout);\n const signal = req.signal ? AbortSignal.any([req.signal, timeoutSignal]) : timeoutSignal;\n\n const isForm = req.body instanceof FormData;\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `bulkit-node/${VERSION}`,\n ...this.#defaultHeaders,\n ...req.headers,\n Authorization: `Bearer ${this.#apiKey}`,\n };\n if (req.body !== undefined && !isForm) headers['Content-Type'] = 'application/json';\n if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;\n\n try {\n return await this.#fetch(url, {\n method: req.method,\n headers,\n body:\n req.body === undefined\n ? undefined\n : isForm\n ? (req.body as FormData)\n : JSON.stringify(req.body),\n signal,\n });\n } catch (error) {\n if (req.signal?.aborted) throw new APIUserAbortError();\n if (timeoutSignal.aborted) throw new APIConnectionTimeoutError();\n throw new APIConnectionError(undefined, { cause: error });\n }\n }\n}\n\n/**\n * What is worth retrying, per the API's contract:\n * - 429 and 409 `request_in_progress`: transient by definition.\n * - 408, 502, 503, 504: the request was not (fully) attempted.\n * - 500: only on reads. A write's idempotency key is kept on a 500, so retrying it\n * would only replay the same failure; the caller must inspect state first.\n * - 402 `quota_exceeded` and every other 4xx: retrying can never succeed.\n */\nfunction shouldRetry(error: APIError, method: Method): boolean {\n const { status } = error;\n if (status === 429 || status === 408 || status === 502 || status === 503 || status === 504) {\n return true;\n }\n if (status === 409) return error.code === 'request_in_progress';\n if (status === 500) return method === 'GET' || method === 'DELETE';\n return false;\n}\n\nfunction retryDelay(attempt: number, error?: APIError): number {\n if (error instanceof RateLimitError && error.retryAfter !== undefined) {\n return Math.min(error.retryAfter * 1000, 60_000);\n }\n const backoff = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);\n // Jitter between 75% and 100% of the backoff, so clients do not retry in lockstep.\n return backoff * (0.75 + Math.random() * 0.25);\n}\n\nasync function parseBody<T>(response: Response): Promise<T> {\n if (response.status === 204) return undefined as T;\n const text = await response.text();\n if (!text) return undefined as T;\n const type = response.headers.get('content-type') ?? '';\n return (type.includes('json') ? JSON.parse(text) : text) as T;\n}\n"],"mappings":";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ACpC,MAAM,OAAO,MAAM,SAAS,KAAK;CACjC,IAAI,CAAC,MAAM,OAAO,KAAA;CAElB,QADa,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CACxC,SAAS,MAAM,IAAI,KAAK,MAAM,IAAI,IAAI;AACrD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/core/api-promise.ts","../src/core/errors.ts","../src/core/pagination.ts","../src/core/utils.ts","../src/core/resource.ts","../src/resources/channels.ts","../src/resources/media.ts","../src/resources/platforms.ts","../src/resources/posts.ts","../src/resources/stats.ts","../src/resources/tags.ts","../src/resources/usage.ts","../src/webhooks.ts","../src/resources/webhooks.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["export interface APIResponse<T> {\n data: T;\n response: Response;\n /** The `x-request-id` of the response. Quote it when contacting support. */\n requestId: string | null;\n /** Requests per minute allowed for this key, from `X-RateLimit-*` headers. */\n rateLimit: RateLimitInfo;\n}\n\nexport interface RateLimitInfo {\n limit: number | null;\n remaining: number | null;\n /** Seconds until the window refills. */\n reset: number | null;\n}\n\n/**\n * A `Promise` of the parsed response body that can also hand back the raw `Response`:\n *\n * ```ts\n * const post = await client.posts.retrieve('pst_123');\n * const { data, requestId, rateLimit } = await client.posts.retrieve('pst_123').withResponse();\n * ```\n */\nexport class APIPromise<T> extends Promise<T> {\n readonly #responsePromise: Promise<APIResponse<T>>;\n\n constructor(responsePromise: Promise<APIResponse<T>>) {\n // `Promise` subclasses must accept an executor; resolution is driven by `responsePromise`.\n super((resolve) => resolve(null as T));\n this.#responsePromise = responsePromise;\n }\n\n /** Resolves to the body together with the raw response and its metadata. */\n withResponse(): Promise<APIResponse<T>> {\n return this.#responsePromise;\n }\n\n #parsed?: Promise<T>;\n #parse(): Promise<T> {\n this.#parsed ??= this.#responsePromise.then((r) => r.data);\n return this.#parsed;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: an APIPromise is deliberately a thenable.\n override then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.#parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult> {\n return this.#parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#parse().finally(onfinally);\n }\n\n // Derived promises (from `.then`) should be plain Promises, not APIPromises.\n static override get [Symbol.species]() {\n return Promise;\n }\n}\n\nexport function rateLimitFrom(headers: Headers): RateLimitInfo {\n const num = (name: string) => {\n const raw = headers.get(name);\n const value = raw === null ? Number.NaN : Number(raw);\n return Number.isFinite(value) ? value : null;\n };\n return {\n limit: num('x-ratelimit-limit'),\n remaining: num('x-ratelimit-remaining'),\n reset: num('x-ratelimit-reset'),\n };\n}\n","import type { components } from '../generated/openapi';\n\nexport type ErrorBody = components['schemas']['ErrorDetail'];\nexport type FieldError = components['schemas']['FieldError'];\n/**\n * Error codes documented today. New ones may be added without notice,\n * so the type stays open to any string.\n */\nexport type ErrorCode = ErrorBody['code'] | (string & {});\n\n/** Base class for every error this SDK throws. `instanceof BulkitError` catches them all. */\nexport class BulkitError extends Error {\n override name = 'BulkitError';\n}\n\n/**\n * The API answered with a non-2xx status.\n *\n * Branch on `code` (stable within v1) rather than `message` (prose, may change).\n * New codes can appear at any time, so always keep a fallback branch.\n */\nexport class APIError extends BulkitError {\n override name = 'APIError';\n\n /** HTTP status code. */\n readonly status: number;\n /** Machine-readable error code, e.g. `content_too_long`. */\n readonly code: ErrorCode | undefined;\n /** Path into the request body (or the header name) that caused the failure. */\n readonly field: string | undefined;\n /** Every field-level failure when schema validation rejected more than one. */\n readonly details: FieldError[] | undefined;\n /** Quote this when contacting support: it is what Bulkit searches on. */\n readonly requestId: string | undefined;\n readonly headers: Headers;\n /** The parsed `error` object exactly as the API sent it. */\n readonly error: ErrorBody | undefined;\n\n constructor(status: number, error: ErrorBody | undefined, message: string, headers: Headers) {\n super(message);\n this.status = status;\n this.error = error;\n this.code = error?.code;\n this.field = error?.field ?? undefined;\n this.details = error?.details ?? undefined;\n this.requestId = error?.requestId ?? headers.get('x-request-id') ?? undefined;\n this.headers = headers;\n }\n\n /** @internal */\n static from(status: number, body: unknown, headers: Headers): APIError {\n const error = extractError(body);\n const message = error?.message ?? `Request failed with status ${status}`;\n const ErrorClass = errorClassFor(status);\n return new ErrorClass(status, error, message, headers);\n }\n}\n\n/** 400 — the request was malformed or failed schema validation. */\nexport class BadRequestError extends APIError {\n override name = 'BadRequestError';\n}\n\n/** 401 — the API key is missing, malformed, revoked or unknown. */\nexport class AuthenticationError extends APIError {\n override name = 'AuthenticationError';\n}\n\n/**\n * 402 — the plan's allowance for this period is spent.\n *\n * This is NOT a rate limit: retrying will never succeed until the period resets.\n * `client.usage.retrieve()` has the numbers and `periodEnd`. The SDK never retries it.\n */\nexport class QuotaExceededError extends APIError {\n override name = 'QuotaExceededError';\n}\n\n/** 403 — the key lacks the scope for this call (e.g. a read-only key attempting a write). */\nexport class PermissionDeniedError extends APIError {\n override name = 'PermissionDeniedError';\n}\n\n/** 404 — the resource does not exist in this workspace. */\nexport class NotFoundError extends APIError {\n override name = 'NotFoundError';\n}\n\n/** 409 — the resource is in a state that does not allow this, or a request with the same idempotency key is still running. */\nexport class ConflictError extends APIError {\n override name = 'ConflictError';\n}\n\n/** 413 — the request body or uploaded file is too large. */\nexport class PayloadTooLargeError extends APIError {\n override name = 'PayloadTooLargeError';\n}\n\n/** 415 — the uploaded file's type is not accepted. */\nexport class UnsupportedMediaTypeError extends APIError {\n override name = 'UnsupportedMediaTypeError';\n}\n\n/** 422 — well-formed but refused, e.g. a platform rule or an idempotency key reused with a different body. */\nexport class UnprocessableEntityError extends APIError {\n override name = 'UnprocessableEntityError';\n}\n\n/** 429 — too many requests. Retried automatically, honouring `Retry-After`. */\nexport class RateLimitError extends APIError {\n override name = 'RateLimitError';\n\n /** Seconds the API asked us to wait before retrying, if it said. */\n get retryAfter(): number | undefined {\n const value = Number(this.headers.get('retry-after'));\n return Number.isFinite(value) && value >= 0 ? value : undefined;\n }\n}\n\n/** 5xx — a fault on Bulkit's side or an unreachable dependency. */\nexport class InternalServerError extends APIError {\n override name = 'InternalServerError';\n}\n\n/** The request never got an HTTP response (DNS, TLS, connection reset, …). */\nexport class APIConnectionError extends BulkitError {\n override name = 'APIConnectionError';\n\n constructor(message = 'Connection error.', options?: { cause?: unknown }) {\n super(message, options);\n }\n}\n\n/** The request exceeded the configured `timeout`. */\nexport class APIConnectionTimeoutError extends APIConnectionError {\n override name = 'APIConnectionTimeoutError';\n\n constructor(message = 'Request timed out.') {\n super(message);\n }\n}\n\n/** The caller aborted the request through its `AbortSignal`. */\nexport class APIUserAbortError extends BulkitError {\n override name = 'APIUserAbortError';\n\n constructor(message = 'Request was aborted.') {\n super(message);\n }\n}\n\n/** A webhook delivery failed signature or timestamp verification. Respond 400 and drop it. */\nexport class WebhookVerificationError extends BulkitError {\n override name = 'WebhookVerificationError';\n}\n\nfunction errorClassFor(status: number): typeof APIError {\n switch (status) {\n case 400:\n return BadRequestError;\n case 401:\n return AuthenticationError;\n case 402:\n return QuotaExceededError;\n case 403:\n return PermissionDeniedError;\n case 404:\n return NotFoundError;\n case 409:\n return ConflictError;\n case 413:\n return PayloadTooLargeError;\n case 415:\n return UnsupportedMediaTypeError;\n case 422:\n return UnprocessableEntityError;\n case 429:\n return RateLimitError;\n default:\n return status >= 500 ? InternalServerError : APIError;\n }\n}\n\nfunction extractError(body: unknown): ErrorBody | undefined {\n if (body && typeof body === 'object' && 'error' in body) {\n const error = (body as { error: unknown }).error;\n if (error && typeof error === 'object' && 'code' in error) return error as ErrorBody;\n }\n return undefined;\n}\n","import { APIPromise, type APIResponse } from './api-promise';\nimport { BulkitError } from './errors';\n\ninterface CursorPageBody<T> {\n data: T[];\n nextCursor: string | null;\n}\n\ntype FetchPage<T> = (cursor: string | undefined) => Promise<APIResponse<CursorPageBody<T>>>;\n\n/**\n * One page of a cursor-paginated list.\n *\n * Iterate it with `for await` to walk every item across every page, or page\n * manually with `hasNextPage()` / `getNextPage()`.\n */\nexport class CursorPage<T> implements AsyncIterable<T> {\n readonly data: T[];\n /** Opaque. Pass it back as `cursor`; never parse or construct one. */\n readonly nextCursor: string | null;\n readonly response: Response;\n readonly #fetchPage: FetchPage<T>;\n\n constructor(body: CursorPageBody<T>, response: Response, fetchPage: FetchPage<T>) {\n // A server that predates paging for this endpoint answers with a bare array (or some other\n // shape). Fail loudly here rather than read a missing `nextCursor` as \"there's another page\"\n // and re-request page one forever.\n if (!Array.isArray(body?.data)) {\n throw new BulkitError(\n `Expected a paged response ({ data, nextCursor }) from ${response.url || 'the API'}, ` +\n 'but got something else. The server may be running an older API version.',\n );\n }\n this.data = body.data;\n this.nextCursor = body.nextCursor ?? null;\n this.response = response;\n this.#fetchPage = fetchPage;\n }\n\n /** A null `nextCursor` — not an empty `data` — is the end of the list. */\n hasNextPage(): boolean {\n return this.nextCursor !== null;\n }\n\n async getNextPage(): Promise<CursorPage<T>> {\n if (this.nextCursor === null) {\n throw new Error('No next page; check `hasNextPage()` before calling `getNextPage()`.');\n }\n const { data, response } = await this.#fetchPage(this.nextCursor);\n return new CursorPage(data, response, this.#fetchPage);\n }\n\n /** Yields this page and every page after it. */\n async *iterPages(): AsyncGenerator<CursorPage<T>> {\n let page: CursorPage<T> = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n for await (const page of this.iterPages()) {\n yield* page.data;\n }\n }\n}\n\n/**\n * Resolves to the first `CursorPage`, and is also directly async-iterable over every item:\n *\n * ```ts\n * for await (const post of client.posts.list({ status: 'scheduled' })) { ... }\n * ```\n */\nexport class PagePromise<T> extends APIPromise<CursorPage<T>> implements AsyncIterable<T> {\n constructor(fetchPage: FetchPage<T>, firstCursor?: string) {\n super(\n fetchPage(firstCursor).then((res) => ({\n ...res,\n data: new CursorPage(res.data, res.response, fetchPage),\n })),\n );\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n const page = await this;\n yield* page;\n }\n}\n","export type QueryValue = string | number | boolean | null | undefined;\nexport type Query = Record<string, QueryValue | QueryValue[]>;\n\n/** Reads an environment variable on runtimes that have `process`, and nothing on those that do not. */\nexport function readEnv(name: string): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n const value = env?.[name]?.trim();\n return value ? value : undefined;\n}\n\n/** Tagged template that URI-encodes every interpolated path segment. */\nexport function path(strings: TemplateStringsArray, ...params: string[]): string {\n return strings.reduce((acc, part, i) => {\n const param = params[i];\n if (param === undefined) return acc + part;\n if (param === '') throw new TypeError('Path parameters must not be empty.');\n return acc + part + encodeURIComponent(param);\n }, '');\n}\n\nexport function buildQuery(query: Query | undefined): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function uuid(): string {\n return globalThis.crypto.randomUUID();\n}\n\nexport function isBrowser(): boolean {\n return (\n typeof (globalThis as { window?: unknown }).window !== 'undefined' &&\n typeof (globalThis as { document?: unknown }).document !== 'undefined'\n );\n}\n","import type { Bulkit } from '../client';\n\nexport abstract class APIResource {\n protected readonly _client: Bulkit;\n\n constructor(client: Bulkit) {\n this._client = client;\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type { Channel, ChannelCapabilities, OptionChoices, OptionChoicesParams } from '../types';\n\nexport class Channels extends APIResource {\n /** Every channel this workspace can post to. Call this before composing a post. */\n list(options?: RequestOptions): APIPromise<Channel[]> {\n return this._client.get('/channels', undefined, options);\n }\n\n /** Account-level rules for one channel (privacy levels, required flair, …), read live from the platform. */\n capabilities(channelId: string, options?: RequestOptions): APIPromise<ChannelCapabilities> {\n return this._client.get(path`/channels/${channelId}/capabilities`, undefined, options);\n }\n\n /**\n * Search the values of a `search`-type option, such as Instagram's `location_id`.\n * Pass `q` to turn a name into values, or `value` to turn a stored value back into its label.\n */\n optionChoices(\n channelId: string,\n key: string,\n params?: OptionChoicesParams,\n options?: RequestOptions,\n ): APIPromise<OptionChoices> {\n return this._client.get(path`/channels/${channelId}/options/${key}/choices`, params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIConnectionError } from '../core/errors';\nimport type { PagePromise } from '../core/pagination';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type {\n MediaItem,\n MediaListParams,\n MediaUpload,\n MediaUploadPart,\n MediaUploadStartParams,\n} from '../types';\n\n/**\n * Anything that holds a file's bytes. In Node, `await fs.openAsBlob(filePath)` gives you a\n * `Blob` without reading the whole file into memory.\n */\nexport type Uploadable = Blob | ArrayBuffer | ArrayBufferView;\n\nexport interface MediaUploadParams {\n /** Required unless `file` is a `File`, which carries its own name. */\n fileName?: string | undefined;\n /** Defaults to the `Blob`'s own type. */\n mimeType?: string | undefined;\n}\n\nexport interface MultipartUploadParams extends MediaUploadParams {\n /** How many parts to upload at once. Default 4. */\n concurrency?: number | undefined;\n}\n\nexport class Media extends APIResource {\n readonly uploads: MediaUploads = new MediaUploads(this._client);\n\n /**\n * The workspace's media library, newest first. Await it for one page, or iterate it\n * for every file:\n *\n * ```ts\n * for await (const item of bulkit.media.list()) { ... }\n * ```\n */\n list(params?: MediaListParams, options?: RequestOptions): PagePromise<MediaItem> {\n return this._client.getPage('/media', params, options);\n }\n\n /**\n * Upload a file in one request: images up to 10 MB, video and PDFs up to 100 MB,\n * subtitles up to 5 MB. For larger video, use `uploadMultipart()`.\n */\n upload(\n file: Uploadable,\n params: MediaUploadParams = {},\n options?: RequestOptions,\n ): APIPromise<MediaItem> {\n const blob = toBlob(file, params.mimeType);\n const fileName = params.fileName ?? (file instanceof File ? file.name : undefined);\n if (!fileName) throw new TypeError('`fileName` is required unless `file` is a File.');\n\n const form = new FormData();\n form.append('file', blob, fileName);\n return this._client.post('/media', form, options);\n }\n\n /**\n * Upload a large video through an upload session: start it, PUT every part to its\n * signed URL, then complete it. The session is aborted if any step fails.\n *\n * An `idempotencyKey` passed here is split per step (`<key>:start`, `<key>:complete`),\n * since the API holds a key to one route. Keep it under 246 characters so both fit.\n */\n async uploadMultipart(\n file: Uploadable,\n params: MultipartUploadParams = {},\n options?: RequestOptions,\n ): Promise<MediaItem> {\n const blob = toBlob(file, params.mimeType);\n const fileName = params.fileName ?? (file instanceof File ? file.name : undefined);\n const mimeType = params.mimeType ?? blob.type;\n if (!fileName) throw new TypeError('`fileName` is required unless `file` is a File.');\n if (!mimeType) throw new TypeError('`mimeType` is required when the Blob has no type.');\n\n const session = await this.uploads.start(\n { fileName, mimeType, size: blob.size },\n stepOptions(options, 'start'),\n );\n const concurrency = Math.max(1, Math.min(params.concurrency ?? 4, 100));\n\n try {\n const partNumbers = Array.from({ length: session.partCount }, (_, i) => i + 1);\n // Signed URLs expire after an hour, so sign each batch just before uploading it.\n for (let i = 0; i < partNumbers.length; i += concurrency) {\n const batch = partNumbers.slice(i, i + concurrency);\n // Signing changes nothing, so each batch gets a fresh key of its own.\n const parts = await this.uploads.signParts(\n session.id,\n { partNumbers: batch },\n { ...options, idempotencyKey: undefined },\n );\n await Promise.all(parts.map((part) => this.#putPart(blob, session, part, options?.signal)));\n }\n return await this.uploads.complete(session.id, stepOptions(options, 'complete'));\n } catch (error) {\n await this.uploads.abort(session.id).catch(() => undefined);\n throw error;\n }\n }\n\n /** Delete a file from the media library. */\n delete(mediaId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/media/${mediaId}`, options);\n }\n\n async #putPart(\n blob: Blob,\n session: MediaUpload,\n part: MediaUploadPart,\n signal: AbortSignal | undefined,\n ): Promise<void> {\n const start = (part.partNumber - 1) * session.partSize;\n const body = blob.slice(start, start + session.partSize);\n // Presigned storage URL: no API key, raw bytes as the body.\n const response = await this._client.fetchExternal(part.url, { method: 'PUT', body, signal });\n if (!response.ok) {\n throw new APIConnectionError(\n `Uploading part ${part.partNumber} failed with status ${response.status}.`,\n );\n }\n }\n}\n\n/** Low-level upload-session calls. `media.uploadMultipart()` drives them for you. */\nexport class MediaUploads extends APIResource {\n start(params: MediaUploadStartParams, options?: RequestOptions): APIPromise<MediaUpload> {\n return this._client.post('/media/uploads', params, options);\n }\n\n /** Signed PUT URLs for up to 100 parts. Valid for an hour, so ask as you go. */\n signParts(\n uploadId: string,\n params: { partNumbers: number[] },\n options?: RequestOptions,\n ): APIPromise<MediaUploadPart[]> {\n return this._client.post(path`/media/uploads/${uploadId}/parts`, params, options);\n }\n\n /** Finish the session. Returns the new media item, whose `id` goes in `mediaIds`. */\n complete(uploadId: string, options?: RequestOptions): APIPromise<MediaItem> {\n return this._client.post(path`/media/uploads/${uploadId}/complete`, undefined, options);\n }\n\n abort(uploadId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/media/uploads/${uploadId}`, options);\n }\n}\n\nfunction toBlob(file: Uploadable, type: string | undefined): Blob {\n if (file instanceof Blob) return type && type !== file.type ? new Blob([file], { type }) : file;\n // Copy into a fresh ArrayBuffer: a view may sit on a SharedArrayBuffer, which Blob rejects.\n const bytes =\n file instanceof ArrayBuffer\n ? new Uint8Array(file)\n : new Uint8Array(file.buffer, file.byteOffset, file.byteLength).slice();\n return new Blob([bytes as Uint8Array<ArrayBuffer>], type ? { type } : {});\n}\n\n/** The caller's key for one step of a multi-request call, or the options untouched. */\nfunction stepOptions(\n options: RequestOptions | undefined,\n step: string,\n): RequestOptions | undefined {\n if (!options?.idempotencyKey) return options;\n return { ...options, idempotencyKey: `${options.idempotencyKey}:${step}` };\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Platform } from '../types';\n\nexport class Platforms extends APIResource {\n /**\n * Live per-platform rules: character counts, attachments, thread length, accepted\n * media types. Read these instead of hard-coding them — they change.\n */\n list(options?: RequestOptions): APIPromise<Platform[]> {\n return this._client.get('/platforms', undefined, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport type { PagePromise } from '../core/pagination';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type {\n Comment,\n CommentListParams,\n CommentReply,\n CommentReplyParams,\n Post,\n PostCreateParams,\n PostListParams,\n PostMetrics,\n PostReviseParams,\n RetractResult,\n ReviseResult,\n} from '../types';\n\nexport class Posts extends APIResource {\n readonly comments: Comments = new Comments(this._client);\n\n /**\n * Create one submission targeting one or more channels.\n *\n * Call this ONCE with several `channels`, not once per channel. With `intent: 'now'`\n * it returns as soon as the work is queued (`status: 'publishing'`); the outcome\n * arrives later via webhooks or `retrieve()`.\n */\n create(params: PostCreateParams, options?: RequestOptions): APIPromise<Post> {\n return this._client.post('/posts', params, options);\n }\n\n retrieve(postId: string, options?: RequestOptions): APIPromise<Post> {\n return this._client.get(path`/posts/${postId}`, undefined, options);\n }\n\n /**\n * Submissions, newest first. Await it for one page, or iterate it for every post:\n *\n * ```ts\n * for await (const post of bulkit.posts.list({ status: 'failed' })) { ... }\n * ```\n */\n list(params?: PostListParams, options?: RequestOptions): PagePromise<Post> {\n return this._client.getPage('/posts', params, options);\n }\n\n /** Replace an unpublished submission. Once it has published, use `revise()`. */\n update(postId: string, params: PostCreateParams, options?: RequestOptions): APIPromise<Post> {\n return this._client.put(path`/posts/${postId}`, params, options);\n }\n\n /**\n * Remove Bulkit's record of a submission. Published copies stay LIVE on the\n * platforms — use `retract()` to take them down.\n */\n delete(postId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/posts/${postId}`, options);\n }\n\n /**\n * Publish now, or retry a failed / partially published submission. Channels that\n * already published are skipped. Asynchronous, like `intent: 'now'`.\n */\n publish(postId: string, options?: RequestOptions): APIPromise<Post> {\n return this._client.post(path`/posts/${postId}/publish`, undefined, options);\n }\n\n /**\n * PERMANENTLY delete the published copies from their platforms, with their likes and\n * replies. Not every channel can be retracted: always read `remaining`.\n */\n retract(postId: string, options?: RequestOptions): APIPromise<RetractResult> {\n return this._client.post(path`/posts/${postId}/retract`, undefined, options);\n }\n\n /** Rewrite live copy in place, where the platform allows it (`limits.remoteEdit`). */\n revise(\n postId: string,\n params: PostReviseParams,\n options?: RequestOptions,\n ): APIPromise<ReviseResult> {\n return this._client.post(path`/posts/${postId}/revise`, params, options);\n }\n\n metrics(postId: string, options?: RequestOptions): APIPromise<PostMetrics> {\n return this._client.get(path`/posts/${postId}/metrics`, undefined, options);\n }\n}\n\nexport class Comments extends APIResource {\n /** Comments on one channel's copy of a post, read live from the platform. */\n list(postId: string, params: CommentListParams, options?: RequestOptions): PagePromise<Comment> {\n return this._client.getPage(path`/posts/${postId}/comments`, params, options);\n }\n\n /** Reply publicly to a comment. The reply is visible the moment this returns. */\n reply(\n postId: string,\n commentId: string,\n params: CommentReplyParams,\n options?: RequestOptions,\n ): APIPromise<CommentReply> {\n return this._client.post(path`/posts/${postId}/comments/${commentId}/replies`, params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Stats as StatsData, StatsInsights, StatsInsightsParams, StatsParams } from '../types';\n\nexport class Stats extends APIResource {\n /** Analytics counted from the posts themselves. Can go down when posts are deleted. */\n retrieve(params: StatsParams, options?: RequestOptions): APIPromise<StatsData> {\n return this._client.get('/stats', params, options);\n }\n\n /** When, where and in what format the workspace's posts perform best. */\n insights(params: StatsInsightsParams, options?: RequestOptions): APIPromise<StatsInsights> {\n return this._client.get('/stats/insights', params, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Tag } from '../types';\n\nexport class Tags extends APIResource {\n /** The workspace's own labels for submissions. Never published, unlike hashtags. */\n list(options?: RequestOptions): APIPromise<Tag[]> {\n return this._client.get('/tags', undefined, options);\n }\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport { APIResource } from '../core/resource';\nimport type { Usage as UsageData } from '../types';\n\nexport class Usage extends APIResource {\n /**\n * The billing meter for the current period. The only endpoint that predicts a\n * `QuotaExceededError` — do not use `stats` for that.\n */\n retrieve(options?: RequestOptions): APIPromise<UsageData> {\n return this._client.get('/usage', undefined, options);\n }\n}\n","import { WebhookVerificationError } from './core/errors';\nimport type { WebhookEvent } from './types';\n\nexport const SIGNATURE_HEADER = 'x-bulkit-signature';\nconst DEFAULT_TOLERANCE_SECONDS = 300;\n\n/** Fetch `Headers`, or the plain object Node / Express / Fastify give you. */\nexport type HeadersLike = Headers | Record<string, string | string[] | undefined>;\n\nexport interface VerifyWebhookOptions {\n /** The endpoint's signing secret (`whsec_…`), returned when it was created or rolled. */\n secret: string;\n /** Reject deliveries signed more than this many seconds from now. Default 300. */\n toleranceSeconds?: number | undefined;\n /** @internal For tests. */\n now?: (() => number) | undefined;\n}\n\n/**\n * Verify a webhook delivery and return the parsed event.\n *\n * `payload` MUST be the raw request body exactly as received — not `JSON.stringify(req.body)`,\n * whose key order and whitespace differ and so produce a different signature.\n *\n * ```ts\n * app.post('/webhooks/bulkit', express.raw({ type: 'application/json' }), async (req, res) => {\n * const event = await verifyWebhook(req.body, req.headers, { secret });\n * res.sendStatus(200);\n * });\n * ```\n *\n * @throws {WebhookVerificationError} if the signature or timestamp does not check out.\n */\nexport async function verifyWebhook(\n payload: string | Uint8Array,\n headers: HeadersLike,\n options: VerifyWebhookOptions,\n): Promise<WebhookEvent> {\n const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);\n const header = getHeader(headers, SIGNATURE_HEADER);\n if (!header) throw new WebhookVerificationError(`Missing ${SIGNATURE_HEADER} header.`);\n\n const { timestamp, signatures } = parseSignatureHeader(header);\n const now = Math.floor((options.now?.() ?? Date.now()) / 1000);\n const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookVerificationError('Webhook timestamp is outside the tolerance window.');\n }\n\n const expected = await sign(options.secret, `${timestamp}.${body}`);\n if (!signatures.some((candidate) => timingSafeEqual(expected, candidate))) {\n throw new WebhookVerificationError('Webhook signature does not match.');\n }\n\n try {\n return JSON.parse(body) as WebhookEvent;\n } catch {\n throw new WebhookVerificationError('Webhook body is not valid JSON.');\n }\n}\n\n/** Compute the `x-bulkit-signature` header value for a payload. Useful for testing your receiver. */\nexport async function signWebhookPayload(\n payload: string,\n secret: string,\n timestamp: number = Math.floor(Date.now() / 1000),\n): Promise<string> {\n return `t=${timestamp},v1=${await sign(secret, `${timestamp}.${payload}`)}`;\n}\n\nasync function sign(secret: string, message: string): Promise<string> {\n const encoder = new TextEncoder();\n const key = await globalThis.crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const digest = await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction parseSignatureHeader(header: string): { timestamp: number; signatures: string[] } {\n let timestamp = Number.NaN;\n const signatures: string[] = [];\n for (const part of header.split(',')) {\n const [key, value] = part.trim().split('=', 2);\n if (key === 't') timestamp = Number(value);\n else if (key === 'v1' && value) signatures.push(value);\n }\n if (!Number.isInteger(timestamp) || signatures.length === 0) {\n throw new WebhookVerificationError(`Malformed ${SIGNATURE_HEADER} header.`);\n }\n return { timestamp, signatures };\n}\n\n/** Constant-time string comparison, so timing does not leak how much of a guess was right. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\nfunction getHeader(headers: HeadersLike, name: string): string | undefined {\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n const key = Object.keys(headers).find((k) => k.toLowerCase() === name);\n const value = key === undefined ? undefined : headers[key];\n return Array.isArray(value) ? value[0] : value;\n}\n","import type { RequestOptions } from '../client';\nimport type { APIPromise } from '../core/api-promise';\nimport type { PagePromise } from '../core/pagination';\nimport { APIResource } from '../core/resource';\nimport { path } from '../core/utils';\nimport type {\n IssuedWebhookEndpoint,\n WebhookCreateParams,\n WebhookDelivery,\n WebhookDeliveryListParams,\n WebhookEndpoint,\n WebhookEvent,\n WebhookTestResult,\n WebhookUpdateParams,\n} from '../types';\nimport { type HeadersLike, type VerifyWebhookOptions, verifyWebhook } from '../webhooks';\n\nexport class Webhooks extends APIResource {\n /**\n * Register an endpoint. The response carries the signing `secret` — store it now;\n * no other call returns it.\n */\n create(params: WebhookCreateParams, options?: RequestOptions): APIPromise<IssuedWebhookEndpoint> {\n return this._client.post('/webhooks', params, options);\n }\n\n retrieve(webhookId: string, options?: RequestOptions): APIPromise<WebhookEndpoint> {\n return this._client.get(path`/webhooks/${webhookId}`, undefined, options);\n }\n\n list(options?: RequestOptions): APIPromise<WebhookEndpoint[]> {\n return this._client.get('/webhooks', undefined, options);\n }\n\n /** Update an endpoint. Setting `enabled: true` also clears its failure streak. */\n update(\n webhookId: string,\n params: WebhookUpdateParams,\n options?: RequestOptions,\n ): APIPromise<WebhookEndpoint> {\n return this._client.put(path`/webhooks/${webhookId}`, params, options);\n }\n\n delete(webhookId: string, options?: RequestOptions): APIPromise<void> {\n return this._client.delete(path`/webhooks/${webhookId}`, options);\n }\n\n /** Every delivery attempt to this endpoint, newest first. */\n deliveries(\n webhookId: string,\n params?: WebhookDeliveryListParams,\n options?: RequestOptions,\n ): PagePromise<WebhookDelivery> {\n return this._client.getPage(path`/webhooks/${webhookId}/deliveries`, params, options);\n }\n\n /** Issue a new signing secret. The old one stops working immediately. */\n rollSecret(webhookId: string, options?: RequestOptions): APIPromise<IssuedWebhookEndpoint> {\n return this._client.post(path`/webhooks/${webhookId}/roll-secret`, undefined, options);\n }\n\n /** Send a signed `webhook.test` event now. Works with test keys, which emit no real events. */\n test(webhookId: string, options?: RequestOptions): APIPromise<WebhookTestResult> {\n return this._client.post(path`/webhooks/${webhookId}/test`, undefined, options);\n }\n\n /**\n * Verify a delivery's signature and parse it. Same as the standalone `verifyWebhook()`,\n * which needs no API key — prefer that in a receiver that makes no API calls.\n */\n unwrap(\n payload: string | Uint8Array,\n headers: HeadersLike,\n options: VerifyWebhookOptions,\n ): Promise<WebhookEvent> {\n return verifyWebhook(payload, headers, options);\n }\n}\n","export const VERSION = '0.2.0';\n","import { APIPromise, type APIResponse, rateLimitFrom } from './core/api-promise';\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIError,\n APIUserAbortError,\n BulkitError,\n RateLimitError,\n} from './core/errors';\nimport { PagePromise } from './core/pagination';\nimport { buildQuery, isBrowser, type Query, readEnv, sleep, uuid } from './core/utils';\nimport { Channels } from './resources/channels';\nimport { Media } from './resources/media';\nimport { Platforms } from './resources/platforms';\nimport { Posts } from './resources/posts';\nimport { Stats } from './resources/stats';\nimport { Tags } from './resources/tags';\nimport { Usage } from './resources/usage';\nimport { Webhooks } from './resources/webhooks';\nimport { VERSION } from './version';\n\nconst DEFAULT_BASE_URL = 'https://api.bulkit.io';\nconst API_PREFIX = '/public/v1';\nconst DEFAULT_TIMEOUT_MS = 60_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst INITIAL_RETRY_DELAY_MS = 500;\nconst MAX_RETRY_DELAY_MS = 8_000;\n\nexport type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\nexport interface ClientOptions {\n /** Your API key (`bk_live_…` or `bk_test_…`). Defaults to `process.env.BULKIT_API_KEY`. */\n apiKey?: string | undefined;\n /**\n * Scheme and host to send requests to. Only change this to route through a proxy or a mock\n * server. Defaults to `process.env.BULKIT_BASE_URL`, then `https://api.bulkit.io`.\n */\n baseURL?: string | undefined;\n /** Per-attempt timeout in milliseconds. Default 60 000. */\n timeout?: number | undefined;\n /** How many times to retry a retryable failure. Default 2. */\n maxRetries?: number | undefined;\n /** Headers sent with every request. */\n defaultHeaders?: Record<string, string> | undefined;\n /** A `fetch` implementation to use instead of the global one (proxies, testing, …). */\n fetch?: Fetch | undefined;\n /**\n * Your API key is a secret: shipping it to a browser hands it to every visitor.\n * Set this only if you understand that, e.g. for an internal tool.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n}\n\nexport interface RequestOptions {\n /**\n * Sent as `Idempotency-Key` on writes. The SDK generates one per call by default and\n * reuses it across its own retries; pass your own to make retries safe across processes.\n */\n idempotencyKey?: string | undefined;\n timeout?: number | undefined;\n maxRetries?: number | undefined;\n signal?: AbortSignal | undefined;\n headers?: Record<string, string> | undefined;\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\ninterface FinalRequest extends RequestOptions {\n method: Method;\n path: string;\n query?: Query | undefined;\n body?: unknown;\n}\n\n/**\n * The Bulkit API client.\n *\n * ```ts\n * import { Bulkit } from 'bulkit';\n *\n * const bulkit = new Bulkit(); // reads BULKIT_API_KEY\n * const channels = await bulkit.channels.list();\n * ```\n */\nexport class Bulkit {\n readonly channels: Channels = new Channels(this);\n readonly platforms: Platforms = new Platforms(this);\n readonly posts: Posts = new Posts(this);\n readonly media: Media = new Media(this);\n readonly tags: Tags = new Tags(this);\n readonly stats: Stats = new Stats(this);\n readonly usage: Usage = new Usage(this);\n readonly webhooks: Webhooks = new Webhooks(this);\n\n readonly baseURL: string;\n readonly timeout: number;\n readonly maxRetries: number;\n readonly #apiKey: string;\n readonly #fetch: Fetch;\n readonly #defaultHeaders: Record<string, string>;\n\n constructor(options: ClientOptions = {}) {\n const apiKey = options.apiKey ?? readEnv('BULKIT_API_KEY');\n if (!apiKey) {\n throw new BulkitError(\n 'Missing API key. Pass `apiKey` to `new Bulkit()` or set the BULKIT_API_KEY environment variable.',\n );\n }\n if (isBrowser() && !options.dangerouslyAllowBrowser) {\n throw new BulkitError(\n 'Running in a browser would expose your secret API key to every visitor. ' +\n 'Call Bulkit from your server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.',\n );\n }\n\n const baseURL = options.baseURL ?? readEnv('BULKIT_BASE_URL') ?? DEFAULT_BASE_URL;\n this.baseURL = baseURL.replace(/\\/+$/, '');\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.#apiKey = apiKey;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#defaultHeaders = options.defaultHeaders ?? {};\n }\n\n /** `true` for a `bk_test_…` key: validates like live, but publishes nothing and bills nothing. */\n get isTestMode(): boolean {\n return this.#apiKey.startsWith('bk_test_');\n }\n\n get<T>(path: string, query?: Query, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'GET', path, query, ...options });\n }\n\n post<T>(path: string, body?: unknown, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'POST', path, body, ...options });\n }\n\n put<T>(path: string, body?: unknown, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'PUT', path, body, ...options });\n }\n\n delete<T = void>(path: string, options?: RequestOptions): APIPromise<T> {\n return this.request({ method: 'DELETE', path, ...options });\n }\n\n /** @internal */\n getPage<T>(path: string, query: Query | undefined, options?: RequestOptions): PagePromise<T> {\n return new PagePromise<T>((cursor) =>\n this.request<{ data: T[]; nextCursor: string | null }>({\n method: 'GET',\n path,\n query: cursor ? { ...query, cursor } : query,\n ...options,\n }).withResponse(),\n );\n }\n\n /** @internal Fetch a non-API URL (e.g. a presigned upload URL) without credentials. */\n fetchExternal(url: string, init: RequestInit): Promise<Response> {\n return this.#fetch(url, init);\n }\n\n /** Sends a request, retrying what is safe to retry. Prefer the resource methods. */\n request<T>(req: FinalRequest): APIPromise<T> {\n return new APIPromise(this.#send<T>(req));\n }\n\n async #send<T>(req: FinalRequest): Promise<APIResponse<T>> {\n const maxRetries = req.maxRetries ?? this.maxRetries;\n const isWrite = req.method === 'POST' || req.method === 'PUT';\n // One key per logical call, reused across retries — that is what makes a retry safe.\n const idempotencyKey = isWrite ? (req.idempotencyKey ?? uuid()) : undefined;\n const url = this.baseURL + API_PREFIX + req.path + buildQuery(req.query);\n\n for (let attempt = 0; ; attempt++) {\n const retriesLeft = maxRetries - attempt;\n let response: Response;\n try {\n response = await this.#fetchWithTimeout(url, req, idempotencyKey);\n } catch (error) {\n if (error instanceof APIUserAbortError || retriesLeft <= 0) throw error;\n await sleep(retryDelay(attempt));\n continue;\n }\n\n if (response.ok) {\n return {\n data: await parseBody<T>(response),\n response,\n requestId: response.headers.get('x-request-id'),\n rateLimit: rateLimitFrom(response.headers),\n };\n }\n\n const body = await parseBody<unknown>(response).catch(() => undefined);\n const error = APIError.from(response.status, body, response.headers);\n if (retriesLeft <= 0 || !shouldRetry(error, req.method)) throw error;\n await sleep(retryDelay(attempt, error));\n }\n }\n\n async #fetchWithTimeout(\n url: string,\n req: FinalRequest,\n idempotencyKey: string | undefined,\n ): Promise<Response> {\n const timeout = req.timeout ?? this.timeout;\n const timeoutSignal = AbortSignal.timeout(timeout);\n const signal = req.signal ? AbortSignal.any([req.signal, timeoutSignal]) : timeoutSignal;\n\n const isForm = req.body instanceof FormData;\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `bulkit-node/${VERSION}`,\n ...this.#defaultHeaders,\n ...req.headers,\n Authorization: `Bearer ${this.#apiKey}`,\n };\n if (req.body !== undefined && !isForm) headers['Content-Type'] = 'application/json';\n if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;\n\n try {\n return await this.#fetch(url, {\n method: req.method,\n headers,\n body:\n req.body === undefined\n ? undefined\n : isForm\n ? (req.body as FormData)\n : JSON.stringify(req.body),\n signal,\n });\n } catch (error) {\n if (req.signal?.aborted) throw new APIUserAbortError();\n if (timeoutSignal.aborted) throw new APIConnectionTimeoutError();\n throw new APIConnectionError(undefined, { cause: error });\n }\n }\n}\n\n/**\n * What is worth retrying, per the API's contract:\n * - 429 and 409 `request_in_progress`: transient by definition.\n * - 408, 502, 503, 504: the request was not (fully) attempted.\n * - 500: only on reads. A write's idempotency key is kept on a 500, so retrying it\n * would only replay the same failure; the caller must inspect state first.\n * - 402 `quota_exceeded` and every other 4xx: retrying can never succeed.\n */\nfunction shouldRetry(error: APIError, method: Method): boolean {\n const { status } = error;\n if (status === 429 || status === 408 || status === 502 || status === 503 || status === 504) {\n return true;\n }\n if (status === 409) return error.code === 'request_in_progress';\n if (status === 500) return method === 'GET' || method === 'DELETE';\n return false;\n}\n\nfunction retryDelay(attempt: number, error?: APIError): number {\n if (error instanceof RateLimitError && error.retryAfter !== undefined) {\n return Math.min(error.retryAfter * 1000, 60_000);\n }\n const backoff = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);\n // Jitter between 75% and 100% of the backoff, so clients do not retry in lockstep.\n return backoff * (0.75 + Math.random() * 0.25);\n}\n\nasync function parseBody<T>(response: Response): Promise<T> {\n if (response.status === 204) return undefined as T;\n const text = await response.text();\n if (!text) return undefined as T;\n const type = response.headers.get('content-type') ?? '';\n return (type.includes('json') ? JSON.parse(text) : text) as T;\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,aAAb,cAAmC,QAAW;CAC5C;CAEA,YAAY,iBAA0C;EAEpD,OAAO,YAAY,QAAQ,IAAS,CAAC;EACrC,KAAK,mBAAmB;CAC1B;;CAGA,eAAwC;EACtC,OAAO,KAAK;CACd;CAEA;CACA,SAAqB;EACnB,KAAK,YAAY,KAAK,iBAAiB,MAAM,MAAM,EAAE,IAAI;EACzD,OAAO,KAAK;CACd;CAGA,KACE,aACA,YAC8B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