-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
215 lines (206 loc) · 7.23 KB
/
index.mjs
File metadata and controls
215 lines (206 loc) · 7.23 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
// based on https://github.com/vitejs/vite-plugin-vue
import xxhash from "xxhash-wasm";
const xxhashPromise = xxhash();
/** compute the xxhash of a string. */
async function computeHash(input) {
const { h64 } = await xxhashPromise;
return h64(input).toString(36);
}
/**
* Versions before 3.4.3 have issues when the user has passed additional
* template parse options e.g. `isCustomElement`.
*/
function canReuseAST(version) {
if (version) {
const [_, minor, patch] = version.split(".").map(Number);
if (minor >= 4 && patch >= 3) {
return true;
}
}
return false;
}
/**
* Transform a Vue SFC into a JS module.
* @param {string} filename - The filename of the SFC
* @param {string} sourceCode - The source code of the SFC
* @param {{ devRuntime?: string, isDev?: boolean, imports?: Record<string, any> }} options - Transform options
* @returns {Promise<{ lang: "js" | "ts", code: string, map?: object }>}
*/
export async function transform(filename, sourceCode, { devRuntime = "" , isDev = false, imports = {} } = {}) {
/** @type import("@vue/compiler-sfc") */
const vueCompilerSFC = await (imports["@vue/compiler-sfc"] ?? import("@vue/compiler-sfc"));
const { compileScript, compileStyleAsync, compileTemplate, parse, version } = vueCompilerSFC;
const { descriptor, errors } = parse(sourceCode, { filename });
const { template, styles, script, scriptSetup, slotted, cssVars } = descriptor;
const id = (await computeHash(filename)).slice(0, 8);
const scriptLang = (script && script.lang) || (scriptSetup && scriptSetup.lang);
const isProd = !isDev;
const sourceMap = !!isDev;
const hasScript = !!script || !!scriptSetup;
const hasScoped = styles.some((s) => s.scoped);
const inlineTemplate = isProd && !!scriptSetup && !template?.src;
if (errors.length > 0) {
throw new Error("VueSFCLoader: " + errors[0].message, { cause: errors });
}
if (template.lang && template.lang !== "html") {
throw new Error(`VueSFCLoader: Only lang="html" is supported for <template> blocks.`);
}
if (scriptLang && scriptLang !== "ts") {
throw new Error(`VueSFCLoader: Only lang="ts" is supported for <script> blocks.`);
}
if (styles.some((style) => style.module)) {
throw new Error(`VueSFCLoader: <style module> is not supported yet.`);
}
const templateOptions = {
id,
filename,
scoped: hasScoped,
slotted,
isProd,
inMap: !template?.src ? template?.map : undefined,
ssr: false,
ssrCssVars: cssVars,
compilerOptions: {
scopeId: hasScoped ? `data-v-${id}` : undefined,
sourceMap,
},
ast: canReuseAST(version) ? template?.ast : undefined,
};
const compiledScript = hasScript
? compileScript(descriptor, {
id,
isProd,
inlineTemplate,
sourceMap,
templateOptions,
genDefaultAs: "$SFC",
})
: undefined;
const compiledStyles = await Promise.all(styles.map(async (style) => {
const result = await compileStyleAsync({
id,
filename,
source: style.content,
scoped: style.scoped,
modules: style.module != null,
inMap: style.map,
isProd,
});
if (result.errors.length > 0) {
// proceed even if css compile errors
return "";
}
// todo: add source map URL
return result.code;
}));
let compiledTemplate = undefined;
if (!inlineTemplate) {
compiledTemplate = compileTemplate({
...templateOptions,
compilerOptions: {
...templateOptions.compilerOptions,
bindingMetadata: compiledScript?.bindings,
},
source: template.content,
});
}
let map = compiledScript?.map ?? compiledTemplate?.map;
if (compiledScript?.map && compiledTemplate?.map) {
const [
{ eachMapping, TraceMap },
{ addMapping, fromMap, toEncodedMap },
] = await Promise.all([
import("@jridgewell/trace-mapping"),
import("@jridgewell/gen-mapping"),
]);
// concatenate the script map and the template map
const gen = fromMap(compiledScript.map);
const tracer = new TraceMap(compiledTemplate.map);
const offset = (compiledScript.content.match(/\r?\n/g)?.length ?? 0) + 1;
eachMapping(tracer, (m) => {
if (m.source) {
addMapping(gen, {
source: m.source,
original: { line: m.originalLine, column: m.originalColumn },
generated: {
line: m.generatedLine + offset,
column: m.generatedColumn,
},
});
}
});
map = toEncodedMap(gen);
// if this is a template only update, we will be reusing a cached version
// of the main module compile result, which has outdated sourcesContent.
map.sourcesContent = compiledTemplate.map.sourcesContent;
}
const buf = [];
if (compiledScript) {
buf.push(compiledScript.content);
}
if (compiledTemplate) {
buf.push(compiledTemplate.code.replace(/\nexport (function|const) render/, "\n$1 $SFC_render"));
}
if (!compiledScript) {
buf.push(`const $SFC = Object.create(null);`);
}
if (compiledTemplate) {
buf.push(`$SFC.render = $SFC_render;`);
}
if (isDev) {
buf.push(`$SFC.styles = ${JSON.stringify(compiledStyles)};`);
}
buf.push(`$SFC.__file = ${JSON.stringify(filename)};`);
if (hasScoped) {
buf.push(`$SFC.__scopeId = "data-v-${id}";`);
}
if (isDev) {
const hashes = await Promise.all([compiledScript?.content ?? "", compiledTemplate.code, compiledStyles.join("\n")].map(computeHash));
if (devRuntime) {
buf.push(`import __VUE_DEV_RUNTIME__ from "${devRuntime}";`);
} else {
buf.push(
[
`const __VUE_DEV_RUNTIME__ = {`,
`updateStyle(id, styles) {`,
`const head = globalThis.document.head;`,
`head.querySelectorAll("style[data-v-" + id + "]").forEach(e => e.remove());`,
`for (const css of styles) {`,
`head.insertAdjacentHTML("beforeend", "<style data-v-" + id + ">" + css + "</style>");`,
`}}};`,
].join(" "),
);
}
buf.push("/* if it's first time import, apply the styles */");
buf.push(`if (!(new URL(import.meta.url).searchParams.has("t"))) {`);
buf.push(` __VUE_DEV_RUNTIME__.updateStyle("${id}", $SFC.styles);`);
buf.push("}");
buf.push("/* hot reload */");
buf.push(`$SFC.__hmrId = "${id}";`);
buf.push(`$SFC.__hashes = ${JSON.stringify(hashes)};`);
buf.push(`if (globalThis.__VUE_HMR_RUNTIME__) {`);
buf.push(` __VUE_HMR_RUNTIME__.createRecord($SFC.__hmrId, $SFC);`);
buf.push(
` import.meta.hot.accept(({ default: sfc }) => {`,
` const updates = $SFC.__hashes.map((hash, i) => hash !== sfc.__hashes[i]);`,
` $SFC.__hashes = [...sfc.__hashes];`,
` updates[0] && __VUE_HMR_RUNTIME__.reload(sfc.__hmrId, sfc);`,
` updates[1] && __VUE_HMR_RUNTIME__.rerender(sfc.__hmrId, sfc.render);`,
` updates[2] && __VUE_DEV_RUNTIME__.updateStyle(sfc.__hmrId, sfc.styles);`,
` });`,
`}`,
);
} else if (compiledStyles.length > 0) {
buf.push(
`for (const css of ${JSON.stringify(compiledStyles)}) {`,
` globalThis.document.head.insertAdjacentHTML("beforeend", "<style>" + css + "</style>");`,
`}`,
);
}
buf.push("export default $SFC;");
return {
code: buf.join("\n"),
lang: scriptLang === "ts" ? "ts" : "js",
map,
};
}