-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathpublish.post.ts
More file actions
307 lines (275 loc) · 9.08 KB
/
publish.post.ts
File metadata and controls
307 lines (275 loc) · 9.08 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
import {
Comment,
isPullRequest,
isWhitelisted,
} from "@pkg-pr-new/utils";
import { randomUUID } from "uncrypto";
import { setItemStream, useTemplatesBucket } from "~/utils/bucket";
import { useOctokitInstallation } from "~/utils/octokit";
import { generateTemplateHtml } from "~/utils/template";
import type { PackageManager } from "@pkg-pr-new/utils";
import type { components as OctokitComponents } from "@octokit/openapi-types";
export default eventHandler(async (event) => {
const origin = getRequestURL(event).origin;
const {
"sb-run-id": runIdHeader,
"sb-key": key,
"sb-shasums": shasumsHeader,
"sb-comment": commentHeader,
"sb-compact": compactHeader,
"sb-package-manager": packageManagerHeader,
"sb-only-templates": onlyTemplatesHeader,
} = getHeaders(event);
const compact = compactHeader === "true";
const onlyTemplates = onlyTemplatesHeader === "true";
const comment: Comment = (commentHeader ?? "update") as Comment;
const packageManager: PackageManager =
(packageManagerHeader as PackageManager) || "npm";
if (!key || !runIdHeader || !shasumsHeader) {
throw createError({
statusCode: 400,
message:
"sb-commit-timestamp, sb-key and sb-shasums headers are required",
});
}
const runId = Number(runIdHeader);
const workflowsBucket = useWorkflowsBucket(event);
const workflowData = await workflowsBucket.getItem(key);
if (!workflowData) {
throw createError({
statusCode: 404,
fatal: true,
message: `There is no workflow defined for ${key}`,
});
}
const whitelisted = await isWhitelisted(
workflowData.owner,
workflowData.repo,
);
const contentLength = Number(getHeader(event, "content-length"));
// 20mb limit for now
if (!whitelisted && contentLength > 1024 * 1024 * 20) {
// Payload too large
throw createError({
statusCode: 413,
message:
"Max payload limit is 20mb! Feel free to apply for the whitelist: https://github.com/stackblitz-labs/pkg.pr.new/blob/main/.whitelist",
});
}
const shasums: Record<string, string> = JSON.parse(shasumsHeader);
const formData = await readFormData(event);
const packages = [...formData.keys()].filter((k) => k.startsWith("package:"));
const packagesWithoutPrefix = packages.map((p) => p.slice("package:".length));
const templateAssets = [...formData.keys()].filter((k) =>
k.startsWith("template:"),
);
if (!packages.length) {
throw createError({
statusCode: 400,
message: "No packages",
});
}
const { appId } = useRuntimeConfig(event);
const cursorBucket = useCursorsBucket(event);
if (!(await workflowsBucket.hasItem(key))) {
throw createError({
statusCode: 401,
message:
"Try publishing from a github workflow! Also make sure you install https://github.com/apps/pkg-pr-new GitHub app on the repo",
});
}
const baseKey = `${workflowData.owner}:${workflowData.repo}`;
const cursorKey = `${baseKey}:${workflowData.ref}`;
const currentCursor = await cursorBucket.getItem(cursorKey);
await Promise.all(
packages.map(async (packageNameWithPrefix) => {
const packageName = packageNameWithPrefix.slice("package:".length);
const packageKey = `${baseKey}:${workflowData.sha}:${packageName}`;
const file = formData.get(packageNameWithPrefix)!;
if (file instanceof File) {
const stream = file.stream();
return setItemStream(
event,
usePackagesBucket.base,
packageKey,
stream,
{
sha1: shasums[packageName],
},
);
}
}),
);
const templatesMap = new Map<string, Record<string, string>>();
await Promise.all(
templateAssets.map(async (templateAssetWithPrefix) => {
const file = formData.get(templateAssetWithPrefix)!;
const [template, encodedTemplateAsset] = templateAssetWithPrefix
.slice("template:".length)
.split(":");
const templateAsset = decodeURIComponent(encodedTemplateAsset);
const isBinary = !(typeof file === "string");
const uuid = randomUUID();
templatesMap.set(template, {
...templatesMap.get(template),
[templateAsset]: isBinary
? new URL(`/template/${uuid}`, origin).href
: file,
});
if (isBinary) {
const stream = file.stream();
return setItemStream(event, useTemplatesBucket.base, uuid, stream);
}
}),
);
const templatesBucket = useTemplatesBucket(event);
const textEncoder = new TextEncoder();
const templatesHtmlMap: Record<string, string> = {};
for (const [template, files] of templatesMap) {
const html = generateTemplateHtml(template, files);
const uuid = randomUUID();
await templatesBucket.setItemRaw(uuid, textEncoder.encode(html));
templatesHtmlMap[template] = new URL(`/template/${uuid}`, origin).href;
}
if (!currentCursor || currentCursor.timestamp < runId) {
await cursorBucket.setItem(cursorKey, {
sha: workflowData.sha,
timestamp: runId,
});
}
await workflowsBucket.removeItem(key);
const installation = await useOctokitInstallation(
event,
workflowData.owner,
workflowData.repo,
);
const checkName = "Continuous Releases";
const {
data: { check_runs },
} = await installation.request(
"GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
{
check_name: checkName,
owner: workflowData.owner,
repo: workflowData.repo,
ref: workflowData.sha,
app_id: Number(appId),
},
);
let checkRunUrl = check_runs[0]?.html_url ?? "";
if (!check_runs.length) {
const {
data: { html_url },
} = await installation.request("POST /repos/{owner}/{repo}/check-runs", {
name: checkName,
owner: workflowData.owner,
repo: workflowData.repo,
head_sha: workflowData.sha,
output: {
title: "Successful",
summary: "Published successfully.",
text: generateCommitPublishMessage(
origin,
templatesHtmlMap,
packagesWithoutPrefix,
workflowData,
compact,
packageManager,
),
},
conclusion: "success",
});
checkRunUrl = html_url!;
}
if (isPullRequest(workflowData.ref)) {
let prevComment: OctokitComponents["schemas"]["issue-comment"];
await installation.paginate(
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
{
owner: workflowData.owner,
repo: workflowData.repo,
issue_number: Number(workflowData.ref),
},
({ data }, done) => {
for (const c of data) {
if (c.performed_via_github_app?.id === Number(appId)) {
prevComment = c;
done();
break;
}
}
return [];
},
);
if (comment !== "off") {
if (comment === "update" && prevComment!) {
await installation.request(
"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}",
{
owner: workflowData.owner,
repo: workflowData.repo,
comment_id: prevComment.id,
body: generatePullRequestPublishMessage(
origin,
templatesHtmlMap,
packagesWithoutPrefix,
workflowData,
compact,
onlyTemplates,
checkRunUrl,
packageManager,
"ref",
),
},
);
} else {
try {
await installation.request(
"POST /repos/{owner}/{repo}/issues/{issue_number}/comments",
{
owner: workflowData.owner,
repo: workflowData.repo,
issue_number: Number(workflowData.ref),
body: generatePullRequestPublishMessage(
origin,
templatesHtmlMap,
packagesWithoutPrefix,
workflowData,
compact,
onlyTemplates,
checkRunUrl,
packageManager,
comment === "update" ? "ref" : "sha",
),
},
);
} catch (error) {
throw createError({
statusCode: 500,
message: `Failed to create pull request comment. Details:
Error: ${error instanceof Error ? error.message : String(error)}
Context:
- Owner: ${workflowData.owner}
- Repo: ${workflowData.repo}
- Issue Number: ${Number(workflowData.ref)}
- Origin: ${origin}
- Templates: ${JSON.stringify(templatesHtmlMap)}
- Packages: ${packagesWithoutPrefix.join(', ')}
- Workflow Data: ${JSON.stringify(workflowData)}
- Compact: ${compact}
- Only Templates: ${onlyTemplates}
- Check Run URL: ${checkRunUrl}
- Package Manager: ${packageManager}
- Comment Type: ${comment === "update" ? "ref" : "sha"}`,
});
}
}
}
}
return {
ok: true,
urls: packagesWithoutPrefix.map((packageName) =>
generatePublishUrl("sha", origin, packageName, workflowData, compact),
),
};
});