-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
308 lines (272 loc) · 8.72 KB
/
main.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
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
import { markdown } from './src/util/remark/markdown.js'
import {
compileCss,
convertToUSA,
generateSingleFile,
handleUTC,
parseYaml,
replaceBody,
replaceHead,
startServer,
} from './src/util/utils.js'
import {
getRss,
giscus,
templateArticle,
templateBox,
templateProcess,
} from './src/util/template.js'
import { copy, ensureDir, ensureFile, exists, existsSync } from 'fs'
import 'https://deno.land/[email protected]/dotenv/load.ts'
/**
* @typedef {Object} MetaData
* @property {string} MetaData.date
* @property {string} MetaData.title
* @property {string} MetaData.summary
* @property {string[]} MetaData.tags
*/
/**@type {MetaData[]}*/
const metaData = []
const dist = import.meta.resolve('./dist/')
const src = import.meta.resolve('./src/')
const randomNumber = Math.floor(Math.random() * 1000000)
// global config
const website = Deno.env.get('WEBSITE')
const author = Deno.env.get('AUTHOR')
const port = Deno.env.get('PORT')
const header = await Deno.readTextFile(new URL('./util/header.html', src))
const footer = await Deno.readTextFile(new URL('./util/footer.html', src))
const getPosts = (title, content, isPosts = false) =>
`${templateArticle({ title, content, giscus: isPosts ? giscus : '' })}`
const getTags = (title, tags) =>
tags.reduce(
(acc, tag) =>
acc + `<a class="tag" href="/./${title}/${tag}/">
<i class="fa-solid fa-tag"></i> ${tag}
</a>`,
'',
)
/**
* @param {string} title
* @param {MetaData[]} iters
*/
function getArchive(title, iters) {
const content = iters.reduce(
(acc, { date, summary }) => {
const place = `/./posts/${handleUTC(date)}/`
return acc +
`<p><a class="decoration-line" href=${place} target="_blank"> ${summary} ··· ${convertToUSA(date)
}</a></p>`
},
'',
)
return templateArticle({ title, content })
}
/**
* @param {Map<string,MetaData[]>} map
* @param {string} url
* @param {string} dest
*/
async function completeTask(map, url, dest) {
for (const k of map.keys()) {
const tagsUrl = new URL(`./${k}/index.html`, url)
const task = await generatePage(tagsUrl, k, `${author} ~ ${k}`, k)
await task(getArchive, map.get(k))
}
const task = await generatePage(
new URL('./index.html', url),
[...map.keys()].join(', '),
`${author} ~ ${dest}`,
dest,
)
await task(getPosts, getTags(dest, [...map.keys()]))
}
async function generatePage(
/**@type {string}*/ dist,
/**@type {string}*/ keywords,
/**@type {string}*/ description,
/**@type {string}*/ title,
) {
if (!await exists(dist)) await ensureFile(dist)
const head = await replaceHead(keywords, description, title, randomNumber)
return async (fn, ...params) => {
const content = fn(title, ...params)
const index = `${head}${header}${content}${footer}`
await Deno.writeTextFile(dist, index)
}
}
// Handle the meta data
async function handlePosts() {
const posts = import.meta.resolve('./src/posts/')
const iter = Deno.readDir(new URL(posts))[Symbol.asyncIterator]()
while (true) {
const { value, done } = await iter.next()
if (done) break
const file = await Deno.readTextFile(new URL(value.name, posts))
const [{ date, title, summary, tags }, md] = parseYaml(file)
// Handle the posts
{
const timeDir = new URL(`./posts/${handleUTC(date)}/index.html`, dist)
const task = await generatePage(timeDir, tags.join(', '), summary, title)
await task(getPosts, await markdown(md), true)
}
metaData.push({ date, title, summary, tags })
}
metaData.sort((a, b) => new Date(b.date) - new Date(a.date))
}
// Handle the others source
async function Others() {
await ensureDir(new URL('./public/', dist))
for await (const entry of Deno.readDir(new URL('../public/', src))) {
if (entry.name === 'css') continue
const __src_p = new URL(`../public/${entry.name}`, src)
const __dist_p = new URL(`./public/${entry.name}`, dist)
if (entry.name === 'JavaScript') {
await ensureFile(
new URL(`./${entry.name}/index.${randomNumber}.js`, __dist_p),
)
await copy(
new URL(`./${entry.name}/index.js`, __src_p),
new URL(`./${entry.name}/index.${randomNumber}.js`, __dist_p),
{ overwrite: true },
)
continue
}
await copy(__src_p, __dist_p, { overwrite: true })
}
// compile the css
const __css_d = new URL('./public/css/', dist)
await ensureDir(__css_d)
for await (const entry of Deno.readDir(new URL('../public/css/', src))) {
const path = new URL(`../public/css/${entry.name}`, src)
const code = await compileCss(path)
const fileName = entry.name.split('.').join(`.${randomNumber}.`)
await Deno.writeFile(new URL(fileName, __css_d), code)
}
// Handle the CNAME
const cname = new URL('./CNAME', dist)
// Handle the RSS
const rss = new URL('./feed.xml', dist)
const itemsRss = metaData.reduce((acc, { date, title, summary }) => {
const url = `${website}posts/${handleUTC(date)}/`
return acc + `<item>
<title>${title}</title>
<link>${url}</link>
<description>${summary}</description>
<pubDate>${new Date(date).toUTCString()}</pubDate>
</item>`
}, '')
// sitemap
const sitemap = new URL('./sitemap.xml', dist)
const itemsSitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${metaData.reduce((acc, { date }) =>
`${acc}<url><loc>${website}posts/${handleUTC(date)}/</loc></url>`, '')
}
</urlset>`
// robots
const robots = new URL('./robots.txt', dist)
const robotsContent = `User-agent: *
Allow: /
Sitemap: ${website}sitemap.xml`
const files = [
[rss, getRss(author, website, itemsRss)],
[sitemap, itemsSitemap],
[robots, robotsContent],
]
const g = generateSingleFile(cname, 'www.fwqaq.us')
g.next()
files.forEach((file) => g.next(file))
}
// Home page
async function Home() {
const homeDest = new URL('./home/', dist)
let indexPage = await Deno.readTextFile(new URL('../index.html', src))
indexPage = replaceBody(indexPage, header, footer, randomNumber)
const mLength = metaData.length
const lastPage = Math.ceil(mLength / 8)
let content = ''
for (let index = 0; index < mLength; index++) {
const { date, title, summary, tags } = metaData[index]
const aTags = getTags('tags', tags)
content += templateBox({
place: `/./posts/${handleUTC(date)}/`,
title,
summary,
time: convertToUSA(date),
tags: aTags,
})
if ((index + 1) % 8 === 0 || index + 1 === mLength) {
const cur = index + 1 === mLength
? lastPage
: Math.floor((index + 1) / 8)
const process = templateProcess({
before: cur > 2 ? `/./home/${cur - 1}/` : '/',
page: `${cur} / ${lastPage}`,
after: index === mLength ? '#' : `/./home/${cur + 1}/`,
})
const home = indexPage.replace('<!-- Template -->', content + process)
// Reset the content
content = ''
// Generate the home dir
if (cur !== 1) await ensureDir(new URL(`${cur}/`, homeDest))
const url = cur === 1
? new URL('./index.html', dist)
: new URL(`${cur}/index.html`, homeDest)
await Deno.writeTextFile(url, home)
}
}
}
// Archive page
async function Archive() {
const archiveDest = new URL('./archive/', dist)
const map = new Map()
for (const meta of metaData) {
const year = new Date(meta.date).getFullYear()
map.has(year) ? map.get(year).push(meta) : map.set(year, [meta])
}
await completeTask(map, archiveDest, 'archive')
}
// Tags page
async function Tags() {
const tagsDest = new URL('./tags/', dist)
const map = new Map()
for (const meta of metaData) {
meta.tags.forEach((tag) => {
map.has(tag) ? map.get(tag).push(meta) : map.set(tag, [meta])
})
}
await completeTask(map, tagsDest, 'tags')
}
async function About() {
const __dist_about = new URL('./about/index.html', dist)
if (!await exists(__dist_about)) await ensureFile(__dist_about)
const __src_about = new URL('./about/about.md', src)
const about = await Deno.readTextFile(__src_about)
const head = await replaceHead(
'fwqaaq, GitHub fwqaaq, study, about',
'关于我',
'关于我',
randomNumber,
)
const [, md] = parseYaml(about)
const content = await markdown(md)
const generated = `${head}${header}${templateArticle({ title: '关于我', content })
}${footer}`
await Deno.writeTextFile(__dist_about, generated)
}
async function main() {
if (existsSync(new URL(dist))) {
Deno.removeSync(new URL(dist), { recursive: true })
}
await handlePosts()
Promise.all([Home(), Archive(), Tags(), Others(), About()])
}
// Handle the http server
const mode = Deno.env.get('MODE')
if (mode === 'DEV' || mode === 'PRO') {
main()
}
if (mode === 'DEV' || mode === 'PRE') {
startServer(port)
}