Merge pull request #17107 from webpack/some-types

refactor(type): small improve
This commit is contained in:
Sean Larkin 2023-05-03 09:27:47 -07:00 committed by GitHub
commit 12d477df73
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 134 additions and 2 deletions

View File

@ -188,6 +188,7 @@
"prewalking",
"prioritise",
"promisify",
"proxied",
"quasis",
"queryloader",
"querystrings",

View File

@ -89,7 +89,8 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
)}`;
result.add(
`var ${varName} = __webpack_exports__${propertyAccess([
exportInfo.getUsedName(exportInfo.name, chunk.runtime)
/** @type {string} */
(exportInfo.getUsedName(exportInfo.name, chunk.runtime))
])};\n`
);
exports.push(`${varName} as ${exportInfo.name}`);

View File

@ -132,6 +132,10 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule {
const s = JSON.stringify(str);
return s.slice(1, s.length - 1);
};
/**
* @param {string} value string
* @returns {function(number): string} string to put in quotes with length
*/
const unquotedStringifyWithLength = value => length =>
unquotedStringify(`${value}`.slice(0, length));
const chunkFilenameValue =

View File

@ -13,6 +13,10 @@ const NormalModule = require("../NormalModule");
// http://www.ietf.org/rfc/rfc2397.txt
const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i;
/**
* @param {string} uri data URI
* @returns {Buffer|null} decoded data
*/
const decodeDataURI = uri => {
const match = URIRegEx.exec(uri);
if (!match) return null;

View File

@ -71,11 +71,19 @@ const validate = createSchemaValidation(
}
);
/**
* @param {string} str path
* @returns {string} safe path
*/
const toSafePath = str =>
str
.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "")
.replace(/[^a-zA-Z0-9._-]+/g, "_");
/**
* @param {Buffer} content content
* @returns {string} integrity
*/
const computeIntegrity = content => {
const hash = createHash("sha512");
hash.update(content);
@ -83,6 +91,11 @@ const computeIntegrity = content => {
return integrity;
};
/**
* @param {Buffer} content content
* @param {string} integrity integrity
* @returns {boolean} true, if integrity matches
*/
const verifyIntegrity = (content, integrity) => {
if (integrity === "ignore") return true;
return computeIntegrity(content) === integrity;
@ -110,6 +123,11 @@ const parseKeyValuePairs = str => {
return result;
};
/**
* @param {string | undefined} cacheControl Cache-Control header
* @param {number} requestTime timestamp of request
* @returns {{storeCache: boolean, storeLock: boolean, validUntil: number}} Logic for storing in cache and lockfile cache
*/
const parseCacheControl = (cacheControl, requestTime) => {
// When false resource is not stored in cache
let storeCache = true;
@ -147,6 +165,10 @@ const areLockfileEntriesEqual = (a, b) => {
);
};
/**
* @param {LockfileEntry} entry lockfile entry
* @returns {`resolved: ${string}, integrity: ${string}, contentType: ${*}`} stringified entry
*/
const entryToString = entry => {
return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;
};
@ -158,6 +180,10 @@ class Lockfile {
this.entries = new Map();
}
/**
* @param {string} content content of the lockfile
* @returns {Lockfile} lockfile
*/
static parse(content) {
// TODO handle merge conflicts
const data = JSON.parse(content);
@ -180,6 +206,9 @@ class Lockfile {
return lockfile;
}
/**
* @returns {string} stringified lockfile
*/
toString() {
let str = "{\n";
const entries = Array.from(this.entries).sort(([a], [b]) =>
@ -342,6 +371,7 @@ class HttpUriPlugin {
const fs = compilation.inputFileSystem;
const cache = compilation.getCache("webpack.HttpUriPlugin");
const logger = compilation.getLogger("webpack.HttpUriPlugin");
/** @type {string} */
const lockfileLocation =
this._lockfileLocation ||
join(
@ -351,6 +381,7 @@ class HttpUriPlugin {
? `${toSafePath(compiler.name)}.webpack.lock`
: "webpack.lock"
);
/** @type {string | false} */
const cacheLocation =
this._cacheLocation !== undefined
? this._cacheLocation
@ -364,6 +395,7 @@ class HttpUriPlugin {
let warnedAboutEol = false;
/** @type {Map<string, string>} */
const cacheKeyCache = new Map();
/**
* @param {string} url the url
@ -447,6 +479,12 @@ class HttpUriPlugin {
/** @type {Map<string, LockfileEntry | "ignore" | "no-cache"> | undefined} */
let lockfileUpdates = undefined;
/**
* @param {Lockfile} lockfile lockfile instance
* @param {string} url url to store
* @param {LockfileEntry | "ignore" | "no-cache"} entry lockfile entry
*/
const storeLockEntry = (lockfile, url, entry) => {
const oldEntry = lockfile.entries.get(url);
if (lockfileUpdates === undefined) lockfileUpdates = new Map();

View File

@ -12,6 +12,12 @@
const DATA_URI_CONTENT_LENGTH = 16;
const MAX_MODULE_IDENTIFIER_LENGTH = 80;
/**
* @param {number} n a number
* @param {string} singular singular
* @param {string} plural plural
* @returns {string} if n is 1, singular, else plural
*/
const plural = (n, singular, plural) => (n === 1 ? singular : plural);
/**
@ -29,6 +35,10 @@ const printSizes = (sizes, { formatSize = n => `${n}` }) => {
}
};
/**
* @param {string} resource resource
* @returns {string} resource name for display
*/
const getResourceName = resource => {
const dataUrl = /^data:[^,]+,/.exec(resource);
if (!dataUrl) return resource;
@ -41,6 +51,10 @@ const getResourceName = resource => {
)}..`;
};
/**
* @param {string} name module name
* @returns {[string,string]} prefix and module name
*/
const getModuleName = name => {
const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name);
@ -59,6 +73,11 @@ const getModuleName = name => {
return [prefix, getResourceName(resource)];
};
/**
* @param {string} str string
* @param {function(string): string} fn function to apply to each line
* @returns {string} joined string
*/
const mapLines = (str, fn) => str.split("\n").map(fn).join("\n");
/**
@ -71,6 +90,12 @@ const isValidId = id => {
return typeof id === "number" || id;
};
/**
* @template T
* @param {Array<T>} list of items
* @param {number} count number of items to show
* @returns {string} string representation of list
*/
const moreCount = (list, count) => {
return list && list.length > 0 ? `+ ${count}` : `${count}`;
};

View File

@ -83,6 +83,9 @@ class StackedCacheMap {
this.map.clear();
}
/**
* @returns {number} size of the map
*/
get size() {
let size = this.map.size;
for (const map of this.stack) {
@ -91,6 +94,9 @@ class StackedCacheMap {
return size;
}
/**
* @returns {Iterator<[K, V]>} iterator
*/
[Symbol.iterator]() {
const iterators = this.stack.map(map => map[Symbol.iterator]());
let current = this.map[Symbol.iterator]();

View File

@ -5,10 +5,18 @@
"use strict";
/**
* @param {string} str string
* @returns {string} quoted meta
*/
const quoteMeta = str => {
return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
};
/**
* @param {string} str string
* @returns {string} string
*/
const toSimpleString = str => {
if (`${+str}` === str) {
return str;
@ -49,19 +57,28 @@ const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
}
};
/**
* @param {Set<string>} itemsSet items set
* @param {(str: string) => string | false} getKey get key function
* @param {(str: Array<string>) => boolean} condition condition
* @returns {Array<Array<string>>} list of common items
*/
const popCommonItems = (itemsSet, getKey, condition) => {
/** @type {Map<string, Array<string>>} */
const map = new Map();
for (const item of itemsSet) {
const key = getKey(item);
if (key) {
let list = map.get(key);
if (list === undefined) {
/** @type {Array<string>} */
list = [];
map.set(key, list);
}
list.push(item);
}
}
/** @type {Array<Array<string>>} */
const result = [];
for (const list of map.values()) {
if (condition(list)) {
@ -74,6 +91,10 @@ const popCommonItems = (itemsSet, getKey, condition) => {
return result;
};
/**
* @param {Array<string>} items items
* @returns {string} common prefix
*/
const getCommonPrefix = items => {
let prefix = items[0];
for (let i = 1; i < items.length; i++) {
@ -88,6 +109,10 @@ const getCommonPrefix = items => {
return prefix;
};
/**
* @param {Array<string>} items items
* @returns {string} common suffix
*/
const getCommonSuffix = items => {
let suffix = items[0];
for (let i = 1; i < items.length; i++) {
@ -102,10 +127,15 @@ const getCommonSuffix = items => {
return suffix;
};
/**
* @param {Array<string>} itemsArr array of items
* @returns {string} regexp
*/
const itemsToRegexp = itemsArr => {
if (itemsArr.length === 1) {
return quoteMeta(itemsArr[0]);
}
/** @type {Array<string>} */
const finishedItems = [];
// merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
@ -146,6 +176,7 @@ const itemsToRegexp = itemsArr => {
// special case for 2 items with common suffix
if (finishedItems.length === 0 && items.size === 2) {
/** @type {Iterator<string>} */
const it = items[Symbol.iterator]();
const a = it.next().value;
const b = it.next().value;

View File

@ -178,6 +178,14 @@ exports.createArrayToSetDeprecationSet = name => {
return SetDeprecatedArray;
};
/**
* @template T
* @param {Object} obj object
* @param {string} name property name
* @param {string} code deprecation code
* @param {string} note additional note
* @returns {Object} frozen object with deprecation when modifying
*/
exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {
const message = `${name} will be frozen in future, all modifications are deprecated.${
note && `\n${note}`

View File

@ -15,6 +15,10 @@ const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
* @property {Map<string, Map<string, string>>=} relativePaths
*/
/**
* @param {string} relativePath relative path
* @returns {string} request
*/
const relativePathToRequest = relativePath => {
if (relativePath === "") return "./.";
if (relativePath === "..") return "../.";

View File

@ -60,6 +60,11 @@ const RESERVED_IDENTIFIER = new Set([
"false"
]);
/**
* @param {ArrayLike<string>} properties properties
* @param {number} start start index
* @returns {string} chain of property accesses
*/
const propertyAccess = (properties, start = 0) => {
let str = "";
for (let i = start; i < properties.length; i++) {

View File

@ -85,6 +85,7 @@ class AsyncWebAssemblyJavascriptGenerator extends Generator {
}
}
/** @type {Array<string>} */
const promises = [];
const importStatements = Array.from(

View File

@ -47,7 +47,7 @@ class WebAssemblyParser extends Parser {
// parse it
const program = decode(source, decoderOpts);
const module = program.body[0];
/** @type {Array<string>} */
const exports = [];
t.traverse(module, {
ModuleExport({ node }) {

View File

@ -12,6 +12,10 @@
/** @type {WeakMap<Compiler, Set<WasmLoadingType>>} */
const enabledTypes = new WeakMap();
/**
* @param {Compiler} compiler compiler instance
* @returns {Set<WasmLoadingType>} enabled types
*/
const getEnabledTypes = compiler => {
let set = enabledTypes.get(compiler);
if (set === undefined) {