-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstaticalize.ts
More file actions
112 lines (97 loc) · 2.77 KB
/
staticalize.ts
File metadata and controls
112 lines (97 loc) · 2.77 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
import {
call,
type Operation,
resource,
spawn,
useAbortSignal,
} from "effection";
import { join } from "@std/path";
import { ensureDir } from "@std/fs/ensure-dir";
import { stringify } from "@libs/xml/stringify";
import { parse } from "@libs/xml/parse";
import { useDownloader } from "./downloader.ts";
export interface StaticalizeOptions {
host: URL;
base: URL;
dir: string;
}
export interface Staticalizer {
urls: ReadonlySet<URL>;
staticalize(): Operation<void>;
}
export function useStaticalizer(
options: StaticalizeOptions,
): Operation<Staticalizer> {
let { host, base, dir } = options;
return resource(function* (provide) {
let signal = yield* useAbortSignal();
let urls: Set<URL> = yield* call(async () => {
let url = new URL("/sitemap.xml", host);
let response = await fetch(url, { signal });
if (!response.ok) {
let error = new Error(
`GET ${url} ${response.status} ${response.statusText}`,
);
error.name = `SitemapError`;
throw error;
}
let text = await response.text();
let xml = parse(text, {
flatten: { attributes: false, empty: false, text: true },
}) as unknown as SitemapXML;
let entries = xml.urlset.url ?? xml.urlset.urls ?? [];
let list = Array.isArray(entries) ? entries : [entries];
return new Set(
list.filter(Boolean).map((entry) => {
let loc = typeof entry === "string" ? entry : entry.loc;
return new URL(loc);
}),
);
});
let downloader = yield* useDownloader({ host, base, outdir: dir });
yield* provide({
urls,
*staticalize() {
yield* call(() => ensureDir(dir));
for (let url of urls) {
yield* downloader.download(url.toString());
}
let sitemap = yield* spawn(function* () {
let xml = stringify({
urlset: {
"@xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9",
"urls": [...urls].map((url) => {
let loc = new URL(url);
loc.host = base.host;
loc.port = base.port;
loc.protocol = base.protocol;
return { loc: { "#text": loc } };
}),
},
});
yield* call(() =>
Deno.writeFile(
join(dir, "sitemap.xml"),
new TextEncoder().encode(xml),
)
);
});
yield* sitemap;
yield* downloader;
},
});
});
}
export interface SitemapURL {
loc: string;
lastmod?: string;
changefreq?: string;
priority?: string;
}
interface SitemapXML {
urlset: {
url?: SitemapEntry | SitemapEntry[];
urls?: SitemapEntry | SitemapEntry[];
};
}
type SitemapEntry = SitemapURL | string;