diff --git a/package-lock.json b/package-lock.json index 84c5325..9e63a6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7812,9 +7812,20 @@ "dev": true }, "node_modules/fast-uri": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.1.tgz", - "integrity": "sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw==" + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" }, "node_modules/fastq": { "version": "1.17.1", @@ -21372,9 +21383,9 @@ "dev": true }, "fast-uri": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.1.tgz", - "integrity": "sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw==" + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==" }, "fastq": { "version": "1.17.1", diff --git a/src/worker.js b/src/worker.js index 903a2f5..33fa831 100644 --- a/src/worker.js +++ b/src/worker.js @@ -3,11 +3,11 @@ import fs from 'fs'; import NativeModule from 'module'; import querystring from 'querystring'; +import util from 'util'; import loaderRunner from 'loader-runner'; import asyncQueue from 'neo-async/queue'; import parseJson from 'json-parse-better-errors'; -import { validate } from 'schema-utils'; import readBuffer from './readBuffer'; import { replacer, reviver } from './serializer'; @@ -210,12 +210,13 @@ const queue = asyncQueue(({ id, data }, taskCallback) => { } }, // Not an arrow function because it uses this - getOptions(schema) { + getOptions(schema, configurationOrCheck, precompiledCheck) { // loaders, loaderIndex will be defined by runLoaders const loader = this.loaders[this.loaderIndex]; // Verbatim copy from - // https://github.com/webpack/webpack/blob/v5.31.2/lib/NormalModule.js#L471-L508 + // https://github.com/webpack/webpack/blob/v5.113.0/lib/module/NormalModule.js + // and lib/util/validateSchema.js // except eslint/prettier differences // -- unfortunate result of getOptions being synchronous functions. @@ -241,17 +242,53 @@ const queue = asyncQueue(({ id, data }, taskCallback) => { } if (schema) { - let name = 'Loader'; - let baseDataPath = 'options'; + // A configuration is an object and a check a function, so the + // check can come last or in the configuration's place + const check = + typeof configurationOrCheck === 'function' + ? configurationOrCheck + : precompiledCheck; + const configuration = + typeof configurationOrCheck === 'function' + ? // eslint-disable-next-line no-undefined + undefined + : configurationOrCheck; + + // A precompiled check that passes skips the schema, so valid + // options never load `schema-utils` or compile it + if (check && check(options)) { + return options; + } + + const resolvedSchema = + typeof schema === 'function' ? schema() : schema; + let title; let match; - // eslint-disable-next-line no-cond-assign - if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { - [, name, baseDataPath] = match; + if ( + typeof resolvedSchema.title === 'string' && + // eslint-disable-next-line no-cond-assign + (match = /^(.+) (.+)$/.exec(resolvedSchema.title)) + ) { + title = { name: match[1], baseDataPath: match[2] }; + } + const resolvedConfiguration = { + ...(title || { name: 'Loader', baseDataPath: 'options' }), + ...configuration, + }; + + // eslint-disable-next-line global-require + const { validate } = require('schema-utils'); + + validate(resolvedSchema, options, resolvedConfiguration); + + // The schema accepts what the check rejected, so the check is stale + if (check) { + util.deprecate( + () => {}, + `${resolvedConfiguration.name} pre-compiled schema reports error while real schema is happy. This has performance drawbacks.`, + 'DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID', + )(); } - validate(schema, options, { - name, - baseDataPath, - }); } return options; diff --git a/test/options-check.test.js b/test/options-check.test.js new file mode 100644 index 0000000..0f8967a --- /dev/null +++ b/test/options-check.test.js @@ -0,0 +1,119 @@ +import os from 'os'; +import path from 'path'; + +import webpack from 'webpack'; + +const threadLoader = require('../dist'); + +const loader = require.resolve('./options-check/options-check-loader'); + +const run = (options, mode = 'check') => + new Promise((resolve, reject) => { + webpack( + { + mode: 'none', + context: path.resolve(__dirname, 'options-check'), + devtool: false, + entry: `./file.js?${mode}`, + output: { + path: path.join(os.tmpdir(), 'thread-loader-options-check', mode), + }, + module: { + rules: [ + { + test: /file\.js$/, + use: [ + { + loader: path.resolve(__dirname, '../dist/index.js'), + options: { workers: 1, poolTimeout: 2000 }, + }, + { loader, options }, + ], + }, + ], + }, + }, + (err, stats) => (err ? reject(err) : resolve(stats)), + ); + }); + +beforeAll(() => { + threadLoader.warmup({ workers: 1, poolTimeout: 2000 }, [loader]); +}); + +test('skips the schema when the precompiled check passes', async () => { + const stats = await run({ trusted: true }); + + expect(stats.compilation.errors).toHaveLength(0); +}); + +test('validates against the schema when the precompiled check fails', async () => { + const stats = await run({ name: 1 }); + + expect(stats.compilation.errors).toHaveLength(1); + expect(stats.compilation.errors[0].message).toMatch( + /Invalid options object\. Loader has been initialized using an options object that does not match the API schema\.\n - options\.name should be a string/, + ); +}); + +test('takes the check after the configuration', async () => { + expect( + (await run({ trusted: true }, 'configuration')).compilation.errors, + ).toHaveLength(0); + + const stats = await run({ name: 1 }, 'configuration'); + + expect(stats.compilation.errors).toHaveLength(1); + expect(stats.compilation.errors[0].message).toMatch( + /Invalid query object\. Named Loader has been initialized.*\n - query\.name should be a string/, + ); +}); + +test('reads a schema function only when the check fails', async () => { + expect( + (await run({ trusted: true }, 'lazy')).compilation.errors, + ).toHaveLength(0); + + const stats = await run({ name: 1 }, 'lazy'); + + expect(stats.compilation.errors).toHaveLength(1); + expect(stats.compilation.errors[0].message).toMatch( + /options\.name should be a string/, + ); +}); + +test('names the loader by the schema title', async () => { + const stats = await run({ name: 1 }, 'title'); + + expect(stats.compilation.errors).toHaveLength(1); + expect(stats.compilation.errors[0].message).toMatch( + /Invalid query object\. Titled Loader has been initialized.*\n - query\.name should be a string/, + ); +}); + +test('reports a check that rejects what the schema accepts', async () => { + const write = jest.spyOn(process.stderr, 'write'); + // The worker's stderr reaches this process on its own pipe, so the warning + // can arrive after the compilation finished + const warned = () => + /\[DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID\] DeprecationWarning: Loader pre-compiled schema reports error while real schema is happy/.test( + write.mock.calls.join(''), + ); + + try { + const stats = await run({ name: 'valid' }, 'stale'); + + expect(stats.compilation.errors).toHaveLength(0); + + for (let i = 0; i < 50 && !warned(); i++) { + // eslint-disable-next-line no-await-in-loop + await new Promise((resolve) => { + setTimeout(resolve, 20); + }); + } + + expect(warned()).toBe(true); + } finally { + write.mockRestore(); + } +}); diff --git a/test/options-check/file.js b/test/options-check/file.js new file mode 100644 index 0000000..3a8edd0 --- /dev/null +++ b/test/options-check/file.js @@ -0,0 +1 @@ +module.exports = 'file'; diff --git a/test/options-check/options-check-loader.js b/test/options-check/options-check-loader.js new file mode 100644 index 0000000..de1e563 --- /dev/null +++ b/test/options-check/options-check-loader.js @@ -0,0 +1,39 @@ +const schema = { + type: 'object', + properties: { name: { type: 'string' } }, + additionalProperties: false, +}; + +const titledSchema = { ...schema, title: 'Titled Loader query' }; + +const trusting = (value) => value.trusted === true; + +const modes = { + // the check in the configuration's place + check: (context) => context.getOptions(schema, trusting), + // the check last, after the configuration + configuration: (context) => + context.getOptions( + schema, + { name: 'Named Loader', baseDataPath: 'query' }, + trusting, + ), + // a function returning the schema, read only when the check fails + lazy: (context) => + context.getOptions(() => { + if (context.getOptions().trusted === true) { + throw new Error('the schema was read although the check passed'); + } + + return schema; + }, trusting), + title: (context) => context.getOptions(titledSchema), + // a check that rejects what the schema accepts + stale: (context) => context.getOptions(schema, () => false), +}; + +module.exports = function optionsCheckLoader() { + const options = modes[this.resourceQuery.slice(1)](this); + + return `module.exports = ${JSON.stringify(options)};`; +};