Repository navigation
perf: format - #7950
perf: format#7950
Conversation
| }, | ||
| } | ||
| }, | ||
| } |
There was a problem hiding this comment.
Review of the ESLint rule (import grouping/sorting)
Bugs / Correctness issues
-
specifiers.filter((s) => !types.includes(s))is O(n²) —Array.prototype.includesontypesis linear. For imports this is negligible, butnew Set(types)or a simplespecifier.importKind !== 'type'predicate is cleaner. More importantly, in an inline mixed import (e.g.import { A, type B } from 'x'), splitting into twoimportlines changes semantics only mildly — but the split path runs whennode.importKind !== 'type', and the resulting value statement keeps all non-type specifiers. That's fine, but the emittedrenderImport(node, values, false, …)reusescode.getText(node.source)and slices trailing text fromnode.source.range[1]tonode.range[1]. If the original had a semicolon after the source (no assertions), that works; if it had import attributes / assertions (assert { type: 'json' }) they are preserved by the slice — good. However the same slice is applied to both the type sub-import and the value sub-import, so an attribute clause would end up duplicated onto the type import (which is illegal). Worth guarding. -
inlineTypesOnlydetection vs.typesfilter inconsistency. Incheck, you decide "all specifiers are type" per-node withnode.importKind === 'type' || specifier.importKind === 'type'. InProgram,inlineTypesOnlyusesnode.type === 'ImportDeclaration'while elsewhere you consistently testnode.type === 'ImportDeclaration'. Then later againif (node.type === 'ImportDeclaration' && …). Minor redundancy, not a bug. But the comment says such imports are kept in place to preserve side effects — yetgroupOffor a pureimport typenode returns group 1 regardless of whether the source is external/relative. So aimport typefrom./localwill be sorted among other type imports before runtime imports. That matches most conventions; just confirm intent. -
length > 150magic number. The comment says it mirrors.prettierrc.json printWidth, but 150 is hard-coded. If prettier config changes, this silently diverges. Better to read it once (or at least define a named constantconst PRINT_WIDTH = 150). -
Length calculation is approximate.
prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6— the+ 6accounts for' from 'and';'?' from 'is 6 chars, yes, plus possibly a trailing;on another line. This approximation ignores the trailing slice (attributes, comments). For typical cases it's fine; for correctness, compute against the fully rendered string instead:const candidate = `${prefix}${[...bindings, singleLine].join(', ')} from ${code.getText(node.source)}${tail}`
and check
candidate.length > PRINT_WIDTH. -
compare(left.imported.name ?? left.imported.value, …)doesn't handleImportNamespaceSpecifier/ImportDefaultSpecifierinnamed— those never appear there because of the filter, so it's fine, butleft.importedmay be undefined forimport { type Foo }where the middle AST differs across parsers (ImportSpecifier.importedis always present, so OK). Still,?? ''fallback would be safer. -
sourceregexes assume@/and/src/without an anchor. For instancesome-lib/src/api/foo(a published package with asrcfolder reused verbatim) would land in group 3. Rare but possible. Consider anchoring one segment less aggressively or documenting. -
path.resolve(...).replaceAll('\\', '/')—path.resolverequiresfilenameto be absolute;context.filenameis, so fine. But resolving aliases like@/api/enumscannot go throughpath.resolve(it produces nonsense paths). The subsequent regex still matches the literal@/api/enums, so behavior is unaffected — but theresolvedvalue is misleading. Split alias handling from relative handling for clarity. -
leadingCommentcheck usescomment.loc.end.line >= node.loc.start.line - 1. That treats a comment on the previous line as attached even if separated by a blank line (blank line should de-attach). Also, comments have already been used to reset the block viagap.trim()— if there's a comment in the gap,gap.trim()is non-empty, soleadingCommentis effectively redundant there except for the case where the comment sits between the import and the previous statement with no other text. Simplify: rely ongap.trim(). -
trailingCommentfor the block boundary. On a trailing same-line comment youcheck(block)andblock = [], then push nothing — meaning the current node starts a fresh block but is never pushed. Next iteration,previousis undefined, sogapis'', treating the next import as adjacent. This can produce wrong grouping across the commented import. Should be:if (trailingComment) { check(block); block = []; continue-ish } else block.push(node)
As written, after a trailing-comment import, the following import becomes the start of a new block spanning from that import onwards — which loses the commented import entirely from ordering. Whether intended (freeze position) or not, document it.
-
range = [nodes[0].range[0], nodes.at(-1).range[1]]— this replaces the whole span including inter-import blank lines. Sinceentries.map(text).join('\n')emits no blank lines, deliberate blank-line groupings between imports are destroyed. Most format-preserving rules re-emit with one blank line between groups. Confirm this is desired; otherwise you're fighting Prettier/dev expectations. -
node.specifiers.lengthguard — bareimport 'x.css'resets the block. Good, but a side-effect import between otherwise-sortable imports means the sort is never re-established after it. Consider starting a fresh block after it (push nothing, then continue — butpreviousmust beundefinedso the gap check restarts). Currently that's exactly what happens becauseblock=[]; fine. -
Type-only default imports:
import type Foo from 'x'—defaultsincludesFoo, but the specifier'simportKindis'value'on the specifier itself (parser moves it to node level). Fine. Butimport { type A }where entire list is type triggersinlineTypesOnly, skipping sort — intentional but silently skips these; add a comment. -
Missing
importKind === 'typeof'handling (TS pre-verbatim syntax). Low risk under modern TS. -
Repeated calls to
code.getText(specifier)/code.getText(node.source)within loops — cheap butrenderImportrecomputescode.getText(node.source)twice. Store once. -
typein meta is'layout'. Valid, but import ordering is usually'suggestion'; both work. Formeta.messages, adding an English message alongside is optional — enterprise lint configs often require i18n consistency; the Chinese message is consistent here. -
No
docsfield inmeta. Add at least{ description }for tooling/introspection. -
Schema empty array — fine, but if
printWidthwere made configurable, schema would need updating. -
The fix only reports on
nodes[0]. If a fix fails repeatedly ESLint disables autofix for the file. Fine, but multiplereportentries per problematic block would give clearer errors. Optional.
Style / minor
flatMapproducing arrays of objects is fine; readability could be improved by extracting the "split into type/value pair" logic.- Comment mentions
permbut the sorting regex targets/^@\/permission/. Consistency: rename comment to match, e.g. "permission". frameworks.indexOf(source)inside sort → memoize with aMapfor clarity (trivial perf)._entry.textjoins with'\n'while original may use\r\non Windows (code.textis raw). Consider normalizing or joining with the detected EOL from the first node's line break.
Summary of recommended fixes (priority order)
| Priority | Item |
|---|---|
| High | #9 – block reset after trailing comment drops the node |
| High | #10 – confirm blank-line preservation strategy |
| High | #1 – don't duplicate import attributes to the synthetic type import |
| Medium | #4/#3 – compute length from rendered string; extract PRINT_WIDTH |
| Medium | #8 – simplify double leading-comment checks (blank-line aware) |
| Low | #6 – anchor src/api regex not to match third-party paths |
| Low | Cleanups: named constants, docs, memoized framework rank, remove redundant node.type === 'ImportDeclaration' guards |
Overall the rule logic is solid and defensively guards execution order — the main real risks are the trailing-comment block reset and the loss of intentional blank-line grouping.
| import { createPortalConversation } from './index' | ||
| const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>() | ||
| const bundle = createPortalConversation({ openApplicationSelector: () => applicationSelectorRef.value?.open() }) |
There was a problem hiding this comment.
Here's my review of the diff:
Issues
1. Missing file extensions in some imports (inconsistency)
import { MESSAGE_INPUT_KEY } from '../../components/message-input/index'This is inconsistent with '../index.ts' used later. Mixed extension usage (.ts vs none) can cause resolution differences between bundlers/TS configs, and can break if moduleResolution changes.
2. Import ordering looks auto-sorted but may violate project conventions
The new order (notably placing VIEW_TYPE, createDeviceType) looks like it came from an alphabetical sorter. If the repo uses ESLint import/order with grouping rules, verify this matches the configured groups (external → internal → relative). The sorting also mixes .vue imports with key imports — confirm this is intentional.
3. ./index imported last among relatives (potentially circular)
import { createPortalConversation } from './index'Importing ./index (the same folder's barrel) after other module-level imports, especially when those modules may themselves import from ./index, risks circular dependencies. This was present before the change, but the reordering didn't address it. Consider importing createPortalConversation directly from its defining file rather than the barrel.
4. InstanceType<typeof ...> without generic discipline
const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>()Also pre-existing, but since SelectApplicationDrawer.vue uses <script setup>, InstanceType inference depends on defineExpose. Verify the open method is actually exposed; otherwise TS won't error but runtime ?.open() will silently no-op.
5. Unused / missing context (cannot fully validate from diff only)
onMounted,onBeforeUnmount,watch,provideare imported but their usage isn't shown — ensure all remain used after reordering (dead imports often accumulate through refactors).FILE_SOURCE_TYPE,AxiosProgressEventsimilarly need verification.
Optimization suggestions
- Standardize import resolution: pick one convention (either always include
.ts/.vue, or never for barrels) and enforce via ESLint. - Replace
./indexbarrier import with a direct path to avoid circular-dependency risk. - Add explicit type to the ref if
defineExposeisn't guaranteed:interface ApplicationSelectorExposed { open: () => void } const applicationSelectorRef = ref<ApplicationSelectorExposed>()
- Run
eslint --fix+tsc --noEmitafter this purely-reordering change — pure import reorders occasionally surface latent circular deps that previously resolved by accident of order. - Consider
unplugin-auto-importor path aliases for the deeply nested../../paths (already using@/api/...); mixing@/and deep relatives reduces readability.
Summary
No functional logic changed — this is a pure import reorder, which is low-risk. The main things to verify: (a) extension consistency, (b) no newly-surfaced circular dependency via ./index, and (c) no accidentally unused imports. Otherwise the change is safe to merge.
| import { isSystemResource } from '@/utils/resource-context' | ||
|
|
||
| /** | ||
| * debug 模式:装配各组件 store。adapter 走 admin(带 applicationId)。 |
There was a problem hiding this comment.
Review of the diff
1. Import reordering (the main change)
The diff mostly reorders imports. This is fine but a few notes:
-
Ordering is inconsistent. Imports aren't sorted alphabetically or by group (types first, then local, then external). If your project has an ESLint
import/orderrule, this ordering may fail lint. Either let the linter auto-fix or adopt a consistent convention:- Vue core / third-party
@/aliases- relative imports
- type-only imports (or interleaved—pick one scheme).
-
type Refmoved out of thevueimport into a standaloneimport type { Ref } from 'vue'. This is fine and even slightly preferred if you useverbatimModuleSyntax/ explicit type imports, but be aware it's now two separate statements against the same module. A common style is:import { computed, type Ref } from 'vue'
Both work; just keep it consistent across files.
-
Mixed
import typestyles: some are inline (import { computed, type Ref }originally), some are dedicated (import type { ConversationApiAdapter }). Since you're moving to dedicatedimport type, apply it uniformly (the original in-fileRefwas inconsistent with theConversationApiAdapterstyle — so the change actually improves consistency here).
2. No functional changes
No logic is altered in the visible hunk — good. Confirm the rest of the file (not shown) isn't affected.
3. Potential optimizations / issues to verify
These aren't in the hunk but worth checking given the imports:
-
Static vs dynamic imports:
WorkspaceConversationApi,SystemResourceConversationApi,FileApi, andcreateConversationListStore/createMessageListStoreare all statically imported. IfisSystemResourcegates which API is used, consider lazyimport()for the unused branch to avoid loading both admin workspace and system-resource API modules on every page load. Minor bundle-size win. -
Tree-shaking:
import typechanges are tree-safe, but ensure no value is accidentally referenced from type-only imports elsewhere (e.g., usingFILE_SOURCE_TYPEas a value vs. type — it's an enum, so it must remain a value import; confirm it isn't aconst enumthat gets inlined differently). -
useRouteretained but check usage: IfuseRoutewas kept while other imports were pruned, verify it's still used; otherwise remove it. -
Duplicate
@/api/typesencoding:ApplicationDetailis type-only, which is correct.
Summary
The change is safe (import reorganization only). Main recommendations:
- Enforce/normalize import ordering via lint to prevent future churn.
- Pick one
import typeconvention and apply it everywhere. - Consider lazy-loading the mutually-exclusive API adapters to reduce initial bundle size.
No description provided.