-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
312 lines (280 loc) · 8.57 KB
/
index.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
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
const fs = require('fs');
const { pbjs, pbts } = require('protobufjs-cli');
const protobuf = require('protobufjs');
const tmp = require('tmp');
const validateOptions = require('schema-utils').validate;
const TARGET_STATIC_MODULE = 'static-module';
/** @type { Parameters<typeof validateOptions>[0] } */
const schema = {
type: 'object',
properties: {
target: {
type: 'string',
default: TARGET_STATIC_MODULE,
},
paths: {
type: 'array',
},
pbjsArgs: {
type: 'array',
default: [],
},
pbts: {
oneOf: [
{
type: 'boolean',
},
{
type: 'object',
properties: {
args: {
type: 'array',
default: [],
},
output: {
anyOf: [{ type: 'null' }, { instanceof: 'Function' }],
default: null,
},
},
additionalProperties: false,
},
],
default: false,
},
},
additionalProperties: false,
};
/**
* Shared type for the validated options object, with no missing
* properties (i.e. the user-provided object merged with default
* values).
*
* @typedef {{ args: string[], output: ((resourcePath: string) => string | Promise<string>) | null }} PbtsOptions
* @typedef {{
* paths: string[], pbjsArgs: string[],
* pbts: boolean | PbtsOptions,
* target: string,
* }} LoaderOptions
*/
/**
* The generic parameter is the type of the options object in the
* configuration. All `LoaderOptions` fields are optional at this
* stage.
*
* @typedef { import('webpack').LoaderContext<Partial<LoaderOptions>> } LoaderContext
*/
/** @type { (resourcePath: string, pbtsOptions: true | PbtsOptions, compiledContent: string | undefined) => Promise<void> } */
const execPbts = async (resourcePath, pbtsOptions, compiledContent) => {
/** @type PbtsOptions */
const normalizedOptions = {
args: [],
output: null,
...(pbtsOptions === true ? {} : pbtsOptions),
};
/**
* Immediately run the function to get the typescript output path. If
* the function is asynchronous, it will run in the background while
* we kick off other async operations.
*
* @type { (resourcePath: string) => string | Promise<string> }
*/
const output =
normalizedOptions.output === null
? (r) => `${r}.d.ts`
: normalizedOptions.output;
const declarationFilenamePromise = Promise.resolve(output(resourcePath));
// pbts CLI only supports streaming from stdin without a lot of
// duplicated logic, so we need to use a tmp file. :(
const compiledFilename = await new Promise((resolve, reject) => {
tmp.file({ postfix: '.js' }, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
// Write the compiled JS content to the tmp file.
await new Promise((resolve, reject) => {
fs.writeFile(compiledFilename, compiledContent || '', (err) => {
if (err) {
reject(err);
} else {
resolve(compiledFilename);
}
});
});
const declarationFilename = await declarationFilenamePromise;
const pbtsArgs = ['-o', declarationFilename]
.concat(normalizedOptions.args)
.concat([compiledFilename]);
/** @type { Promise<void> } */
const pbtsPromise = new Promise((resolve, reject) => {
pbts.main(pbtsArgs, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
await pbtsPromise;
};
/**
* Main loader invocation. Return the pbjs-transformed content of a
* protobuf source, and write typescript declarations if appropriate.
*
* @type { (source: string, context: LoaderContext) => Promise<string | undefined> }
*/
const loadSource = async (source, context) => {
const defaultPaths = (() => {
// eslint-disable-next-line no-underscore-dangle
if (context._compiler) {
// The `_compiler` property is deprecated, but still works as
// of webpack@5.
//
// eslint-disable-next-line no-underscore-dangle
return (context._compiler.options.resolve || {}).modules;
}
return undefined;
})();
/** @type LoaderOptions */
const options = {
target: TARGET_STATIC_MODULE,
// Default to the module search paths given to the compiler.
paths: defaultPaths || [],
pbjsArgs: [],
pbts: false,
...context.getOptions(),
};
validateOptions(schema, options, { name: 'protobufjs-loader' });
/**
* Get a temp file location and write the protobuf file content.
*
* Note: we could potentially remove the need for a temp file here
* by spawning a subprocess, passing "-" as a filename, and passing
* the protobuf content on its stdin. We could also feasibly do this
* through the in-process `pbjs.main` call (though it appears this
* would require manipulating this process' own stdin, which would
* be inappropriate for a loader).
*
* However, a subprocess would add some complexity, and we'd need to
* figure out how to add dependencies to the context without calling
* `protobuf.load` with a temp file.
*
* @type { string }
*/
const filename = await new Promise((resolve, reject) => {
tmp.file((err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
await new Promise((resolve, reject) => {
fs.writeFile(filename, source, (err) => {
if (err) {
reject(err);
} else {
resolve(filename);
}
});
});
const { paths } = options;
/**
* Adapted from the import resolution setup in
* https://github.com/dcodeIO/protobuf.js/blob/master/cli/pbjs.js.
*
* In addition to the main pbjs invocation, run a manual compilation
* pass which resolves imports using the provided include paths, and
* mark all visited imports as dependencies of the current resource.
*
* @type { Promise<protobuf.Root> }
*/
const loadDependencies = new Promise((resolve, reject) => {
const root = new protobuf.Root();
// Set up the resolver which will mark dependencies as it goes.
root.resolvePath = (origin, target) => {
const normOrigin = protobuf.util.path.normalize(origin);
const normTarget = protobuf.util.path.normalize(target);
let resolved = protobuf.util.path.resolve(normOrigin, normTarget, true);
const idx = resolved.lastIndexOf('google/protobuf/');
if (idx > -1) {
const altname = resolved.substring(idx);
if (altname in protobuf.common) {
resolved = altname;
}
}
if (fs.existsSync(resolved)) {
// Don't add a dependency on the temp file
if (resolved !== protobuf.util.path.normalize(filename)) {
context.addDependency(resolved);
}
return resolved;
}
for (let i = 0; i < paths.length; i += 1) {
const iresolved = protobuf.util.path.resolve(`${paths[i]}/`, target);
if (fs.existsSync(iresolved)) {
context.addDependency(iresolved);
return iresolved;
}
}
return null;
};
// Perform the actual parsing/dependency resolution, and resolve
// when finished, i.e. after all dependencies have been visited
// and marked.
protobuf.load(filename, root, (err, result) => {
if (err || result === undefined) {
reject(err);
} else {
resolve(result);
}
});
});
/** @type { string[] } */
let args = ['-t', options.target];
paths.forEach((path) => {
args = args.concat(['-p', path]);
});
args = args.concat(options.pbjsArgs).concat([filename]);
/**
* Run the pbjs compiler and get the compiled content.
*
* @type { string | undefined }
*/
const compiledContent = await new Promise((resolve, reject) => {
pbjs.main(args, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
// If appropriate, run the pbts compiler.
if (options.pbts) {
await execPbts(context.resourcePath, options.pbts, compiledContent);
}
// Ensure all dependencies are marked before returning a value.
await loadDependencies;
return compiledContent;
};
/** @type { (this: LoaderContext, source: string) => void } */
module.exports = function protobufJsLoader(source) {
const callback = this.async();
// Explicitly check this case, as the typescript compiler thinks
// it's possible.
if (callback === undefined) {
throw new Error('Failed to request async execution from webpack');
}
loadSource(source, this)
.then((compiled) => {
callback(undefined, compiled);
})
.catch((err) => {
callback(err, undefined);
});
};