@zerodot/buffer 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1746 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let zod = require("zod");
3
+ let _zerodot_node_sdk = require("@zerodot/node-sdk");
4
+ // src/api.ts
5
+ const BUFFER_CREDENTIAL = "buffer.apiKey";
6
+ /** The most items that "return all" collects. A node output has a size limit too. */
7
+ const MAX_ITEMS = 5e3;
8
+ /** The most items that Buffer gives in one page. */
9
+ const PAGE_SIZE = 100;
10
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
11
+ /** The token and the API address of a Buffer credential. */
12
+ function bufferAccess(credential) {
13
+ if (!credential || credential.type !== "buffer.apiKey") throw new Error("The node needs a Buffer credential");
14
+ const token = text(credential.data.apiKey);
15
+ if (!token) throw new Error("The credential has no \"apiKey\"");
16
+ return {
17
+ token,
18
+ baseUrl: (text(credential.data.server) ?? "https://api.buffer.com").replace(/\/+$/, "")
19
+ };
20
+ }
21
+ /** The value at a path with dots, for example `account.organizations`. */
22
+ function at(data, path) {
23
+ let value = data;
24
+ for (const key of path.split(".")) {
25
+ if (typeof value !== "object" || value === null) return void 0;
26
+ value = value[key];
27
+ }
28
+ return value;
29
+ }
30
+ /** One call. Returns `data`. The error text never has the token. */
31
+ async function callBuffer(access, request, options) {
32
+ const response = await fetch(access.baseUrl, {
33
+ method: "POST",
34
+ headers: {
35
+ authorization: `Bearer ${access.token}`,
36
+ accept: "application/json",
37
+ "content-type": "application/json",
38
+ "user-agent": "zerodot"
39
+ },
40
+ body: JSON.stringify({
41
+ query: request.query,
42
+ variables: request.variables ?? {}
43
+ }),
44
+ redirect: "error",
45
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
46
+ });
47
+ const answer = await response.json().catch(() => null);
48
+ if (!response.ok || answer?.errors && answer.errors.length > 0) {
49
+ const message = answer?.errors?.map((error) => error.message).filter(Boolean).join("; ") || "no message";
50
+ const hint = response.status === 401 ? " Check the API key." : response.status === 429 ? " The rate limit is reached. Try again later." : "";
51
+ throw new Error(`Buffer request failed (${response.status}): ${message}.${hint}`);
52
+ }
53
+ if (!answer?.data) throw new Error("Buffer sent no data");
54
+ return answer.data;
55
+ }
56
+ /**
57
+ * Buffer answers a mutation error with HTTP 200 and an object in `data` that has a `message`.
58
+ * Every mutation asks for `... on MutationError { message }`, so a typed error has a message.
59
+ */
60
+ function throwTypedError(value) {
61
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
62
+ const record = value;
63
+ if (typeof record.message !== "string") return;
64
+ const details = Array.isArray(record.errors) ? record.errors.map((error) => error?.message).filter((message) => typeof message === "string") : [];
65
+ const kind = typeof record.__typename === "string" ? ` (${record.__typename})` : "";
66
+ throw new Error(`Buffer refused the request${kind}: ${[record.message, ...details].join("; ")}`);
67
+ }
68
+ /** A list. Follows the cursors until it has `limit` items, or all items when `limit` is null. */
69
+ async function callBufferList(access, request, limit, options) {
70
+ const wanted = Math.min(limit ?? 5e3, MAX_ITEMS);
71
+ const items = [];
72
+ let after = null;
73
+ while (items.length < wanted) {
74
+ const page = at(await callBuffer(access, {
75
+ query: request.query,
76
+ variables: {
77
+ ...request.variables,
78
+ first: Math.min(PAGE_SIZE, wanted - items.length),
79
+ after
80
+ }
81
+ }, options), request.result);
82
+ if (!page || !Array.isArray(page.edges)) throw new Error(`Buffer sent no list for "${request.result}"`);
83
+ for (const edge of page.edges) items.push(edge.node);
84
+ if (!page.pageInfo?.hasNextPage || !page.pageInfo.endCursor) break;
85
+ after = page.pageInfo.endCursor;
86
+ }
87
+ return items.slice(0, wanted);
88
+ }
89
+ // src/icon.ts
90
+ const BUFFER_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../buffer.svg");
91
+ // src/credential.ts
92
+ const TIMEOUT_MS = 1e4;
93
+ /** Checks the key with a cheap read of the account. */
94
+ async function check({ type, data }) {
95
+ const access = bufferAccess({
96
+ type,
97
+ data
98
+ });
99
+ const response = await fetch(access.baseUrl, {
100
+ method: "POST",
101
+ headers: {
102
+ authorization: `Bearer ${access.token}`,
103
+ accept: "application/json",
104
+ "content-type": "application/json",
105
+ "user-agent": "zerodot"
106
+ },
107
+ body: JSON.stringify({ query: "query { account { id } }" }),
108
+ redirect: "error",
109
+ signal: AbortSignal.timeout(TIMEOUT_MS)
110
+ });
111
+ if (response.status === 401) throw new Error("Buffer did not accept the API key");
112
+ if (!response.ok) throw new Error(`Buffer answered with status ${response.status}`);
113
+ const answer = await response.json().catch(() => null);
114
+ if (answer?.errors?.length) throw new Error(`Buffer refused the API key: ${answer.errors[0]?.message ?? "no message"}`);
115
+ }
116
+ const bufferCredential = {
117
+ type: BUFFER_CREDENTIAL,
118
+ label: "Buffer API key",
119
+ fields: zod.z.object({
120
+ apiKey: zod.z.string().min(1).meta({
121
+ title: "API Key",
122
+ description: "Make a key in Buffer: Settings > API. An OAuth access token also works"
123
+ }),
124
+ /** The API address, for a test server. Empty means the Buffer cloud. */
125
+ server: zod.z.url().optional().meta({ placeholder: "https://api.buffer.com" })
126
+ }),
127
+ secretFields: ["apiKey"],
128
+ icon: "Key01Icon",
129
+ iconUrl: BUFFER_ICON,
130
+ test: check
131
+ };
132
+ // src/config.ts
133
+ const RESOURCES = [
134
+ "account",
135
+ "organization",
136
+ "channel",
137
+ "post",
138
+ "idea",
139
+ "tag",
140
+ "contentItem",
141
+ "note",
142
+ "teamMember",
143
+ "snippet",
144
+ "template",
145
+ "asset",
146
+ "pinterestBoard",
147
+ "instagramAudio"
148
+ ];
149
+ const OPERATIONS_OF = {
150
+ account: ["get"],
151
+ organization: ["getAll", "getConfiguration"],
152
+ channel: [
153
+ "get",
154
+ "getAll",
155
+ "getDailyPostingLimits",
156
+ "shortenLink"
157
+ ],
158
+ post: [
159
+ "create",
160
+ "get",
161
+ "getAll",
162
+ "update",
163
+ "delete",
164
+ "publishNow",
165
+ "moveInQueue",
166
+ "getAggregatedMetrics"
167
+ ],
168
+ idea: [
169
+ "create",
170
+ "getAll",
171
+ "getGroups"
172
+ ],
173
+ tag: [
174
+ "create",
175
+ "get",
176
+ "getAll",
177
+ "update",
178
+ "delete"
179
+ ],
180
+ contentItem: [
181
+ "create",
182
+ "createDraft",
183
+ "get",
184
+ "getAll",
185
+ "update",
186
+ "updateDraft",
187
+ "promoteDraft",
188
+ "delete",
189
+ "addPost",
190
+ "removePost"
191
+ ],
192
+ note: [
193
+ "create",
194
+ "getAll",
195
+ "update",
196
+ "delete"
197
+ ],
198
+ teamMember: ["getAll"],
199
+ snippet: [
200
+ "create",
201
+ "getAll",
202
+ "update",
203
+ "delete"
204
+ ],
205
+ template: [
206
+ "create",
207
+ "get",
208
+ "getAll",
209
+ "update",
210
+ "delete"
211
+ ],
212
+ asset: ["getAll"],
213
+ pinterestBoard: ["create", "refresh"],
214
+ instagramAudio: [
215
+ "get",
216
+ "search",
217
+ "getTrending",
218
+ "getCatalog",
219
+ "searchCatalog"
220
+ ]
221
+ };
222
+ const ALL_OPERATIONS = [...new Set(Object.values(OPERATIONS_OF).flat())];
223
+ const SHARE_MODES = [
224
+ "addToQueue",
225
+ "shareNext",
226
+ "shareNow",
227
+ "customScheduled"
228
+ ];
229
+ const SCHEDULING_TYPES = ["automatic", "notification"];
230
+ const POST_STATUSES = [
231
+ "draft",
232
+ "needs_approval",
233
+ "scheduled",
234
+ "sending",
235
+ "sent",
236
+ "error"
237
+ ];
238
+ /** Show a field only for these operations of these resources. */
239
+ const on = (resources, ...operations) => ({ showWhen: {
240
+ resource: Array.isArray(resources) ? resources : [resources],
241
+ operation: operations
242
+ } });
243
+ /** The operations that need an organization ID. */
244
+ const ORGANIZATION_OPERATIONS = [
245
+ {
246
+ resource: "organization",
247
+ operations: ["getConfiguration"]
248
+ },
249
+ {
250
+ resource: "channel",
251
+ operations: ["getAll"]
252
+ },
253
+ {
254
+ resource: "post",
255
+ operations: ["getAll", "getAggregatedMetrics"]
256
+ },
257
+ {
258
+ resource: "idea",
259
+ operations: [
260
+ "create",
261
+ "getAll",
262
+ "getGroups"
263
+ ]
264
+ },
265
+ {
266
+ resource: "tag",
267
+ operations: ["create", "getAll"]
268
+ },
269
+ {
270
+ resource: "contentItem",
271
+ operations: [
272
+ "create",
273
+ "createDraft",
274
+ "getAll"
275
+ ]
276
+ },
277
+ {
278
+ resource: "teamMember",
279
+ operations: ["getAll"]
280
+ },
281
+ {
282
+ resource: "snippet",
283
+ operations: [
284
+ "create",
285
+ "getAll",
286
+ "update",
287
+ "delete"
288
+ ]
289
+ },
290
+ {
291
+ resource: "template",
292
+ operations: ["create", "getAll"]
293
+ },
294
+ {
295
+ resource: "asset",
296
+ operations: ["getAll"]
297
+ }
298
+ ];
299
+ /** The operations that return a list with cursors. */
300
+ const LIST_OPERATIONS = [
301
+ ["post", "getAll"],
302
+ ["idea", "getAll"],
303
+ ["tag", "getAll"],
304
+ ["contentItem", "getAll"],
305
+ ["note", "getAll"],
306
+ ["teamMember", "getAll"],
307
+ ["snippet", "getAll"],
308
+ ["template", "getAll"],
309
+ ["asset", "getAll"]
310
+ ];
311
+ const bufferConfig = zod.z.object({
312
+ resource: zod.z.enum(RESOURCES).default("post").meta({
313
+ labels: {
314
+ account: "Account",
315
+ organization: "Organization",
316
+ channel: "Channel",
317
+ post: "Post",
318
+ idea: "Idea",
319
+ tag: "Tag",
320
+ contentItem: "Content Item",
321
+ note: "Note",
322
+ teamMember: "Team Member",
323
+ snippet: "Snippet",
324
+ template: "Post Template",
325
+ asset: "Asset",
326
+ pinterestBoard: "Pinterest Board",
327
+ instagramAudio: "Instagram Audio"
328
+ },
329
+ hints: {
330
+ account: "Get the account of the API key",
331
+ organization: "Get organizations and their settings",
332
+ channel: "Get connected social channels, limits, and short links",
333
+ post: "Create, schedule, change, publish, and delete posts, and read metrics",
334
+ idea: "Save content ideas before they go to a channel",
335
+ tag: "Label posts and ideas",
336
+ contentItem: "Make posts for many channels in one call, or keep a draft",
337
+ note: "Notes on a post or a content item",
338
+ teamMember: "Find team members for Note mentions",
339
+ snippet: "Saved sets of hashtags",
340
+ template: "Reusable post templates",
341
+ asset: "Read uploaded assets of an organization",
342
+ pinterestBoard: "Make or refresh boards of a Pinterest channel",
343
+ instagramAudio: "Find music and sounds for Instagram Reels"
344
+ }
345
+ }),
346
+ operation: zod.z.enum(ALL_OPERATIONS).default("getAll").meta({
347
+ labels: {
348
+ get: "Get",
349
+ getAll: "Get Many",
350
+ create: "Create",
351
+ update: "Update",
352
+ delete: "Delete",
353
+ getConfiguration: "Get Configuration",
354
+ getDailyPostingLimits: "Get Daily Posting Limits",
355
+ shortenLink: "Shorten Link",
356
+ publishNow: "Publish Now",
357
+ moveInQueue: "Move In Queue",
358
+ getAggregatedMetrics: "Get Aggregated Metrics",
359
+ getGroups: "Get Groups",
360
+ createDraft: "Create Draft",
361
+ updateDraft: "Update Draft",
362
+ promoteDraft: "Promote Draft To Posts",
363
+ addPost: "Add Post",
364
+ removePost: "Remove Post",
365
+ refresh: "Refresh",
366
+ search: "Search",
367
+ getTrending: "Get Trending",
368
+ getCatalog: "Get Catalog",
369
+ searchCatalog: "Search Catalog"
370
+ },
371
+ hints: {
372
+ get: "Get one item",
373
+ getAll: "Get all items, or use filters",
374
+ create: "Create a new item",
375
+ update: "Change an item",
376
+ delete: "Delete an item",
377
+ getConfiguration: "Get the channels and the capabilities of each service",
378
+ getDailyPostingLimits: "Check if channels reached the posting limit",
379
+ shortenLink: "Shorten a link with the link shortener of a channel",
380
+ publishNow: "Send a post now, with no queue",
381
+ moveInQueue: "Move a queued post to the top or the bottom of the queue",
382
+ getAggregatedMetrics: "Add up post metrics for a date range",
383
+ getGroups: "Get the idea groups of an organization",
384
+ createDraft: "Make a content item that holds a draft with no channel",
385
+ updateDraft: "Replace the draft of a content item",
386
+ promoteDraft: "Turn the draft into posts for channels",
387
+ addPost: "Add a post that exists to a content item",
388
+ removePost: "Remove a post from a content item. The post stays",
389
+ refresh: "Read the boards again from Pinterest",
390
+ search: "Find audio by text",
391
+ getTrending: "Get trending audio",
392
+ getCatalog: "Get trending music and original sounds",
393
+ searchCatalog: "Find music and original sounds by text"
394
+ }
395
+ }),
396
+ organizationId: zod.z.string().optional().meta({
397
+ title: "Organization ID",
398
+ showWhen: {
399
+ resource: [...new Set(ORGANIZATION_OPERATIONS.map((entry) => entry.resource))],
400
+ operation: [...new Set(ORGANIZATION_OPERATIONS.flatMap((entry) => entry.operations))]
401
+ },
402
+ description: "Use Organization Get Many to find the ID"
403
+ }),
404
+ channelId: zod.z.string().optional().meta({
405
+ title: "Channel ID",
406
+ showWhen: {
407
+ resource: [
408
+ "channel",
409
+ "post",
410
+ "pinterestBoard",
411
+ "instagramAudio",
412
+ "teamMember"
413
+ ],
414
+ operation: [
415
+ "get",
416
+ "shortenLink",
417
+ "create",
418
+ "refresh",
419
+ "search",
420
+ "getTrending",
421
+ "getCatalog",
422
+ "searchCatalog",
423
+ "getAll"
424
+ ]
425
+ },
426
+ description: "The channel. For Team Member it is optional: the members that can read Notes of the channel. Empty means the organization"
427
+ }),
428
+ channelIds: zod.z.string().optional().meta({
429
+ title: "Channel IDs",
430
+ ...on(["channel", "post"], "getDailyPostingLimits", "getAll", "getAggregatedMetrics"),
431
+ description: "IDs with commas between. For posts, empty means all channels"
432
+ }),
433
+ postId: zod.z.string().optional().meta({
434
+ title: "Post ID",
435
+ showWhen: {
436
+ resource: [
437
+ "post",
438
+ "note",
439
+ "contentItem"
440
+ ],
441
+ operation: [
442
+ "get",
443
+ "update",
444
+ "delete",
445
+ "publishNow",
446
+ "moveInQueue",
447
+ "create",
448
+ "getAll",
449
+ "addPost",
450
+ "removePost"
451
+ ]
452
+ },
453
+ description: "For a Note, set the Post ID or the Content Item ID"
454
+ }),
455
+ contentItemId: zod.z.string().optional().meta({
456
+ title: "Content Item ID",
457
+ showWhen: {
458
+ resource: ["contentItem", "note"],
459
+ operation: [
460
+ "get",
461
+ "update",
462
+ "updateDraft",
463
+ "promoteDraft",
464
+ "delete",
465
+ "addPost",
466
+ "removePost",
467
+ "create",
468
+ "getAll"
469
+ ]
470
+ }
471
+ }),
472
+ noteId: zod.z.string().optional().meta({
473
+ ...on("note", "update", "delete"),
474
+ title: "Note ID"
475
+ }),
476
+ tagId: zod.z.string().optional().meta({
477
+ ...on("tag", "get", "update", "delete"),
478
+ title: "Tag ID"
479
+ }),
480
+ snippetId: zod.z.string().optional().meta({
481
+ ...on("snippet", "update", "delete"),
482
+ title: "Snippet ID"
483
+ }),
484
+ templateId: zod.z.string().optional().meta({
485
+ ...on("template", "get", "update", "delete"),
486
+ title: "Template ID"
487
+ }),
488
+ ideaId: zod.z.string().optional().meta({
489
+ ...on("post", "create", "update"),
490
+ title: "Idea ID",
491
+ description: "Set when the post comes from an idea"
492
+ }),
493
+ draftId: zod.z.string().optional().meta({
494
+ ...on("post", "create", "update"),
495
+ title: "Draft ID",
496
+ description: "Set when the post comes from a draft"
497
+ }),
498
+ tagIds: zod.z.string().optional().meta({
499
+ title: "Tag IDs",
500
+ showWhen: {
501
+ resource: [
502
+ "post",
503
+ "contentItem",
504
+ "idea"
505
+ ],
506
+ operation: [
507
+ "create",
508
+ "update",
509
+ "createDraft",
510
+ "updateDraft",
511
+ "promoteDraft",
512
+ "getAll",
513
+ "getAggregatedMetrics"
514
+ ]
515
+ },
516
+ description: "IDs with commas between. For a list, only items with one of the tags. On update, an empty value keeps the tags of the post"
517
+ }),
518
+ assetIds: zod.z.string().optional().meta({
519
+ ...on("asset", "getAll"),
520
+ title: "Asset IDs",
521
+ description: "IDs with commas between. From 1 to 100 IDs"
522
+ }),
523
+ text: zod.z.string().optional().meta({
524
+ ui: "textarea",
525
+ showWhen: {
526
+ resource: [
527
+ "post",
528
+ "contentItem",
529
+ "idea",
530
+ "note",
531
+ "snippet"
532
+ ],
533
+ operation: [
534
+ "create",
535
+ "update",
536
+ "createDraft",
537
+ "updateDraft"
538
+ ]
539
+ },
540
+ description: "The text. For a snippet, the hashtags"
541
+ }),
542
+ title: zod.z.string().optional().meta({ showWhen: {
543
+ resource: [
544
+ "contentItem",
545
+ "idea",
546
+ "template"
547
+ ],
548
+ operation: [
549
+ "create",
550
+ "update",
551
+ "createDraft"
552
+ ]
553
+ } }),
554
+ name: zod.z.string().optional().meta({ showWhen: {
555
+ resource: [
556
+ "tag",
557
+ "snippet",
558
+ "pinterestBoard"
559
+ ],
560
+ operation: ["create", "update"]
561
+ } }),
562
+ color: zod.z.string().optional().meta({
563
+ ...on("tag", "create", "update"),
564
+ placeholder: "#F523F1",
565
+ description: "A hex triplet: # and six hex digits"
566
+ }),
567
+ description: zod.z.string().optional().meta({ ...on(["pinterestBoard", "template"], "create", "update") }),
568
+ emoji: zod.z.string().optional().meta({ ...on("template", "create", "update") }),
569
+ body: zod.z.string().optional().meta({
570
+ ...on("template", "create", "update"),
571
+ ui: "textarea",
572
+ description: "The template text. It can have {{placeholders}}"
573
+ }),
574
+ visibility: zod.z.enum(["private", "internal"]).optional().meta({
575
+ ...on("template", "create", "update", "getAll"),
576
+ labels: {
577
+ private: "Private",
578
+ internal: "Internal"
579
+ },
580
+ hints: {
581
+ private: "Only you can use the template",
582
+ internal: "All members of the organization can use the template"
583
+ },
584
+ description: "Create: empty means Private"
585
+ }),
586
+ url: zod.z.string().optional().meta({
587
+ ...on("channel", "shortenLink"),
588
+ title: "URL"
589
+ }),
590
+ services: zod.z.string().optional().meta({
591
+ ...on("idea", "create"),
592
+ description: "Services with commas between, for example instagram,linkedin. The idea is for these services"
593
+ }),
594
+ imageUrls: zod.z.string().optional().meta({
595
+ ...on([
596
+ "post",
597
+ "contentItem",
598
+ "idea"
599
+ ], "create", "update", "createDraft", "updateDraft"),
600
+ title: "Image URLs",
601
+ ui: "textarea",
602
+ description: "URLs with commas or new lines between. Buffer does not host files: the URLs must be public. Not used if Assets (JSON) is set"
603
+ }),
604
+ videoUrl: zod.z.string().optional().meta({
605
+ ...on(["post", "contentItem"], "create", "update", "createDraft", "updateDraft"),
606
+ title: "Video URL",
607
+ description: "A public URL of a video. Not used if Assets (JSON) is set"
608
+ }),
609
+ assets: zod.z.string().optional().meta({
610
+ ...on(["post", "contentItem"], "create", "update", "createDraft", "updateDraft"),
611
+ title: "Assets (JSON)",
612
+ ui: "code",
613
+ placeholder: "[{\"image\":{\"url\":\"https://example.com/a.jpg\"}}]",
614
+ description: "A JSON array of assets. Each entry has one of image, video, or document. On update, an empty array removes all assets"
615
+ }),
616
+ metadata: zod.z.string().optional().meta({
617
+ ...on("post", "create", "update"),
618
+ title: "Metadata (JSON)",
619
+ ui: "code",
620
+ placeholder: "{\"instagram\":{\"type\":\"post\",\"shouldShareToFeed\":true}}",
621
+ description: "A JSON object for options of one network, for example instagram, facebook, youtube, pinterest, or a thread for twitter"
622
+ }),
623
+ posts: zod.z.string().optional().meta({
624
+ ...on("contentItem", "create", "promoteDraft"),
625
+ title: "Posts (JSON)",
626
+ ui: "code",
627
+ placeholder: "[{\"channelId\":\"…\",\"text\":\"…\",\"schedulingType\":\"automatic\",\"mode\":\"addToQueue\"}]",
628
+ description: "A JSON array of posts, one for each channel. Each entry is a Buffer CreatePostInput"
629
+ }),
630
+ aiAssisted: zod.z.boolean().default(false).meta({
631
+ ...on([
632
+ "post",
633
+ "contentItem",
634
+ "idea"
635
+ ], "create", "update", "createDraft", "updateDraft"),
636
+ title: "AI Assisted",
637
+ description: "Turn on if AI helped to write the content"
638
+ }),
639
+ additionalInput: zod.z.string().optional().meta({
640
+ ui: "code",
641
+ title: "Additional Input (JSON)",
642
+ placeholder: "{\"source\":\"zerodot\"}",
643
+ description: "A JSON object. Its fields go into the input of the Buffer call and replace fields that are set above. Use it for fields that this node has no field for",
644
+ showWhen: {
645
+ resource: [
646
+ "post",
647
+ "idea",
648
+ "tag",
649
+ "contentItem",
650
+ "note",
651
+ "snippet",
652
+ "template",
653
+ "pinterestBoard"
654
+ ],
655
+ operation: [
656
+ "create",
657
+ "update",
658
+ "createDraft",
659
+ "updateDraft",
660
+ "promoteDraft",
661
+ "getAll",
662
+ "refresh"
663
+ ]
664
+ }
665
+ }),
666
+ mode: zod.z.enum(SHARE_MODES).optional().meta({
667
+ ...on("post", "create", "update"),
668
+ title: "Mode",
669
+ labels: {
670
+ addToQueue: "Add To Queue",
671
+ shareNext: "Share Next",
672
+ shareNow: "Share Now",
673
+ customScheduled: "Custom Scheduled"
674
+ },
675
+ hints: {
676
+ addToQueue: "The next free slot of the posting schedule",
677
+ shareNext: "The next slot, before other posts in the queue",
678
+ shareNow: "Send the post at once",
679
+ customScheduled: "Send the post at the Due At time"
680
+ },
681
+ description: "Create: empty means Add To Queue. Update: empty means no change"
682
+ }),
683
+ schedulingType: zod.z.enum(SCHEDULING_TYPES).optional().meta({
684
+ ...on("post", "create", "update"),
685
+ title: "Scheduling Type",
686
+ labels: {
687
+ automatic: "Automatic",
688
+ notification: "Notification"
689
+ },
690
+ hints: {
691
+ automatic: "Buffer publishes the post",
692
+ notification: "Buffer sends a reminder to the mobile app, and a person publishes"
693
+ },
694
+ description: "Create: empty means Automatic"
695
+ }),
696
+ dueAt: zod.z.string().optional().meta({
697
+ ...on([
698
+ "post",
699
+ "idea",
700
+ "channel"
701
+ ], "create", "update", "getDailyPostingLimits"),
702
+ title: "Due At",
703
+ placeholder: "2026-12-01T10:00:00.000Z",
704
+ description: "A date and time in ISO 8601. Use with the Custom Scheduled mode"
705
+ }),
706
+ saveToDraft: zod.z.boolean().default(false).meta({
707
+ ...on("post", "create", "update"),
708
+ title: "Save To Draft",
709
+ description: "Save the post as a draft. Buffer does not publish it"
710
+ }),
711
+ needsApproval: zod.z.boolean().default(false).meta({
712
+ ...on("post", "create"),
713
+ title: "Needs Approval",
714
+ description: "Send the post for approval. Only for channels with an approval policy"
715
+ }),
716
+ approvalChange: zod.z.enum(["request", "revert"]).optional().meta({
717
+ ...on("post", "update"),
718
+ title: "Approval Change",
719
+ labels: {
720
+ request: "Request Approval",
721
+ revert: "Withdraw Request"
722
+ },
723
+ description: "Empty keeps the approval state"
724
+ }),
725
+ position: zod.z.enum(["top", "bottom"]).default("top").meta({
726
+ ...on("post", "moveInQueue"),
727
+ labels: {
728
+ top: "Top",
729
+ bottom: "Bottom"
730
+ }
731
+ }),
732
+ statuses: zod.z.string().optional().meta({
733
+ ...on("post", "getAll"),
734
+ title: "Statuses",
735
+ description: `Statuses with commas between: ${POST_STATUSES.join(", ")}. Empty means all`
736
+ }),
737
+ startDate: zod.z.string().optional().meta({
738
+ ...on("post", "getAll", "getAggregatedMetrics"),
739
+ title: "Start Date",
740
+ placeholder: "2026-01-01T00:00:00Z",
741
+ description: "Posts created or due after this date. For metrics, the start of the range, not more than 2 years ago"
742
+ }),
743
+ endDate: zod.z.string().optional().meta({
744
+ ...on("post", "getAll", "getAggregatedMetrics"),
745
+ title: "End Date",
746
+ placeholder: "2026-01-31T00:00:00Z",
747
+ description: "Posts created or due before this date. For metrics, the end of the range. The range is 365 days at most"
748
+ }),
749
+ sortField: zod.z.enum(["dueAt", "createdAt"]).optional().meta({
750
+ ...on("post", "getAll"),
751
+ title: "Sort By",
752
+ labels: {
753
+ dueAt: "Due At",
754
+ createdAt: "Created At"
755
+ }
756
+ }),
757
+ sortDirection: zod.z.enum(["asc", "desc"]).default("desc").meta({
758
+ ...on(["post", "contentItem"], "getAll"),
759
+ title: "Sort Order",
760
+ labels: {
761
+ asc: "Ascending",
762
+ desc: "Descending"
763
+ }
764
+ }),
765
+ lockedFilter: zod.z.enum([
766
+ "any",
767
+ "locked",
768
+ "unlocked"
769
+ ]).default("any").meta({
770
+ ...on(["channel", "tag"], "getAll"),
771
+ title: "Locked",
772
+ labels: {
773
+ any: "All",
774
+ locked: "Locked Only",
775
+ unlocked: "Unlocked Only"
776
+ }
777
+ }),
778
+ product: zod.z.enum([
779
+ "",
780
+ "buffer",
781
+ "publish",
782
+ "analyze",
783
+ "engage",
784
+ "comments",
785
+ "startPage"
786
+ ]).default("").meta({
787
+ ...on("channel", "getAll"),
788
+ description: "Only channels that this Buffer product supports. Empty means all",
789
+ labels: {
790
+ "": "All",
791
+ buffer: "Buffer",
792
+ publish: "Publish",
793
+ analyze: "Analyze",
794
+ engage: "Engage",
795
+ comments: "Comments",
796
+ startPage: "Start Page"
797
+ }
798
+ }),
799
+ contentStatus: zod.z.enum([
800
+ "",
801
+ "draftContent",
802
+ "postContent"
803
+ ]).default("").meta({
804
+ ...on("contentItem", "getAll"),
805
+ title: "Content Status",
806
+ labels: {
807
+ "": "All",
808
+ draftContent: "Draft",
809
+ postContent: "Posts"
810
+ }
811
+ }),
812
+ groupMembership: zod.z.enum([
813
+ "",
814
+ "grouped",
815
+ "ungrouped"
816
+ ]).default("").meta({
817
+ ...on("idea", "getAll"),
818
+ title: "Group",
819
+ labels: {
820
+ "": "All",
821
+ grouped: "In a Group",
822
+ ungrouped: "Not in a Group"
823
+ }
824
+ }),
825
+ groupId: zod.z.string().optional().meta({
826
+ ...on("idea", "create", "getAll"),
827
+ title: "Group ID",
828
+ description: "Create: the group for the idea. List: only ideas of this group"
829
+ }),
830
+ placeAfterId: zod.z.string().optional().meta({
831
+ ...on("idea", "create"),
832
+ title: "Place After Idea ID",
833
+ description: "Empty means the top of the group"
834
+ }),
835
+ targetDate: zod.z.string().optional().meta({
836
+ ...on("contentItem", "create", "createDraft", "update", "updateDraft"),
837
+ title: "Target Date",
838
+ placeholder: "2026-12-01T00:00:00Z",
839
+ description: "A date for planning. It does not schedule posts"
840
+ }),
841
+ search: zod.z.string().optional().meta({
842
+ ...on("teamMember", "getAll"),
843
+ description: "Text in the name or the email"
844
+ }),
845
+ audioId: zod.z.string().optional().meta({
846
+ ...on("instagramAudio", "get"),
847
+ title: "Audio ID"
848
+ }),
849
+ audioType: zod.z.enum(["music", "originalSound"]).default("music").meta({
850
+ ...on("instagramAudio", "search", "getTrending"),
851
+ title: "Audio Type",
852
+ labels: {
853
+ music: "Music",
854
+ originalSound: "Original Sound"
855
+ }
856
+ }),
857
+ query: zod.z.string().optional().meta({
858
+ ...on("instagramAudio", "search", "searchCatalog"),
859
+ title: "Search Text"
860
+ }),
861
+ returnAll: zod.z.boolean().default(false).meta({ showWhen: {
862
+ resource: [...new Set(LIST_OPERATIONS.map(([resource]) => resource))],
863
+ operation: ["getAll"]
864
+ } }),
865
+ limit: zod.z.number().int().min(1).max(5e3).default(50).meta({ showWhen: {
866
+ resource: [...new Set(LIST_OPERATIONS.map(([resource]) => resource))],
867
+ operation: ["getAll"],
868
+ returnAll: [false]
869
+ } }),
870
+ timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
871
+ }).superRefine((config, context) => {
872
+ if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
873
+ code: "custom",
874
+ path: ["operation"],
875
+ message: `"${config.operation}" is not an operation of "${config.resource}"`
876
+ });
877
+ });
878
+ // src/request.ts
879
+ /** A trimmed text, or `undefined` for an empty text. */
880
+ const s = (value) => {
881
+ const trimmed = value?.trim();
882
+ return trimmed ? trimmed : void 0;
883
+ };
884
+ /** A list of texts from a text with commas or new lines between. */
885
+ const list = (text) => {
886
+ const items = text?.split(/[,\n]/).map((item) => item.trim()).filter(Boolean);
887
+ return items && items.length > 0 ? items : void 0;
888
+ };
889
+ const need = (value, name, operation) => {
890
+ if (value === void 0 || value === "") throw new Error(`"${name}" is needed to ${operation}`);
891
+ return value;
892
+ };
893
+ const compact = (body) => Object.fromEntries(Object.entries(body).filter(([, value]) => value !== void 0));
894
+ const parseJson = (text, name) => {
895
+ const value = s(text);
896
+ if (value === void 0) return void 0;
897
+ try {
898
+ return JSON.parse(value);
899
+ } catch {
900
+ throw new Error(`"${name}" must be valid JSON`);
901
+ }
902
+ };
903
+ const jsonObject = (text, name) => {
904
+ const value = parseJson(text, name);
905
+ if (value === void 0) return void 0;
906
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`"${name}" must be a JSON object`);
907
+ return value;
908
+ };
909
+ const jsonArray = (text, name) => {
910
+ const value = parseJson(text, name);
911
+ if (value === void 0) return void 0;
912
+ if (!Array.isArray(value)) throw new Error(`"${name}" must be a JSON array`);
913
+ return value;
914
+ };
915
+ /** The assets of a post or a draft. The JSON field wins over the URL fields. */
916
+ function assetsOf(c) {
917
+ const custom = jsonArray(c.assets, "assets");
918
+ if (custom) return custom;
919
+ const entries = [...(list(c.imageUrls) ?? []).map((url) => ({ image: { url } })), ...s(c.videoUrl) ? [{ video: { url: s(c.videoUrl) } }] : []];
920
+ return entries.length > 0 ? entries : void 0;
921
+ }
922
+ /** Fields of the additional input go into the input and replace fields that are set. */
923
+ const withExtra = (input, c) => ({
924
+ ...input,
925
+ ...jsonObject(c.additionalInput, "additionalInput")
926
+ });
927
+ const ASSET = "id type mimeType source thumbnail status";
928
+ const TAG = "id name color colorName isLocked";
929
+ const POST = `
930
+ id text status dueAt sentAt createdAt updatedAt channelId channelService externalLink
931
+ shareMode schedulingType isCustomScheduled sharedNow via contentItemId ideaId
932
+ notificationStatus allowedActions
933
+ error { message supportUrl }
934
+ author { id name email }
935
+ tags { ${TAG} }
936
+ assets { ${ASSET} }
937
+ metadata { __typename ... on CommonPostMetadata { type } }
938
+ metrics { type name value unit description }
939
+ metricsUpdatedAt`;
940
+ const CONTENT_ITEM = `
941
+ id title targetDate createdAt organizationId accountId allowedActions
942
+ author { id name email }
943
+ tags { ${TAG} }
944
+ body {
945
+ __typename
946
+ ... on DraftContent { id text aiAssisted assets { ${ASSET} } }
947
+ ... on PostContent { posts { ${POST} } }
948
+ }`;
949
+ const CHANNEL = `
950
+ id name displayName descriptor service serviceId type avatar externalLink timezone
951
+ organizationId isLocked isDisconnected isQueuePaused isNew products scopes allowedActions
952
+ postingSchedule { day paused times }
953
+ postingGoal { goal periodStart periodEnd scheduledCount sentCount status }
954
+ linkShortening { isEnabled }
955
+ createdAt updatedAt`;
956
+ const ORGANIZATION = `
957
+ id name ownerEmail channelCount
958
+ members { totalCount }
959
+ limits { channels ideas ideaGroups members postTemplates scheduledPosts tags }`;
960
+ const IDEA = `
961
+ id groupId organizationId position createdAt updatedAt
962
+ content {
963
+ title text date aiAssisted services
964
+ tags { id name color colorName }
965
+ media { id url type alt thumbnailUrl size }
966
+ }`;
967
+ const NOTE = `
968
+ id text authorId createdAt updatedAt allowedActions
969
+ author { id name email }
970
+ annotations { type text content indices url serviceEntityId displayValue }`;
971
+ const AUDIO = "id title type duration displayArtist creatorUsername coverArtworkUrl previewUrl";
972
+ const SNIPPET = "id name text";
973
+ const TEMPLATE = "id title body description emoji visibility organizationId createdAt updatedAt";
974
+ const PAGE = "pageInfo { hasNextPage endCursor }";
975
+ /** A query with a plain answer. */
976
+ const read = (name, inputType, fields, variables, pick) => ({
977
+ query: `query ($input: ${inputType}!) {\n ${name}(input: $input) {${fields}\n }\n}`,
978
+ variables,
979
+ result: name,
980
+ pick
981
+ });
982
+ /** A query with cursors. The node of each edge is the item. */
983
+ const readList = (name, inputType, fields, input) => ({
984
+ query: `query ($first: Int, $after: String, $input: ${inputType}!) {\n ${name}(first: $first, after: $after, input: $input) {\n edges { cursor node {${fields}\n } }\n ${PAGE}\n }\n}`,
985
+ variables: { input },
986
+ result: name,
987
+ connection: true
988
+ });
989
+ /** A query or a mutation with a union answer. A typed error becomes an error of the node. */
990
+ const union = (kind, name, inputType, body, input, pick) => ({
991
+ query: `${kind} ($input: ${inputType}!) {\n ${name}(input: $input) {\n __typename${body}\n ... on MutationError {\n message\n }\n }\n}`,
992
+ variables: { input },
993
+ result: name,
994
+ pick,
995
+ typed: true
996
+ });
997
+ const mutation = (name, inputType, body, input, pick) => union("mutation", name, inputType, body, input, pick);
998
+ /** The failure types of a content item carry a list of errors. */
999
+ const failure = (type) => `\n ... on ${type} {\n message\n errors { __typename ... on MutationError { message } }\n }`;
1000
+ const success = (type, fields) => `\n ... on ${type} {${fields}\n }`;
1001
+ /** The input of a post for `createPost` and `editPost`. */
1002
+ function postInput(c, creating) {
1003
+ const op = `${c.resource}.${c.operation}`;
1004
+ const dueAt = s(c.dueAt);
1005
+ const metadata = jsonObject(c.metadata, "metadata");
1006
+ const assets = assetsOf(c);
1007
+ const base = {
1008
+ text: s(c.text),
1009
+ dueAt,
1010
+ saveToDraft: c.saveToDraft ? true : void 0,
1011
+ aiAssisted: c.aiAssisted ? true : void 0,
1012
+ assets,
1013
+ metadata,
1014
+ tagIds: list(c.tagIds),
1015
+ ideaId: s(c.ideaId),
1016
+ draftId: s(c.draftId)
1017
+ };
1018
+ if (creating) return withExtra(compact({
1019
+ ...base,
1020
+ channelId: need(s(c.channelId), "channelId", op),
1021
+ mode: c.mode ?? (dueAt ? "customScheduled" : "addToQueue"),
1022
+ schedulingType: c.schedulingType ?? "automatic",
1023
+ needsApproval: c.needsApproval ? true : void 0
1024
+ }), c);
1025
+ return withExtra(compact({
1026
+ ...base,
1027
+ id: need(s(c.postId), "postId", op),
1028
+ mode: c.mode,
1029
+ schedulingType: c.schedulingType,
1030
+ approvalChange: c.approvalChange
1031
+ }), c);
1032
+ }
1033
+ /** A draft with no channel. */
1034
+ function draftInput(c) {
1035
+ return {
1036
+ text: c.text ?? "",
1037
+ aiAssisted: c.aiAssisted,
1038
+ assets: assetsOf(c) ?? []
1039
+ };
1040
+ }
1041
+ /** The subject of a Note: a post or a content item. */
1042
+ function subject(c, op) {
1043
+ const postId = s(c.postId);
1044
+ if (postId) return { postId };
1045
+ return { contentItemId: need(s(c.contentItemId), "postId or contentItemId", op) };
1046
+ }
1047
+ const lockedOf = (c) => c.lockedFilter === "locked" ? true : c.lockedFilter === "unlocked" ? false : void 0;
1048
+ /** The API call for one operation, without the network. */
1049
+ function buildRequest(c) {
1050
+ const op = `${c.resource}.${c.operation}`;
1051
+ const organizationId = () => need(s(c.organizationId), "organizationId", op);
1052
+ const channelId = () => need(s(c.channelId), "channelId", op);
1053
+ const postId = () => need(s(c.postId), "postId", op);
1054
+ const contentItemId = () => need(s(c.contentItemId), "contentItemId", op);
1055
+ switch (op) {
1056
+ case "account.get": return {
1057
+ query: `query {\n account {\n id email backupEmail name avatar timezone createdAt\n }\n}`,
1058
+ result: "account"
1059
+ };
1060
+ case "organization.getAll": return {
1061
+ query: `query {\n account {\n organizations {${ORGANIZATION}\n }\n }\n}`,
1062
+ result: "account",
1063
+ pick: "organizations"
1064
+ };
1065
+ case "organization.getConfiguration": return read("configuration", "ConfigurationInput", `
1066
+ channels { channelId channelType service }
1067
+ services { channelType service }`, { input: { organizationId: organizationId() } });
1068
+ case "channel.get": return read("channel", "ChannelInput", CHANNEL, { input: { id: channelId() } });
1069
+ case "channel.getAll": return read("channels", "ChannelsInput", CHANNEL, { input: {
1070
+ organizationId: organizationId(),
1071
+ filter: compact({
1072
+ isLocked: lockedOf(c),
1073
+ product: s(c.product)
1074
+ })
1075
+ } });
1076
+ case "channel.getDailyPostingLimits": return read("dailyPostingLimits", "DailyPostingLimitsInput", "\n channelId isAtLimit limit scheduled sent", { input: compact({
1077
+ channelIds: need(list(c.channelIds), "channelIds", op),
1078
+ date: s(c.dueAt)
1079
+ }) });
1080
+ case "channel.shortenLink": return mutation("shortenLink", "ShortenLinkInput", success("ShortenLinkSuccess", "\n url longUrl"), {
1081
+ channelId: channelId(),
1082
+ url: need(s(c.url), "url", op)
1083
+ });
1084
+ case "post.create": return mutation("createPost", "CreatePostInput", success("PostActionSuccess", `\n post {${POST}\n }`), postInput(c, true), "post");
1085
+ case "post.get": return read("post", "PostInput", POST, { input: { id: postId() } });
1086
+ case "post.getAll": {
1087
+ const filter = compact({
1088
+ channelIds: list(c.channelIds),
1089
+ status: list(c.statuses),
1090
+ startDate: s(c.startDate),
1091
+ endDate: s(c.endDate),
1092
+ tagIds: list(c.tagIds)
1093
+ });
1094
+ return readList("posts", "PostsInput", POST, withExtra(compact({
1095
+ organizationId: organizationId(),
1096
+ filter: Object.keys(filter).length > 0 ? filter : void 0,
1097
+ sort: c.sortField ? [{
1098
+ field: c.sortField,
1099
+ direction: c.sortDirection
1100
+ }] : void 0
1101
+ }), c));
1102
+ }
1103
+ case "post.update": return mutation("editPost", "EditPostInput", success("PostActionSuccess", `\n post {${POST}\n }`), postInput(c, false), "post");
1104
+ case "post.delete": return mutation("deletePost", "DeletePostInput", success("DeletePostSuccess", "\n id"), { id: postId() });
1105
+ case "post.publishNow": return mutation("publishPostNow", "PublishPostNowInput", success("PostActionSuccess", `\n post {${POST}\n }`), { id: postId() }, "post");
1106
+ case "post.moveInQueue": return mutation("movePostInQueue", "MovePostInQueueInput", success("PostActionSuccess", `\n post {${POST}\n }`), {
1107
+ id: postId(),
1108
+ position: c.position
1109
+ }, "post");
1110
+ case "post.getAggregatedMetrics": {
1111
+ const tags = list(c.tagIds);
1112
+ return read("aggregatedPostMetrics", "AggregatedPostMetricsInput", "\n metricsUpdatedAt\n metrics { type name value unit description }", { input: compact({
1113
+ organizationId: organizationId(),
1114
+ startDateTime: need(s(c.startDate), "startDate", op),
1115
+ endDateTime: need(s(c.endDate), "endDate", op),
1116
+ channelIds: list(c.channelIds),
1117
+ tags: tags ? { in: tags } : void 0
1118
+ }) });
1119
+ }
1120
+ case "idea.create": {
1121
+ const media = (list(c.imageUrls) ?? []).map((url) => ({
1122
+ url,
1123
+ type: "image"
1124
+ }));
1125
+ const groupId = s(c.groupId);
1126
+ const placeAfterId = s(c.placeAfterId);
1127
+ return mutation("createIdea", "CreateIdeaInput", `\n ... on Idea {${IDEA}\n }\n ... on IdeaResponse {\n refreshIdeas\n idea {${IDEA}\n }\n }`, withExtra(compact({
1128
+ organizationId: organizationId(),
1129
+ content: compact({
1130
+ title: s(c.title),
1131
+ text: s(c.text),
1132
+ date: s(c.dueAt),
1133
+ services: list(c.services),
1134
+ aiAssisted: c.aiAssisted ? true : void 0,
1135
+ media: media.length > 0 ? media : void 0
1136
+ }),
1137
+ group: groupId || placeAfterId ? compact({
1138
+ groupId,
1139
+ placeAfterId
1140
+ }) : void 0
1141
+ }), c), "idea");
1142
+ }
1143
+ case "idea.getAll": {
1144
+ const groupId = s(c.groupId);
1145
+ const tags = list(c.tagIds);
1146
+ const groupFilter = groupId ? { groups: [groupId] } : c.groupMembership ? { membership: c.groupMembership } : void 0;
1147
+ return readList("ideas", "IdeasInput", IDEA, withExtra(compact({
1148
+ organizationId: organizationId(),
1149
+ groupFilter,
1150
+ tagsFilter: tags ? { in: tags } : void 0
1151
+ }), c));
1152
+ }
1153
+ case "idea.getGroups": return read("ideaGroups", "IdeaGroupsInput", "\n id name isLocked", { input: { organizationId: organizationId() } });
1154
+ case "tag.create": return mutation("createTag", "CreateTagInput", success("TagActionSuccess", `\n tag { ${TAG} }`), {
1155
+ organizationId: organizationId(),
1156
+ tag: {
1157
+ name: need(s(c.name), "name", op),
1158
+ color: need(s(c.color), "color", op)
1159
+ }
1160
+ }, "tag");
1161
+ case "tag.get": return read("tag", "TagByIdInput", `\n ${TAG}`, { input: { id: need(s(c.tagId), "tagId", op) } });
1162
+ case "tag.getAll": {
1163
+ const isLocked = lockedOf(c);
1164
+ return readList("tagsV2", "TagsInput", `\n ${TAG}`, compact({
1165
+ organizationId: organizationId(),
1166
+ filter: isLocked === void 0 ? void 0 : { isLocked }
1167
+ }));
1168
+ }
1169
+ case "tag.update": return mutation("updateTag", "UpdateTagInput", success("TagActionSuccess", `\n tag { ${TAG} }`), {
1170
+ id: need(s(c.tagId), "tagId", op),
1171
+ tag: {
1172
+ name: need(s(c.name), "name", op),
1173
+ color: need(s(c.color), "color", op)
1174
+ }
1175
+ }, "tag");
1176
+ case "tag.delete": return mutation("deleteTag", "DeleteTagInput", success("DeleteTagActionSuccess", "\n id"), { id: need(s(c.tagId), "tagId", op) });
1177
+ case "contentItem.create": return mutation("createContentItem", "CreateContentItemInput", success("CreateContentItemSuccess", `\n content {${CONTENT_ITEM}\n }`) + failure("CreateContentItemFailure"), withExtra(compact({
1178
+ organizationId: organizationId(),
1179
+ posts: need(jsonArray(c.posts, "posts"), "posts", op),
1180
+ tagIds: list(c.tagIds),
1181
+ targetDate: s(c.targetDate),
1182
+ title: s(c.title)
1183
+ }), c), "content");
1184
+ case "contentItem.createDraft": return mutation("createContentItemDraft", "CreateContentItemDraftInput", success("CreateContentItemDraftSuccess", `\n contentItem {${CONTENT_ITEM}\n }`) + failure("CreateContentItemDraftFailure"), withExtra(compact({
1185
+ organizationId: organizationId(),
1186
+ draft: draftInput(c),
1187
+ tagIds: list(c.tagIds),
1188
+ targetDate: s(c.targetDate),
1189
+ title: s(c.title)
1190
+ }), c), "contentItem");
1191
+ case "contentItem.get": return read("contentItem", "ContentItemInput", CONTENT_ITEM, { input: { id: contentItemId() } });
1192
+ case "contentItem.getAll": {
1193
+ const tags = list(c.tagIds);
1194
+ const filter = compact({
1195
+ contentStatus: s(c.contentStatus),
1196
+ tags: tags ? { in: tags } : void 0
1197
+ });
1198
+ return readList("contentItems", "ContentItemsInput", CONTENT_ITEM, withExtra(compact({
1199
+ organizationId: organizationId(),
1200
+ filter: Object.keys(filter).length > 0 ? filter : void 0,
1201
+ sort: [{
1202
+ field: "createdAt",
1203
+ direction: c.sortDirection
1204
+ }]
1205
+ }), c));
1206
+ }
1207
+ case "contentItem.update": return mutation("updateContentItem", "UpdateContentItemInput", success("UpdateContentItemSuccess", `\n contentItem {${CONTENT_ITEM}\n }`) + failure("UpdateContentItemFailure"), withExtra(compact({
1208
+ id: contentItemId(),
1209
+ title: s(c.title),
1210
+ targetDate: s(c.targetDate)
1211
+ }), c), "contentItem");
1212
+ case "contentItem.updateDraft": return mutation("updateContentItemDraft", "UpdateContentItemDraftInput", success("UpdateContentItemDraftSuccess", `\n contentItem {${CONTENT_ITEM}\n }`) + failure("UpdateContentItemDraftFailure"), withExtra(compact({
1213
+ id: contentItemId(),
1214
+ draft: draftInput(c),
1215
+ tagIds: list(c.tagIds),
1216
+ targetDate: s(c.targetDate)
1217
+ }), c), "contentItem");
1218
+ case "contentItem.promoteDraft": return mutation("promoteContentItemDraftToPosts", "PromoteContentItemDraftToPostsInput", success("PromoteContentItemDraftToPostsSuccess", `\n contentItem {${CONTENT_ITEM}\n }`) + failure("PromoteContentItemDraftToPostsFailure"), withExtra(compact({
1219
+ id: contentItemId(),
1220
+ posts: need(jsonArray(c.posts, "posts"), "posts", op),
1221
+ tagIds: list(c.tagIds)
1222
+ }), c), "contentItem");
1223
+ case "contentItem.delete": return mutation("deleteContentItem", "DeleteContentItemInput", `\n ... on EmptySuccess {\n __typename\n }${failure("DeleteContentItemFailure")}`, { id: contentItemId() });
1224
+ case "contentItem.addPost": return mutation("addPostToContentItem", "AddPostToContentItemInput", success("AddPostToContentItemSuccess", `\n contentItem {${CONTENT_ITEM}\n }\n post {${POST}\n }`), {
1225
+ id: contentItemId(),
1226
+ postId: postId()
1227
+ });
1228
+ case "contentItem.removePost": return mutation("removePostFromContentItem", "RemovePostFromContentItemInput", success("RemovePostFromContentItemSuccess", `\n contentItem {${CONTENT_ITEM}\n }\n post {${POST}\n }`), {
1229
+ id: contentItemId(),
1230
+ postId: postId()
1231
+ });
1232
+ case "note.create": return mutation("createCollaborationNote", "CreateCollaborationNoteInput", success("CreateCollaborationNoteSuccess", `\n edge { cursor node {${NOTE}\n } }`), withExtra({
1233
+ subject: subject(c, op),
1234
+ text: need(s(c.text), "text", op)
1235
+ }, c), "edge.node");
1236
+ case "note.getAll": return readList("collaborationNotes", "CollaborationNotesInput", NOTE, { subject: subject(c, op) });
1237
+ case "note.update": return mutation("updateCollaborationNote", "UpdateCollaborationNoteInput", success("UpdateCollaborationNoteSuccess", `\n note {${NOTE}\n }`), withExtra({
1238
+ noteId: need(s(c.noteId), "noteId", op),
1239
+ text: need(s(c.text), "text", op)
1240
+ }, c), "note");
1241
+ case "note.delete": return mutation("deleteCollaborationNote", "DeleteCollaborationNoteInput", success("DeleteCollaborationNoteSuccess", "\n noteId"), { noteId: need(s(c.noteId), "noteId", op) });
1242
+ case "teamMember.getAll": {
1243
+ const channel = s(c.channelId);
1244
+ return readList("selectableTeamMembers", "SelectableTeamMembersInput", "\n id name email avatar urn isLocked", compact({
1245
+ scope: channel ? { channelId: channel } : { organizationId: organizationId() },
1246
+ search: s(c.search)
1247
+ }));
1248
+ }
1249
+ case "snippet.create": return mutation("createSnippet", "CreateSnippetInput", success("CreateSnippetSuccess", `\n snippet { ${SNIPPET} }`), {
1250
+ organizationId: organizationId(),
1251
+ name: need(s(c.name), "name", op),
1252
+ text: need(s(c.text), "text", op)
1253
+ }, "snippet");
1254
+ case "snippet.getAll": return readList("snippets", "SnippetsInput", `\n ${SNIPPET}`, { organizationId: organizationId() });
1255
+ case "snippet.update": return mutation("updateSnippet", "UpdateSnippetInput", success("UpdateSnippetSuccess", `\n snippet { ${SNIPPET} }`), {
1256
+ id: need(s(c.snippetId), "snippetId", op),
1257
+ organizationId: organizationId(),
1258
+ name: need(s(c.name), "name", op),
1259
+ text: need(s(c.text), "text", op)
1260
+ }, "snippet");
1261
+ case "snippet.delete": return mutation("deleteSnippet", "DeleteSnippetInput", success("DeleteSnippetSuccess", "\n id"), {
1262
+ id: need(s(c.snippetId), "snippetId", op),
1263
+ organizationId: organizationId()
1264
+ });
1265
+ case "template.create": return mutation("createPostTemplate", "CreatePostTemplateInput", success("CreatePostTemplateSuccess", `\n postTemplate { ${TEMPLATE} }`), withExtra(compact({
1266
+ organizationId: organizationId(),
1267
+ title: need(s(c.title), "title", op),
1268
+ body: need(s(c.body), "body", op),
1269
+ description: need(s(c.description), "description", op),
1270
+ emoji: s(c.emoji),
1271
+ visibility: c.visibility
1272
+ }), c), "postTemplate");
1273
+ case "template.get": return read("postTemplate", "PostTemplateInput", `\n ${TEMPLATE}`, { input: { id: need(s(c.templateId), "templateId", op) } });
1274
+ case "template.getAll": return readList("postTemplates", "PostTemplatesInput", `\n ${TEMPLATE}`, compact({
1275
+ organizationId: organizationId(),
1276
+ filter: c.visibility ? { visibility: c.visibility } : void 0
1277
+ }));
1278
+ case "template.update": return mutation("updatePostTemplate", "UpdatePostTemplateInput", success("UpdatePostTemplateSuccess", `\n postTemplate { ${TEMPLATE} }`), withExtra(compact({
1279
+ id: need(s(c.templateId), "templateId", op),
1280
+ title: s(c.title),
1281
+ body: s(c.body),
1282
+ description: s(c.description),
1283
+ emoji: s(c.emoji),
1284
+ visibility: c.visibility
1285
+ }), c), "postTemplate");
1286
+ case "template.delete": return mutation("deletePostTemplate", "DeletePostTemplateInput", "\n ... on EmptySuccess {\n __typename\n }", { id: need(s(c.templateId), "templateId", op) });
1287
+ case "asset.getAll": return readList("assets", "AssetsInput", `\n ${ASSET}`, {
1288
+ organizationId: organizationId(),
1289
+ ids: need(list(c.assetIds), "assetIds", op)
1290
+ });
1291
+ case "pinterestBoard.create": return mutation("createPinterestBoard", "CreatePinterestBoardInput", success("CreatePinterestBoardSuccess", "\n board { id serviceId name description url avatar isShared }"), withExtra(compact({
1292
+ channelId: channelId(),
1293
+ name: need(s(c.name), "name", op),
1294
+ description: s(c.description)
1295
+ }), c), "board");
1296
+ case "pinterestBoard.refresh": return mutation("refreshPinterestBoards", "RefreshPinterestBoardsInput", success("RefreshPinterestBoardsSuccess", "\n boards { id serviceId name description url avatar isShared }"), { channelId: channelId() }, "boards");
1297
+ case "instagramAudio.get": return union("query", "instagramAudio", "InstagramAudioInput", success("InstagramAudioSuccess", `\n audio { ${AUDIO} }`), {
1298
+ channelId: channelId(),
1299
+ audioId: need(s(c.audioId), "audioId", op)
1300
+ }, "audio");
1301
+ case "instagramAudio.search": return union("query", "searchInstagramAudio", "SearchInstagramAudioInput", success("SearchInstagramAudioSuccess", `\n audio { ${AUDIO} }`), {
1302
+ channelId: channelId(),
1303
+ audioType: c.audioType,
1304
+ query: need(s(c.query), "query", op)
1305
+ }, "audio");
1306
+ case "instagramAudio.getTrending": return union("query", "trendingInstagramAudio", "TrendingInstagramAudioInput", success("SearchInstagramAudioSuccess", `\n audio { ${AUDIO} }`), {
1307
+ channelId: channelId(),
1308
+ audioType: c.audioType
1309
+ }, "audio");
1310
+ case "instagramAudio.getCatalog": return union("query", "instagramAudioCatalog", "InstagramAudioCatalogInput", success("InstagramAudioCatalogSuccess", `\n failedAudioTypes\n audio { ${AUDIO} }`), { channelId: channelId() });
1311
+ case "instagramAudio.searchCatalog": return union("query", "searchInstagramAudioCatalog", "SearchInstagramAudioCatalogInput", success("InstagramAudioCatalogSuccess", `\n failedAudioTypes\n audio { ${AUDIO} }`), {
1312
+ channelId: channelId(),
1313
+ query: need(s(c.query), "query", op)
1314
+ });
1315
+ }
1316
+ throw new Error(`Unknown Buffer operation "${op}"`);
1317
+ }
1318
+ // src/node.ts
1319
+ /** The answer of a union has `__typename`. The user needs only the data. */
1320
+ function clean(value) {
1321
+ if (Array.isArray(value)) return value.map(clean);
1322
+ if (typeof value !== "object" || value === null) return value;
1323
+ const entries = Object.entries(value).filter(([key]) => key !== "__typename").map(([key, item]) => [key, clean(item)]);
1324
+ return Object.fromEntries(entries);
1325
+ }
1326
+ // src/index.ts
1327
+ const nodes = [(0, _zerodot_node_sdk.defineNode)({
1328
+ type: "buffer.api",
1329
+ label: "Buffer",
1330
+ description: "Create, schedule, and manage posts, ideas, tags, notes, and channels in Buffer",
1331
+ category: "integration",
1332
+ app: "Buffer",
1333
+ actions: [
1334
+ {
1335
+ label: "Get the account",
1336
+ config: {
1337
+ resource: "account",
1338
+ operation: "get"
1339
+ }
1340
+ },
1341
+ {
1342
+ label: "Get many organizations",
1343
+ config: {
1344
+ resource: "organization",
1345
+ operation: "getAll"
1346
+ }
1347
+ },
1348
+ {
1349
+ label: "Get a channel",
1350
+ config: {
1351
+ resource: "channel",
1352
+ operation: "get"
1353
+ }
1354
+ },
1355
+ {
1356
+ label: "Get many channels",
1357
+ config: {
1358
+ resource: "channel",
1359
+ operation: "getAll"
1360
+ }
1361
+ },
1362
+ {
1363
+ label: "Get the daily posting limits of channels",
1364
+ config: {
1365
+ resource: "channel",
1366
+ operation: "getDailyPostingLimits"
1367
+ }
1368
+ },
1369
+ {
1370
+ label: "Shorten a link",
1371
+ config: {
1372
+ resource: "channel",
1373
+ operation: "shortenLink"
1374
+ }
1375
+ },
1376
+ {
1377
+ label: "Create a post",
1378
+ config: {
1379
+ resource: "post",
1380
+ operation: "create"
1381
+ }
1382
+ },
1383
+ {
1384
+ label: "Get a post",
1385
+ config: {
1386
+ resource: "post",
1387
+ operation: "get"
1388
+ }
1389
+ },
1390
+ {
1391
+ label: "Get many posts",
1392
+ config: {
1393
+ resource: "post",
1394
+ operation: "getAll"
1395
+ }
1396
+ },
1397
+ {
1398
+ label: "Update a post",
1399
+ config: {
1400
+ resource: "post",
1401
+ operation: "update"
1402
+ }
1403
+ },
1404
+ {
1405
+ label: "Delete a post",
1406
+ config: {
1407
+ resource: "post",
1408
+ operation: "delete"
1409
+ }
1410
+ },
1411
+ {
1412
+ label: "Publish a post now",
1413
+ config: {
1414
+ resource: "post",
1415
+ operation: "publishNow"
1416
+ }
1417
+ },
1418
+ {
1419
+ label: "Move a post in the queue",
1420
+ config: {
1421
+ resource: "post",
1422
+ operation: "moveInQueue"
1423
+ }
1424
+ },
1425
+ {
1426
+ label: "Get aggregated post metrics",
1427
+ config: {
1428
+ resource: "post",
1429
+ operation: "getAggregatedMetrics"
1430
+ }
1431
+ },
1432
+ {
1433
+ label: "Create an idea",
1434
+ config: {
1435
+ resource: "idea",
1436
+ operation: "create"
1437
+ }
1438
+ },
1439
+ {
1440
+ label: "Get many ideas",
1441
+ config: {
1442
+ resource: "idea",
1443
+ operation: "getAll"
1444
+ }
1445
+ },
1446
+ {
1447
+ label: "Get many idea groups",
1448
+ config: {
1449
+ resource: "idea",
1450
+ operation: "getGroups"
1451
+ }
1452
+ },
1453
+ {
1454
+ label: "Create a tag",
1455
+ config: {
1456
+ resource: "tag",
1457
+ operation: "create"
1458
+ }
1459
+ },
1460
+ {
1461
+ label: "Get a tag",
1462
+ config: {
1463
+ resource: "tag",
1464
+ operation: "get"
1465
+ }
1466
+ },
1467
+ {
1468
+ label: "Get many tags",
1469
+ config: {
1470
+ resource: "tag",
1471
+ operation: "getAll"
1472
+ }
1473
+ },
1474
+ {
1475
+ label: "Update a tag",
1476
+ config: {
1477
+ resource: "tag",
1478
+ operation: "update"
1479
+ }
1480
+ },
1481
+ {
1482
+ label: "Delete a tag",
1483
+ config: {
1484
+ resource: "tag",
1485
+ operation: "delete"
1486
+ }
1487
+ },
1488
+ {
1489
+ label: "Create a content item",
1490
+ config: {
1491
+ resource: "contentItem",
1492
+ operation: "create"
1493
+ }
1494
+ },
1495
+ {
1496
+ label: "Create a content item draft",
1497
+ config: {
1498
+ resource: "contentItem",
1499
+ operation: "createDraft"
1500
+ }
1501
+ },
1502
+ {
1503
+ label: "Get a content item",
1504
+ config: {
1505
+ resource: "contentItem",
1506
+ operation: "get"
1507
+ }
1508
+ },
1509
+ {
1510
+ label: "Get many content items",
1511
+ config: {
1512
+ resource: "contentItem",
1513
+ operation: "getAll"
1514
+ }
1515
+ },
1516
+ {
1517
+ label: "Update a content item",
1518
+ config: {
1519
+ resource: "contentItem",
1520
+ operation: "update"
1521
+ }
1522
+ },
1523
+ {
1524
+ label: "Update the draft of a content item",
1525
+ config: {
1526
+ resource: "contentItem",
1527
+ operation: "updateDraft"
1528
+ }
1529
+ },
1530
+ {
1531
+ label: "Promote a draft to posts",
1532
+ config: {
1533
+ resource: "contentItem",
1534
+ operation: "promoteDraft"
1535
+ }
1536
+ },
1537
+ {
1538
+ label: "Delete a content item",
1539
+ config: {
1540
+ resource: "contentItem",
1541
+ operation: "delete"
1542
+ }
1543
+ },
1544
+ {
1545
+ label: "Add a post to a content item",
1546
+ config: {
1547
+ resource: "contentItem",
1548
+ operation: "addPost"
1549
+ }
1550
+ },
1551
+ {
1552
+ label: "Remove a post from a content item",
1553
+ config: {
1554
+ resource: "contentItem",
1555
+ operation: "removePost"
1556
+ }
1557
+ },
1558
+ {
1559
+ label: "Create a note",
1560
+ config: {
1561
+ resource: "note",
1562
+ operation: "create"
1563
+ }
1564
+ },
1565
+ {
1566
+ label: "Get many notes",
1567
+ config: {
1568
+ resource: "note",
1569
+ operation: "getAll"
1570
+ }
1571
+ },
1572
+ {
1573
+ label: "Update a note",
1574
+ config: {
1575
+ resource: "note",
1576
+ operation: "update"
1577
+ }
1578
+ },
1579
+ {
1580
+ label: "Delete a note",
1581
+ config: {
1582
+ resource: "note",
1583
+ operation: "delete"
1584
+ }
1585
+ },
1586
+ {
1587
+ label: "Get many team members",
1588
+ config: {
1589
+ resource: "teamMember",
1590
+ operation: "getAll"
1591
+ }
1592
+ },
1593
+ {
1594
+ label: "Create a snippet",
1595
+ config: {
1596
+ resource: "snippet",
1597
+ operation: "create"
1598
+ }
1599
+ },
1600
+ {
1601
+ label: "Get many snippets",
1602
+ config: {
1603
+ resource: "snippet",
1604
+ operation: "getAll"
1605
+ }
1606
+ },
1607
+ {
1608
+ label: "Update a snippet",
1609
+ config: {
1610
+ resource: "snippet",
1611
+ operation: "update"
1612
+ }
1613
+ },
1614
+ {
1615
+ label: "Delete a snippet",
1616
+ config: {
1617
+ resource: "snippet",
1618
+ operation: "delete"
1619
+ }
1620
+ },
1621
+ {
1622
+ label: "Create a post template",
1623
+ config: {
1624
+ resource: "template",
1625
+ operation: "create"
1626
+ }
1627
+ },
1628
+ {
1629
+ label: "Get a post template",
1630
+ config: {
1631
+ resource: "template",
1632
+ operation: "get"
1633
+ }
1634
+ },
1635
+ {
1636
+ label: "Get many post templates",
1637
+ config: {
1638
+ resource: "template",
1639
+ operation: "getAll"
1640
+ }
1641
+ },
1642
+ {
1643
+ label: "Update a post template",
1644
+ config: {
1645
+ resource: "template",
1646
+ operation: "update"
1647
+ }
1648
+ },
1649
+ {
1650
+ label: "Delete a post template",
1651
+ config: {
1652
+ resource: "template",
1653
+ operation: "delete"
1654
+ }
1655
+ },
1656
+ {
1657
+ label: "Get many assets",
1658
+ config: {
1659
+ resource: "asset",
1660
+ operation: "getAll"
1661
+ }
1662
+ },
1663
+ {
1664
+ label: "Create a Pinterest board",
1665
+ config: {
1666
+ resource: "pinterestBoard",
1667
+ operation: "create"
1668
+ }
1669
+ },
1670
+ {
1671
+ label: "Refresh the Pinterest boards of a channel",
1672
+ config: {
1673
+ resource: "pinterestBoard",
1674
+ operation: "refresh"
1675
+ }
1676
+ },
1677
+ {
1678
+ label: "Get Instagram audio",
1679
+ config: {
1680
+ resource: "instagramAudio",
1681
+ operation: "get"
1682
+ }
1683
+ },
1684
+ {
1685
+ label: "Search Instagram audio",
1686
+ config: {
1687
+ resource: "instagramAudio",
1688
+ operation: "search"
1689
+ }
1690
+ },
1691
+ {
1692
+ label: "Get trending Instagram audio",
1693
+ config: {
1694
+ resource: "instagramAudio",
1695
+ operation: "getTrending"
1696
+ }
1697
+ }
1698
+ ],
1699
+ icon: "Share08Icon",
1700
+ iconUrl: BUFFER_ICON,
1701
+ config: bufferConfig,
1702
+ defaultConfig: {
1703
+ resource: "post",
1704
+ operation: "getAll",
1705
+ sortDirection: "desc",
1706
+ lockedFilter: "any",
1707
+ position: "top",
1708
+ audioType: "music",
1709
+ saveToDraft: false,
1710
+ needsApproval: false,
1711
+ aiAssisted: false,
1712
+ returnAll: false,
1713
+ limit: 50,
1714
+ timeoutMs: 3e4
1715
+ },
1716
+ credentialTypes: [BUFFER_CREDENTIAL],
1717
+ ports: {
1718
+ in: ["in"],
1719
+ out: ["out"]
1720
+ },
1721
+ subtitle: (config) => typeof config.operation === "string" ? `${String(config.resource ?? "post")}: ${config.operation}` : void 0,
1722
+ async run({ config, credential, signal }) {
1723
+ const access = bufferAccess(credential);
1724
+ const options = {
1725
+ signal,
1726
+ timeoutMs: config.timeoutMs
1727
+ };
1728
+ const request = buildRequest(config);
1729
+ if (request.connection) return {
1730
+ port: "out",
1731
+ data: clean(await callBufferList(access, request, config.returnAll ? null : config.limit, options))
1732
+ };
1733
+ let result = at(await callBuffer(access, request, options), request.result);
1734
+ if (request.typed) throwTypedError(result);
1735
+ if (request.pick) result = at(result, request.pick) ?? result;
1736
+ const out = clean(result);
1737
+ const empty = typeof out === "object" && out !== null && Object.keys(out).length === 0;
1738
+ return {
1739
+ port: "out",
1740
+ data: out === null || out === void 0 || empty ? { success: true } : out
1741
+ };
1742
+ }
1743
+ })];
1744
+ const credentialTypes = [bufferCredential];
1745
+ exports.credentialTypes = credentialTypes;
1746
+ exports.nodes = nodes;