@sku-lib/rolldown-plugin-display-name 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +65 -2
- package/dist/index.d.mts +79 -0
- package/dist/index.mjs +390 -0
- package/package.json +51 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 SEEK
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sku-lib/rolldown-plugin-display-name
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [Rolldown](https://rolldown.rs) and [Vite](https://vite.dev) plugin that adds a `displayName` to React components.
|
|
4
|
+
It is a port of `@sku-lib/babel-plugin-display-name` to the [oxc](https://oxc.rs) toolchain.
|
|
5
|
+
That plugin is a fork of [`@mui/internal-babel-plugin-display-name`](https://github.com/mui/mui-public/tree/master/packages/babel-plugin-display-name).
|
|
6
|
+
Unlike the MUI plugin, this plugin adds the `displayName` in production builds too.
|
|
7
|
+
|
|
8
|
+
```js
|
|
9
|
+
// vite.config.js
|
|
10
|
+
import { displayName } from '@sku-lib/rolldown-plugin-display-name';
|
|
11
|
+
|
|
12
|
+
export default {
|
|
13
|
+
plugins: [displayName()],
|
|
14
|
+
};
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The plugin adds a statement after the declaration:
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
const Test = () => <img />;
|
|
21
|
+
Test.displayName = 'Test';
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This applies to:
|
|
25
|
+
|
|
26
|
+
- Function components that are assigned to a variable, a property, or an object path, e.g. `foo.bar = () => <img />` or `const Components = { path: { test: () => <img /> } }`
|
|
27
|
+
- Results of `createContext`, `forwardRef` and `memo` from `react`
|
|
28
|
+
|
|
29
|
+
The plugin does not change function declarations, class components, default exports, and functions inside JSX.
|
|
30
|
+
|
|
31
|
+
## Options
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
displayName({
|
|
35
|
+
// Extra callees. The keys are module specifiers, and the values are export names.
|
|
36
|
+
// The plugin always allows `{ react: ['createContext', 'forwardRef', 'memo'] }`.
|
|
37
|
+
allowedCallees: { 'react-fela': ['createComponent'] },
|
|
38
|
+
|
|
39
|
+
// Options for Rolldown only.
|
|
40
|
+
include: /\.[cm]?[jt]sx?(?:$|\?)/, // IDs of the modules to transform
|
|
41
|
+
exclude: /[\\/]node_modules[\\/]|\0rolldown\/runtime\.js/, // IDs of the modules to skip (the default skips dependencies and the Rolldown runtime)
|
|
42
|
+
sourcemap: true, // the plugin skips source maps in Vite builds with `build.sourcemap: false`
|
|
43
|
+
rawTransfer: true, // use oxc-parser's experimental raw transfer where supported
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The package also exports the transform function on its own:
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
import { transform } from '@sku-lib/rolldown-plugin-display-name';
|
|
51
|
+
|
|
52
|
+
const result = transform(code, 'file.jsx'); // { code, map } | null
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Ordering
|
|
56
|
+
|
|
57
|
+
The plugin must see JSX, so it must run before the plugins that compile it.
|
|
58
|
+
The plugin sets `enforce: 'pre'` for this reason.
|
|
59
|
+
|
|
60
|
+
## Differences from the Babel plugin
|
|
61
|
+
|
|
62
|
+
- The plugin finds imports from the import declarations of the module.
|
|
63
|
+
It does not track scopes, so a local variable with the name of an import can fool it.
|
|
64
|
+
- It supports aliased imports, e.g. `import { memo as m } from 'react'`.
|
|
65
|
+
- It does not rename anonymous functions that it passes to a wrapper.
|
|
66
|
+
- It does not add a `displayName` to a component that has a name that it cannot express as a member expression, e.g. `{ 'foo-bar': () => <img /> }`.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { SourceMap } from "magic-string";
|
|
2
|
+
import { ParserOptions } from "oxc-parser";
|
|
3
|
+
import { Plugin } from "rolldown";
|
|
4
|
+
type AllowedCallees = Record<string, string[]>;
|
|
5
|
+
interface DisplayNameOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Extra callees that make the plugin add a `displayName` to the result.
|
|
8
|
+
* The keys are module specifiers, and the values are the names of the exports to match.
|
|
9
|
+
* These are added to the default, which is `{ react: ['createContext', 'forwardRef', 'memo'] }`.
|
|
10
|
+
*/
|
|
11
|
+
allowedCallees?: AllowedCallees;
|
|
12
|
+
}
|
|
13
|
+
declare const defaultAllowedCallees: Readonly<AllowedCallees>;
|
|
14
|
+
interface TransformOptions {
|
|
15
|
+
/**
|
|
16
|
+
* The language of the code.
|
|
17
|
+
* If you do not set it, the plugin infers the language from the file name.
|
|
18
|
+
* The plugin parses `js` as `jsx`.
|
|
19
|
+
*/
|
|
20
|
+
language?: 'js' | 'jsx' | 'ts' | 'tsx';
|
|
21
|
+
/**
|
|
22
|
+
* The source type of the code.
|
|
23
|
+
* If you do not set it, oxc-parser infers the source type from the file name.
|
|
24
|
+
*/
|
|
25
|
+
sourceType?: ParserOptions['sourceType'];
|
|
26
|
+
/**
|
|
27
|
+
* Generate a source map.
|
|
28
|
+
* @default true
|
|
29
|
+
*/
|
|
30
|
+
sourcemap?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Use the experimental raw transfer of oxc-parser to build the AST.
|
|
33
|
+
* Raw transfer is much faster.
|
|
34
|
+
* The plugin ignores this option if the runtime does not support raw transfer.
|
|
35
|
+
* @default true
|
|
36
|
+
*/
|
|
37
|
+
rawTransfer?: boolean;
|
|
38
|
+
}
|
|
39
|
+
interface TransformResult {
|
|
40
|
+
code: string;
|
|
41
|
+
map: SourceMap | null;
|
|
42
|
+
}
|
|
43
|
+
declare function transform(code: string, filename: string, options?: DisplayNameOptions, transformOptions?: TransformOptions): TransformResult | null;
|
|
44
|
+
type StringFilter = string | RegExp | Array<string | RegExp>;
|
|
45
|
+
interface DisplayNamePluginOptions extends DisplayNameOptions {
|
|
46
|
+
/**
|
|
47
|
+
* The IDs of the modules to transform.
|
|
48
|
+
* @default /\.[cm]?[jt]sx?(?:$|\?)/
|
|
49
|
+
*/
|
|
50
|
+
include?: StringFilter;
|
|
51
|
+
/**
|
|
52
|
+
* The IDs of the modules to skip.
|
|
53
|
+
* If you set it, you must add back the default entries that you still want to skip.
|
|
54
|
+
* @default /[\\/]node_modules[\\/]|\0rolldown\/runtime\.js/
|
|
55
|
+
*/
|
|
56
|
+
exclude?: StringFilter;
|
|
57
|
+
/**
|
|
58
|
+
* Generate source maps.
|
|
59
|
+
* In a Vite build with `build.sourcemap: false`, the plugin does not generate them.
|
|
60
|
+
* @default true
|
|
61
|
+
*/
|
|
62
|
+
sourcemap?: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Use the experimental raw transfer of oxc-parser to build the AST.
|
|
65
|
+
* Raw transfer is much faster.
|
|
66
|
+
* The plugin ignores this option if the runtime does not support raw transfer.
|
|
67
|
+
* @default true
|
|
68
|
+
*/
|
|
69
|
+
rawTransfer?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The plugin must see the JSX, so it must run before the transforms that compile it.
|
|
73
|
+
* Vite reads `enforce`, and Rolldown ignores it.
|
|
74
|
+
*/
|
|
75
|
+
type DisplayNamePlugin = Plugin & {
|
|
76
|
+
enforce: 'pre';
|
|
77
|
+
};
|
|
78
|
+
declare function displayName(options?: DisplayNamePluginOptions): DisplayNamePlugin;
|
|
79
|
+
export { type AllowedCallees, type DisplayNameOptions, DisplayNamePluginOptions, type TransformOptions, type TransformResult, defaultAllowedCallees, displayName, transform };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import MagicString from "magic-string";
|
|
2
|
+
import { parseSync, rawTransferSupported, visitorKeys } from "oxc-parser";
|
|
3
|
+
// src/transform.ts
|
|
4
|
+
const defaultAllowedCallees = Object.freeze({ react: [
|
|
5
|
+
"createContext",
|
|
6
|
+
"forwardRef",
|
|
7
|
+
"memo"
|
|
8
|
+
] });
|
|
9
|
+
const STATEMENT_LIST_KEYS = {
|
|
10
|
+
Program: "body",
|
|
11
|
+
BlockStatement: "body",
|
|
12
|
+
StaticBlock: "body",
|
|
13
|
+
TSModuleBlock: "body",
|
|
14
|
+
SwitchCase: "consequent"
|
|
15
|
+
};
|
|
16
|
+
const FUNCTIONS = /* @__PURE__ */ new Set([
|
|
17
|
+
"ArrowFunctionExpression",
|
|
18
|
+
"FunctionDeclaration",
|
|
19
|
+
"FunctionExpression"
|
|
20
|
+
]);
|
|
21
|
+
function createCalleeModuleMapping(allowedCallees = {}) {
|
|
22
|
+
const mapping = /* @__PURE__ */ new Map();
|
|
23
|
+
for (const callees of [defaultAllowedCallees, allowedCallees]) for (const [moduleName, methodNames] of Object.entries(callees)) for (const methodName of methodNames) {
|
|
24
|
+
const moduleNames = mapping.get(methodName) ?? [];
|
|
25
|
+
moduleNames.push(moduleName);
|
|
26
|
+
mapping.set(methodName, moduleNames);
|
|
27
|
+
}
|
|
28
|
+
return mapping;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns the strings of which at least one must be in the code of a module
|
|
32
|
+
* that the plugin can change.
|
|
33
|
+
*/
|
|
34
|
+
function displayNameSearchTerms(mapping) {
|
|
35
|
+
return [
|
|
36
|
+
"<",
|
|
37
|
+
"createElement",
|
|
38
|
+
...mapping.keys()
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
function isJSX(node) {
|
|
42
|
+
return node?.type === "JSXElement" || node?.type === "JSXFragment";
|
|
43
|
+
}
|
|
44
|
+
function isFunction(node) {
|
|
45
|
+
return node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression";
|
|
46
|
+
}
|
|
47
|
+
/** An object method, getter or setter. Babel has a node type for these, but ESTree does not. */
|
|
48
|
+
function isObjectMethod(node) {
|
|
49
|
+
return node?.type === "Property" && node.value?.type === "FunctionExpression" && (node.method || node.kind !== "init");
|
|
50
|
+
}
|
|
51
|
+
function isObjectProperty(node) {
|
|
52
|
+
return node.type === "Property" && !isObjectMethod(node);
|
|
53
|
+
}
|
|
54
|
+
/** Checks if the node creates a scope, as `@babel/traverse` does. */
|
|
55
|
+
function isScope(node, parent) {
|
|
56
|
+
switch (node.type) {
|
|
57
|
+
case "Program":
|
|
58
|
+
case "CatchClause":
|
|
59
|
+
case "ClassDeclaration":
|
|
60
|
+
case "ClassExpression":
|
|
61
|
+
case "StaticBlock":
|
|
62
|
+
case "SwitchStatement":
|
|
63
|
+
case "ForStatement":
|
|
64
|
+
case "ForInStatement":
|
|
65
|
+
case "ForOfStatement":
|
|
66
|
+
case "MethodDefinition": return true;
|
|
67
|
+
case "Property": return isObjectMethod(node);
|
|
68
|
+
case "ArrowFunctionExpression":
|
|
69
|
+
case "FunctionDeclaration": return true;
|
|
70
|
+
case "FunctionExpression": return !(parent && (parent.type === "MethodDefinition" || isObjectMethod(parent)));
|
|
71
|
+
case "BlockStatement": return !(parent && (FUNCTIONS.has(parent.type) || parent.type === "CatchClause" || parent.type === "MethodDefinition" || isObjectMethod(parent)));
|
|
72
|
+
default: return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Generates a display name from an identifier or from a chain of member expressions.
|
|
77
|
+
* Returns `null` for all other nodes.
|
|
78
|
+
*/
|
|
79
|
+
function generateNodeDisplayName(node) {
|
|
80
|
+
if (node.type === "Identifier") return node.name;
|
|
81
|
+
if (node.type === "MemberExpression") {
|
|
82
|
+
const objectName = generateNodeDisplayName(node.object);
|
|
83
|
+
const propertyName = generateNodeDisplayName(node.property);
|
|
84
|
+
if (objectName === null || propertyName === null) return null;
|
|
85
|
+
return node.computed ? `${objectName}[${propertyName}]` : `${objectName}.${propertyName}`;
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function generateDisplayName(identifiers) {
|
|
90
|
+
let displayName = "";
|
|
91
|
+
for (const { node, computed } of identifiers) {
|
|
92
|
+
const name = !computed && node.type !== "Identifier" && node.type !== "MemberExpression" ? null : generateNodeDisplayName(node);
|
|
93
|
+
if (!name) return null;
|
|
94
|
+
displayName += computed ? `[${name}]` : `.${name}`;
|
|
95
|
+
}
|
|
96
|
+
return displayName.slice(1);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Checks if this function returns JSX nodes.
|
|
100
|
+
* It does not do type-checking, which means that calling
|
|
101
|
+
* other functions that return JSX will still return `false`.
|
|
102
|
+
*/
|
|
103
|
+
function doesReturnJSX(body) {
|
|
104
|
+
if (!body) return false;
|
|
105
|
+
return (body.type === "BlockStatement" ? body.body.map((statement) => {
|
|
106
|
+
if (statement.type === "ReturnStatement") return { argument: statement.argument };
|
|
107
|
+
if (statement.type === "ExpressionStatement" && statement.expression.type !== "CallExpression") return { argument: statement.expression };
|
|
108
|
+
return null;
|
|
109
|
+
}) : [body.type === "CallExpression" ? null : { argument: body }]).some((statement) => {
|
|
110
|
+
if (!statement) return false;
|
|
111
|
+
const current = statement.argument;
|
|
112
|
+
if (current?.type === "CallExpression" && current.callee.type === "MemberExpression" && current.callee.property.type === "Identifier" && current.callee.property.name === "createElement") return true;
|
|
113
|
+
if (current?.type === "ConditionalExpression") return isJSX(current.consequent) || isJSX(current.alternate);
|
|
114
|
+
if (current?.type === "LogicalExpression") return isJSX(current.left) || isJSX(current.right);
|
|
115
|
+
if (current?.type === "ArrayExpression") return current.elements.some((element) => isJSX(element));
|
|
116
|
+
return isJSX(current);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function collectImportBindings(program) {
|
|
120
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
121
|
+
for (const statement of program.body) {
|
|
122
|
+
if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
|
|
123
|
+
const source = statement.source.value;
|
|
124
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportDefaultSpecifier") bindings.set(specifier.local.name, {
|
|
125
|
+
source,
|
|
126
|
+
imported: "default"
|
|
127
|
+
});
|
|
128
|
+
else if (specifier.type === "ImportNamespaceSpecifier") bindings.set(specifier.local.name, {
|
|
129
|
+
source,
|
|
130
|
+
imported: "*"
|
|
131
|
+
});
|
|
132
|
+
else if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type") {
|
|
133
|
+
const { imported } = specifier;
|
|
134
|
+
bindings.set(specifier.local.name, {
|
|
135
|
+
source,
|
|
136
|
+
imported: imported.type === "Identifier" ? imported.name : imported.value
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return bindings;
|
|
141
|
+
}
|
|
142
|
+
const isRawTransferSupported = rawTransferSupported();
|
|
143
|
+
const visitorKeysByType = visitorKeys;
|
|
144
|
+
const NO_OPTIONS = Object.freeze({});
|
|
145
|
+
const calleeModuleMappingCache = /* @__PURE__ */ new WeakMap();
|
|
146
|
+
function getCalleeModuleMapping(options) {
|
|
147
|
+
let mapping = calleeModuleMappingCache.get(options);
|
|
148
|
+
if (!mapping) {
|
|
149
|
+
mapping = createCalleeModuleMapping(options.allowedCallees);
|
|
150
|
+
calleeModuleMappingCache.set(options, mapping);
|
|
151
|
+
}
|
|
152
|
+
return mapping;
|
|
153
|
+
}
|
|
154
|
+
function transform(code, filename, options = NO_OPTIONS, transformOptions = {}) {
|
|
155
|
+
const calleeModuleMapping = getCalleeModuleMapping(options);
|
|
156
|
+
if (!displayNameSearchTerms(calleeModuleMapping).some((term) => code.includes(term))) return null;
|
|
157
|
+
const language = transformOptions.language === "js" ? "jsx" : transformOptions.language;
|
|
158
|
+
const result = parseSync(filename, code, {
|
|
159
|
+
lang: language,
|
|
160
|
+
sourceType: transformOptions.sourceType,
|
|
161
|
+
preserveParens: false,
|
|
162
|
+
...isRawTransferSupported && transformOptions.rawTransfer !== false && { experimentalRawTransfer: true }
|
|
163
|
+
});
|
|
164
|
+
const fatal = result.errors.find((error) => error.severity === "Error");
|
|
165
|
+
if (fatal) throw new SyntaxError(`${filename}: ${fatal.message}`);
|
|
166
|
+
const program = result.program;
|
|
167
|
+
const importBindings = collectImportBindings(program);
|
|
168
|
+
const magicString = new MagicString(code);
|
|
169
|
+
const seenDisplayNames = /* @__PURE__ */ new Set();
|
|
170
|
+
const insertedStatements = [];
|
|
171
|
+
/** The nodes from the root to the node that the walk is visiting. */
|
|
172
|
+
const stack = [];
|
|
173
|
+
/**
|
|
174
|
+
* Checks if this is a call of one of the allowed callees:
|
|
175
|
+
* - `memo()`, if `memo` is a named import of one of the allowed modules
|
|
176
|
+
* - `React.memo()`, if `React` is a default or namespace import of one of the allowed modules
|
|
177
|
+
*/
|
|
178
|
+
function isAllowedCallExpression(call) {
|
|
179
|
+
const { callee } = call;
|
|
180
|
+
if (callee.type === "Identifier") {
|
|
181
|
+
const binding = importBindings.get(callee.name);
|
|
182
|
+
return Boolean(binding && calleeModuleMapping.get(binding.imported)?.includes(binding.source));
|
|
183
|
+
}
|
|
184
|
+
if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.property.type === "Identifier") {
|
|
185
|
+
const moduleNames = calleeModuleMapping.get(callee.property.name);
|
|
186
|
+
const binding = importBindings.get(callee.object.name);
|
|
187
|
+
return Boolean(moduleNames && binding && (binding.imported === "default" || binding.imported === "*") && moduleNames.includes(binding.source));
|
|
188
|
+
}
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
/** Checks if the statement assigns `pattern` (like `foo.bar.displayName`). */
|
|
192
|
+
function isAssignmentTo(statement, pattern) {
|
|
193
|
+
return statement.type === "ExpressionStatement" && statement.expression.type === "AssignmentExpression" && statement.expression.operator === "=" && generateNodeDisplayName(statement.expression.left) === pattern;
|
|
194
|
+
}
|
|
195
|
+
/** Checks if this statement has been previously assigned a particular value. */
|
|
196
|
+
function hasBeenAssignedPrev(list, index, pattern, name) {
|
|
197
|
+
return list.slice(0, index).some((statement) => isAssignmentTo(statement, pattern) && statement.expression.right.type === "Literal" && statement.expression.right.value === name) || insertedStatements.some((inserted) => inserted.list === list && inserted.index < index && inserted.name === name);
|
|
198
|
+
}
|
|
199
|
+
/** Checks if the name will be assigned later in the scope. */
|
|
200
|
+
function hasBeenAssignedNext(list, index, pattern) {
|
|
201
|
+
return list.slice(index + 1).some((statement) => isAssignmentTo(statement, pattern));
|
|
202
|
+
}
|
|
203
|
+
/** Returns the index in the stack of the node that is the scope of the node at `index`. */
|
|
204
|
+
function findScopeIndex(index) {
|
|
205
|
+
for (let i = index; i >= 0; i--) {
|
|
206
|
+
const node = stack[i];
|
|
207
|
+
if (node && isScope(node, stack[i - 1])) return i;
|
|
208
|
+
}
|
|
209
|
+
return -1;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Adds a `displayName` to the function component if it is:
|
|
213
|
+
* - assigned to a variable or object path
|
|
214
|
+
* - not within other JSX elements
|
|
215
|
+
* - not called by a react hook or _createClass helper
|
|
216
|
+
*
|
|
217
|
+
* The node is the last node of the stack.
|
|
218
|
+
*/
|
|
219
|
+
function addDisplayNamesToFunctionComponent(node) {
|
|
220
|
+
const identifiers = [];
|
|
221
|
+
if (isObjectMethod(node)) {
|
|
222
|
+
if (node.computed) return;
|
|
223
|
+
identifiers.push({
|
|
224
|
+
node: node.key,
|
|
225
|
+
computed: false
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
const parentScopeIndex = findScopeIndex(findScopeIndex(stack.length - 1) - 1);
|
|
229
|
+
const scopeNode = parentScopeIndex === -1 ? null : stack[parentScopeIndex];
|
|
230
|
+
let assignmentIndex = -1;
|
|
231
|
+
let hasObjectProperty = false;
|
|
232
|
+
for (let i = stack.length - 1; i >= 0 && assignmentIndex === -1; i--) {
|
|
233
|
+
const current = stack[i];
|
|
234
|
+
if (!current) return;
|
|
235
|
+
if (current === scopeNode) return;
|
|
236
|
+
if (isJSX(current)) return;
|
|
237
|
+
if (current.type === "CallExpression") {
|
|
238
|
+
if (isFunction(current.callee)) return;
|
|
239
|
+
const calleeName = current.callee.type === "Identifier" ? current.callee.name : void 0;
|
|
240
|
+
if (calleeName && (calleeName.startsWith("_") || calleeName.startsWith("use"))) return;
|
|
241
|
+
}
|
|
242
|
+
if (current.type === "AssignmentExpression") {
|
|
243
|
+
identifiers.unshift({
|
|
244
|
+
node: current.left,
|
|
245
|
+
computed: false
|
|
246
|
+
});
|
|
247
|
+
assignmentIndex = i - 1;
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
if (current.type === "VariableDeclarator") {
|
|
251
|
+
if (current.init?.type === "ConditionalExpression") {
|
|
252
|
+
const { consequent, alternate } = current.init;
|
|
253
|
+
if (!isFunction(consequent) || !isFunction(alternate)) continue;
|
|
254
|
+
}
|
|
255
|
+
identifiers.unshift({
|
|
256
|
+
node: current.id,
|
|
257
|
+
computed: false
|
|
258
|
+
});
|
|
259
|
+
assignmentIndex = i - 1;
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
if (hasObjectProperty && !(isObjectProperty(current) || current.type === "ObjectExpression")) return;
|
|
263
|
+
if (isObjectProperty(current)) {
|
|
264
|
+
hasObjectProperty = true;
|
|
265
|
+
identifiers.unshift({
|
|
266
|
+
node: current.key,
|
|
267
|
+
computed: current.computed
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (assignmentIndex === -1 || identifiers.length === 0) return;
|
|
272
|
+
let statementIndex = assignmentIndex;
|
|
273
|
+
const statement = stack[statementIndex];
|
|
274
|
+
if (statement?.type !== "VariableDeclaration" && statement?.type !== "ExpressionStatement") return;
|
|
275
|
+
if (stack[statementIndex - 1]?.type === "ExportNamedDeclaration") statementIndex--;
|
|
276
|
+
const target = stack[statementIndex];
|
|
277
|
+
const container = stack[statementIndex - 1];
|
|
278
|
+
const listKey = container && STATEMENT_LIST_KEYS[container.type];
|
|
279
|
+
if (!target || !container || !listKey) return;
|
|
280
|
+
const list = container[listKey];
|
|
281
|
+
const index = list.indexOf(target);
|
|
282
|
+
if (index === -1) return;
|
|
283
|
+
const name = generateDisplayName(identifiers);
|
|
284
|
+
if (!name) return;
|
|
285
|
+
const pattern = `${name}.displayName`;
|
|
286
|
+
if (seenDisplayNames.has(name) && !hasBeenAssignedPrev(list, index, pattern, name)) return;
|
|
287
|
+
if (hasBeenAssignedNext(list, index, pattern)) return;
|
|
288
|
+
let lineStart = target.start;
|
|
289
|
+
while (lineStart > 0 && /[ \t]/.test(code.charAt(lineStart - 1))) lineStart--;
|
|
290
|
+
const indentation = lineStart === 0 || code[lineStart - 1] === "\n" ? code.slice(lineStart, target.start) : "";
|
|
291
|
+
magicString.appendLeft(target.end, `\n${indentation}${pattern} = ${JSON.stringify(name)};`);
|
|
292
|
+
insertedStatements.push({
|
|
293
|
+
list,
|
|
294
|
+
index,
|
|
295
|
+
name
|
|
296
|
+
});
|
|
297
|
+
seenDisplayNames.add(name);
|
|
298
|
+
}
|
|
299
|
+
function enter(node) {
|
|
300
|
+
const parent = stack[stack.length - 2];
|
|
301
|
+
if (node.type === "CallExpression") {
|
|
302
|
+
if (isAllowedCallExpression(node)) addDisplayNamesToFunctionComponent(node);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
let body;
|
|
306
|
+
if (isObjectMethod(node)) body = node.value.body;
|
|
307
|
+
else if (isFunction(node)) {
|
|
308
|
+
if (parent?.type === "MethodDefinition" || isObjectMethod(parent)) return;
|
|
309
|
+
body = node.body;
|
|
310
|
+
} else return;
|
|
311
|
+
if (parent?.type === "CallExpression" && !isAllowedCallExpression(parent)) return;
|
|
312
|
+
if (doesReturnJSX(body)) addDisplayNamesToFunctionComponent(node);
|
|
313
|
+
}
|
|
314
|
+
function visit(node) {
|
|
315
|
+
stack.push(node);
|
|
316
|
+
enter(node);
|
|
317
|
+
const keys = visitorKeysByType[node.type];
|
|
318
|
+
if (keys) for (const key of keys) {
|
|
319
|
+
const child = node[key];
|
|
320
|
+
if (Array.isArray(child)) {
|
|
321
|
+
for (const item of child) if (item && typeof item.type === "string") visit(item);
|
|
322
|
+
} else if (child && typeof child.type === "string") visit(child);
|
|
323
|
+
}
|
|
324
|
+
stack.pop();
|
|
325
|
+
}
|
|
326
|
+
visit(program);
|
|
327
|
+
if (!magicString.hasChanged()) return null;
|
|
328
|
+
return {
|
|
329
|
+
code: magicString.toString(),
|
|
330
|
+
map: transformOptions.sourcemap === false ? null : magicString.generateMap({
|
|
331
|
+
source: filename,
|
|
332
|
+
includeContent: true,
|
|
333
|
+
hires: "boundary"
|
|
334
|
+
})
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
// src/vite.ts
|
|
338
|
+
function isViteTransformContext(context) {
|
|
339
|
+
return "environment" in context && typeof context.environment === "object" && context.environment !== null;
|
|
340
|
+
}
|
|
341
|
+
function viteDiscardsSourcemaps(context) {
|
|
342
|
+
return isViteTransformContext(context) && context.environment.mode === "build" && context.environment.config.build.sourcemap === false;
|
|
343
|
+
}
|
|
344
|
+
// src/index.ts
|
|
345
|
+
const DEFAULT_EXCLUDE = /[\\/]node_modules[\\/]|\0rolldown\/runtime\.js/;
|
|
346
|
+
const DEFAULT_INCLUDE = /\.[cm]?[jt]sx?(?:$|\?)/;
|
|
347
|
+
const SUPPORTED_LANGUAGE_SET = /* @__PURE__ */ new Set([
|
|
348
|
+
"js",
|
|
349
|
+
"jsx",
|
|
350
|
+
"ts",
|
|
351
|
+
"tsx"
|
|
352
|
+
]);
|
|
353
|
+
function isSupportedLanguage(value) {
|
|
354
|
+
return value !== void 0 && SUPPORTED_LANGUAGE_SET.has(value);
|
|
355
|
+
}
|
|
356
|
+
function languageFromId(id) {
|
|
357
|
+
const extension = /\.[cm]?([jt]sx?)$/.exec(id.replace(/[?#].*$/, ""))?.[1];
|
|
358
|
+
return isSupportedLanguage(extension) ? extension : "js";
|
|
359
|
+
}
|
|
360
|
+
function displayName(options = {}) {
|
|
361
|
+
const { include = DEFAULT_INCLUDE, exclude = DEFAULT_EXCLUDE, sourcemap = true, rawTransfer, ...displayNameOptions } = options;
|
|
362
|
+
const searchTerms = displayNameSearchTerms(createCalleeModuleMapping(displayNameOptions.allowedCallees));
|
|
363
|
+
return {
|
|
364
|
+
name: "sku-display-name",
|
|
365
|
+
enforce: "pre",
|
|
366
|
+
transform: {
|
|
367
|
+
filter: {
|
|
368
|
+
id: {
|
|
369
|
+
include,
|
|
370
|
+
exclude
|
|
371
|
+
},
|
|
372
|
+
code: { include: searchTerms }
|
|
373
|
+
},
|
|
374
|
+
handler(code, id, meta) {
|
|
375
|
+
const language = meta?.moduleType ?? languageFromId(id);
|
|
376
|
+
if (!isSupportedLanguage(language)) return null;
|
|
377
|
+
try {
|
|
378
|
+
return transform(code, id, displayNameOptions, {
|
|
379
|
+
language,
|
|
380
|
+
sourcemap: sourcemap && !viteDiscardsSourcemaps(this),
|
|
381
|
+
rawTransfer
|
|
382
|
+
});
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return this.error(error instanceof Error ? error : String(error));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
export { defaultAllowedCallees, displayName, transform };
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sku-lib/rolldown-plugin-display-name",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Rolldown/Vite plugin that adds `displayName` to React components, powered by oxc",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"displayName",
|
|
7
|
+
"oxc",
|
|
8
|
+
"react",
|
|
9
|
+
"rolldown-plugin",
|
|
10
|
+
"vite-plugin"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/seek-oss/sku.git",
|
|
16
|
+
"directory": "packages/rolldown-plugin-display-name"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./dist/index.mjs",
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.19.0"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"magic-string": "^1.4.5",
|
|
32
|
+
"oxc-parser": "^0.159.0"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@sku-private/tsdown": "0.0.0",
|
|
36
|
+
"@types/node": "^24.12.4",
|
|
37
|
+
"dedent": "^1.7.2",
|
|
38
|
+
"rolldown": "^1.3.2",
|
|
39
|
+
"vite": "^8.0.1",
|
|
40
|
+
"vitest": "^5.0.3"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"rolldown": "^1.0.0",
|
|
44
|
+
"vite": "^8.0.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"rolldown": {
|
|
48
|
+
"optional": true
|
|
49
|
+
},
|
|
50
|
+
"vite": {
|
|
51
|
+
"optional": true
|
|
52
|
+
}
|
|
53
|
+
}
|
|
6
54
|
}
|