Repository navigation
Expand file tree
/
Copy pathrun-syndicate-post.mjs
More file actions
490 lines (437 loc) · 17.8 KB
/
Copy pathrun-syndicate-post.mjs
File metadata and controls
490 lines (437 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import { createClient } from "@sanity/client";
import { createImageUrlBuilder } from "@sanity/image-url";
import { portableTextToMarkdown } from "@portabletext/markdown";
const projectId = process.env.SANITY_STUDIO_PROJECT_ID || "hfh83o0w";
const dataset = process.env.SANITY_STUDIO_DATASET || "production";
const token = process.env.SANITY_API_WRITE_TOKEN || process.env.SANITY_AUTH_TOKEN;
const devtoApiKey = process.env.DEVTO_API_KEY || process.env.PRIVATE_DEVTO;
const hashnodeToken = process.env.HASHNODE_ACCESS_TOKEN || process.env.PRIVATE_HASHNODE;
const docId = process.env.TARGET_DOCUMENT_ID || "05eda048-efff-4e0f-8b76-83a2f482fa13";
console.log("Syndication script starting with config:");
console.log("- Document ID:", docId);
console.log("- Project ID:", projectId);
console.log("- Dataset:", dataset);
console.log("- Has Write Token:", Boolean(token));
console.log("- Has Dev.to Key:", Boolean(devtoApiKey));
console.log("- Has Hashnode Key:", Boolean(hashnodeToken));
if (!token) {
console.error("Missing SANITY_API_WRITE_TOKEN or SANITY_AUTH_TOKEN.");
process.exit(1);
}
const client = createClient({
projectId,
dataset,
token,
apiVersion: "2025-09-30",
useCdn: false,
});
async function run() {
const doc = await client.getDocument(docId);
if (!doc) {
console.error(`Document not found: ${docId}`);
process.exit(1);
}
console.log(`Loaded document: "${doc.title}" (type: ${doc._type})`);
const slug = typeof doc.slug === "object" ? doc.slug?.current : (doc.slug || docId);
const canonicalUrl = `https://codingcat.dev/${doc._type}/${slug}`;
const imgBuilder = createImageUrlBuilder({ projectId, dataset });
const urlForImage = (source) => {
if (!source || !source.asset) return undefined;
return imgBuilder.image(source).auto("format").fit("max");
};
const serializeContent = (content) => {
if (!content || !Array.isArray(content) || content.length === 0) {
return "";
}
try {
return portableTextToMarkdown(content, {
types: {
code: ({ value }) => "```" + (value?.language || "") + "\n" + (value?.code || "") + "\n```",
image: ({ value }) => {
const url = urlForImage(value)?.url();
return url ? `` : "";
},
codepen: ({ value }) => `{% codepen ${value?.url || ""} %}`,
codesandbox: ({ value }) => {
const id = value?.url?.split("https://codesandbox.io/p/sandbox/")?.at(-1);
return `{% codesandbox ${id || value?.url || ""} %}`;
},
twitter: ({ value }) => `{% twitter ${value?.id || ""} %}`,
quote: ({ value }) => `> ${serializeContent(value?.content)}`,
},
});
} catch (err) {
console.warn("Error serializing content:", err);
return doc.excerpt || "";
}
};
const contentMarkdown = serializeContent(doc.content);
console.log(`Content serialized to Markdown: ${contentMarkdown.length} characters`);
const docTags = Array.isArray(doc.tags) ? doc.tags : [];
const hasAwsTag = docTags.some(
(t) => t?.value?.toLowerCase() === "aws" || t?.label?.toLowerCase() === "aws"
);
const isSponsored = Array.isArray(doc.sponsor) && doc.sponsor.length > 0;
const shouldSyndicateAws =
(hasAwsTag && !isSponsored) ||
Boolean(doc.awsbuilder) ||
process.env.FORCE_AWS_BUILDER === "true";
// --- DEV.TO SYNDICATION ---
if (devtoApiKey) {
console.log("\n--- Syndicating to Dev.to ---");
const syndicationDocId = `syndication.${doc._id}.devto`;
const normalizedDocTags = docTags
.map((t) => (t?.value || t?.label || "").toLowerCase().replace(/[^a-z0-9]/g, ""))
.filter((v) => v.length >= 2 && v.length <= 20);
const devtoTags = Array.from(
new Set([
...(normalizedDocTags.length > 0
? normalizedDocTags.slice(0, 3)
: ["webdev", "javascript", "programming"]),
...(doc._type === "podcast" ? ["podcast"] : []),
])
).slice(0, 4);
const mainImageUrl = urlForImage(doc.coverImage)?.width(1280).url() || "";
const youtubeEmbed = doc.youtube ? `{% youtube ${doc.youtube.replace("live", "embed")} %}\n\n` : "";
const devtoArticlePayload = {
article: {
title: doc.title || "Untitled",
published: true,
tags: devtoTags,
main_image: mainImageUrl,
canonical_url: canonicalUrl,
description: doc.excerpt || "",
organization_id: "1009",
body_markdown: `Original: ${canonicalUrl}\n\n${youtubeEmbed}${contentMarkdown}`,
},
};
if (doc._type === "podcast") {
devtoArticlePayload.article.series = `codingcatdev_podcast_${doc.season || 4}`;
}
try {
const existingSyndication = await client.getDocument(syndicationDocId).catch(() => null);
let existingArticleId =
existingSyndication?.externalId && !String(existingSyndication.externalId).startsWith("simulated-")
? String(existingSyndication.externalId)
: null;
if (!existingArticleId && doc.devto) {
const pathSlug = doc.devto.split("https://dev.to/").at(-1);
if (pathSlug) {
const lookupRes = await fetch(`https://dev.to/api/articles/${pathSlug}`, {
headers: {
"api-key": devtoApiKey,
"Content-Type": "application/json",
},
});
if (lookupRes.ok) {
const lookupJson = await lookupRes.json();
if (lookupJson?.id) {
existingArticleId = String(lookupJson.id);
}
}
}
}
const method = existingArticleId ? "PUT" : "POST";
const targetUrl = existingArticleId
? `https://dev.to/api/articles/${existingArticleId}`
: "https://dev.to/api/articles";
// First attempt with organization_id: 1009
console.log(`Sending ${method} to ${targetUrl} with organization_id: 1009...`);
let res = await fetch(targetUrl, {
method,
headers: {
"api-key": devtoApiKey,
"Content-Type": "application/json",
},
body: JSON.stringify(devtoArticlePayload),
});
let resText = await res.text();
console.log("Dev.to initial response status:", res.status);
console.log("Dev.to initial response body:", resText);
// If org 1009 fails (e.g. 401 or 422 unauthorized org), retry without organization_id
if (!res.ok && resText.toLowerCase().includes("organization")) {
console.warn("Dev.to rejected organization_id 1009. Retrying under personal account without organization_id...");
delete devtoArticlePayload.article.organization_id;
res = await fetch(targetUrl, {
method,
headers: {
"api-key": devtoApiKey,
"Content-Type": "application/json",
},
body: JSON.stringify(devtoArticlePayload),
});
resText = await res.text();
console.log("Dev.to retry response status:", res.status);
console.log("Dev.to retry response body:", resText);
}
if (res.ok) {
const resJson = JSON.parse(resText);
console.log(`✓ Dev.to published: ${resJson.url} (ID: ${resJson.id})`);
await client.createOrReplace({
_id: syndicationDocId,
_type: "syndication",
target: { _type: "reference", _ref: doc._id },
platform: "devto",
status: "published",
canonicalUrl,
externalUrl: resJson.url,
externalId: String(resJson.id ?? ""),
syndicatedAt: new Date().toISOString(),
});
await client.patch(doc._id).set({ devto: resJson.url }).commit();
console.log(`✓ Updated Sanity doc ${doc._id} devto URL`);
} else {
console.error("✗ Dev.to publication failed:", resText);
}
} catch (err) {
console.error("✗ Dev.to request error:", err);
}
} else {
console.log("Dev.to key missing, skipping Dev.to");
}
// --- HASHNODE SYNDICATION ---
if (hashnodeToken) {
console.log("\n--- Syndicating to Hashnode ---");
const syndicationDocId = `syndication.${doc._id}.hashnode`;
const publicationId = process.env.HASHNODE_PUBLICATION_ID || "60242f8180da6c44eadf775b";
const subtitle = doc.excerpt && doc.excerpt.length > 250
? doc.excerpt.substring(0, 247) + "..."
: (doc.excerpt || "");
const mappedHashnodeTags = docTags
.map((t) => ({
name: t?.label || t?.value || "",
slug: (t?.value || t?.label || "").toLowerCase().replace(/[^a-z0-9-]/g, "-"),
}))
.filter((t) => t.name && t.slug)
.slice(0, 4);
const hashnodeTags = mappedHashnodeTags.length > 0
? mappedHashnodeTags
: [
{ name: "JavaScript", slug: "javascript" },
{ name: "Web Development", slug: "web-development" },
{ name: "Beginner Developers", slug: "beginners" },
];
const hashnodeCoverImageUrl = urlForImage(doc.coverImage)?.width(1600).url() || "";
const youtubeEmbed = doc.youtube ? `%[${doc.youtube.replace("live", "embed")}]\n\n` : "";
const articleInput = {
title: doc.title || "Untitled",
subtitle,
publicationId,
slug: `${doc._type}-${slug}`,
tags: hashnodeTags,
...(hashnodeCoverImageUrl ? { coverImage: hashnodeCoverImageUrl } : {}),
originalArticleURL: canonicalUrl,
contentMarkdown: `Original: ${canonicalUrl}\n\n${youtubeEmbed}${contentMarkdown}`,
};
try {
const authHeader = hashnodeToken.startsWith("Bearer ") ? hashnodeToken : `Bearer ${hashnodeToken}`;
const publishRes = await fetch("https://gql-beta.hashnode.com", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: authHeader,
"x-hashnode-client": "hashnode-cli",
},
body: JSON.stringify({
operationName: "publishPost",
query: `mutation publishPost($input: PublishPostInput!) {
publishPost(input: $input) {
post {
id
title
slug
url
}
}
}`,
variables: { input: articleInput },
}),
});
const publishData = await publishRes.json();
console.log("Hashnode response:", JSON.stringify(publishData, null, 2));
const publishedPost = publishData?.data?.publishPost?.post;
if (publishedPost) {
const externalUrl = publishedPost.url || `https://hashnode.codingcat.dev/${publishedPost.slug}`;
console.log(`✓ Hashnode published: ${externalUrl}`);
await client.createOrReplace({
_id: syndicationDocId,
_type: "syndication",
target: { _type: "reference", _ref: doc._id },
platform: "hashnode",
status: "published",
canonicalUrl,
externalUrl,
externalId: publishedPost.slug || publishedPost.id,
syndicatedAt: new Date().toISOString(),
});
const postSlug = publishedPost.slug || publishedPost.id;
await client.patch(doc._id).set({ hashnode: postSlug }).commit();
console.log(`✓ Updated Sanity doc ${doc._id} hashnode slug`);
} else {
console.error("✗ Hashnode publication failed:", publishData?.errors);
}
} catch (err) {
console.error("✗ Hashnode request error:", err);
}
}
// --- AWS BUILDER CENTER SYNDICATION (Gated on AWS tag) ---
const awsSessionToken = process.env.AWS_BUILDER_SESSION_TOKEN;
if (shouldSyndicateAws && awsSessionToken) {
console.log("\n--- Syndicating to AWS Builder Center ---");
const syndicationDocId = `syndication.${doc._id}.awsbuilder`;
const awsHeaders = {
"Content-Type": "application/json",
Accept: "application/json",
"builder-session-token": awsSessionToken,
};
try {
const existingSyndication = await client.getDocument(syndicationDocId).catch(() => null);
const urlContentIdMatch = doc.awsbuilder?.match(/builder\.aws\.com\/content\/([A-Za-z0-9]+)/);
let contentId =
(existingSyndication?.externalId && !String(existingSyndication.externalId).startsWith("simulated-")
? String(existingSyndication.externalId)
: null) ||
(urlContentIdMatch ? urlContentIdMatch[1] : null);
let versionId = null;
if (contentId) {
const editInitRes = await fetch("https://api.builder.aws.com/cs/article/InitializeEditArticle", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify({ contentId }),
});
if (editInitRes.ok) {
const editInitJson = await editInitRes.json();
versionId = editInitJson?.versionId || null;
}
}
if (!contentId || !versionId) {
const initRes = await fetch("https://api.builder.aws.com/cs/article/InitializeArticle", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify({}),
});
if (!initRes.ok) {
throw new Error(`InitializeArticle failed (${initRes.status}): ${await initRes.text()}`);
}
const initJson = await initRes.json();
contentId = initJson?.contentId;
versionId = initJson?.versionId;
}
let coverImageUploadKey;
const coverImageUrl = urlForImage(doc.coverImage)?.width(1280).format("jpg").url() || "";
if (coverImageUrl) {
const imgRes = await fetch(coverImageUrl);
if (imgRes.ok) {
const imgBuf = await imgRes.arrayBuffer();
const presignRes = await fetch("https://api.builder.aws.com/cs/upload/generate-presigned-post", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify({
contentId,
fileName: `${slug}-cover.jpg`,
contentType: "image/jpeg",
uploadType: "ARTICLE",
}),
});
if (presignRes.ok) {
const presignData = await presignRes.json();
const formData = new FormData();
for (const [k, v] of Object.entries(presignData.presignedPostFields || {})) {
formData.append(k, String(v));
}
formData.append("file", new Blob([imgBuf], { type: "image/jpeg" }), `${slug}-cover.jpg`);
const s3Res = await fetch(presignData.presignedPostUrl, {
method: "POST",
body: formData,
});
if (s3Res.ok || s3Res.status === 204) {
coverImageUploadKey = presignData.uploadKey;
}
}
}
}
const awsTags = Array.from(
new Set(docTags.map((t) => (t?.value || t?.label || "").toLowerCase()).filter(Boolean).slice(0, 5))
);
if (awsTags.length === 0) awsTags.push("aws");
const youtubeMd = doc.youtube ? `Watch on YouTube: [${doc.youtube}](${doc.youtube})\n\n` : "";
const draftPayload = {
contentId,
versionId,
title: doc.title || "Untitled",
summary: (doc.excerpt || doc.title || "").slice(0, 300),
contentBody: `*Originally published at [${canonicalUrl}](${canonicalUrl})*\n\n${youtubeMd}${contentMarkdown}`,
canonicalUrl,
preferredUrlSlug: slug,
tags: awsTags,
autoSave: false,
...(coverImageUploadKey ? { coverImageUploadKey, coverImageAlt: doc.title || "Cover image" } : {}),
};
const saveRes = await fetch("https://api.builder.aws.com/cs/article/SaveArticleDraft", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify(draftPayload),
});
if (!saveRes.ok) {
throw new Error(`SaveArticleDraft failed (${saveRes.status}): ${await saveRes.text()}`);
}
await fetch("https://api.builder.aws.com/cs/article/SubmissionCheck", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify({ contentId, versionId }),
});
const pubRes = await fetch("https://api.builder.aws.com/cs/article/PublishArticle", {
method: "POST",
headers: awsHeaders,
body: JSON.stringify({ contentId, versionId }),
});
if (!pubRes.ok) {
throw new Error(`PublishArticle failed (${pubRes.status}): ${await pubRes.text()}`);
}
const externalUrl = `https://builder.aws.com/content/${contentId}/${slug}`;
console.log(`✓ AWS Builder Center published: ${externalUrl}`);
await client.createOrReplace({
_id: syndicationDocId,
_type: "syndication",
target: { _type: "reference", _ref: doc._id },
platform: "awsbuilder",
status: "published",
canonicalUrl,
externalUrl,
externalId: String(contentId),
syndicatedAt: new Date().toISOString(),
});
await client.patch(doc._id).set({ awsbuilder: externalUrl }).commit();
} catch (err) {
console.error("✗ AWS Builder Center syndication error:", err);
}
}
// --- LINK SYNDICATION REFERENCES ON PARENT ---
try {
const platforms = ["devto", "hashnode", ...(shouldSyndicateAws ? ["awsbuilder"] : [])];
const expectedRefs = platforms.map((p) => `syndication.${doc._id}.${p}`);
const latestDoc = await client.getDocument(doc._id);
const existingRefs = (latestDoc?.syndications || []).map((s) => s._ref);
const newRefs = expectedRefs.filter((ref) => !existingRefs.includes(ref));
if (newRefs.length > 0) {
const referencesToAppend = newRefs.map((ref) => ({
_key: `syn_${ref.replace(/[^a-zA-Z0-9]/g, "_")}`,
_type: "reference",
_ref: ref,
}));
await client
.patch(doc._id)
.setIfMissing({ syndications: [] })
.append("syndications", referencesToAppend)
.commit();
console.log(`✓ Linked ${newRefs.length} syndications to parent document ${doc._id}`);
}
} catch (err) {
console.warn("Could not append syndications array to parent:", err);
}
console.log("\nSyndication run completed successfully!");
}
run().catch((err) => {
console.error("Run error:", err);
process.exit(1);
});