-
Notifications
You must be signed in to change notification settings - Fork 98
/
index.ts
179 lines (153 loc) · 5.76 KB
/
index.ts
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
import { getInput, setOutput, setFailed, summary } from "@actions/core";
import type { Project, Deployment } from "@cloudflare/types";
import { context, getOctokit } from "@actions/github";
import shellac from "shellac";
import { fetch } from "undici";
import { env } from "process";
import path from "node:path";
type Octokit = ReturnType<typeof getOctokit>;
try {
const apiToken = getInput("apiToken", { required: true });
const accountId = getInput("accountId", { required: true });
const projectName = getInput("projectName", { required: true });
const directory = getInput("directory", { required: true });
const gitHubToken = getInput("gitHubToken", { required: false });
const branch = getInput("branch", { required: false });
const workingDirectory = getInput("workingDirectory", { required: false });
const wranglerVersion = getInput("wranglerVersion", { required: false });
const getProject = async () => {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/pages/projects/${projectName}`,
{ headers: { Authorization: `Bearer ${apiToken}` } }
);
if (response.status !== 200) {
console.error(`Cloudflare API returned non-200: ${response.status}`);
const json = await response.text();
console.error(`API returned: ${json}`);
throw new Error("Failed to get Pages project, API returned non-200");
}
const { result } = (await response.json()) as { result: Project | null };
if (result === null) {
throw new Error("Failed to get Pages project, project does not exist. Check the project name or create it!");
}
return result;
};
const createPagesDeployment = async () => {
// TODO: Replace this with an API call to wrangler so we can get back a full deployment response object
await shellac.in(path.join(process.cwd(), workingDirectory))`
$ export CLOUDFLARE_API_TOKEN="${apiToken}"
if ${accountId} {
$ export CLOUDFLARE_ACCOUNT_ID="${accountId}"
}
$$ npx wrangler@${wranglerVersion} pages publish "${directory}" --project-name="${projectName}" --branch="${branch}"
`;
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/pages/projects/${projectName}/deployments`,
{ headers: { Authorization: `Bearer ${apiToken}` } }
);
const {
result: [deployment],
} = (await response.json()) as { result: Deployment[] };
return deployment;
};
const githubBranch = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;
const createGitHubDeployment = async (octokit: Octokit, productionEnvironment: boolean, environment: string) => {
const deployment = await octokit.rest.repos.createDeployment({
owner: context.repo.owner,
repo: context.repo.repo,
ref: githubBranch || context.ref,
auto_merge: false,
description: "Cloudflare Pages",
required_contexts: [],
environment,
production_environment: productionEnvironment,
});
if (deployment.status === 201) {
return deployment.data;
}
};
const createGitHubDeploymentStatus = async ({
id,
url,
deploymentId,
environmentName,
productionEnvironment,
octokit,
}: {
octokit: Octokit;
id: number;
url: string;
deploymentId: string;
environmentName: string;
productionEnvironment: boolean;
}) => {
await octokit.rest.repos.createDeploymentStatus({
owner: context.repo.owner,
repo: context.repo.repo,
deployment_id: id,
// @ts-ignore
environment: environmentName,
environment_url: url,
production_environment: productionEnvironment,
log_url: `https://dash.cloudflare.com/${accountId}/pages/view/${projectName}/${deploymentId}`,
description: "Cloudflare Pages",
state: "success",
auto_inactive: false,
});
};
const createJobSummary = async ({ deployment, aliasUrl }: { deployment: Deployment; aliasUrl: string }) => {
const deployStage = deployment.stages.find((stage) => stage.name === "deploy");
let status = "⚡️ Deployment in progress...";
if (deployStage?.status === "success") {
status = "✅ Deploy successful!";
} else if (deployStage?.status === "failure") {
status = "🚫 Deployment failed";
}
await summary
.addRaw(
`
# Deploying with Cloudflare Pages
| Name | Result |
| ----------------------- | - |
| **Last commit:** | \`${deployment.deployment_trigger.metadata.commit_hash.substring(0, 8)}\` |
| **Status**: | ${status} |
| **Preview URL**: | ${deployment.url} |
| **Branch Preview URL**: | ${aliasUrl} |
`
)
.write();
};
(async () => {
const project = await getProject();
const productionEnvironment = githubBranch === project.production_branch || branch === project.production_branch;
const environmentName = `${projectName} (${productionEnvironment ? "Production" : "Preview"})`;
let gitHubDeployment: Awaited<ReturnType<typeof createGitHubDeployment>>;
if (gitHubToken && gitHubToken.length) {
const octokit = getOctokit(gitHubToken);
gitHubDeployment = await createGitHubDeployment(octokit, productionEnvironment, environmentName);
}
const pagesDeployment = await createPagesDeployment();
setOutput("id", pagesDeployment.id);
setOutput("url", pagesDeployment.url);
setOutput("environment", pagesDeployment.environment);
let alias = pagesDeployment.url;
if (!productionEnvironment && pagesDeployment.aliases && pagesDeployment.aliases.length > 0) {
alias = pagesDeployment.aliases[0];
}
setOutput("alias", alias);
await createJobSummary({ deployment: pagesDeployment, aliasUrl: alias });
if (gitHubDeployment) {
const octokit = getOctokit(gitHubToken);
await createGitHubDeploymentStatus({
id: gitHubDeployment.id,
url: pagesDeployment.url,
deploymentId: pagesDeployment.id,
environmentName,
productionEnvironment,
octokit,
});
}
})();
} catch (thrown) {
setFailed(thrown.message);
}