forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
96 lines (83 loc) · 2.11 KB
/
worker.js
File metadata and controls
96 lines (83 loc) · 2.11 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
/* eslint-env worker */
/* eslint no-var: off, strict: off */
const parsersLoaded = {};
const loadParser = parser => {
if (!parsersLoaded[parser]) {
if (parser === "vue") {
loadParser("typescript");
loadParser("babylon");
loadParser("postcss");
}
importScripts("/static/js/prettier/1.13.0/parser-" + parser + ".js");
parsersLoaded[parser] = true;
}
};
importScripts("/static/js/prettier/1.13.0/standalone.js");
if (typeof prettier === "undefined") {
prettier = module.exports; // eslint-disable-line
}
if (typeof prettier === "undefined") {
prettier = index; // eslint-disable-line
}
function formatCode(text, options) {
try {
const useCursorOffset = options.cursorOffset !== undefined;
if (useCursorOffset) {
return self.prettier.formatWithCursor(text, options);
}
const formatted = self.prettier.format(text, options);
return { formatted };
} catch (e) {
if (e.constructor && e.constructor.name === "SyntaxError") {
// Likely something wrong with the user's code
throw e;
}
// Likely a bug in Prettier
// Provide the whole stack for debugging
throw e;
}
}
self.onmessage = message => {
var options = message.data.options || {};
options.parser = options.parser || "babylon";
loadParser(options.parser);
let result;
options.plugins = self.prettierPlugins;
try {
result = formatCode(message.data.text, options);
} catch (e) {
console.error(e);
self.postMessage({ error: e.message, text: message.data.text });
return;
}
var doc;
var ast;
if (message.data.ast) {
try {
ast = JSON.stringify(
prettier.__debug.parse(message.data.text, options),
null,
2
);
} catch (e) {
ast = e.toString();
}
}
if (message.data.doc) {
lazyLoadParser("babylon");
try {
doc = prettier.__debug.formatDoc(
prettier.__debug.printToDoc(message.data.text, options),
{ parser: "babylon" }
);
} catch (e) {
doc = e.toString();
}
}
self.postMessage({
result,
text: message.data.text,
doc: doc,
ast: ast
});
};