-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
215 lines (192 loc) · 6.15 KB
/
index.js
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
const fs = require("fs");
const core = require("@actions/core");
const { getPlaygroundUrl } = require("livecodes");
const { encode } = require("js-base64");
const mime = require("mime");
const sha = process.env.SHA || "";
const ref = process.env.REF || "";
const pr = process.env.PR || "";
const lastUpdated = process.env.LAST_UPDATED || "";
const repo = process.env.REPO || "";
const baseUrl = (process.env.BASE_URL || "")
.replace(/{{\s*LC::SHA\s*}}/g, sha)
.replace(/{{\s*LC::SHORT_SHA\s*}}/g, sha.substring(0, 7))
.replace(/{{\s*LC::REF\s*}}/g, ref)
.replace(/{{\s*LC::PR\s*}}/g, pr)
.replace(/{{\s*LC::REPO\s*}}/g, repo);
const projectsRoot = ".livecodes";
const replaceValues = (str) => {
const getPattern = (type = "TO_DATA_URL") =>
`{{\\s*LC::${type}\\(['"]?(?:\\.[\\/\\\\])?([^\\)'"]+)['"]?\\)\\s*}}`;
return str
.replace(/{{\s*LC::SHA\s*}}/g, sha)
.replace(/{{\s*LC::SHORT_SHA\s*}}/g, sha.substring(0, 7))
.replace(/{{\s*LC::REF\s*}}/g, ref)
.replace(/{{\s*LC::PR\s*}}/g, pr)
.replace(/{{\s*LC::REPO\s*}}/g, repo)
.replace(new RegExp(getPattern("TO_DATA_URL"), "g"), (_match, file) => {
try {
const type = mime.getType(file) || "text/javascript";
const content = fs.readFileSync(file, "utf8");
return content ? toDataUrl(content, type) : file;
} catch {
return file;
}
})
.replace(new RegExp(getPattern("TO_URL"), "g"), (_match, file) => {
if (!baseUrl) return file;
try {
return new URL(file, baseUrl).href;
} catch {
return file;
}
});
};
const uploadConfig = async (config) => {
const dpasteGetUrl = "https://dpaste.com/";
const dpastePostUrl = "https://dpaste.com/api/v2/";
try {
const res = await fetch(dpastePostUrl, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "LiveCodes / https://livecodes.io/",
},
body: `content=${encodeURIComponent(
JSON.stringify(config)
)}&title=${encodeURIComponent(
config.title || ""
)}&syntax=json&expiry_days=365`,
});
if (!res.ok) return "";
const url = await res.text();
return url.replace(dpasteGetUrl, "").trim();
} catch (error) {
return "";
}
};
const getProjects = () => {
const files = fs.readdirSync(projectsRoot);
return files
.map((file) => {
try {
const path = `${projectsRoot}/${file}`;
const content = fs.readFileSync(path, "utf8");
const hasDataUrls = content.includes("{{LC::TO_DATA_URL");
const contentWithUrls = replaceValues(content);
const options = JSON.parse(contentWithUrls);
const isConfig = !Object.keys(options).find((key) =>
[
"appUrl",
"config",
"params",
"import",
"template",
"view",
"lite",
"loading",
].includes(key)
);
const config = isConfig ? options : options.config;
const embedOptions = isConfig ? { config: options } : options;
const prLabel =
config?.title ||
getStarterTitle(embedOptions.template) ||
removeExtension(file);
return { prLabel, hasDataUrls, ...embedOptions };
} catch (error) {
console.error(error);
return;
}
})
.filter((x) => x != null);
};
const toDataUrl = (content, type) =>
`data:${type};charset=UTF-8;base64,` + encode(content);
const removeExtension = (path) => path.split(".").slice(0, -1).join(".");
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
const getStarterTitle = (name) =>
!name ? "" : name.split("-").map(capitalize).join(" ") + " Template";
const trimLongUrl = (url, max) => {
if (url.length > max) {
return url.slice(0, max) + "...";
}
return url;
};
const getFormattedDate = (dateStr) => {
try {
const date = new Date(dateStr);
return (
"**Last updated:** " +
date.toLocaleString("en-US", { month: "short", timeZone: "UTC" }) +
" " +
date.getUTCDate() +
", " +
date.getUTCFullYear() +
" " +
date
.toLocaleString("en-US", {
hour: "numeric",
minute: "numeric",
hour12: true,
timeZone: "UTC",
})
.split(" ")
.join("")
.toLocaleLowerCase() +
" (UTC)"
);
} catch {
return "";
}
};
const generateOutput = (projects) => {
const projectsMarkDown = projects.map(
(project) =>
`| **${project.title}** | [${trimLongUrl(project.url, 50)}](${
project.url
}) |`
);
return `
## <a href="https://livecodes.io"><img alt="LiveCodes logo" src="https://livecodes.io/livecodes/assets/images/livecodes-logo.svg" width="32"></a> Preview in <a href="https://livecodes.io">LiveCodes</a>
**Latest commit:** ${sha}
${getFormattedDate(lastUpdated)}
| Playground | Link |
|:-:|------------------------|
${projectsMarkDown.join("\n")}
---
_See [documentations](https://github.com/live-codes/preview-in-livecodes) for usage instructions._
`;
};
const run = async () => {
try {
if (!fs.existsSync(projectsRoot)) {
console.error(`Directory ${projectsRoot} does not exist.`);
}
const projectOptions = getProjects();
if (Object.keys(projectOptions).length === 0) {
console.error(`No configuration files found in ${projectsRoot}.`);
}
const projects = [];
for (const project of projectOptions) {
const { prLabel, hasDataUrls, ...options } = project;
if (hasDataUrls && options.config) {
// sequential requests and delay to respect rate limit of 1 request/second
await new Promise((resolve) => setTimeout(resolve, 1500));
const id = await uploadConfig(options.config);
if (id) {
options.import = "id/" + id;
delete options.config;
}
}
const playgroundUrl = getPlaygroundUrl(options).replace(/%2F/g, "/");
projects.push({ title: prLabel, url: playgroundUrl });
}
const message = generateOutput(projects);
core.setOutput("message", message);
} catch (error) {
core.setFailed(error.message);
}
};
run();