diff options
author | Ty Hopp <hopp.ty.c@gmail.com> | 2023-12-17 17:38:26 +0800 |
---|---|---|
committer | Ty Hopp <hopp.ty.c@gmail.com> | 2023-12-20 12:31:00 +0800 |
commit | e2ce8c751e0910fc19fb884cb55d8037d1cee48c (patch) | |
tree | ec06606ad00bee9024e1842a32d80ecae918c873 /includes/ResourceLoader/CodexModule.php | |
parent | 837cda18e37d23f7977228ca4205673bca5df9a5 (diff) | |
download | mediawikicore-e2ce8c751e0910fc19fb884cb55d8037d1cee48c.tar.gz mediawikicore-e2ce8c751e0910fc19fb884cb55d8037d1cee48c.zip |
CodexModule: Throw helpful error if component not listed in module definition
This patch adds a runtime check to identify when a Codex component is imported without first being defined in the `codexComponents` array of the module definition file.
The currently shown warnings or errors are not consistent between components and are confusing since they occur at different points in the code paths of each component.
The proposed change throws a custom error message mentioning the component missing from the module definition. The location of the component's `require` call can also be inferred from the stack trace.
Bug: T353187
Change-Id: Iee8e3b0769c10407ce08de35ba38e8e5a804d6c9
Diffstat (limited to 'includes/ResourceLoader/CodexModule.php')
-rw-r--r-- | includes/ResourceLoader/CodexModule.php | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/includes/ResourceLoader/CodexModule.php b/includes/ResourceLoader/CodexModule.php index 0cae721dc03e..a4c0b8a8f50e 100644 --- a/includes/ResourceLoader/CodexModule.php +++ b/includes/ResourceLoader/CodexModule.php @@ -304,9 +304,29 @@ class CodexModule extends FileModule { } // Add a synthetic top-level "exports" file + $syntheticExports = Html::encodeJsVar( HtmlJsCode::encodeObject( $exports ) ); + + // Proxy the synthetic exports object so that we can throw a useful error if a component + // is not defined in the module definition + $proxiedSyntheticExports = <<<JAVASCRIPT +module.exports = new Proxy( $syntheticExports, { + get( target, prop ) { + if ( !(prop in target) ) { + throw new Error( + `Codex component "\${prop}" ` + + 'is not listed in the "codexComponents" array ' + + 'of the "{$this->getName()}" module in your module definition file' + ); + } + + return target [ prop ]; + } +} ); +JAVASCRIPT; + $this->packageFiles[] = [ 'name' => 'codex.js', - 'content' => 'module.exports = ' . Html::encodeJsVar( HtmlJsCode::encodeObject( $exports ) ) . ';' + 'content' => $proxiedSyntheticExports ]; // Add each of the referenced scripts to the package |