@pubnio/sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,331 @@
1
- # Temporary Holding Version
1
+ # PubNio SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install `@pubnio/sdk` for JavaScript and TypeScript clients that call the
4
+ PubNio HTTP API.
5
+
6
+ ```sh
7
+ bun add @pubnio/sdk
8
+ npm install @pubnio/sdk
9
+ pnpm add @pubnio/sdk
10
+ ```
11
+
12
+ The package ships ESM and CommonJS builds with TypeScript declarations for the
13
+ root client and the Solid adapter. Node 20.19 or newer is required for the
14
+ CommonJS entry.
15
+
16
+ ```ts
17
+ // ESM
18
+ import { createPubNioClient } from "@pubnio/sdk";
19
+ ```
20
+
21
+ ```ts
22
+ // CommonJS
23
+ const { createPubNioClient } = require("@pubnio/sdk");
24
+ ```
25
+
26
+ ```ts
27
+ const client = createPubNioClient({
28
+ baseUrl: "https://pubnio.com",
29
+ accessToken,
30
+ });
31
+ const { workspaces } = await client.workspaces.list();
32
+ const workspace = client.workspace(workspaces[0].id);
33
+
34
+ const { data: drafts } = await workspace.posts.list({ isDraft: true });
35
+ ```
36
+
37
+ `createPubNioClient` exposes only account-level namespaces: `me`,
38
+ `workspaces`, and `workspace(id)`. Everything scoped to a workspace hangs off
39
+ the scoped client, which reuses the parent transport, so callers never pass
40
+ `workspaceId` again.
41
+
42
+ `client.workspaces.create({ name, defaultTimezone? })` and
43
+ `client.workspaces.update(workspaceId, { name?, defaultTimezone? })` manage
44
+ workspace metadata. `defaultTimezone` starts at UTC, and a new queue without
45
+ `timezone` uses it. An explicit queue `timezone` always wins.
46
+
47
+ | Scoped namespace | Operations |
48
+ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
+ | `posts` | list, create, get, update, validate, publish, delete, attempts, retry, reconcile, wait |
50
+ | `media` | list, upload, importUrl, status, wait, get, download, delete |
51
+ | `accounts` | list, compact ready list, get, move, setEnabled, connection helpers |
52
+ | `profiles` | list, create, get, update, archive |
53
+ | `capabilities` | list, catalog, get |
54
+ | `limits` | get |
55
+ | `apiKeys` | create, list, get, update, revoke |
56
+ | `webhooks` | create, list, get, update, delete, test, deliveries, replay |
57
+ | `queues` | list, create, get, update, archive, slots, next, preview, skips, blackouts; create/update accept `isDefault`; create defaults `timezone` to the workspace default |
58
+ | `schedule` | list, iterateRange, change, skipToNext |
59
+ | `analytics` | post, series, accounts, account, capabilities, refresh |
60
+ | `inbox` | conversations, messages, comments, mentions, capabilities, sync |
61
+
62
+ `accounts` maps to the `/api/v1/integrations` routes. `Account` and
63
+ `AccountId` are exported aliases for the `ProviderAccount` wire schema and its
64
+ identifier.
65
+
66
+ Identifiers such as `PostId`, `TargetId`, `AttemptId`, `AccountId`, `MediaId`,
67
+ and `WorkspaceId` are branded UUID strings. Encoded values and the OpenAPI
68
+ document stay plain UUID strings.
69
+
70
+ Pass the PubNio origin as `baseUrl`. External clients supply a WorkOS access
71
+ token. A browser on the PubNio origin can use its session cookie by omitting
72
+ `accessToken`. Requests rejected by the API throw `PubNioError`, which exposes
73
+ `status`, `problem`, `requestId`, `isProblem(type)`, `code`, `param`,
74
+ `nextAction`, `candidates`, `currentRevision`, `currentAttemptId`,
75
+ `retryable`, and `idempotencyKey`.
76
+
77
+ ```ts
78
+ import { PubNioError } from "@pubnio/sdk";
79
+
80
+ try {
81
+ await workspace.posts.create({ text: "Launch day", platforms: ["x"] });
82
+ } catch (error) {
83
+ if (error instanceof PubNioError) {
84
+ console.error(error.code, error.status, error.requestId);
85
+ console.error(error.param, error.nextAction, error.candidates);
86
+ }
87
+ }
88
+ ```
89
+
90
+ `code` is stable and machine-readable. `param` names the offending field,
91
+ `nextAction` says how to recover, and `candidates` carries account choices when
92
+ a lookup is ambiguous. A failed mutation keeps its generated
93
+ `idempotencyKey` on the error.
94
+
95
+ `accounts.list({ ready: true })` returns compact ready account rows and never
96
+ includes ad accounts. `capabilities.get()` and `limits.get()` return the
97
+ provider catalog and documented budgets behind `GET /api/v1/capabilities` and
98
+ `GET /api/v1/limits`.
99
+
100
+ ## Transport
101
+
102
+ ```ts
103
+ const client = createPubNioClient({
104
+ baseUrl: "https://pubnio.com",
105
+ timeoutMs: 60_000, // per request; 0 disables; max 3,600,000
106
+ retries: 2, // safe requests only; 0 disables
107
+ signal: abortController.signal,
108
+ headers: { "x-trace-id": traceId },
109
+ clientName: "cli",
110
+ clientVersion: "1.2.3",
111
+ });
112
+ ```
113
+
114
+ Every request sends `x-pubnio-client: <name>/<version>`; the default is
115
+ `sdk/<package version>`. Media upload requests default to five minutes per part
116
+ and accept `timeoutMs` and `signal` in their options.
117
+
118
+ Every request also sends `PubNio-Version` with the API version the SDK was
119
+ built against. The current value is exported as `currentApiVersion`
120
+ (`2026-12-02`) and every accepted value is exported as `supportedApiVersions`.
121
+ The SDK overrides a caller-supplied version so a client always uses its own
122
+ contract. An unsupported-version `PubNioError` exposes `supportedVersions` and
123
+ `nextAction` alongside `code`.
124
+
125
+ ### Retries
126
+
127
+ GET and HEAD requests retry twice with exponential backoff. Mutations retry
128
+ only when they carry an `Idempotency-Key`, so an ambiguous transport failure
129
+ never duplicates an unsafe write. A `429` or `503` response is delayed by the
130
+ later of the backoff and its `Retry-After` header. Timeouts, client signals,
131
+ and operation signals stop the retry loop immediately.
132
+
133
+ The SDK never retries unsafe writes, even when the failure looks transient. If
134
+ a write fails with `retryable: true` and has no `idempotencyKey`, read the
135
+ resource before deciding whether to try again.
136
+
137
+ ### Auto-pagination
138
+
139
+ Every cursor list has an `iterate` method that reads pages for you and yields
140
+ rows. Filters stay applied on every page; do not append `nextCursor` yourself.
141
+
142
+ ```ts
143
+ for await (const post of workspace.posts.iterate({
144
+ isDraft: true,
145
+ limit: 50,
146
+ })) {
147
+ console.log(post.postId, post.textPreview);
148
+ }
149
+ ```
150
+
151
+ The schedule range uses the same envelope. Pass inclusive ISO instants no more
152
+ than 90 days apart and optional `accountId` or `queueId` filters:
153
+
154
+ ```ts
155
+ const range = await workspace.schedule.list({
156
+ from: "2026-12-01T00:00:00Z",
157
+ to: "2026-12-31T23:59:59Z",
158
+ });
159
+ for await (const entry of workspace.schedule.iterateRange({ from, to }))
160
+ console.log(entry.scheduledFor, entry.status, entry.textPreview);
161
+ ```
162
+
163
+ `schedule.skipToNext` moves one queue-assigned target to the next free
164
+ occurrence after its current scheduled time. It uses the target's queue and
165
+ attempt unless `queueId` or `expectedAttemptId` is given:
166
+
167
+ ```ts
168
+ const skipped = await workspace.schedule.skipToNext(postId, targetId);
169
+ if (skipped.skipped) console.log(skipped.result.scheduledAt);
170
+ else console.log("no slot before", skipped.horizonEndsAt);
171
+ ```
172
+
173
+ A target with no queue rejects with a `schedule_required` problem
174
+ (`param: "queueId"`); use `schedule.change` with an explicit `scheduledAt`
175
+ instead, or pass a queue. An empty horizon returns `skipped: false` without a
176
+ write.
177
+
178
+ The generic helpers are exported too: `iterateItems(fetchPage, options)` yields
179
+ rows and `iteratePages(fetchPage, options)` yields the raw
180
+ `{ data, hasMore, nextCursor }` envelope. A repeated cursor throws instead of
181
+ looping. Use `{ signal, maxPages }` as the second argument to bound work.
182
+
183
+ Lists with parameters use the same pattern: `media.iterate`,
184
+ `profiles.iterate`, `apiKeys.iterate`, `webhooks.iterate`,
185
+ `webhooks.iterateDeliveries`, `queues.iterate`, `schedule.iterateRange`,
186
+ `analytics.iterateAccounts`,
187
+ `inbox.iterateConversations`, and the `ads.iterate*` methods for accounts,
188
+ campaigns, creatives, insights, and the ad tree.
189
+
190
+ ## Mutations and waits
191
+
192
+ ```ts
193
+ // One call: derive the account, provider, and placement.
194
+ const accepted = await workspace.posts.create({
195
+ text: "Launch day",
196
+ platforms: ["x"],
197
+ idempotencyKey,
198
+ });
199
+ accepted.idempotencyKey; // resolved key
200
+ accepted.targets; // accepted status per destination
201
+ accepted.warnings; // non-blocking issues
202
+ accepted.billing; // estimated cost and included quota
203
+
204
+ // Exact destinations remain available.
205
+ await workspace.posts.create({ text, targets, idempotencyKey });
206
+ await workspace.media.importUrl(url, { idempotencyKey });
207
+
208
+ // Advanced: save a draft, validate it, and publish the saved revision.
209
+ const draft = await workspace.posts.create({
210
+ isDraft: true,
211
+ text,
212
+ targets,
213
+ });
214
+ const validation = await workspace.posts.validate(draft.postId);
215
+ if (!validation.canPublish) throw new Error(JSON.stringify(validation.errors));
216
+ const published = await workspace.posts.publish(draft.postId, {
217
+ expectedRevision: draft.revision,
218
+ idempotencyKey, // optional; generated when omitted
219
+ });
220
+ published.idempotencyKey; // resolved key
221
+
222
+ const { settled, post } = await workspace.posts.wait(postId, {
223
+ timeoutMs: 60_000,
224
+ signal,
225
+ });
226
+
227
+ const intake = await workspace.media.wait(mediaId, { timeoutMs: 300_000 });
228
+ if (intake.status === "ready") console.log(intake.asset?.mediaId);
229
+ ```
230
+
231
+ Publish, post creation, and media import generate `crypto.randomUUID()` when no
232
+ key is provided, send it as `Idempotency-Key`, return it, and attach it to a
233
+ failed `PubNioError` so an ambiguous transport failure can be retried safely.
234
+ `retryable` is a signal, not automatic retry.
235
+
236
+ A draft reports `draft` until it is submitted. Delivery targets and posts then
237
+ share one status: `scheduled`, `queued`, `submitting`, `confirming`,
238
+ `published`, `provider_draft`, `failed`, `unresolved`, or `cancelled`. A
239
+ target always reports `canRetry` and `canReconcile`; failed and unresolved
240
+ targets add `nextAction`. Confirmed targets include
241
+ `providerRef: { id, kind }` and an optional `url`.
242
+
243
+ ## Webhooks
244
+
245
+ Verify the raw body before decoding it. `verifyWebhookSignature` implements
246
+ Standard Webhooks HMAC-SHA256, a five-minute timestamp tolerance, and a
247
+ constant-time signature comparison, then returns the decoded event. It never
248
+ logs the secret or the raw body.
249
+
250
+ ```ts
251
+ import { verifyWebhookSignature } from "@pubnio/sdk";
252
+
253
+ const event = await verifyWebhookSignature({
254
+ secret: process.env.PUBNIO_WEBHOOK_SECRET,
255
+ body: rawBody, // the exact bytes or string received, before JSON.parse
256
+ headers: request.headers,
257
+ toleranceSeconds: 300, // default; 0 disables the timestamp check
258
+ });
259
+ console.log(event.id, event.type);
260
+ ```
261
+
262
+ Failures throw `WebhookVerificationError` with a `reason`
263
+ (`missing_headers`, `invalid_secret`, `invalid_signature`,
264
+ `stale_timestamp`, or `invalid_payload`) and a `code` such as
265
+ `webhook_invalid_signature`. Deliveries are at least once: deduplicate by
266
+ `event.id` and apply each event to its stated attempt. `decodeWebhookEvent`
267
+ remains available when you verify signatures yourself.
268
+
269
+ A workspace owner can inspect and replay deliveries:
270
+
271
+ ```ts
272
+ const { data: deliveries } = await workspace.webhooks.listDeliveries(
273
+ endpointId,
274
+ { limit: 50 },
275
+ );
276
+
277
+ const replayed = await workspace.webhooks.replayDelivery(
278
+ endpointId,
279
+ deliveries[0].id,
280
+ );
281
+ console.log(replayed.status, replayed.attemptCount); // pending 0
282
+
283
+ // Auto-paginate instead of passing cursors.
284
+ for await (const delivery of workspace.webhooks.iterateDeliveries(endpointId)) {
285
+ console.log(delivery.id, delivery.status);
286
+ }
287
+ ```
288
+
289
+ Only `delivered`, `failed`, and `cancelled` deliveries can be replayed.
290
+ Replaying a pending or sending delivery throws `PubNioError` with
291
+ `code: "webhook_delivery_not_replayable"` and `nextAction`; read the delivery
292
+ until it settles, then replay again. Replay requires a human workspace owner,
293
+ so workspace members and API keys receive `403`.
294
+
295
+ ## Solid Query
296
+
297
+ Use `@pubnio/sdk/solid` with `@tanstack/solid-query` v6 in a Solid 2 app.
298
+ The helpers take the scoped client, so query keys include its workspace ID.
299
+
300
+ ```ts
301
+ import { useMutation, useQuery } from "@tanstack/solid-query";
302
+ import {
303
+ accountsListOptions,
304
+ postsCreateMutation,
305
+ postsListOptions,
306
+ } from "@pubnio/sdk/solid";
307
+
308
+ const workspace = client.workspace(workspaceId);
309
+ const drafts = useQuery(() => postsListOptions(workspace, { isDraft: true }));
310
+ const createDraft = useMutation(() => postsCreateMutation(workspace));
311
+ const accounts = useQuery(() => accountsListOptions(workspace));
312
+ ```
313
+
314
+ `workspacesListOptions(client)` lists the available workspaces.
315
+
316
+ ## Generation
317
+
318
+ The low-level client is generated from `PubNioApi` with `bun run sdk:generate`
319
+ and wrapped by `src/index.ts`. See [SDK generation](../../docs/sdk-generation.md)
320
+ for the Forge evaluation and the decision to keep the current generator.
321
+
322
+ ## Package from the monorepo
323
+
324
+ Run `bun run sdk:pack` from the repository root. It checks the generated public
325
+ client, builds ESM and CommonJS with declarations, and writes
326
+ `dist/npm/pubnio-sdk-<version>.tgz`. The packed manifest has no `private` flag,
327
+ publishes at public access, and exports the root and `@pubnio/sdk/solid`.
328
+
329
+ Install that tarball in a fresh npm project and check the entry points with Node
330
+ and TypeScript before publishing it. The SDK test suite also packs the tarball
331
+ and verifies ESM import, CommonJS require, and declarations.