forked from rottencandy/esbuild-plugin-glslx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
81 lines (72 loc) · 2.51 KB
/
main.js
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
const glslx = require('glslx');
module.exports = ({
writeTypeDeclarations = false,
renaming = 'all',
disableRewriting = false,
prettyPrint = false,
preprocess = null
} = {}) => ({
name: 'glslx',
setup(build) {
const path = require('path');
const fs = require('fs');
const prepr = (preprocess === null) ? arg => { return arg; } : require('prepr');
build.onLoad({ filter: /\.glslx$/ }, async (args) => {
const contents = prepr(await fs.promises.readFile(args.path, 'utf8'), preprocess);
const input = [{ name: args.path, contents }];
const errors = [];
const warnings = [];
const watchFiles = [];
const cache = Object.create(null);
cache[args.path] = contents;
const fileAccess = (filePath, relativeTo) => {
const name = path.join(path.dirname(relativeTo), filePath);
let contents = cache[name];
if (contents === undefined) {
watchFiles.push(name);
try {
contents = prepr(fs.readFileSync(name, 'utf8'), preprocess);
} catch {
return null;
}
cache[name] = contents;
}
return { name, contents };
};
for (const { kind, text, range } of glslx.compileIDE(input, { fileAccess }).diagnostics) {
const message = { text };
if (range) {
const lineText = cache[range.source].split(/\r|\n|\r\n/g)[range.start.line];
message.location = {
file: range.source,
line: range.start.line + 1,
column: range.start.column,
length: range.end.line === range.start.line ? range.end.column - range.start.column : 0,
lineText,
};
}
if (kind === 'error') errors.push(message);
if (kind === 'warning') warnings.push(message);
}
if (errors.length > 0) return { errors, warnings, watchFiles };
const json = JSON.parse(glslx.compile(input, {
format: 'json',
fileAccess,
prettyPrint,
disableRewriting,
renaming,
}).output);
let js = '';
let ts = '';
for (const shader of json.shaders) {
js += `export var ${shader.name} = ${JSON.stringify(shader.contents)};\n`;
ts += `export var ${shader.name}: string;\n`;
}
js += `export var renaming = ${JSON.stringify(json.renaming)};\n`;
if (writeTypeDeclarations) {
await fs.promises.writeFile(args.path + '.d.ts', ts);
}
return { contents: js, warnings, watchFiles };
});
},
});