-
Notifications
You must be signed in to change notification settings - Fork 456
/
raw.ts
91 lines (82 loc) · 2.03 KB
/
raw.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
import { promises as fsp } from "node:fs";
import { extname } from "pathe";
import type { Plugin } from "rollup";
export interface RawOptions {
extensions?: string[];
}
const HELPER_ID = "\0raw-helpers";
export function raw(opts: RawOptions = {}): Plugin {
const extensions = new Set([
".md",
".mdx",
".yml",
".txt",
".css",
".htm",
".html",
...(opts.extensions || []),
]);
// TODO: use ext=>mime
const isBinary = (id) => !extensions.has(extname(id));
return {
name: "raw",
resolveId(id) {
if (id === HELPER_ID) {
return id;
}
if (id[0] === "\0") {
return;
}
let isRawId = id.startsWith("raw:");
if (isRawId) {
id = id.slice(4);
} else if (extensions.has(extname(id))) {
isRawId = true;
}
// TODO: Support reasolving. Blocker is CommonJS custom resolver!
if (isRawId) {
return { id: "\0raw:" + id };
}
},
load(id) {
if (id === HELPER_ID) {
return getHelpers();
}
if (id.startsWith("\0raw:")) {
// this.addWatchFile(id.substring(5))
return fsp.readFile(id.slice(5), isBinary(id) ? "binary" : "utf8");
}
},
transform(code, id) {
if (!id.startsWith("\0raw:")) {
return;
}
if (isBinary(id)) {
const serialized = Buffer.from(code, "binary").toString("base64");
return {
code: `// ROLLUP_NO_REPLACE \n import {base64ToUint8Array } from "${HELPER_ID}" \n export default base64ToUint8Array("${serialized}")`,
map: null,
};
} else {
return {
code: `// ROLLUP_NO_REPLACE \n export default ${JSON.stringify(code)}`,
map: null,
};
}
},
};
}
function getHelpers() {
const js = String.raw;
return js`
export function base64ToUint8Array(str) {
const data = atob(str);
const size = data.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = data.charCodeAt(i);
}
return bytes;
}
`;
}