1 import { Octokit } from "@octokit/core"
2 import * as core from "@actions/core"
3
4 const octokit = new Octokit({
5 auth: process.env.GH_TOKEN,
6 })
7
8 interface AnnouncementPayload {
9 title: string
10 subtitle?: string
11 image: {
12 content: string
13 mimeType: string
14 filename?: string
15 }
16 content: string
17 type: string
18 link_url?: string
19 published: boolean
20 published_at?: string
21 }
22
23 /**
24 * Extracts metadata from the release markdown content.
25 * Expected format:
26 * <!--
27 * ![alt](image-url)
28 * # Subtitle text
29 * Content text
30 * CMS_BREAK -->
31 */
32 function parseReleaseContent(body: string): {
33 imageUrl: string | null
34 subtitle: string | null
35 content: string | null
36 } {
37 let imageUrl: string | null = null
38 let subtitle: string | null = null
39 let content: string | null = null
40
41 // Extract content between <!-- and CMS_BREAK -->
42 const commentMatch = body.match(/<!--\s*([\s\S]*?)\s*CMS_BREAK\s*-->/i)
43 if (!commentMatch) {
44 return { imageUrl, subtitle, content }
45 }
46
47 const commentContent = commentMatch[1].trim()
48
49 // Extract image URL from markdown image syntax
50 const imageMatch = commentContent.match(/!\[.*?\]\((.*?)\)/)
51 if (imageMatch) {
52 imageUrl = imageMatch[1].trim()
53 }
54
55 // Extract h1 heading as subtitle
56 const h1Match = commentContent.match(/^#\s+(.+)$/m)
57 if (h1Match) {
58 subtitle = h1Match[1].trim()
59 }
60
61 // Extract content after h1 heading
62 if (h1Match) {
63 const h1Index = commentContent.indexOf(h1Match[0])
64 const afterH1 = commentContent.substring(h1Index + h1Match[0].length).trim()
65 // Remove any remaining markdown image syntax
66 content = afterH1.replace(/!\[.*?\]\(.*?\)/g, "").trim()
67 }
68
69 return { imageUrl, subtitle, content }
70 }
71
72 /**
73 * Downloads an image and converts it to base64
74 */
75 async function downloadImageAsBase64(
76 imageUrl: string
77 ): Promise<{ content: string; mimeType: string; filename: string }> {
78 const response = await fetch(imageUrl)
79 if (!response.ok) {
80 throw new Error(`Failed to download image: ${response.statusText}`)
81 }
82
83 const arrayBuffer = await response.arrayBuffer()
84 const buffer = Buffer.from(arrayBuffer)
85 const base64 = buffer.toString("base64")
86
87 // Determine mime type from response or URL
88 const mimeType = response.headers.get("content-type") || "image/jpeg"
89
90 // Extract filename from URL
91 const urlParts = imageUrl.split("/")
92 const filename = urlParts[urlParts.length - 1] || "release-image.jpg"
93
94 return {
95 content: base64,
96 mimeType,
97 filename,
98 }
99 }
100
101 /**
102 * Sends the announcement to the cloud API
103 */
104 async function sendAnnouncement(payload: AnnouncementPayload): Promise<void> {
105 const apiUrl = process.env.ANNOUNCEMENTS_API_URL
106 const apiToken = process.env.ANNOUNCEMENTS_API_TOKEN
107 if (!apiUrl || !apiToken) {
108 throw new Error(
109 "ANNOUNCEMENTS_API_URL or ANNOUNCEMENTS_API_TOKEN environment variable is not set"
110 )
111 }
112
113 const response = await fetch(apiUrl, {
114 method: "POST",
115 headers: {
116 "Content-Type": "application/json",
117 Authorization: `Basic ${apiToken}`,
118 },
119 body: JSON.stringify(payload),
120 })
121
122 if (!response.ok) {
123 const errorText = await response.text()
124 throw new Error(
125 `Failed to create announcement: ${response.status} ${response.statusText} - ${errorText}`
126 )
127 }
128
129 const result = await response.json()
130 console.log("Announcement created successfully:", result)
131 }
132
133 async function createCloudAnnouncement() {
134 console.log("Fetching latest release...")
135
136 // Retrieve latest release
137 const { data: release } = await octokit.request(
138 "GET /repos/{owner}/{repo}/releases/latest",
139 {
140 owner: process.env.GIT_OWNER || "medusajs",
141 repo: process.env.GIT_REPO || "medusa",
142 headers: {
143 "X-GitHub-Api-Version": "2022-11-28",
144 },
145 }
146 )
147
148 if (!release) {
149 throw new Error("No release found.")
150 }
151
152 console.log(`Found release: ${release.name} (${release.tag_name})`)
153
154 // Parse release body
155 const { imageUrl, subtitle, content } = parseReleaseContent(
156 release.body || ""
157 )
158
159 if (!imageUrl) {
160 throw new Error(
161 "No image URL found in release body. Expected format: <!-- ![alt](image-url) ... CMS_BREAK -->"
162 )
163 }
164
165 if (!subtitle) {
166 console.warn(
167 "No subtitle found in release body. Using release title as fallback."
168 )
169 }
170
171 if (!content) {
172 console.warn(
173 "No content found in release body. Using default message as fallback."
174 )
175 }
176
177 console.log(`Downloading image from: ${imageUrl}`)
178
179 // Download and convert image to base64
180 const image = await downloadImageAsBase64(imageUrl)
181
182 console.log(`Image downloaded: ${image.filename} (${image.mimeType})`)
183
184 // Prepare announcement payload
185 const payload: AnnouncementPayload = {
186 title: "New Medusa Version Released",
187 subtitle: subtitle || release.name || undefined,
188 image,
189 content: content || "Learn more about the latest Medusa release",
190 type: "release",
191 link_url: release.html_url,
192 published: false,
193 published_at: new Date().toISOString(),
194 }
195
196 console.log("Sending announcement to API...")
197
198 // Send to API
199 await sendAnnouncement(payload)
200
201 core.setOutput("announcement_created", true)
202 core.setOutput("release_tag", release.tag_name)
203 }
204
205 void createCloudAnnouncement()