-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathindex.ts
More file actions
241 lines (218 loc) · 7.95 KB
/
index.ts
File metadata and controls
241 lines (218 loc) · 7.95 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
import type { AstroIntegration } from "astro";
import type { Root as MdastRoot } from "mdast";
import type { Root as HastRoot } from "hast";
import { VFile } from "vfile";
import { selectAll } from "hast-util-select";
import { visit as unistVisit } from "unist-util-visit";
import { visit as estreeVisit } from "estree-util-visit";
import rehypeRaw from "rehype-raw";
import "mdast-util-mdx";
import path from "node:path";
import { glob } from "glob";
import yaml from "js-yaml";
import { fileURLToPath } from "node:url";
import { readFile, copyFile, mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
/** @type {[string, ...string[]]} */
const ORIGINS = [
"https://utelecon.adm.u-tokyo.ac.jp",
"https://utelecon.github.io",
];
/**
* 画像などのアセットを src/pages 配下のページ自体と同居させるための処理を行う一連の機能群.
* 詳しくは {@link ./README.md} を参照.
*/
export default function assetColocation(
extensions: string[],
): AstroIntegration {
const usedImages = new Set<string>();
const referredPaths = new Set<string>();
return {
name: "asset-colocation",
hooks: {
"astro:config:setup"({ updateConfig }) {
updateConfig({
markdown: {
remarkPlugins: [
[collectImagePaths, { usedImages }],
[collectReferredPaths, { referredPaths }],
],
rehypePlugins: [
rehypeRaw,
[rehypeCollectImagePaths, { usedImages }],
[rehypeCollectReferredPaths, { referredPaths }],
],
},
});
},
async "astro:build:done"() {
const noticeProcessor = unified()
.use(remarkParse)
.use(collectReferredPaths, { referredPaths })
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeCollectReferredPaths, { referredPaths })
.use(rehypeStringify); // ないと process できない
// notice.yml だけは特別扱いして,そこが参照しているパスも収集する
const noticeYmlPath = path.resolve("src/data/notice.yml");
const noticeYml = await readFile(noticeYmlPath, "utf-8");
const notice = yaml.load(noticeYml) as {
content: Record<"ja" | "en", string>;
}[];
for (const { content } of notice) {
const value = Object.values(content).join("\n");
const vfile = new VFile({ path: noticeYmlPath, value });
await noticeProcessor.process(vfile);
}
// Warn for unused assets
const files = await glob("**/!(_)*", {
cwd: "src/pages",
ignore: ["**/*.{md,markdown,mdx,html,astro}"],
nodir: true,
absolute: false,
});
const assets = new Set(
files
.filter((file) => extensions.includes(path.extname(file)))
.map((file) => "/" + file),
);
const publicFiles = await glob("**", {
cwd: "public",
nodir: true,
absolute: false,
});
const publicAssets = new Set(
publicFiles
.filter((file) => extensions.includes(path.extname(file)))
.map((file) => "/" + file),
);
for (const asset of assets) {
if (!usedImages.has(asset) && !referredPaths.has(asset)) {
console.warn(
`[asset-colocation] Warning: Asset "${asset}" is not used in any page and will be ignored.`,
);
}
}
// Warn for referred assets not existing
const copyFiles: { from: string; to: string }[] = [];
for (const referredPath of referredPaths) {
if (!extensions.includes(path.extname(referredPath))) continue;
if (assets.has(referredPath)) {
const from = path.resolve("src/pages", "." + referredPath);
const to = path.resolve("dist", "." + referredPath);
copyFiles.push({ from, to });
} else if (
!publicAssets.has(referredPath) &&
!existsSync(`src/pages${referredPath}.md`) // redirect file
) {
console.warn(
`[asset-colocation] Warning: Referred asset "${referredPath}" does not exist in src/pages.`,
);
}
}
// Copy assets from source to output directory
await Promise.all(
copyFiles.map(async ({ from, to }) => {
await mkdir(path.dirname(to), { recursive: true });
await copyFile(from, to);
}),
);
},
},
};
}
const ALLOWED_PREFIXES = ["http:", "https:", "/", "./", "../", "@"];
function createFixAndCollect(usedImages: Set<string>, file: VFile) {
const imagePaths = new Set(file.data.astro!.localImagePaths);
const basePath = "/" + path.dirname(path.relative("src/pages", file.path));
function fixAndCollect(p: string) {
if (!ALLOWED_PREFIXES.some((prefix) => p.startsWith(prefix))) {
p = `./${p}`;
}
if (p.startsWith(".")) imagePaths.add(p);
const resolvedPath = path.resolve(basePath, p);
usedImages.add(resolvedPath);
return p;
}
return Object.assign(fixAndCollect, {
[Symbol.dispose]() {
file.data.astro!.localImagePaths = Array.from(imagePaths);
},
});
}
function collectImagePaths({ usedImages }: { usedImages: Set<string> }) {
return (root: MdastRoot, file: VFile) => {
using fixAndCollect = createFixAndCollect(usedImages, file);
// For MDX (remark-images-to-components)
unistVisit(root, "mdxjsEsm", (node) => {
if (!node.data?.estree) return;
estreeVisit(node.data.estree, (node) => {
if (node.type !== "ImportDeclaration") return;
if (node.specifiers[0]?.type !== "ImportDefaultSpecifier") return;
if (typeof node.source.value !== "string") return;
node.source.value = fixAndCollect(node.source.value);
});
});
// For md
unistVisit(root, "image", (node) => {
node.url = fixAndCollect(node.url);
});
};
}
function rehypeCollectImagePaths({ usedImages }: { usedImages: Set<string> }) {
return (root: HastRoot, file: VFile) => {
using fixAndCollect = createFixAndCollect(usedImages, file);
selectAll("img", root).forEach((img) => {
if (typeof img.properties.src !== "string") return;
img.properties.src = fixAndCollect(img.properties.src);
});
};
}
function createCollectReferredPaths(referredPaths: Set<string>, file: VFile) {
const baseUrl = new URL(path.relative("src/pages", file.path), ORIGINS[0]);
if (path.parse(file.path).name !== "index") baseUrl.pathname += "/";
return function collect(p: string) {
const url = new URL(p, baseUrl);
if (!ORIGINS.includes(url.origin)) return;
referredPaths.add(fileURLToPath(new URL(url.pathname, "file:///")));
};
}
function collectReferredPaths({
referredPaths,
}: {
referredPaths: Set<string>;
}) {
return (root: MdastRoot, file: VFile) => {
const collect = createCollectReferredPaths(referredPaths, file);
unistVisit(root, "mdxJsxFlowElement", (node) => {
if (node.data?.hName !== "a") return;
if (typeof node.data.hProperties?.href !== "string") return;
collect(node.data.hProperties.href);
});
unistVisit(root, "mdxJsxTextElement", (node) => {
if (node.data?.hName !== "a") return;
if (typeof node.data.hProperties?.href !== "string") return;
collect(node.data.hProperties.href);
});
unistVisit(root, "link", (node) => {
collect(node.url);
});
};
}
function rehypeCollectReferredPaths({
referredPaths,
}: {
referredPaths: Set<string>;
}) {
return (root: HastRoot, file: VFile) => {
const collect = createCollectReferredPaths(referredPaths, file);
selectAll("a", root).forEach((a) => {
if (typeof a.properties.href !== "string") return;
collect(a.properties.href);
});
};
}