refactor(types): enable `isolatedDeclarations` (#11178)

This commit is contained in:
Kevin Deng 三咲智子 2024-08-08 23:05:21 +08:00 committed by GitHub
parent 506c4c53fd
commit 928af5fe2f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
132 changed files with 775 additions and 525 deletions

View File

@ -618,7 +618,7 @@ export function createVNodeCall(
isBlock: VNodeCall['isBlock'] = false,
disableTracking: VNodeCall['disableTracking'] = false,
isComponent: VNodeCall['isComponent'] = false,
loc = locStub,
loc: SourceLocation = locStub,
): VNodeCall {
if (context) {
if (isBlock) {
@ -851,18 +851,24 @@ export function createReturnStatement(
}
}
export function getVNodeHelper(ssr: boolean, isComponent: boolean) {
export function getVNodeHelper(
ssr: boolean,
isComponent: boolean,
): typeof CREATE_VNODE | typeof CREATE_ELEMENT_VNODE {
return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE
}
export function getVNodeBlockHelper(ssr: boolean, isComponent: boolean) {
export function getVNodeBlockHelper(
ssr: boolean,
isComponent: boolean,
): typeof CREATE_BLOCK | typeof CREATE_ELEMENT_BLOCK {
return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK
}
export function convertToBlock(
node: VNodeCall,
{ helper, removeHelper, inSSR }: TransformContext,
) {
): void {
if (!node.isBlock) {
node.isBlock = true
removeHelper(getVNodeHelper(inSSR, node.isComponent))

View File

@ -28,7 +28,7 @@ export function walkIdentifiers(
includeAll = false,
parentStack: Node[] = [],
knownIds: Record<string, number> = Object.create(null),
) {
): void {
if (__BROWSER__) {
return
}
@ -108,7 +108,7 @@ export function isReferencedIdentifier(
id: Identifier,
parent: Node | null,
parentStack: Node[],
) {
): boolean {
if (__BROWSER__) {
return false
}
@ -177,7 +177,7 @@ export function isInNewExpression(parentStack: Node[]): boolean {
export function walkFunctionParams(
node: Function,
onIdent: (id: Identifier) => void,
) {
): void {
for (const p of node.params) {
for (const id of extractIdentifiers(p)) {
onIdent(id)
@ -188,7 +188,7 @@ export function walkFunctionParams(
export function walkBlockDeclarations(
block: BlockStatement | Program,
onIdent: (node: Identifier) => void,
) {
): void {
for (const stmt of block.body) {
if (stmt.type === 'VariableDeclaration') {
if (stmt.declare) continue
@ -313,7 +313,7 @@ export const isStaticProperty = (node: Node): node is ObjectProperty =>
(node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
!node.computed
export const isStaticPropertyKey = (node: Node, parent: Node) =>
export const isStaticPropertyKey = (node: Node, parent: Node): boolean =>
isStaticProperty(parent) && parent.key === node
/**
@ -495,7 +495,7 @@ function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean {
return true
}
export const TS_NODE_TYPES = [
export const TS_NODE_TYPES: string[] = [
'TSAsExpression', // foo as number
'TSTypeAssertion', // (<number>foo)
'TSNonNullExpression', // foo!

View File

@ -106,7 +106,7 @@ function getCompatValue(
export function isCompatEnabled(
key: CompilerDeprecationTypes,
context: MergedParserOptions | TransformContext,
) {
): boolean {
const mode = getCompatValue('MODE', context)
const value = getCompatValue(key, context)
// in v3 mode, only enable if explicitly set to true
@ -132,7 +132,7 @@ export function warnDeprecation(
context: MergedParserOptions | TransformContext,
loc: SourceLocation | null,
...args: any[]
) {
): void {
const val = getCompatValue(key, context)
if (val === 'suppress-warning') {
return

View File

@ -9,11 +9,11 @@ export interface CoreCompilerError extends CompilerError {
code: ErrorCodes
}
export function defaultOnError(error: CompilerError) {
export function defaultOnError(error: CompilerError): never {
throw error
}
export function defaultOnWarn(msg: CompilerError) {
export function defaultOnWarn(msg: CompilerError): void {
__DEV__ && console.warn(`[Vue warn] ${msg.message}`)
}

View File

@ -1,51 +1,85 @@
export const FRAGMENT = Symbol(__DEV__ ? `Fragment` : ``)
export const TELEPORT = Symbol(__DEV__ ? `Teleport` : ``)
export const SUSPENSE = Symbol(__DEV__ ? `Suspense` : ``)
export const KEEP_ALIVE = Symbol(__DEV__ ? `KeepAlive` : ``)
export const BASE_TRANSITION = Symbol(__DEV__ ? `BaseTransition` : ``)
export const OPEN_BLOCK = Symbol(__DEV__ ? `openBlock` : ``)
export const CREATE_BLOCK = Symbol(__DEV__ ? `createBlock` : ``)
export const CREATE_ELEMENT_BLOCK = Symbol(__DEV__ ? `createElementBlock` : ``)
export const CREATE_VNODE = Symbol(__DEV__ ? `createVNode` : ``)
export const CREATE_ELEMENT_VNODE = Symbol(__DEV__ ? `createElementVNode` : ``)
export const CREATE_COMMENT = Symbol(__DEV__ ? `createCommentVNode` : ``)
export const CREATE_TEXT = Symbol(__DEV__ ? `createTextVNode` : ``)
export const CREATE_STATIC = Symbol(__DEV__ ? `createStaticVNode` : ``)
export const RESOLVE_COMPONENT = Symbol(__DEV__ ? `resolveComponent` : ``)
export const RESOLVE_DYNAMIC_COMPONENT = Symbol(
export const FRAGMENT: unique symbol = Symbol(__DEV__ ? `Fragment` : ``)
export const TELEPORT: unique symbol = Symbol(__DEV__ ? `Teleport` : ``)
export const SUSPENSE: unique symbol = Symbol(__DEV__ ? `Suspense` : ``)
export const KEEP_ALIVE: unique symbol = Symbol(__DEV__ ? `KeepAlive` : ``)
export const BASE_TRANSITION: unique symbol = Symbol(
__DEV__ ? `BaseTransition` : ``,
)
export const OPEN_BLOCK: unique symbol = Symbol(__DEV__ ? `openBlock` : ``)
export const CREATE_BLOCK: unique symbol = Symbol(__DEV__ ? `createBlock` : ``)
export const CREATE_ELEMENT_BLOCK: unique symbol = Symbol(
__DEV__ ? `createElementBlock` : ``,
)
export const CREATE_VNODE: unique symbol = Symbol(__DEV__ ? `createVNode` : ``)
export const CREATE_ELEMENT_VNODE: unique symbol = Symbol(
__DEV__ ? `createElementVNode` : ``,
)
export const CREATE_COMMENT: unique symbol = Symbol(
__DEV__ ? `createCommentVNode` : ``,
)
export const CREATE_TEXT: unique symbol = Symbol(
__DEV__ ? `createTextVNode` : ``,
)
export const CREATE_STATIC: unique symbol = Symbol(
__DEV__ ? `createStaticVNode` : ``,
)
export const RESOLVE_COMPONENT: unique symbol = Symbol(
__DEV__ ? `resolveComponent` : ``,
)
export const RESOLVE_DYNAMIC_COMPONENT: unique symbol = Symbol(
__DEV__ ? `resolveDynamicComponent` : ``,
)
export const RESOLVE_DIRECTIVE = Symbol(__DEV__ ? `resolveDirective` : ``)
export const RESOLVE_FILTER = Symbol(__DEV__ ? `resolveFilter` : ``)
export const WITH_DIRECTIVES = Symbol(__DEV__ ? `withDirectives` : ``)
export const RENDER_LIST = Symbol(__DEV__ ? `renderList` : ``)
export const RENDER_SLOT = Symbol(__DEV__ ? `renderSlot` : ``)
export const CREATE_SLOTS = Symbol(__DEV__ ? `createSlots` : ``)
export const TO_DISPLAY_STRING = Symbol(__DEV__ ? `toDisplayString` : ``)
export const MERGE_PROPS = Symbol(__DEV__ ? `mergeProps` : ``)
export const NORMALIZE_CLASS = Symbol(__DEV__ ? `normalizeClass` : ``)
export const NORMALIZE_STYLE = Symbol(__DEV__ ? `normalizeStyle` : ``)
export const NORMALIZE_PROPS = Symbol(__DEV__ ? `normalizeProps` : ``)
export const GUARD_REACTIVE_PROPS = Symbol(__DEV__ ? `guardReactiveProps` : ``)
export const TO_HANDLERS = Symbol(__DEV__ ? `toHandlers` : ``)
export const CAMELIZE = Symbol(__DEV__ ? `camelize` : ``)
export const CAPITALIZE = Symbol(__DEV__ ? `capitalize` : ``)
export const TO_HANDLER_KEY = Symbol(__DEV__ ? `toHandlerKey` : ``)
export const SET_BLOCK_TRACKING = Symbol(__DEV__ ? `setBlockTracking` : ``)
export const RESOLVE_DIRECTIVE: unique symbol = Symbol(
__DEV__ ? `resolveDirective` : ``,
)
export const RESOLVE_FILTER: unique symbol = Symbol(
__DEV__ ? `resolveFilter` : ``,
)
export const WITH_DIRECTIVES: unique symbol = Symbol(
__DEV__ ? `withDirectives` : ``,
)
export const RENDER_LIST: unique symbol = Symbol(__DEV__ ? `renderList` : ``)
export const RENDER_SLOT: unique symbol = Symbol(__DEV__ ? `renderSlot` : ``)
export const CREATE_SLOTS: unique symbol = Symbol(__DEV__ ? `createSlots` : ``)
export const TO_DISPLAY_STRING: unique symbol = Symbol(
__DEV__ ? `toDisplayString` : ``,
)
export const MERGE_PROPS: unique symbol = Symbol(__DEV__ ? `mergeProps` : ``)
export const NORMALIZE_CLASS: unique symbol = Symbol(
__DEV__ ? `normalizeClass` : ``,
)
export const NORMALIZE_STYLE: unique symbol = Symbol(
__DEV__ ? `normalizeStyle` : ``,
)
export const NORMALIZE_PROPS: unique symbol = Symbol(
__DEV__ ? `normalizeProps` : ``,
)
export const GUARD_REACTIVE_PROPS: unique symbol = Symbol(
__DEV__ ? `guardReactiveProps` : ``,
)
export const TO_HANDLERS: unique symbol = Symbol(__DEV__ ? `toHandlers` : ``)
export const CAMELIZE: unique symbol = Symbol(__DEV__ ? `camelize` : ``)
export const CAPITALIZE: unique symbol = Symbol(__DEV__ ? `capitalize` : ``)
export const TO_HANDLER_KEY: unique symbol = Symbol(
__DEV__ ? `toHandlerKey` : ``,
)
export const SET_BLOCK_TRACKING: unique symbol = Symbol(
__DEV__ ? `setBlockTracking` : ``,
)
/**
* @deprecated no longer needed in 3.5+ because we no longer hoist element nodes
* but kept for backwards compat
*/
export const PUSH_SCOPE_ID = Symbol(__DEV__ ? `pushScopeId` : ``)
export const PUSH_SCOPE_ID: unique symbol = Symbol(__DEV__ ? `pushScopeId` : ``)
/**
* @deprecated kept for backwards compat
*/
export const POP_SCOPE_ID = Symbol(__DEV__ ? `popScopeId` : ``)
export const WITH_CTX = Symbol(__DEV__ ? `withCtx` : ``)
export const UNREF = Symbol(__DEV__ ? `unref` : ``)
export const IS_REF = Symbol(__DEV__ ? `isRef` : ``)
export const WITH_MEMO = Symbol(__DEV__ ? `withMemo` : ``)
export const IS_MEMO_SAME = Symbol(__DEV__ ? `isMemoSame` : ``)
export const POP_SCOPE_ID: unique symbol = Symbol(__DEV__ ? `popScopeId` : ``)
export const WITH_CTX: unique symbol = Symbol(__DEV__ ? `withCtx` : ``)
export const UNREF: unique symbol = Symbol(__DEV__ ? `unref` : ``)
export const IS_REF: unique symbol = Symbol(__DEV__ ? `isRef` : ``)
export const WITH_MEMO: unique symbol = Symbol(__DEV__ ? `withMemo` : ``)
export const IS_MEMO_SAME: unique symbol = Symbol(__DEV__ ? `isMemoSame` : ``)
// Name mapping for runtime helpers that need to be imported from 'vue' in
// generated code. Make sure these are correctly exported in the runtime!
@ -91,7 +125,7 @@ export const helperNameMap: Record<symbol, string> = {
[IS_MEMO_SAME]: `isMemoSame`,
}
export function registerRuntimeHelpers(helpers: Record<symbol, string>) {
export function registerRuntimeHelpers(helpers: Record<symbol, string>): void {
Object.getOwnPropertySymbols(helpers).forEach(s => {
helperNameMap[s] = helpers[s]
})

View File

@ -213,7 +213,15 @@ export interface Callbacks {
* We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
* sequences with an increased offset.
*/
export const Sequences = {
export const Sequences: {
Cdata: Uint8Array
CdataEnd: Uint8Array
CommentEnd: Uint8Array
ScriptEnd: Uint8Array
StyleEnd: Uint8Array
TitleEnd: Uint8Array
TextareaEnd: Uint8Array
} = {
Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]), // CDATA[
CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]), // ]]>
CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]), // `-->`
@ -227,7 +235,7 @@ export const Sequences = {
export default class Tokenizer {
/** The current state the tokenizer is in. */
public state = State.Text
public state: State = State.Text
/** The read buffer. */
private buffer = ''
/** The beginning of the section that is currently being read. */
@ -249,8 +257,8 @@ export default class Tokenizer {
private readonly entityDecoder?: EntityDecoder
public mode = ParseMode.BASE
public get inSFCRoot() {
public mode: ParseMode = ParseMode.BASE
public get inSFCRoot(): boolean {
return this.mode === ParseMode.SFC && this.stack.length === 0
}
@ -526,7 +534,7 @@ export default class Tokenizer {
this.state = State.SpecialStartSequence
}
public enterRCDATA(sequence: Uint8Array, offset: number) {
public enterRCDATA(sequence: Uint8Array, offset: number): void {
this.inRCDATA = true
this.currentSequence = sequence
this.sequenceIndex = offset
@ -917,7 +925,7 @@ export default class Tokenizer {
*
* States that are more likely to be hit are higher up, as a performance improvement.
*/
public parse(input: string) {
public parse(input: string): void {
this.buffer = input
while (this.index < this.buffer.length) {
const c = this.buffer.charCodeAt(this.index)

View File

@ -326,7 +326,7 @@ export function createTransformContext(
return context
}
export function transform(root: RootNode, options: TransformOptions) {
export function transform(root: RootNode, options: TransformOptions): void {
const context = createTransformContext(root, options)
traverseNode(root, context)
if (options.hoistStatic) {
@ -403,7 +403,7 @@ function createRootCodegen(root: RootNode, context: TransformContext) {
export function traverseChildren(
parent: ParentNode,
context: TransformContext,
) {
): void {
let i = 0
const nodeRemoved = () => {
i--
@ -422,7 +422,7 @@ export function traverseChildren(
export function traverseNode(
node: RootNode | TemplateChildNode,
context: TransformContext,
) {
): void {
context.currentNode = node
// apply transform plugins
const { nodeTransforms } = context

View File

@ -31,7 +31,7 @@ import {
OPEN_BLOCK,
} from '../runtimeHelpers'
export function cacheStatic(root: RootNode, context: TransformContext) {
export function cacheStatic(root: RootNode, context: TransformContext): void {
walk(
root,
undefined,

View File

@ -228,7 +228,7 @@ export function resolveComponentType(
node: ComponentNode,
context: TransformContext,
ssr = false,
) {
): string | symbol | CallExpression {
let { tag } = node
// 1. dynamic component
@ -374,7 +374,7 @@ export type PropsExpression = ObjectExpression | CallExpression | ExpressionNode
export function buildProps(
node: ElementNode,
context: TransformContext,
props: ElementNode['props'] = node.props,
props: ElementNode['props'] | undefined = node.props,
isComponent: boolean,
isDynamicComponent: boolean,
ssr = false,

View File

@ -99,7 +99,7 @@ export const transformBind: DirectiveTransform = (dir, _node, context) => {
export const transformBindShorthand = (
dir: DirectiveNode,
context: TransformContext,
) => {
): void => {
const arg = dir.arg!
const propName = camelize((arg as SimpleExpressionNode).content)

View File

@ -1,4 +1,5 @@
import {
type NodeTransform,
type TransformContext,
createStructuralDirectiveTransform,
} from '../transform'
@ -49,7 +50,7 @@ import { validateBrowserExpression } from '../validateExpression'
import { PatchFlags } from '@vue/shared'
import { transformBindShorthand } from './vBind'
export const transformFor = createStructuralDirectiveTransform(
export const transformFor: NodeTransform = createStructuralDirectiveTransform(
'for',
(node, dir, context) => {
const { helper, removeHelper } = context
@ -299,7 +300,7 @@ export function processFor(
const onExit = processCodegen && processCodegen(forNode)
return () => {
return (): void => {
scopes.vFor--
if (!__BROWSER__ && context.prefixIdentifiers) {
value && removeIdentifiers(value)
@ -313,7 +314,7 @@ export function processFor(
export function finalizeForParseResult(
result: ForParseResult,
context: TransformContext,
) {
): void {
if (result.finalized) return
if (!__BROWSER__ && context.prefixIdentifiers) {

View File

@ -1,4 +1,5 @@
import {
type NodeTransform,
type TransformContext,
createStructuralDirectiveTransform,
traverseNode,
@ -33,7 +34,7 @@ import { CREATE_COMMENT, FRAGMENT } from '../runtimeHelpers'
import { findDir, findProp, getMemoedVNodeCall, injectProp } from '../utils'
import { PatchFlagNames, PatchFlags } from '@vue/shared'
export const transformIf = createStructuralDirectiveTransform(
export const transformIf: NodeTransform = createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
(node, dir, context) => {
return processIf(node, dir, context, (ifNode, branch, isRoot) => {
@ -83,7 +84,7 @@ export function processIf(
branch: IfBranchNode,
isRoot: boolean,
) => (() => void) | undefined,
) {
): (() => void) | undefined {
if (
dir.name !== 'else' &&
(!dir.exp || !(dir.exp as SimpleExpressionNode).content.trim())

View File

@ -153,8 +153,11 @@ export const isMemberExpressionBrowser = (path: string): boolean => {
return !currentOpenBracketCount && !currentOpenParensCount
}
export const isMemberExpressionNode = __BROWSER__
? (NOOP as any as (path: string, context: TransformContext) => boolean)
export const isMemberExpressionNode: (
path: string,
context: TransformContext,
) => boolean = __BROWSER__
? (NOOP as any)
: (path: string, context: TransformContext): boolean => {
try {
let ret: Expression = parseExpression(path, {
@ -171,9 +174,10 @@ export const isMemberExpressionNode = __BROWSER__
}
}
export const isMemberExpression = __BROWSER__
? isMemberExpressionBrowser
: isMemberExpressionNode
export const isMemberExpression: (
path: string,
context: TransformContext,
) => boolean = __BROWSER__ ? isMemberExpressionBrowser : isMemberExpressionNode
export function advancePositionWithClone(
pos: Position,
@ -217,7 +221,7 @@ export function advancePositionWithMutation(
return pos
}
export function assert(condition: boolean, msg?: string) {
export function assert(condition: boolean, msg?: string): void {
/* istanbul ignore if */
if (!condition) {
throw new Error(msg || `unexpected compiler condition`)
@ -331,7 +335,7 @@ export function injectProp(
node: VNodeCall | RenderSlotCall,
prop: Property,
context: TransformContext,
) {
): void {
let propsWithInjection: ObjectExpression | CallExpression | undefined
/**
* 1. mergeProps(...)
@ -498,7 +502,9 @@ export function hasScopeRef(
}
}
export function getMemoedVNodeCall(node: BlockCodegenNode | MemoExpression) {
export function getMemoedVNodeCall(
node: BlockCodegenNode | MemoExpression,
): VNodeCall | RenderSlotCall {
if (node.type === NodeTypes.JS_CALL_EXPRESSION && node.callee === WITH_MEMO) {
return node.arguments[1].returns as VNodeCall
} else {
@ -506,4 +512,4 @@ export function getMemoedVNodeCall(node: BlockCodegenNode | MemoExpression) {
}
}
export const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/
export const forAliasRE: RegExp = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/

View File

@ -30,7 +30,7 @@ export function validateBrowserExpression(
context: TransformContext,
asParams = false,
asRawStatements = false,
) {
): void {
const exp = node.content
// empty expressions are validated per-directive since some directives

View File

@ -1,18 +1,30 @@
import { registerRuntimeHelpers } from '@vue/compiler-core'
export const V_MODEL_RADIO = Symbol(__DEV__ ? `vModelRadio` : ``)
export const V_MODEL_CHECKBOX = Symbol(__DEV__ ? `vModelCheckbox` : ``)
export const V_MODEL_TEXT = Symbol(__DEV__ ? `vModelText` : ``)
export const V_MODEL_SELECT = Symbol(__DEV__ ? `vModelSelect` : ``)
export const V_MODEL_DYNAMIC = Symbol(__DEV__ ? `vModelDynamic` : ``)
export const V_MODEL_RADIO: unique symbol = Symbol(__DEV__ ? `vModelRadio` : ``)
export const V_MODEL_CHECKBOX: unique symbol = Symbol(
__DEV__ ? `vModelCheckbox` : ``,
)
export const V_MODEL_TEXT: unique symbol = Symbol(__DEV__ ? `vModelText` : ``)
export const V_MODEL_SELECT: unique symbol = Symbol(
__DEV__ ? `vModelSelect` : ``,
)
export const V_MODEL_DYNAMIC: unique symbol = Symbol(
__DEV__ ? `vModelDynamic` : ``,
)
export const V_ON_WITH_MODIFIERS = Symbol(__DEV__ ? `vOnModifiersGuard` : ``)
export const V_ON_WITH_KEYS = Symbol(__DEV__ ? `vOnKeysGuard` : ``)
export const V_ON_WITH_MODIFIERS: unique symbol = Symbol(
__DEV__ ? `vOnModifiersGuard` : ``,
)
export const V_ON_WITH_KEYS: unique symbol = Symbol(
__DEV__ ? `vOnKeysGuard` : ``,
)
export const V_SHOW = Symbol(__DEV__ ? `vShow` : ``)
export const V_SHOW: unique symbol = Symbol(__DEV__ ? `vShow` : ``)
export const TRANSITION = Symbol(__DEV__ ? `Transition` : ``)
export const TRANSITION_GROUP = Symbol(__DEV__ ? `TransitionGroup` : ``)
export const TRANSITION: unique symbol = Symbol(__DEV__ ? `Transition` : ``)
export const TRANSITION_GROUP: unique symbol = Symbol(
__DEV__ ? `TransitionGroup` : ``,
)
registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,

View File

@ -1,4 +1,4 @@
export const version = __VERSION__
export const version: string = __VERSION__
// API
export { parse } from './parse'
@ -18,7 +18,7 @@ import {
errorMessages as coreErrorMessages,
} from '@vue/compiler-dom'
export const errorMessages = {
export const errorMessages: Record<number, string> = {
...coreErrorMessages,
...DOMErrorMessages,
}

View File

@ -17,6 +17,7 @@ import { parseCssVars } from './style/cssVars'
import { createCache } from './cache'
import type { ImportBinding } from './compileScript'
import { isImportUsed } from './script/importUsageCheck'
import type { LRUCache } from 'lru-cache'
export const DEFAULT_FILENAME = 'anonymous.vue'
@ -103,7 +104,9 @@ export interface SFCParseResult {
errors: (CompilerError | SyntaxError)[]
}
export const parseCache = createCache<SFCParseResult>()
export const parseCache:
| Map<string, SFCParseResult>
| LRUCache<string, SFCParseResult> = createCache<SFCParseResult>()
function genCacheKey(source: string, options: SFCParseOptions): string {
return (

View File

@ -17,11 +17,12 @@ export class ScriptCompileContext {
scriptAst: Program | null
scriptSetupAst: Program | null
source = this.descriptor.source
filename = this.descriptor.filename
s = new MagicString(this.source)
startOffset = this.descriptor.scriptSetup?.loc.start.offset
endOffset = this.descriptor.scriptSetup?.loc.end.offset
source: string = this.descriptor.source
filename: string = this.descriptor.filename
s: MagicString = new MagicString(this.source)
startOffset: number | undefined =
this.descriptor.scriptSetup?.loc.start.offset
endOffset: number | undefined = this.descriptor.scriptSetup?.loc.end.offset
// import / type analysis
scope?: TypeScope
@ -162,7 +163,7 @@ export function resolveParserPlugins(
lang: string,
userPlugins?: ParserPlugin[],
dts = false,
) {
): ParserPlugin[] {
const plugins: ParserPlugin[] = []
if (
!userPlugins ||

View File

@ -48,7 +48,7 @@ export function processDefineProps(
ctx: ScriptCompileContext,
node: Node,
declId?: LVal,
) {
): boolean {
if (!isCallOf(node, DEFINE_PROPS)) {
return processWithDefaults(ctx, node, declId)
}

View File

@ -26,7 +26,7 @@ import { DEFINE_PROPS } from './defineProps'
export function processPropsDestructure(
ctx: ScriptCompileContext,
declId: ObjectPattern,
) {
): void {
if (ctx.options.propsDestructure === 'error') {
ctx.error(`Props destructure is explicitly prohibited via config.`, declId)
} else if (ctx.options.propsDestructure === false) {
@ -97,7 +97,7 @@ type Scope = Record<string, boolean>
export function transformDestructuredProps(
ctx: ScriptCompileContext,
vueImportAliases: Record<string, string>,
) {
): void {
if (ctx.options.propsDestructure === false) {
return
}

View File

@ -3,13 +3,14 @@ import type { ScriptCompileContext } from './context'
import MagicString from 'magic-string'
import { rewriteDefaultAST } from '../rewriteDefault'
import { genNormalScriptCssVarsCode } from '../style/cssVars'
import type { SFCScriptBlock } from '../parse'
export const normalScriptDefaultVar = `__default__`
export function processNormalScript(
ctx: ScriptCompileContext,
scopeId: string,
) {
): SFCScriptBlock {
const script = ctx.descriptor.script!
if (script.lang && !ctx.isJS && !ctx.isTS) {
// do not process non js/ts script blocks

View File

@ -823,7 +823,7 @@ let loadTS: (() => typeof TS) | undefined
/**
* @private
*/
export function registerTS(_loadTS: () => typeof TS) {
export function registerTS(_loadTS: () => typeof TS): void {
loadTS = () => {
try {
return _loadTS()
@ -1107,7 +1107,7 @@ const fileToScopeCache = createCache<TypeScope>()
/**
* @private
*/
export function invalidateTypeCache(filename: string) {
export function invalidateTypeCache(filename: string): void {
filename = normalizePath(filename)
fileToScopeCache.delete(filename)
tsConfigCache.delete(filename)
@ -1439,7 +1439,7 @@ function attachNamespace(
}
}
export function recordImports(body: Statement[]) {
export function recordImports(body: Statement[]): Record<string, Import> {
const imports: TypeScope['imports'] = Object.create(null)
for (const s of body) {
recordImport(s, imports)
@ -1462,7 +1462,7 @@ function recordImport(node: Node, imports: TypeScope['imports']) {
export function inferRuntimeType(
ctx: TypeResolveContext,
node: Node & MaybeWithScope,
scope = node._ownerScope || ctxToScope(ctx),
scope: TypeScope = node._ownerScope || ctxToScope(ctx),
isKeyOf = false,
): string[] {
try {

View File

@ -39,7 +39,7 @@ export function processAwait(
node: AwaitExpression,
needSemi: boolean,
isStatement: boolean,
) {
): void {
const argumentStart =
node.argument.extra && node.argument.extra.parenthesized
? (node.argument.extra.parenStart as number)

View File

@ -12,7 +12,10 @@ import path from 'path'
export const UNKNOWN_TYPE = 'Unknown'
export function resolveObjectKey(node: Node, computed: boolean) {
export function resolveObjectKey(
node: Node,
computed: boolean,
): string | undefined {
switch (node.type) {
case 'StringLiteral':
case 'NumericLiteral':
@ -23,11 +26,13 @@ export function resolveObjectKey(node: Node, computed: boolean) {
return undefined
}
export function concatStrings(strs: Array<string | null | undefined | false>) {
export function concatStrings(
strs: Array<string | null | undefined | false>,
): string {
return strs.filter((s): s is string => !!s).join(', ')
}
export function isLiteralNode(node: Node) {
export function isLiteralNode(node: Node): boolean {
return node.type.endsWith('Literal')
}
@ -46,7 +51,7 @@ export function isCallOf(
)
}
export function toRuntimeTypeString(types: string[]) {
export function toRuntimeTypeString(types: string[]): string {
return types.length > 1 ? `[${types.join(', ')}]` : types[0]
}
@ -55,7 +60,7 @@ export function getImportedName(
| ImportSpecifier
| ImportDefaultSpecifier
| ImportNamespaceSpecifier,
) {
): string {
if (specifier.type === 'ImportSpecifier')
return specifier.imported.type === 'Identifier'
? specifier.imported.name
@ -89,7 +94,9 @@ function toFileNameLowerCase(x: string) {
* but TS does not expose it directly. This implementation is repllicated from
* the TS source code.
*/
export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean) {
export function createGetCanonicalFileName(
useCaseSensitiveFileNames: boolean,
): (str: string) => string {
return useCaseSensitiveFileNames ? identity : toFileNameLowerCase
}
@ -97,25 +104,31 @@ export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean) {
// posix behavior.
const normalize = (path.posix || path).normalize
const windowsSlashRE = /\\/g
export function normalizePath(p: string) {
export function normalizePath(p: string): string {
return normalize(p.replace(windowsSlashRE, '/'))
}
export const joinPaths = (path.posix || path).join
export const joinPaths: (...paths: string[]) => string = (path.posix || path)
.join
/**
* key may contain symbols
* e.g. onUpdate:modelValue -> "onUpdate:modelValue"
*/
export const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/
export const propNameEscapeSymbolsRE: RegExp =
/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/
export function getEscapedPropName(key: string) {
export function getEscapedPropName(key: string): string {
return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key
}
export const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g
export const cssVarNameEscapeSymbolsRE: RegExp =
/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g
export function getEscapedCssVarName(key: string, doubleEscape: boolean) {
export function getEscapedCssVarName(
key: string,
doubleEscape: boolean,
): string {
return key.replace(cssVarNameEscapeSymbolsRE, s =>
doubleEscape ? `\\\\${s}` : `\\${s}`,
)

View File

@ -1,6 +1,6 @@
const hasWarned: Record<string, boolean> = {}
export function warnOnce(msg: string) {
export function warnOnce(msg: string): void {
const isNodeProd =
typeof process !== 'undefined' && process.env.NODE_ENV === 'production'
if (!isNodeProd && !__TEST__ && !hasWarned[msg]) {
@ -9,7 +9,7 @@ export function warnOnce(msg: string) {
}
}
export function warn(msg: string) {
export function warn(msg: string): void {
console.warn(
`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`,
)

View File

@ -1,26 +1,34 @@
import { registerRuntimeHelpers } from '@vue/compiler-dom'
export const SSR_INTERPOLATE = Symbol(`ssrInterpolate`)
export const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`)
export const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`)
export const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`)
export const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`)
export const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`)
export const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`)
export const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`)
export const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`)
export const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`)
export const SSR_RENDER_LIST = Symbol(`ssrRenderList`)
export const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`)
export const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`)
export const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`)
export const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`)
export const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`)
export const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`)
export const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`)
export const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`)
export const SSR_INTERPOLATE: unique symbol = Symbol(`ssrInterpolate`)
export const SSR_RENDER_VNODE: unique symbol = Symbol(`ssrRenderVNode`)
export const SSR_RENDER_COMPONENT: unique symbol = Symbol(`ssrRenderComponent`)
export const SSR_RENDER_SLOT: unique symbol = Symbol(`ssrRenderSlot`)
export const SSR_RENDER_SLOT_INNER: unique symbol = Symbol(`ssrRenderSlotInner`)
export const SSR_RENDER_CLASS: unique symbol = Symbol(`ssrRenderClass`)
export const SSR_RENDER_STYLE: unique symbol = Symbol(`ssrRenderStyle`)
export const SSR_RENDER_ATTRS: unique symbol = Symbol(`ssrRenderAttrs`)
export const SSR_RENDER_ATTR: unique symbol = Symbol(`ssrRenderAttr`)
export const SSR_RENDER_DYNAMIC_ATTR: unique symbol =
Symbol(`ssrRenderDynamicAttr`)
export const SSR_RENDER_LIST: unique symbol = Symbol(`ssrRenderList`)
export const SSR_INCLUDE_BOOLEAN_ATTR: unique symbol = Symbol(
`ssrIncludeBooleanAttr`,
)
export const SSR_LOOSE_EQUAL: unique symbol = Symbol(`ssrLooseEqual`)
export const SSR_LOOSE_CONTAIN: unique symbol = Symbol(`ssrLooseContain`)
export const SSR_RENDER_DYNAMIC_MODEL: unique symbol = Symbol(
`ssrRenderDynamicModel`,
)
export const SSR_GET_DYNAMIC_MODEL_PROPS: unique symbol = Symbol(
`ssrGetDynamicModelProps`,
)
export const SSR_RENDER_TELEPORT: unique symbol = Symbol(`ssrRenderTeleport`)
export const SSR_RENDER_SUSPENSE: unique symbol = Symbol(`ssrRenderSuspense`)
export const SSR_GET_DIRECTIVE_PROPS: unique symbol =
Symbol(`ssrGetDirectiveProps`)
export const ssrHelpers = {
export const ssrHelpers: Record<symbol, string> = {
[SSR_INTERPOLATE]: `ssrInterpolate`,
[SSR_RENDER_VNODE]: `ssrRenderVNode`,
[SSR_RENDER_COMPONENT]: `ssrRenderComponent`,

View File

@ -1,9 +1,11 @@
import {
type BlockStatement,
type CallExpression,
type CompilerError,
type CompilerOptions,
ElementTypes,
type IfStatement,
type JSChildNode,
NodeTypes,
type RootNode,
type TemplateChildNode,
@ -33,7 +35,10 @@ import { SSRErrorCodes, createSSRCompilerError } from './errors'
// transform pass to convert the template AST into a fresh JS AST before
// passing it to codegen.
export function ssrCodegenTransform(ast: RootNode, options: CompilerOptions) {
export function ssrCodegenTransform(
ast: RootNode,
options: CompilerOptions,
): void {
const context = createSSRTransformContext(ast, options)
// inject SFC <style> CSS variables
@ -70,14 +75,24 @@ export function ssrCodegenTransform(ast: RootNode, options: CompilerOptions) {
ast.helpers = new Set(Array.from(ast.helpers).filter(h => !(h in ssrHelpers)))
}
export type SSRTransformContext = ReturnType<typeof createSSRTransformContext>
export interface SSRTransformContext {
root: RootNode
options: CompilerOptions
body: (JSChildNode | IfStatement)[]
helpers: Set<symbol>
withSlotScopeId: boolean
onError: (error: CompilerError) => void
helper<T extends symbol>(name: T): T
pushStringPart(part: TemplateLiteral['elements'][0]): void
pushStatement(statement: IfStatement | CallExpression): void
}
function createSSRTransformContext(
root: RootNode,
options: CompilerOptions,
helpers: Set<symbol> = new Set(),
withSlotScopeId = false,
) {
): SSRTransformContext {
const body: BlockStatement['body'] = []
let currentString: TemplateLiteral | null = null
@ -96,7 +111,7 @@ function createSSRTransformContext(
helpers.add(name)
return name
},
pushStringPart(part: TemplateLiteral['elements'][0]) {
pushStringPart(part) {
if (!currentString) {
const currentCall = createCallExpression(`_push`)
body.push(currentCall)
@ -111,7 +126,7 @@ function createSSRTransformContext(
bufferedElements.push(part)
}
},
pushStatement(statement: IfStatement | CallExpression) {
pushStatement(statement) {
// close current string
currentString = null
body.push(statement)
@ -142,7 +157,7 @@ export function processChildren(
asFragment = false,
disableNestedFragments = false,
disableCommentAsIfAlternate = false,
) {
): void {
if (asFragment) {
context.pushStringPart(`<!--[-->`)
}
@ -231,7 +246,7 @@ export function processChildrenAsStatement(
parent: Container,
parentContext: SSRTransformContext,
asFragment = false,
withSlotScopeId = parentContext.withSlotScopeId,
withSlotScopeId: boolean = parentContext.withSlotScopeId,
): BlockStatement {
const childContext = createChildContext(parentContext, withSlotScopeId)
processChildren(parent, childContext, asFragment)

View File

@ -205,7 +205,7 @@ export function ssrProcessComponent(
node: ComponentNode,
context: SSRTransformContext,
parent: { children: TemplateChildNode[] },
) {
): void {
const component = componentTypeMap.get(node)!
if (!node.ssrCodegenNode) {
// this is a built-in component that fell-through.
@ -268,7 +268,10 @@ export function ssrProcessComponent(
}
}
export const rawOptionsMap = new WeakMap<RootNode, CompilerOptions>()
export const rawOptionsMap: WeakMap<RootNode, CompilerOptions> = new WeakMap<
RootNode,
CompilerOptions
>()
const [baseNodeTransforms, baseDirectiveTransforms] =
getBaseTransformPreset(true)

View File

@ -436,7 +436,7 @@ function findVModel(node: PlainElementNode): DirectiveNode | undefined {
export function ssrProcessElement(
node: PlainElementNode,
context: SSRTransformContext,
) {
): void {
const isVoidTag = context.options.isVoidTag || NO
const elementsToAdd = node.ssrCodegenNode!.elements
for (let j = 0; j < elementsToAdd.length; j++) {

View File

@ -73,7 +73,7 @@ export const ssrTransformSlotOutlet: NodeTransform = (node, context) => {
export function ssrProcessSlotOutlet(
node: SlotOutletNode,
context: SSRTransformContext,
) {
): void {
const renderCall = node.ssrCodegenNode!
// has fallback content

View File

@ -29,7 +29,7 @@ export function ssrTransformSuspense(
node: ComponentNode,
context: TransformContext,
) {
return () => {
return (): void => {
if (node.children.length) {
const wipEntry: WIPEntry = {
slotsExp: null!, // to be immediately set
@ -62,7 +62,7 @@ export function ssrTransformSuspense(
export function ssrProcessSuspense(
node: ComponentNode,
context: SSRTransformContext,
) {
): void {
// complete wip slots with ssr code
const wipEntry = wipMap.get(node)
if (!wipEntry) {

View File

@ -18,7 +18,7 @@ import { SSR_RENDER_TELEPORT } from '../runtimeHelpers'
export function ssrProcessTeleport(
node: ComponentNode,
context: SSRTransformContext,
) {
): void {
const targetProp = findProp(node, 'to')
if (!targetProp) {
context.onError(

View File

@ -15,7 +15,7 @@ export function ssrTransformTransition(
node: ComponentNode,
context: TransformContext,
) {
return () => {
return (): void => {
const appear = findProp(node, 'appear', false, true)
wipMap.set(node, !!appear)
}
@ -24,7 +24,7 @@ export function ssrTransformTransition(
export function ssrProcessTransition(
node: ComponentNode,
context: SSRTransformContext,
) {
): void {
// #5351: filter out comment children inside transition
node.children = node.children.filter(c => c.type !== NodeTypes.COMMENT)

View File

@ -29,7 +29,7 @@ export function ssrTransformTransitionGroup(
node: ComponentNode,
context: TransformContext,
) {
return () => {
return (): void => {
const tag = findProp(node, 'tag')
if (tag) {
const otherProps = node.props.filter(p => p !== tag)
@ -60,7 +60,7 @@ export function ssrTransformTransitionGroup(
export function ssrProcessTransitionGroup(
node: ComponentNode,
context: SSRTransformContext,
) {
): void {
const entry = wipMap.get(node)
if (entry) {
const { tag, propsExp, scopeId } = entry

View File

@ -1,5 +1,6 @@
import {
type ForNode,
type NodeTransform,
NodeTypes,
createCallExpression,
createForLoopParams,
@ -14,10 +15,8 @@ import {
import { SSR_RENDER_LIST } from '../runtimeHelpers'
// Plugin for the first transform pass, which simply constructs the AST node
export const ssrTransformFor = createStructuralDirectiveTransform(
'for',
processFor,
)
export const ssrTransformFor: NodeTransform =
createStructuralDirectiveTransform('for', processFor)
// This is called during the 2nd transform pass to construct the SSR-specific
// codegen nodes.
@ -25,7 +24,7 @@ export function ssrProcessFor(
node: ForNode,
context: SSRTransformContext,
disableNestedFragments = false,
) {
): void {
const needFragmentWrapper =
!disableNestedFragments &&
(node.children.length !== 1 || node.children[0].type !== NodeTypes.ELEMENT)

View File

@ -2,6 +2,7 @@ import {
type BlockStatement,
type IfBranchNode,
type IfNode,
type NodeTransform,
NodeTypes,
createBlockStatement,
createCallExpression,
@ -15,7 +16,7 @@ import {
} from '../ssrCodegenTransform'
// Plugin for the first transform pass, which simply constructs the AST node
export const ssrTransformIf = createStructuralDirectiveTransform(
export const ssrTransformIf: NodeTransform = createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
processIf,
)
@ -27,7 +28,7 @@ export function ssrProcessIf(
context: SSRTransformContext,
disableNestedFragments = false,
disableCommentAsIfAlternate = false,
) {
): void {
const [rootBranch] = node.branches
const ifStatement = createIfStatement(
rootBranch.condition!,

View File

@ -52,7 +52,7 @@ class BaseReactiveHandler implements ProxyHandler<Target> {
protected readonly _isShallow = false,
) {}
get(target: Target, key: string | symbol, receiver: object) {
get(target: Target, key: string | symbol, receiver: object): any {
const isReadonly = this._isReadonly,
isShallow = this._isShallow
if (key === ReactiveFlags.IS_REACTIVE) {
@ -240,12 +240,11 @@ export const mutableHandlers: ProxyHandler<object> =
export const readonlyHandlers: ProxyHandler<object> =
/*#__PURE__*/ new ReadonlyReactiveHandler()
export const shallowReactiveHandlers = /*#__PURE__*/ new MutableReactiveHandler(
true,
)
export const shallowReactiveHandlers: MutableReactiveHandler =
/*#__PURE__*/ new MutableReactiveHandler(true)
// Props handlers are special in the sense that it should not unwrap top-level
// refs (in order to allow refs to be explicitly passed down), but should
// retain the reactivity of the normal readonly object.
export const shallowReadonlyHandlers =
export const shallowReadonlyHandlers: ReadonlyReactiveHandler =
/*#__PURE__*/ new ReadonlyReactiveHandler(true)

View File

@ -47,15 +47,17 @@ export class ComputedRefImpl<T = any> implements Subscriber {
/**
* @internal
*/
readonly dep = new Dep(this)
readonly dep: Dep = new Dep(this)
/**
* @internal
*/
readonly [ReactiveFlags.IS_REF] = true
readonly __v_isRef = true
// TODO isolatedDeclarations ReactiveFlags.IS_REF
/**
* @internal
*/
readonly [ReactiveFlags.IS_READONLY]: boolean
readonly __v_isReadonly: boolean
// TODO isolatedDeclarations ReactiveFlags.IS_READONLY
// A computed is also a subscriber that tracks other deps
/**
* @internal
@ -68,17 +70,17 @@ export class ComputedRefImpl<T = any> implements Subscriber {
/**
* @internal
*/
flags = EffectFlags.DIRTY
flags: EffectFlags = EffectFlags.DIRTY
/**
* @internal
*/
globalVersion = globalVersion - 1
globalVersion: number = globalVersion - 1
/**
* @internal
*/
isSSR: boolean
// for backwards compat
effect = this
effect: this = this
// dev only
onTrack?: (event: DebuggerEvent) => void
@ -103,7 +105,7 @@ export class ComputedRefImpl<T = any> implements Subscriber {
/**
* @internal
*/
notify() {
notify(): void {
// avoid infinite self recursion
if (activeSub !== this) {
this.flags |= EffectFlags.DIRTY
@ -113,7 +115,7 @@ export class ComputedRefImpl<T = any> implements Subscriber {
}
}
get value() {
get value(): T {
const link = __DEV__
? this.dep.track({
target: this,

View File

@ -39,7 +39,7 @@ export class Dep {
*/
subsHead?: Link
constructor(public computed?: ComputedRefImpl) {
constructor(public computed?: ComputedRefImpl | undefined) {
if (__DEV__) {
this.subsHead = undefined
}
@ -115,13 +115,13 @@ export class Dep {
return link
}
trigger(debugInfo?: DebuggerEventExtraInfo) {
trigger(debugInfo?: DebuggerEventExtraInfo): void {
this.version++
globalVersion++
this.notify(debugInfo)
}
notify(debugInfo?: DebuggerEventExtraInfo) {
notify(debugInfo?: DebuggerEventExtraInfo): void {
startBatch()
try {
if (__DEV__) {
@ -185,9 +185,15 @@ function addSub(link: Link) {
type KeyToDepMap = Map<any, Dep>
const targetMap = new WeakMap<object, KeyToDepMap>()
export const ITERATE_KEY = Symbol(__DEV__ ? 'Object iterate' : '')
export const MAP_KEY_ITERATE_KEY = Symbol(__DEV__ ? 'Map keys iterate' : '')
export const ARRAY_ITERATE_KEY = Symbol(__DEV__ ? 'Array iterate' : '')
export const ITERATE_KEY: unique symbol = Symbol(
__DEV__ ? 'Object iterate' : '',
)
export const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(
__DEV__ ? 'Map keys iterate' : '',
)
export const ARRAY_ITERATE_KEY: unique symbol = Symbol(
__DEV__ ? 'Array iterate' : '',
)
/**
* Tracks access to a reactive property.
@ -199,7 +205,7 @@ export const ARRAY_ITERATE_KEY = Symbol(__DEV__ ? 'Array iterate' : '')
* @param type - Defines the type of access to the reactive property.
* @param key - Identifier of the reactive property to track.
*/
export function track(target: object, type: TrackOpTypes, key: unknown) {
export function track(target: object, type: TrackOpTypes, key: unknown): void {
if (shouldTrack && activeSub) {
let depsMap = targetMap.get(target)
if (!depsMap) {
@ -236,7 +242,7 @@ export function trigger(
newValue?: unknown,
oldValue?: unknown,
oldTarget?: Map<unknown, unknown> | Set<unknown>,
) {
): void {
const depsMap = targetMap.get(target)
if (!depsMap) {
// never been tracked
@ -328,7 +334,10 @@ export function trigger(
/**
* Test only
*/
export function getDepFromReactive(object: any, key: string | number | symbol) {
export function getDepFromReactive(
object: any,
key: string | number | symbol,
): Dep | undefined {
// eslint-disable-next-line
return targetMap.get(object)?.get(key)
}

View File

@ -145,11 +145,11 @@ export class ReactiveEffect<T = any>
}
}
pause() {
pause(): void {
this.flags |= EffectFlags.PAUSED
}
resume() {
resume(): void {
if (this.flags & EffectFlags.PAUSED) {
this.flags &= ~EffectFlags.PAUSED
if (pausedQueueEffects.has(this)) {
@ -162,7 +162,7 @@ export class ReactiveEffect<T = any>
/**
* @internal
*/
notify() {
notify(): void {
if (
this.flags & EffectFlags.RUNNING &&
!(this.flags & EffectFlags.ALLOW_RECURSE)
@ -179,7 +179,7 @@ export class ReactiveEffect<T = any>
}
}
run() {
run(): T {
// TODO cleanupEffect
if (!(this.flags & EffectFlags.ACTIVE)) {
@ -211,7 +211,7 @@ export class ReactiveEffect<T = any>
}
}
stop() {
stop(): void {
if (this.flags & EffectFlags.ACTIVE) {
for (let link = this.deps; link; link = link.nextDep) {
removeSub(link)
@ -223,7 +223,7 @@ export class ReactiveEffect<T = any>
}
}
trigger() {
trigger(): void {
if (this.flags & EffectFlags.PAUSED) {
pausedQueueEffects.add(this)
} else if (this.scheduler) {
@ -236,13 +236,13 @@ export class ReactiveEffect<T = any>
/**
* @internal
*/
runIfDirty() {
runIfDirty(): void {
if (isDirty(this)) {
this.run()
}
}
get dirty() {
get dirty(): boolean {
return isDirty(this)
}
}
@ -253,7 +253,7 @@ let batchedEffect: ReactiveEffect | undefined
/**
* @internal
*/
export function startBatch() {
export function startBatch(): void {
batchDepth++
}
@ -261,7 +261,7 @@ export function startBatch() {
* Run batched effects when all batches have ended
* @internal
*/
export function endBatch() {
export function endBatch(): void {
if (batchDepth > 1) {
batchDepth--
return
@ -350,7 +350,7 @@ function isDirty(sub: Subscriber): boolean {
* Returning false indicates the refresh failed
* @internal
*/
export function refreshComputed(computed: ComputedRefImpl) {
export function refreshComputed(computed: ComputedRefImpl): false | undefined {
if (computed.flags & EffectFlags.RUNNING) {
return false
}
@ -474,7 +474,7 @@ export function effect<T = any>(
*
* @param runner - Association with the effect to stop tracking.
*/
export function stop(runner: ReactiveEffectRunner) {
export function stop(runner: ReactiveEffectRunner): void {
runner.effect.stop()
}
@ -487,7 +487,7 @@ const trackStack: boolean[] = []
/**
* Temporarily pauses tracking.
*/
export function pauseTracking() {
export function pauseTracking(): void {
trackStack.push(shouldTrack)
shouldTrack = false
}
@ -495,7 +495,7 @@ export function pauseTracking() {
/**
* Re-enables effect tracking (if it was paused).
*/
export function enableTracking() {
export function enableTracking(): void {
trackStack.push(shouldTrack)
shouldTrack = true
}
@ -503,7 +503,7 @@ export function enableTracking() {
/**
* Resets the previous global effect tracking state.
*/
export function resetTracking() {
export function resetTracking(): void {
const last = trackStack.pop()
shouldTrack = last === undefined ? true : last
}
@ -520,7 +520,7 @@ export function resetTracking() {
* @param failSilently - if `true`, will not throw warning when called without
* an active effect.
*/
export function onEffectCleanup(fn: () => void, failSilently = false) {
export function onEffectCleanup(fn: () => void, failSilently = false): void {
if (activeSub instanceof ReactiveEffect) {
activeSub.cleanup = fn
} else if (__DEV__ && !failSilently) {

View File

@ -46,11 +46,11 @@ export class EffectScope {
}
}
get active() {
get active(): boolean {
return this._active
}
pause() {
pause(): void {
if (this._active) {
this._isPaused = true
if (this.scopes) {
@ -67,7 +67,7 @@ export class EffectScope {
/**
* Resumes the effect scope, including all child scopes and effects.
*/
resume() {
resume(): void {
if (this._active) {
if (this._isPaused) {
this._isPaused = false
@ -101,7 +101,7 @@ export class EffectScope {
* This should only be called on non-detached scopes
* @internal
*/
on() {
on(): void {
activeEffectScope = this
}
@ -109,11 +109,11 @@ export class EffectScope {
* This should only be called on non-detached scopes
* @internal
*/
off() {
off(): void {
activeEffectScope = this.parent
}
stop(fromParent?: boolean) {
stop(fromParent?: boolean): void {
if (this._active) {
let i, l
for (i = 0, l = this.effects.length; i < l; i++) {
@ -151,7 +151,7 @@ export class EffectScope {
* @param detached - Can be used to create a "detached" effect scope.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#effectscope}
*/
export function effectScope(detached?: boolean) {
export function effectScope(detached?: boolean): EffectScope {
return new EffectScope(detached)
}
@ -160,7 +160,7 @@ export function effectScope(detached?: boolean) {
*
* @see {@link https://vuejs.org/api/reactivity-advanced.html#getcurrentscope}
*/
export function getCurrentScope() {
export function getCurrentScope(): EffectScope | undefined {
return activeEffectScope
}
@ -171,7 +171,7 @@ export function getCurrentScope() {
* @param fn - The callback function to attach to the scope's cleanup.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#onscopedispose}
*/
export function onScopeDispose(fn: () => void, failSilently = false) {
export function onScopeDispose(fn: () => void, failSilently = false): void {
if (activeEffectScope) {
activeEffectScope.cleanups.push(fn)
} else if (__DEV__ && !failSilently) {

View File

@ -23,10 +23,16 @@ export interface Target {
[ReactiveFlags.RAW]?: any
}
export const reactiveMap = new WeakMap<Target, any>()
export const shallowReactiveMap = new WeakMap<Target, any>()
export const readonlyMap = new WeakMap<Target, any>()
export const shallowReadonlyMap = new WeakMap<Target, any>()
export const reactiveMap: WeakMap<Target, any> = new WeakMap<Target, any>()
export const shallowReactiveMap: WeakMap<Target, any> = new WeakMap<
Target,
any
>()
export const readonlyMap: WeakMap<Target, any> = new WeakMap<Target, any>()
export const shallowReadonlyMap: WeakMap<Target, any> = new WeakMap<
Target,
any
>()
enum TargetType {
INVALID = 0,
@ -60,8 +66,8 @@ export type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>
declare const ReactiveMarkerSymbol: unique symbol
export declare class ReactiveMarker {
private [ReactiveMarkerSymbol]?: void
export interface ReactiveMarker {
[ReactiveMarkerSymbol]?: void
}
export type Reactive<T> = UnwrapNestedRefs<T> &

View File

@ -181,7 +181,7 @@ class RefImpl<T = any> {
* @param ref - The ref whose tied effects shall be executed.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#triggerref}
*/
export function triggerRef(ref: Ref) {
export function triggerRef(ref: Ref): void {
if (__DEV__) {
;(ref as unknown as RefImpl).dep.trigger({
target: ref,

View File

@ -1,3 +1,3 @@
export function warn(msg: string, ...args: any[]) {
export function warn(msg: string, ...args: any[]): void {
console.warn(`[Vue warn] ${msg}`, ...args)
}

View File

@ -11,7 +11,7 @@ export type InjectionKey<T> = symbol & InjectionConstraint<T>
export function provide<T, K = InjectionKey<T> | string | number>(
key: K,
value: K extends InjectionKey<infer V> ? V : T,
) {
): void {
if (!currentInstance) {
if (__DEV__) {
warn(`provide() can only be used inside setup().`)

View File

@ -63,9 +63,12 @@ export function injectHook(
}
}
export const createHook =
const createHook =
<T extends Function = () => any>(lifecycle: LifecycleHooks) =>
(hook: T, target: ComponentInternalInstance | null = currentInstance) => {
(
hook: T,
target: ComponentInternalInstance | null = currentInstance,
): void => {
// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
if (
!isInSSRComponentSetup ||
@ -74,22 +77,30 @@ export const createHook =
injectHook(lifecycle, (...args: unknown[]) => hook(...args), target)
}
}
type CreateHook<T = any> = (
hook: T,
target?: ComponentInternalInstance | null,
) => void
export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
export const onMounted = createHook(LifecycleHooks.MOUNTED)
export const onBeforeUpdate = createHook(LifecycleHooks.BEFORE_UPDATE)
export const onUpdated = createHook(LifecycleHooks.UPDATED)
export const onBeforeUnmount = createHook(LifecycleHooks.BEFORE_UNMOUNT)
export const onUnmounted = createHook(LifecycleHooks.UNMOUNTED)
export const onServerPrefetch = createHook(LifecycleHooks.SERVER_PREFETCH)
export const onBeforeMount: CreateHook = createHook(LifecycleHooks.BEFORE_MOUNT)
export const onMounted: CreateHook = createHook(LifecycleHooks.MOUNTED)
export const onBeforeUpdate: CreateHook = createHook(
LifecycleHooks.BEFORE_UPDATE,
)
export const onUpdated: CreateHook = createHook(LifecycleHooks.UPDATED)
export const onBeforeUnmount: CreateHook = createHook(
LifecycleHooks.BEFORE_UNMOUNT,
)
export const onUnmounted: CreateHook = createHook(LifecycleHooks.UNMOUNTED)
export const onServerPrefetch: CreateHook = createHook(
LifecycleHooks.SERVER_PREFETCH,
)
export type DebuggerHook = (e: DebuggerEvent) => void
export const onRenderTriggered = createHook<DebuggerHook>(
LifecycleHooks.RENDER_TRIGGERED,
)
export const onRenderTracked = createHook<DebuggerHook>(
LifecycleHooks.RENDER_TRACKED,
)
export const onRenderTriggered: CreateHook<DebuggerHook> =
createHook<DebuggerHook>(LifecycleHooks.RENDER_TRIGGERED)
export const onRenderTracked: CreateHook<DebuggerHook> =
createHook<DebuggerHook>(LifecycleHooks.RENDER_TRACKED)
export type ErrorCapturedHook<TError = unknown> = (
err: TError,
@ -100,6 +111,6 @@ export type ErrorCapturedHook<TError = unknown> = (
export function onErrorCaptured<TError = Error>(
hook: ErrorCapturedHook<TError>,
target: ComponentInternalInstance | null = currentInstance,
) {
): void {
injectHook(LifecycleHooks.ERROR_CAPTURED, hook, target)
}

View File

@ -177,7 +177,7 @@ type ShortEmits<T extends Record<string, any>> = UnionToIntersection<
*/
export function defineExpose<
Exposed extends Record<string, any> = Record<string, any>,
>(exposed?: Exposed) {
>(exposed?: Exposed): void {
if (__DEV__) {
warnRuntimeUsage(`defineExpose`)
}
@ -396,7 +396,7 @@ function getContext(): SetupContext {
*/
export function normalizePropsOrEmits(
props: ComponentPropsOptions | EmitsOptions,
) {
): ComponentObjectPropsOptions | ObjectEmitsOptions {
return isArray(props)
? props.reduce(
(normalized, p) => ((normalized[p] = null), normalized),
@ -444,7 +444,7 @@ export function mergeDefaults(
export function mergeModels(
a: ComponentPropsOptions | EmitsOptions,
b: ComponentPropsOptions | EmitsOptions,
) {
): ComponentPropsOptions | EmitsOptions {
if (!a || !b) return a || b
if (isArray(a) && isArray(b)) return a.concat(b)
return extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b))
@ -489,7 +489,7 @@ export function createPropsRestProxy(
* ```
* @internal
*/
export function withAsyncContext(getAwaitable: () => any) {
export function withAsyncContext(getAwaitable: () => any): [any, () => void] {
const ctx = getCurrentInstance()!
if (__DEV__ && !ctx) {
warn(

View File

@ -96,7 +96,7 @@ export function watchEffect(
export function watchPostEffect(
effect: WatchEffect,
options?: DebuggerOptions,
) {
): WatchStopHandle {
return doWatch(
effect,
null,
@ -107,7 +107,7 @@ export function watchPostEffect(
export function watchSyncEffect(
effect: WatchEffect,
options?: DebuggerOptions,
) {
): WatchStopHandle {
return doWatch(
effect,
null,
@ -471,7 +471,7 @@ export function instanceWatch(
export function createPathGetter(ctx: any, path: string) {
const segments = path.split('.')
return () => {
return (): any => {
let cur = ctx
for (let i = 0; i < segments.length && cur; i++) {
cur = cur[segments[i]]
@ -482,9 +482,9 @@ export function createPathGetter(ctx: any, path: string) {
export function traverse(
value: unknown,
depth = Infinity,
depth: number = Infinity,
seen?: Set<unknown>,
) {
): unknown {
if (depth <= 0 || !isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
return value
}

View File

@ -431,7 +431,7 @@ const warnCount: Record<string, number> = Object.create(null)
// test only
let warningEnabled = true
export function toggleDeprecationWarning(flag: boolean) {
export function toggleDeprecationWarning(flag: boolean): void {
warningEnabled = flag
}
@ -439,7 +439,7 @@ export function warnDeprecation(
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
) {
): void {
if (!__DEV__) {
return
}
@ -502,7 +502,7 @@ export const globalCompatConfig: CompatConfig = {
MODE: 2,
}
export function configureCompat(config: CompatConfig) {
export function configureCompat(config: CompatConfig): void {
if (__DEV__) {
validateCompatConfig(config)
}
@ -516,7 +516,7 @@ const warnedInvalidKeys: Record<string, boolean> = {}
export function validateCompatConfig(
config: CompatConfig,
instance?: ComponentInternalInstance,
) {
): void {
if (seenConfigObjects.has(config)) {
return
}
@ -554,7 +554,7 @@ export function validateCompatConfig(
export function getCompatConfigForKey(
key: DeprecationTypes | 'MODE',
instance: ComponentInternalInstance | null,
) {
): CompatConfig[DeprecationTypes | 'MODE'] {
const instanceConfig =
instance && (instance.type as ComponentOptions).compatConfig
if (instanceConfig && key in instanceConfig) {
@ -594,7 +594,7 @@ export function assertCompatEnabled(
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
) {
): void {
if (!isCompatEnabled(key, instance)) {
throw new Error(`${key} compat has been disabled.`)
} else if (__DEV__) {
@ -610,7 +610,7 @@ export function softAssertCompatEnabled(
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
) {
): boolean {
if (__DEV__) {
warnDeprecation(key, instance, ...args)
}
@ -626,7 +626,7 @@ export function checkCompatEnabled(
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
) {
): boolean {
const enabled = isCompatEnabled(key, instance)
if (__DEV__ && enabled) {
warnDeprecation(key, instance, ...args)

View File

@ -23,7 +23,9 @@ const normalizedAsyncComponentMap = new WeakMap<
Component
>()
export function convertLegacyAsyncComponent(comp: LegacyAsyncComponent) {
export function convertLegacyAsyncComponent(
comp: LegacyAsyncComponent,
): Component {
if (normalizedAsyncComponentMap.has(comp)) {
return normalizedAsyncComponentMap.get(comp)!
}

View File

@ -19,7 +19,9 @@ export const legacySlotProxyHandlers: ProxyHandler<InternalSlots> = {
},
}
export function convertLegacyFunctionalComponent(comp: ComponentOptions) {
export function convertLegacyFunctionalComponent(
comp: ComponentOptions,
): FunctionalComponent {
if (normalizedFunctionalComponentMap.has(comp)) {
return normalizedFunctionalComponentMap.get(comp)!
}

View File

@ -13,7 +13,7 @@ export const compatModelEventPrefix = `onModelCompat:`
const warnedTypes = new WeakSet()
export function convertLegacyVModelProps(vnode: VNode) {
export function convertLegacyVModelProps(vnode: VNode): void {
const { type, shapeFlag, props, dynamicProps } = vnode
const comp = type as ComponentOptions
if (shapeFlag & ShapeFlags.COMPONENT && props && 'modelValue' in props) {
@ -68,7 +68,7 @@ export function compatModelEmit(
instance: ComponentInternalInstance,
event: string,
args: any[],
) {
): void {
if (!isCompatEnabled(DeprecationTypes.COMPONENT_V_MODEL, instance)) {
return
}

View File

@ -1,7 +1,7 @@
import { isPlainObject } from '@vue/shared'
import { DeprecationTypes, warnDeprecation } from './compatConfig'
export function deepMergeData(to: any, from: any) {
export function deepMergeData(to: any, from: any): any {
for (const key in from) {
const toVal = to[key]
const fromVal = from[key]

View File

@ -333,7 +333,7 @@ export function installAppCompatProperties(
app: App,
context: AppContext,
render: RootRenderFunction<any>,
) {
): void {
installFilterMethod(app, context)
installLegacyOptionMergeStrats(app.config)

View File

@ -36,7 +36,7 @@ export type LegacyConfig = {
}
// dev only
export function installLegacyConfigWarnings(config: AppConfig) {
export function installLegacyConfigWarnings(config: AppConfig): void {
const legacyConfigOptions: Record<string, DeprecationTypes> = {
silent: DeprecationTypes.CONFIG_SILENT,
devtools: DeprecationTypes.CONFIG_DEVTOOLS,
@ -62,7 +62,7 @@ export function installLegacyConfigWarnings(config: AppConfig) {
})
}
export function installLegacyOptionMergeStrats(config: AppConfig) {
export function installLegacyOptionMergeStrats(config: AppConfig): void {
config.optionMergeStrategies = new Proxy({} as any, {
get(target, key) {
if (key in target) {

View File

@ -62,7 +62,9 @@ export interface LegacyPublicProperties {
$listeners: Record<string, Function | Function[]>
}
export function installCompatInstanceProperties(map: PublicPropertiesMap) {
export function installCompatInstanceProperties(
map: PublicPropertiesMap,
): void {
const set = (target: any, key: any, val: any) => {
target[key] = val
return target[key]

View File

@ -2,6 +2,7 @@ import { isArray } from '@vue/shared'
import type { ComponentInternalInstance } from '../component'
import { ErrorCodes, callWithAsyncErrorHandling } from '../errorHandling'
import { DeprecationTypes, assertCompatEnabled } from './compatConfig'
import type { ComponentPublicInstance } from '../componentPublicInstance'
interface EventRegistry {
[event: string]: Function[] | undefined
@ -26,7 +27,7 @@ export function on(
instance: ComponentInternalInstance,
event: string | string[],
fn: Function,
) {
): ComponentPublicInstance | null {
if (isArray(event)) {
event.forEach(e => on(instance, e, fn))
} else {
@ -49,7 +50,7 @@ export function once(
instance: ComponentInternalInstance,
event: string,
fn: Function,
) {
): ComponentPublicInstance | null {
const wrapped = (...args: any[]) => {
off(instance, event, wrapped)
fn.call(instance.proxy, ...args)
@ -63,7 +64,7 @@ export function off(
instance: ComponentInternalInstance,
event?: string | string[],
fn?: Function,
) {
): ComponentPublicInstance | null {
assertCompatEnabled(DeprecationTypes.INSTANCE_EVENT_EMITTER, instance)
const vm = instance.proxy
// all
@ -94,7 +95,7 @@ export function emit(
instance: ComponentInternalInstance,
event: string,
args: any[],
) {
): ComponentPublicInstance | null {
const cbs = getRegistry(instance)[event]
if (cbs) {
callWithAsyncErrorHandling(

View File

@ -2,7 +2,9 @@ import { isOn } from '@vue/shared'
import type { ComponentInternalInstance } from '../component'
import { DeprecationTypes, assertCompatEnabled } from './compatConfig'
export function getCompatListeners(instance: ComponentInternalInstance) {
export function getCompatListeners(
instance: ComponentInternalInstance,
): Record<string, Function | Function[]> {
assertCompatEnabled(DeprecationTypes.INSTANCE_LISTENERS, instance)
const listeners: Record<string, Function | Function[]> = {}

View File

@ -11,7 +11,7 @@ export function createPropsDefaultThis(
instance: ComponentInternalInstance,
rawProps: Data,
propKey: string,
) {
): object {
return new Proxy(
{},
{

View File

@ -39,7 +39,9 @@ import {
} from './compatConfig'
import { compatModelEventPrefix } from './componentVModel'
export function convertLegacyRenderFn(instance: ComponentInternalInstance) {
export function convertLegacyRenderFn(
instance: ComponentInternalInstance,
): void {
const Component = instance.type as ComponentOptions
const render = Component.render as InternalRenderFunction | undefined
@ -303,7 +305,7 @@ function convertLegacySlots(vnode: VNode): VNode {
return vnode
}
export function defineLegacyVNodeProperties(vnode: VNode) {
export function defineLegacyVNodeProperties(vnode: VNode): void {
/* istanbul ignore if */
if (
isCompatEnabled(

View File

@ -7,7 +7,7 @@ import {
isReservedProp,
normalizeClass,
} from '@vue/shared'
import type { ComponentInternalInstance } from '../component'
import type { ComponentInternalInstance, Data } from '../component'
import type { Slot } from '../componentSlots'
import { createSlots } from '../helpers/createSlots'
import { renderSlot } from '../helpers/renderSlot'
@ -30,7 +30,7 @@ export function legacyBindObjectProps(
value: any,
_asProp: boolean,
isSync?: boolean,
) {
): any {
if (value && isObject(value)) {
if (isArray(value)) {
value = toObject(value)
@ -62,7 +62,7 @@ export function legacyBindObjectProps(
return data
}
export function legacyBindObjectListeners(props: any, listeners: any) {
export function legacyBindObjectListeners(props: any, listeners: any): Data {
return mergeProps(props, toHandlers(listeners))
}
@ -72,7 +72,7 @@ export function legacyRenderSlot(
fallback?: VNode[],
props?: any,
bindObject?: any,
) {
): VNode {
if (bindObject) {
props = mergeProps(props, bindObject)
}
@ -92,7 +92,7 @@ export function legacyresolveScopedSlots(
raw?: Record<string, Slot>,
// the following are added in 2.6
hasDynamicKeys?: boolean,
) {
): ReturnType<typeof createSlots> {
// v2 default slot doesn't have name
return createSlots(
raw || ({ $stable: !hasDynamicKeys } as any),
@ -122,7 +122,7 @@ const staticCacheMap = /*#__PURE__*/ new WeakMap<
export function legacyRenderStatic(
instance: ComponentInternalInstance,
index: number,
) {
): any {
let cache = staticCacheMap.get(instance)
if (!cache) {
staticCacheMap.set(instance, (cache = []))
@ -142,7 +142,7 @@ export function legacyCheckKeyCodes(
builtInKeyCode?: number | number[],
eventKeyName?: string,
builtInKeyName?: string | string[],
) {
): boolean | undefined {
const config = instance.appContext.config as any
const configKeyCodes = config.keyCodes || {}
const mappedKeyCode = configKeyCodes[key] || builtInKeyCode
@ -163,11 +163,11 @@ function isKeyNotMatch<T>(expect: T | T[], actual: T): boolean {
}
}
export function legacyMarkOnce(tree: VNode) {
export function legacyMarkOnce(tree: VNode): VNode {
return tree
}
export function legacyBindDynamicKeys(props: any, values: any[]) {
export function legacyBindDynamicKeys(props: any, values: any[]): any {
for (let i = 0; i < values.length; i += 2) {
const key = values[i]
if (typeof key === 'string' && key) {
@ -177,6 +177,6 @@ export function legacyBindDynamicKeys(props: any, values: any[]) {
return props
}
export function legacyPrependModifier(value: any, symbol: string) {
export function legacyPrependModifier(value: any, symbol: string): any {
return typeof value === 'string' ? symbol + value : value
}

View File

@ -599,7 +599,7 @@ export function createComponentInstance(
vnode: VNode,
parent: ComponentInternalInstance | null,
suspense: SuspenseBoundary | null,
) {
): ComponentInternalInstance {
const type = vnode.type as ConcreteComponent
// inherit parent app context - or - if root, adopt from root vnode
const appContext =
@ -758,13 +758,13 @@ export const setCurrentInstance = (instance: ComponentInternalInstance) => {
const prev = currentInstance
internalSetCurrentInstance(instance)
instance.scope.on()
return () => {
return (): void => {
instance.scope.off()
internalSetCurrentInstance(prev)
}
}
export const unsetCurrentInstance = () => {
export const unsetCurrentInstance = (): void => {
currentInstance && currentInstance.scope.off()
internalSetCurrentInstance(null)
}
@ -774,7 +774,7 @@ const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component')
export function validateComponentName(
name: string,
{ isNativeTag }: AppConfig,
) {
): void {
if (isBuiltInTag(name) || isNativeTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component id: ' + name,
@ -782,7 +782,9 @@ export function validateComponentName(
}
}
export function isStatefulComponent(instance: ComponentInternalInstance) {
export function isStatefulComponent(
instance: ComponentInternalInstance,
): number {
return instance.vnode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT
}
@ -792,7 +794,7 @@ export function setupComponent(
instance: ComponentInternalInstance,
isSSR = false,
optimized = false,
) {
): Promise<void> | undefined {
isSSR && setInSSRSetupState(isSSR)
const { props, children } = instance.vnode
@ -909,7 +911,7 @@ export function handleSetupResult(
instance: ComponentInternalInstance,
setupResult: unknown,
isSSR: boolean,
) {
): void {
if (isFunction(setupResult)) {
// setup returned an inline render function
if (__SSR__ && (instance.type as ComponentOptions).__ssrInlineRender) {
@ -957,7 +959,7 @@ let installWithProxy: (i: ComponentInternalInstance) => void
* For runtime-dom to register the compiler.
* Note the exported method uses any to avoid d.ts relying on the compiler types.
*/
export function registerRuntimeCompiler(_compile: any) {
export function registerRuntimeCompiler(_compile: any): void {
compile = _compile
installWithProxy = i => {
if (i.render!._rc) {
@ -967,13 +969,13 @@ export function registerRuntimeCompiler(_compile: any) {
}
// dev only
export const isRuntimeOnly = () => !compile
export const isRuntimeOnly = (): boolean => !compile
export function finishComponentSetup(
instance: ComponentInternalInstance,
isSSR: boolean,
skipOptions?: boolean,
) {
): void {
const Component = instance.type as ComponentOptions
if (__COMPAT__) {
@ -1166,7 +1168,7 @@ export function createSetupContext(
export function getComponentPublicInstance(
instance: ComponentInternalInstance,
) {
): ComponentPublicInstance | ComponentInternalInstance['exposed'] | null {
if (instance.exposed) {
return (
instance.exposeProxy ||

View File

@ -31,6 +31,7 @@ import {
} from './compat/componentVModel'
import type { ComponentTypeEmits } from './apiSetupHelpers'
import { getModelModifiers } from './helpers/useModel'
import type { ComponentPublicInstance } from './componentPublicInstance'
export type ObjectEmitsOptions = Record<
string,
@ -104,7 +105,7 @@ export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
): ComponentPublicInstance | null | undefined {
if (instance.isUnmounted) return
const props = instance.vnode.props || EMPTY_OBJ

View File

@ -514,7 +514,7 @@ function createDuplicateChecker() {
export let shouldCacheAccess = true
export function applyOptions(instance: ComponentInternalInstance) {
export function applyOptions(instance: ComponentInternalInstance): void {
const options = resolveMergedOptions(instance)
const publicThis = instance.proxy! as any
const ctx = instance.ctx
@ -791,7 +791,7 @@ export function resolveInjections(
injectOptions: ComponentInjectOptions,
ctx: any,
checkDuplicateProperties = NOOP as any,
) {
): void {
if (isArray(injectOptions)) {
injectOptions = normalizeInject(injectOptions)!
}
@ -847,7 +847,7 @@ export function createWatcher(
ctx: Data,
publicThis: ComponentPublicInstance,
key: string,
) {
): void {
const getter = key.includes('.')
? createPathGetter(publicThis, key)
: () => (publicThis as any)[key]
@ -930,7 +930,7 @@ export function mergeOptions(
from: any,
strats: Record<string, OptionMergeFunction>,
asMixin = false,
) {
): any {
if (__COMPAT__ && isFunction(from)) {
from = from.options
}

View File

@ -191,7 +191,7 @@ export function initProps(
rawProps: Data | null,
isStateful: number, // result of bitwise flag comparison
isSSR = false,
) {
): void {
const props: Data = {}
const attrs: Data = createInternalObject()
@ -238,7 +238,7 @@ export function updateProps(
rawProps: Data | null,
rawPrevProps: Data | null,
optimized: boolean,
) {
): void {
const {
props,
attrs,

View File

@ -401,7 +401,8 @@ export interface ComponentRenderContext {
_: ComponentInternalInstance
}
export const isReservedPrefix = (key: string) => key === '_' || key === '$'
export const isReservedPrefix = (key: string): key is '_' | '$' =>
key === '_' || key === '$'
const hasSetupBinding = (state: Data, key: string) =>
state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key)
@ -612,10 +613,8 @@ if (__DEV__ && !__TEST__) {
}
}
export const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend(
{},
PublicInstanceProxyHandlers,
{
export const RuntimeCompiledPublicInstanceProxyHandlers: ProxyHandler<any> =
/*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
get(target: ComponentRenderContext, key: string) {
// fast path for unscopables when using `with` block
if ((key as any) === Symbol.unscopables) {
@ -634,8 +633,7 @@ export const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend(
}
return has
},
},
)
})
// dev only
// In dev mode, the proxy target exposes the same properties as seen on `this`
@ -669,7 +667,7 @@ export function createDevRenderContext(instance: ComponentInternalInstance) {
// dev only
export function exposePropsOnRenderContext(
instance: ComponentInternalInstance,
) {
): void {
const {
ctx,
propsOptions: [propsOptions],
@ -689,7 +687,7 @@ export function exposePropsOnRenderContext(
// dev only
export function exposeSetupStateOnRenderContext(
instance: ComponentInternalInstance,
) {
): void {
const { ctx, setupState } = instance
Object.keys(toRaw(setupState)).forEach(key => {
if (!setupState.__isScriptSetup) {

View File

@ -36,7 +36,7 @@ export function setCurrentRenderingInstance(
* Set scope id when creating hoisted vnodes.
* @private compiler helper
*/
export function pushScopeId(id: string | null) {
export function pushScopeId(id: string | null): void {
currentScopeId = id
}
@ -45,7 +45,7 @@ export function pushScopeId(id: string | null) {
* API for backwards compat w/ code generated by compilers.
* @private
*/
export function popScopeId() {
export function popScopeId(): void {
currentScopeId = null
}
@ -53,7 +53,7 @@ export function popScopeId() {
* Only for backwards compat
* @private
*/
export const withScopeId = (_id: string) => withCtx
export const withScopeId = (_id: string): typeof withCtx => withCtx
export type ContextualRenderFn = {
(...args: any[]): any
@ -71,7 +71,7 @@ export function withCtx(
fn: Function,
ctx: ComponentInternalInstance | null = currentRenderingInstance,
isNonScopedSlot?: boolean, // __COMPAT__ only
) {
): Function {
if (!ctx) return fn
// already normalized

View File

@ -35,7 +35,7 @@ import { shallowReadonly } from '@vue/reactivity'
*/
let accessedAttrs: boolean = false
export function markAttrsAccessed() {
export function markAttrsAccessed(): void {
accessedAttrs = true
}
@ -452,7 +452,7 @@ function hasPropsChanged(
export function updateHOCHostEl(
{ vnode, parent }: ComponentInternalInstance,
el: typeof vnode.el, // HostNode
) {
): void {
while (parent) {
const root = parent.subTree
if (root.suspense && root.suspense.activeBranch === vnode) {

View File

@ -180,7 +180,7 @@ export const initSlots = (
instance: ComponentInternalInstance,
children: VNodeNormalizedChildren,
optimized: boolean,
) => {
): void => {
const slots = (instance.slots = createInternalObject())
if (instance.vnode.shapeFlag & ShapeFlags.SLOTS_CHILDREN) {
const type = (children as RawSlots)._
@ -202,7 +202,7 @@ export const updateSlots = (
instance: ComponentInternalInstance,
children: VNodeNormalizedChildren,
optimized: boolean,
) => {
): void => {
const { vnode, slots } = instance
let needDeletionCheck = true
let deletionComparisonTarget = EMPTY_OBJ

View File

@ -24,8 +24,8 @@ import { SchedulerJobFlags } from '../scheduler'
type Hook<T = () => void> = T | T[]
const leaveCbKey = Symbol('_leaveCb')
const enterCbKey = Symbol('_enterCb')
const leaveCbKey: unique symbol = Symbol('_leaveCb')
const enterCbKey: unique symbol = Symbol('_enterCb')
export interface BaseTransitionProps<HostElement = RendererElement> {
mode?: 'in-out' | 'out-in' | 'default'
@ -116,7 +116,7 @@ export function useTransitionState(): TransitionState {
const TransitionHookValidator = [Function, Array]
export const BaseTransitionPropsValidators = {
export const BaseTransitionPropsValidators: Record<string, any> = {
mode: String,
appear: Boolean,
persisted: Boolean,
@ -510,7 +510,7 @@ function getInnerChild(vnode: VNode): VNode | undefined {
}
}
export function setTransitionHooks(vnode: VNode, hooks: TransitionHooks) {
export function setTransitionHooks(vnode: VNode, hooks: TransitionHooks): void {
if (vnode.shapeFlag & ShapeFlags.COMPONENT && vnode.component) {
setTransitionHooks(vnode.component.subTree, hooks)
} else if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {

View File

@ -391,14 +391,14 @@ function matches(pattern: MatchPattern, name: string): boolean {
export function onActivated(
hook: Function,
target?: ComponentInternalInstance | null,
) {
): void {
registerKeepAliveHook(hook, LifecycleHooks.ACTIVATED, target)
}
export function onDeactivated(
hook: Function,
target?: ComponentInternalInstance | null,
) {
): void {
registerKeepAliveHook(hook, LifecycleHooks.DEACTIVATED, target)
}

View File

@ -53,7 +53,7 @@ let suspenseId = 0
/**
* For testing only
*/
export const resetSuspenseId = () => (suspenseId = 0)
export const resetSuspenseId = (): number => (suspenseId = 0)
// Suspense exposes a component-like API, and is treated like a component
// in the compiler, but internally it's a special built-in type that hooks
@ -77,7 +77,7 @@ export const SuspenseImpl = {
optimized: boolean,
// platform-specific impl passed from renderer
rendererInternals: RendererInternals,
) {
): void {
if (n1 == null) {
mountSuspense(
n2,
@ -122,8 +122,8 @@ export const SuspenseImpl = {
)
}
},
hydrate: hydrateSuspense,
normalize: normalizeSuspenseChildren,
hydrate: hydrateSuspense as typeof hydrateSuspense,
normalize: normalizeSuspenseChildren as typeof normalizeSuspenseChildren,
}
// Force-casted public typing for h and TSX props inference
@ -816,7 +816,7 @@ function hydrateSuspense(
return result
}
function normalizeSuspenseChildren(vnode: VNode) {
function normalizeSuspenseChildren(vnode: VNode): void {
const { shapeFlag, children } = vnode
const isSlotChildren = shapeFlag & ShapeFlags.SLOTS_CHILDREN
vnode.ssContent = normalizeSuspenseSlot(

View File

@ -23,7 +23,7 @@ export interface TeleportProps {
defer?: boolean
}
export const TeleportEndKey = Symbol('_vte')
export const TeleportEndKey: unique symbol = Symbol('_vte')
export const isTeleport = (type: any): boolean => type.__isTeleport
@ -86,7 +86,7 @@ export const TeleportImpl = {
slotScopeIds: string[] | null,
optimized: boolean,
internals: RendererInternals,
) {
): void {
const {
mc: mountChildren,
pc: patchChildren,
@ -274,7 +274,7 @@ export const TeleportImpl = {
parentSuspense: SuspenseBoundary | null,
{ um: unmount, o: { remove: hostRemove } }: RendererInternals,
doRemove: boolean,
) {
): void {
const {
shapeFlag,
children,
@ -307,8 +307,8 @@ export const TeleportImpl = {
}
},
move: moveTeleport,
hydrate: hydrateTeleport,
move: moveTeleport as typeof moveTeleport,
hydrate: hydrateTeleport as typeof hydrateTeleport,
}
export enum TeleportMoveTypes {
@ -323,7 +323,7 @@ function moveTeleport(
parentAnchor: RendererNode | null,
{ o: { insert }, m: move }: RendererInternals,
moveType: TeleportMoveTypes = TeleportMoveTypes.REORDER,
) {
): void {
// move target anchor if this is a target change.
if (moveType === TeleportMoveTypes.TARGET_CHANGE) {
insert(vnode.targetAnchor!, container, parentAnchor)

View File

@ -10,7 +10,7 @@ import { EMPTY_OBJ, extend, isArray, isFunction, isObject } from '@vue/shared'
import type { ComponentInternalInstance, ComponentOptions } from './component'
import type { ComponentPublicInstance } from './componentPublicInstance'
export function initCustomFormatter() {
export function initCustomFormatter(): void {
/* eslint-disable no-restricted-globals */
if (!__DEV__ || typeof window === 'undefined') {
return

View File

@ -49,7 +49,7 @@ function emit(event: string, ...args: any[]) {
}
}
export function setDevtoolsHook(hook: DevtoolsHook, target: any) {
export function setDevtoolsHook(hook: DevtoolsHook, target: any): void {
devtools = hook
if (devtools) {
devtools.enabled = true
@ -87,7 +87,7 @@ export function setDevtoolsHook(hook: DevtoolsHook, target: any) {
}
}
export function devtoolsInitApp(app: App, version: string) {
export function devtoolsInitApp(app: App, version: string): void {
emit(DevtoolsHooks.APP_INIT, app, version, {
Fragment,
Text,
@ -96,15 +96,14 @@ export function devtoolsInitApp(app: App, version: string) {
})
}
export function devtoolsUnmountApp(app: App) {
export function devtoolsUnmountApp(app: App): void {
emit(DevtoolsHooks.APP_UNMOUNT, app)
}
export const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook(
DevtoolsHooks.COMPONENT_ADDED,
)
export const devtoolsComponentAdded: DevtoolsComponentHook =
/*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_ADDED)
export const devtoolsComponentUpdated =
export const devtoolsComponentUpdated: DevtoolsComponentHook =
/*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_UPDATED)
const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook(
@ -113,7 +112,7 @@ const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook(
export const devtoolsComponentRemoved = (
component: ComponentInternalInstance,
) => {
): void => {
if (
devtools &&
typeof devtools.cleanupBuffer === 'function' &&
@ -124,8 +123,12 @@ export const devtoolsComponentRemoved = (
}
}
type DevtoolsComponentHook = (component: ComponentInternalInstance) => void
/*! #__NO_SIDE_EFFECTS__ */
function createDevtoolsComponentHook(hook: DevtoolsHooks) {
function createDevtoolsComponentHook(
hook: DevtoolsHooks,
): DevtoolsComponentHook {
return (component: ComponentInternalInstance) => {
emit(
hook,
@ -137,15 +140,20 @@ function createDevtoolsComponentHook(hook: DevtoolsHooks) {
}
}
export const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook(
DevtoolsHooks.PERFORMANCE_START,
)
export const devtoolsPerfStart: DevtoolsPerformanceHook =
/*#__PURE__*/ createDevtoolsPerformanceHook(DevtoolsHooks.PERFORMANCE_START)
export const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook(
DevtoolsHooks.PERFORMANCE_END,
)
export const devtoolsPerfEnd: DevtoolsPerformanceHook =
/*#__PURE__*/ createDevtoolsPerformanceHook(DevtoolsHooks.PERFORMANCE_END)
function createDevtoolsPerformanceHook(hook: DevtoolsHooks) {
type DevtoolsPerformanceHook = (
component: ComponentInternalInstance,
type: string,
time: number,
) => void
function createDevtoolsPerformanceHook(
hook: DevtoolsHooks,
): DevtoolsPerformanceHook {
return (component: ComponentInternalInstance, type: string, time: number) => {
emit(hook, component.appContext.app, component.uid, component, type, time)
}
@ -155,7 +163,7 @@ export function devtoolsComponentEmit(
component: ComponentInternalInstance,
event: string,
params: any[],
) {
): void {
emit(
DevtoolsHooks.COMPONENT_EMIT,
component.appContext.app,

View File

@ -114,7 +114,7 @@ export type Directive<
export type DirectiveModifiers<K extends string = string> = Record<K, boolean>
export function validateDirectiveName(name: string) {
export function validateDirectiveName(name: string): void {
if (isBuiltInDirective(name)) {
warn('Do not use built-in directive ids as custom directive id: ' + name)
}
@ -171,7 +171,7 @@ export function invokeDirectiveHook(
prevVNode: VNode | null,
instance: ComponentInternalInstance | null,
name: keyof ObjectDirective,
) {
): void {
const bindings = vnode.dirs!
const oldBindings = prevVNode && prevVNode.dirs!
for (let i = 0; i < bindings.length; i++) {

View File

@ -68,7 +68,7 @@ export function callWithErrorHandling(
instance: ComponentInternalInstance | null | undefined,
type: ErrorTypes,
args?: unknown[],
) {
): any {
try {
return args ? fn(...args) : fn()
} catch (err) {
@ -110,7 +110,7 @@ export function handleError(
instance: ComponentInternalInstance | null | undefined,
type: ErrorTypes,
throwInDev = true,
) {
): void {
const contextVNode = instance ? instance.vnode : null
const { errorHandler, throwUnhandledErrorInProduction } =
(instance && instance.appContext.config) || EMPTY_OBJ

View File

@ -7,7 +7,7 @@ import { getGlobalThis } from '@vue/shared'
*
* istanbul-ignore-next
*/
export function initFeatureFlags() {
export function initFeatureFlags(): void {
const needWarn = []
if (typeof __FEATURE_OPTIONS_API__ !== 'boolean') {

View File

@ -98,7 +98,9 @@ export function renderSlot(
return rendered
}
export function ensureValidVNode(vnodes: VNodeArrayChildren) {
export function ensureValidVNode(
vnodes: VNodeArrayChildren,
): VNodeArrayChildren | null {
return vnodes.some(child => {
if (!isVNode(child)) return true
if (child.type === Comment) return false

View File

@ -26,7 +26,7 @@ export function resolveComponent(
return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name
}
export const NULL_DYNAMIC_COMPONENT = Symbol.for('v-ndc')
export const NULL_DYNAMIC_COMPONENT: unique symbol = Symbol.for('v-ndc')
/**
* @private

View File

@ -4,7 +4,7 @@ import {
} from '../component'
import { warn } from '../warning'
export function useId() {
export function useId(): string | undefined {
const i = getCurrentInstance()
if (i) {
return (i.appContext.config.idPrefix || 'v') + ':' + i.ids[0] + i.ids[1]++
@ -22,6 +22,6 @@ export function useId() {
* - components with async setup()
* - components with serverPrefetch
*/
export function markAsyncBoundary(instance: ComponentInternalInstance) {
export function markAsyncBoundary(instance: ComponentInternalInstance): void {
instance.ids = [instance.ids[0] + instance.ids[2]++ + '-', 0, 0]
}

View File

@ -1,9 +1,9 @@
import { inject } from '../apiInject'
import { warn } from '../warning'
export const ssrContextKey = Symbol.for('v-scx')
export const ssrContextKey: unique symbol = Symbol.for('v-scx')
export const useSSRContext = <T = Record<string, any>>() => {
export const useSSRContext = <T = Record<string, any>>(): T | undefined => {
if (!__GLOBAL__) {
const ctx = inject<T>(ssrContextKey)
if (!ctx) {

View File

@ -6,7 +6,7 @@ export function withMemo(
render: () => VNode<any, any>,
cache: any[],
index: number,
) {
): VNode<any, any> {
const cached = cache[index] as VNode | undefined
if (cached && isMemoSame(cached, memo)) {
return cached
@ -20,7 +20,7 @@ export function withMemo(
return (cache[index] = ret)
}
export function isMemoSame(cached: VNode, memo: any[]) {
export function isMemoSame(cached: VNode, memo: any[]): boolean {
const prev: any[] = cached.memo!
if (prev.length != memo.length) {
return false

View File

@ -14,10 +14,10 @@ type HMRComponent = ComponentOptions | ClassComponent
export let isHmrUpdating = false
export const hmrDirtyComponents = new Map<
export const hmrDirtyComponents: Map<
ConcreteComponent,
Set<ComponentInternalInstance>
>()
> = new Map<ConcreteComponent, Set<ComponentInternalInstance>>()
export interface HMRRuntime {
createRecord: typeof createRecord
@ -49,7 +49,7 @@ const map: Map<
}
> = new Map()
export function registerHMR(instance: ComponentInternalInstance) {
export function registerHMR(instance: ComponentInternalInstance): void {
const id = instance.type.__hmrId!
let record = map.get(id)
if (!record) {
@ -59,7 +59,7 @@ export function registerHMR(instance: ComponentInternalInstance) {
record.instances.add(instance)
}
export function unregisterHMR(instance: ComponentInternalInstance) {
export function unregisterHMR(instance: ComponentInternalInstance): void {
map.get(instance.type.__hmrId!)!.instances.delete(instance)
}
@ -78,7 +78,7 @@ function normalizeClassComponent(component: HMRComponent): ComponentOptions {
return isClassComponent(component) ? component.__vccOpts : component
}
function rerender(id: string, newRender?: Function) {
function rerender(id: string, newRender?: Function): void {
const record = map.get(id)
if (!record) {
return
@ -101,7 +101,7 @@ function rerender(id: string, newRender?: Function) {
})
}
function reload(id: string, newComp: HMRComponent) {
function reload(id: string, newComp: HMRComponent): void {
const record = map.get(id)
if (!record) return

View File

@ -85,7 +85,17 @@ export const isComment = (node: Node): node is Comment =>
// passed in via arguments.
export function createHydrationFunctions(
rendererInternals: RendererInternals<Node, Element>,
) {
): [
RootHydrateFunction,
(
node: Node,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
slotScopeIds: string[] | null,
optimized?: boolean,
) => Node | null,
] {
const {
mt: mountComponent,
p: patch,
@ -744,7 +754,7 @@ export function createHydrationFunctions(
)
}
return [hydrate, hydrateNode] as const
return [hydrate, hydrateNode]
}
/**

View File

@ -85,7 +85,7 @@ export const hydrateOnInteraction: HydrationStrategyFactory<
return teardown
}
export function forEachElement(node: Node, cb: (el: Element) => void) {
export function forEachElement(node: Node, cb: (el: Element) => void): void {
// fragment
if (isComment(node) && node.data === '[') {
let depth = 1

View File

@ -1,6 +1,6 @@
// Core API ------------------------------------------------------------------
export const version = __VERSION__
export const version: string = __VERSION__
export {
// core
reactive,
@ -399,7 +399,16 @@ import { setCurrentRenderingInstance } from './componentRenderContext'
import { isVNode, normalizeVNode } from './vnode'
import { ensureValidVNode } from './helpers/renderSlot'
const _ssrUtils = {
const _ssrUtils: {
createComponentInstance: typeof createComponentInstance
setupComponent: typeof setupComponent
renderComponentRoot: typeof renderComponentRoot
setCurrentRenderingInstance: typeof setCurrentRenderingInstance
isVNode: typeof isVNode
normalizeVNode: typeof normalizeVNode
getComponentPublicInstance: typeof getComponentPublicInstance
ensureValidVNode: typeof ensureValidVNode
} = {
createComponentInstance,
setupComponent,
renderComponentRoot,
@ -435,9 +444,17 @@ import { NOOP } from '@vue/shared'
/**
* @internal only exposed in compat builds
*/
export const resolveFilter = __COMPAT__ ? _resolveFilter : null
export const resolveFilter: typeof _resolveFilter | null = __COMPAT__
? _resolveFilter
: null
const _compatUtils = {
const _compatUtils: {
warnDeprecation: typeof warnDeprecation
createCompatVue: typeof createCompatVue
isCompatEnabled: typeof isCompatEnabled
checkCompatEnabled: typeof checkCompatEnabled
softAssertCompatEnabled: typeof softAssertCompatEnabled
} = {
warnDeprecation,
createCompatVue,
isCompatEnabled,

View File

@ -6,7 +6,8 @@
*/
const internalObjectProto = {}
export const createInternalObject = () => Object.create(internalObjectProto)
export const createInternalObject = (): any =>
Object.create(internalObjectProto)
export const isInternalObject = (obj: object) =>
export const isInternalObject = (obj: object): boolean =>
Object.getPrototypeOf(obj) === internalObjectProto

View File

@ -11,7 +11,7 @@ let perf: Performance
export function startMeasure(
instance: ComponentInternalInstance,
type: string,
) {
): void {
if (instance.appContext.config.performance && isSupported()) {
perf.mark(`vue-${type}-${instance.uid}`)
}
@ -21,7 +21,10 @@ export function startMeasure(
}
}
export function endMeasure(instance: ComponentInternalInstance, type: string) {
export function endMeasure(
instance: ComponentInternalInstance,
type: string,
): void {
if (instance.appContext.config.performance && isSupported()) {
const startTag = `vue-${type}-${instance.uid}`
const endTag = startTag + `:end`

View File

@ -42,6 +42,7 @@ import {
import {
type SchedulerJob,
SchedulerJobFlags,
type SchedulerJobs,
flushPostFlushCbs,
flushPreFlushCbs,
invalidateJob,
@ -282,7 +283,10 @@ export enum MoveType {
REORDER,
}
export const queuePostRenderEffect = __FEATURE_SUSPENSE__
export const queuePostRenderEffect: (
fn: SchedulerJobs,
suspense: SuspenseBoundary | null,
) => void = __FEATURE_SUSPENSE__
? __TEST__
? // vitest can't seem to handle eager circular dependency
(fn: Function | Function[], suspense: SuspenseBoundary | null) =>
@ -308,7 +312,7 @@ export const queuePostRenderEffect = __FEATURE_SUSPENSE__
export function createRenderer<
HostNode = RendererNode,
HostElement = RendererElement,
>(options: RendererOptions<HostNode, HostElement>) {
>(options: RendererOptions<HostNode, HostElement>): Renderer<HostElement> {
return baseCreateRenderer<HostNode, HostElement>(options)
}
@ -317,7 +321,7 @@ export function createRenderer<
// tree-shakable.
export function createHydrationRenderer(
options: RendererOptions<Node, Element>,
) {
): HydrationRenderer {
return baseCreateRenderer(options, createHydrationFunctions)
}
@ -2423,7 +2427,7 @@ function toggleRecurse(
export function needTransition(
parentSuspense: SuspenseBoundary | null,
transition: TransitionHooks | null,
) {
): boolean | null {
return (
(!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
transition &&
@ -2442,7 +2446,11 @@ export function needTransition(
* the children will always be moved. Therefore, in order to ensure correct move
* position, el should be inherited from previous nodes.
*/
export function traverseStaticChildren(n1: VNode, n2: VNode, shallow = false) {
export function traverseStaticChildren(
n1: VNode,
n2: VNode,
shallow = false,
): void {
const ch1 = n1.children
const ch2 = n2.children
if (isArray(ch1) && isArray(ch2)) {
@ -2527,7 +2535,7 @@ function locateNonHydratedAsyncRoot(
}
}
export function invalidateMount(hooks: LifecycleHook) {
export function invalidateMount(hooks: LifecycleHook): void {
if (hooks) {
for (let i = 0; i < hooks.length; i++)
hooks[i].flags! |= SchedulerJobFlags.DISPOSED

View File

@ -26,7 +26,7 @@ export function setRef(
parentSuspense: SuspenseBoundary | null,
vnode: VNode,
isUnmount = false,
) {
): void {
if (isArray(rawRef)) {
rawRef.forEach((r, i) =>
setRef(

View File

@ -90,7 +90,7 @@ function findInsertionIndex(id: number) {
return start
}
export function queueJob(job: SchedulerJob) {
export function queueJob(job: SchedulerJob): void {
if (!(job.flags! & SchedulerJobFlags.QUEUED)) {
if (job.id == null) {
queue.push(job)
@ -118,14 +118,14 @@ function queueFlush() {
}
}
export function invalidateJob(job: SchedulerJob) {
export function invalidateJob(job: SchedulerJob): void {
const i = queue.indexOf(job)
if (i > flushIndex) {
queue.splice(i, 1)
}
}
export function queuePostFlushCb(cb: SchedulerJobs) {
export function queuePostFlushCb(cb: SchedulerJobs): void {
if (!isArray(cb)) {
if (activePostFlushCbs && cb.id === -1) {
activePostFlushCbs.splice(postFlushIndex + 1, 0, cb)
@ -148,8 +148,8 @@ export function flushPreFlushCbs(
instance?: ComponentInternalInstance,
seen?: CountMap,
// if currently flushing, skip the current job itself
i = isFlushing ? flushIndex + 1 : 0,
) {
i: number = isFlushing ? flushIndex + 1 : 0,
): void {
if (__DEV__) {
seen = seen || new Map()
}
@ -170,7 +170,7 @@ export function flushPreFlushCbs(
}
}
export function flushPostFlushCbs(seen?: CountMap) {
export function flushPostFlushCbs(seen?: CountMap): void {
if (pendingPostFlushCbs.length) {
const deduped = [...new Set(pendingPostFlushCbs)].sort(
(a, b) => getId(a) - getId(b),

View File

@ -66,9 +66,9 @@ export const Fragment = Symbol.for('v-fgt') as any as {
$props: VNodeProps
}
}
export const Text = Symbol.for('v-txt')
export const Comment = Symbol.for('v-cmt')
export const Static = Symbol.for('v-stc')
export const Text: unique symbol = Symbol.for('v-txt')
export const Comment: unique symbol = Symbol.for('v-cmt')
export const Static: unique symbol = Symbol.for('v-stc')
export type VNodeTypes =
| string
@ -279,11 +279,11 @@ export let currentBlock: VNode['dynamicChildren'] = null
*
* @private
*/
export function openBlock(disableTracking = false) {
export function openBlock(disableTracking = false): void {
blockStack.push((currentBlock = disableTracking ? null : []))
}
export function closeBlock() {
export function closeBlock(): void {
blockStack.pop()
currentBlock = blockStack[blockStack.length - 1] || null
}
@ -310,7 +310,7 @@ export let isBlockTreeEnabled = 1
*
* @private
*/
export function setBlockTracking(value: number) {
export function setBlockTracking(value: number): void {
isBlockTreeEnabled += value
if (value < 0 && currentBlock) {
// mark current block so it doesn't take fast path and skip possible
@ -343,7 +343,7 @@ export function createElementBlock(
patchFlag?: number,
dynamicProps?: string[],
shapeFlag?: number,
) {
): VNode {
return setupBlock(
createBaseVNode(
type,
@ -415,7 +415,9 @@ let vnodeArgsTransformer:
* It is *internal* but needs to be exposed for test-utils to pick up proper
* typings
*/
export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) {
export function transformVNodeArgs(
transformer?: typeof vnodeArgsTransformer,
): void {
vnodeArgsTransformer = transformer
}
@ -455,10 +457,10 @@ function createBaseVNode(
children: unknown = null,
patchFlag = 0,
dynamicProps: string[] | null = null,
shapeFlag = type === Fragment ? 0 : ShapeFlags.ELEMENT,
shapeFlag: number = type === Fragment ? 0 : ShapeFlags.ELEMENT,
isBlockNode = false,
needFullChildrenNormalization = false,
) {
): VNode {
const vnode = {
__v_isVNode: true,
__v_skip: true,
@ -640,7 +642,9 @@ function _createVNode(
)
}
export function guardReactiveProps(props: (Data & VNodeProps) | null) {
export function guardReactiveProps(
props: (Data & VNodeProps) | null,
): (Data & VNodeProps) | null {
if (!props) return null
return isProxy(props) || isInternalObject(props) ? extend({}, props) : props
}
@ -807,7 +811,7 @@ export function cloneIfMounted(child: VNode): VNode {
: cloneVNode(child)
}
export function normalizeChildren(vnode: VNode, children: unknown) {
export function normalizeChildren(vnode: VNode, children: unknown): void {
let type = 0
const { shapeFlag } = vnode
if (children == null) {
@ -862,7 +866,7 @@ export function normalizeChildren(vnode: VNode, children: unknown) {
vnode.shapeFlag |= type
}
export function mergeProps(...args: (Data & VNodeProps)[]) {
export function mergeProps(...args: (Data & VNodeProps)[]): Data {
const ret: Data = {}
for (let i = 0; i < args.length; i++) {
const toMerge = args[i]
@ -898,7 +902,7 @@ export function invokeVNodeHook(
instance: ComponentInternalInstance | null,
vnode: VNode,
prevVNode: VNode | null = null,
) {
): void {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.VNODE_HOOK, [
vnode,
prevVNode,

View File

@ -22,17 +22,17 @@ type TraceEntry = {
type ComponentTraceStack = TraceEntry[]
export function pushWarningContext(vnode: VNode) {
export function pushWarningContext(vnode: VNode): void {
stack.push(vnode)
}
export function popWarningContext() {
export function popWarningContext(): void {
stack.pop()
}
let isWarning = false
export function warn(msg: string, ...args: any[]) {
export function warn(msg: string, ...args: any[]): void {
if (isWarning) return
isWarning = true
@ -171,7 +171,7 @@ function formatProp(key: string, value: unknown, raw?: boolean): any {
/**
* @internal
*/
export function assertNumber(val: unknown, type: string) {
export function assertNumber(val: unknown, type: string): void {
if (!__DEV__) return
if (val === undefined) {
return

View File

@ -219,7 +219,7 @@ export class VueElement
/**
* @internal
*/
_nonce = this._def.nonce
_nonce: string | undefined = this._def.nonce
private _connected = false
private _resolved = false
@ -272,7 +272,7 @@ export class VueElement
}
}
connectedCallback() {
connectedCallback(): void {
if (!this.shadowRoot) {
this._parseSlots()
}
@ -313,7 +313,7 @@ export class VueElement
}
}
disconnectedCallback() {
disconnectedCallback(): void {
this._connected = false
nextTick(() => {
if (!this._connected) {
@ -456,7 +456,7 @@ export class VueElement
}
}
protected _setAttr(key: string) {
protected _setAttr(key: string): void {
if (key.startsWith('data-v-')) return
const has = this.hasAttribute(key)
let value = has ? this.getAttribute(key) : REMOVAL
@ -470,14 +470,19 @@ export class VueElement
/**
* @internal
*/
protected _getProp(key: string) {
protected _getProp(key: string): any {
return this._props[key]
}
/**
* @internal
*/
_setProp(key: string, val: any, shouldReflect = true, shouldUpdate = false) {
_setProp(
key: string,
val: any,
shouldReflect = true,
shouldUpdate = false,
): void {
if (val !== this._props[key]) {
if (val === REMOVAL) {
delete this._props[key]
@ -640,7 +645,7 @@ export class VueElement
/**
* @internal
*/
_injectChildStyle(comp: ConcreteComponent & CustomElementOptions) {
_injectChildStyle(comp: ConcreteComponent & CustomElementOptions): void {
this._applyStyles(comp.styles, comp)
}

View File

@ -32,7 +32,7 @@ export interface TransitionProps extends BaseTransitionProps<Element> {
leaveToClass?: string
}
export const vtcKey = Symbol('_vtc')
export const vtcKey: unique symbol = Symbol('_vtc')
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
@ -74,7 +74,7 @@ const DOMTransitionPropsValidators = {
leaveToClass: String,
}
export const TransitionPropsValidators = (Transition.props =
export const TransitionPropsValidators: any = (Transition.props =
/*#__PURE__*/ extend(
{},
BaseTransitionPropsValidators as any,
@ -296,7 +296,7 @@ function NumberOf(val: unknown): number {
return res
}
export function addTransitionClass(el: Element, cls: string) {
export function addTransitionClass(el: Element, cls: string): void {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)[vtcKey] ||
@ -304,7 +304,7 @@ export function addTransitionClass(el: Element, cls: string) {
).add(cls)
}
export function removeTransitionClass(el: Element, cls: string) {
export function removeTransitionClass(el: Element, cls: string): void {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const _vtc = (el as ElementWithTransition)[vtcKey]
if (_vtc) {
@ -455,6 +455,6 @@ function toMs(s: string): number {
}
// synchronously force layout to put elements into a certain state
export function forceReflow() {
export function forceReflow(): number {
return document.body.offsetHeight
}

View File

@ -37,7 +37,7 @@ function onCompositionEnd(e: Event) {
}
}
const assignKey = Symbol('_assign')
const assignKey: unique symbol = Symbol('_assign')
type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<
T & { [assignKey]: AssignerFn; _assigning?: boolean },
@ -334,7 +334,7 @@ function callModelHook(
// SSR vnode transforms, only used when user includes client-oriented render
// function in SSR
export function initVModelForSSR() {
export function initVModelForSSR(): void {
vModelText.getSSRProps = ({ value }) => ({ value })
vModelRadio.getSSRProps = ({ value }, vnode) => {

View File

@ -15,7 +15,23 @@ type CompatModifiers = keyof typeof keyNames
export type VOnModifiers = SystemModifiers | ModifierGuards | CompatModifiers
type KeyedEvent = KeyboardEvent | MouseEvent | TouchEvent
const modifierGuards = {
type ModifierGuards =
| 'shift'
| 'ctrl'
| 'alt'
| 'meta'
| 'left'
| 'right'
| 'stop'
| 'prevent'
| 'self'
| 'middle'
| 'exact'
const modifierGuards: Record<
ModifierGuards,
| ((e: Event) => void | boolean)
| ((e: Event, modifiers: string[]) => void | boolean)
> = {
stop: (e: Event) => e.stopPropagation(),
prevent: (e: Event) => e.preventDefault(),
self: (e: Event) => e.target !== e.currentTarget,
@ -28,13 +44,7 @@ const modifierGuards = {
right: (e: Event) => 'button' in e && (e as MouseEvent).button !== 2,
exact: (e, modifiers) =>
systemModifiers.some(m => (e as any)[`${m}Key`] && !modifiers.includes(m)),
} satisfies Record<
string,
| ((e: Event) => void | boolean)
| ((e: Event, modifiers: string[]) => void | boolean)
>
type ModifierGuards = keyof typeof modifierGuards
}
/**
* @private
@ -44,7 +54,7 @@ export const withModifiers = <
>(
fn: T & { _withMods?: { [key: string]: T } },
modifiers: VOnModifiers[],
) => {
): T => {
const cache = fn._withMods || (fn._withMods = {})
const cacheKey = modifiers.join('.')
return (
@ -61,7 +71,10 @@ export const withModifiers = <
// Kept for 2.x compat.
// Note: IE11 compat for `spacebar` and `del` is removed for now.
const keyNames = {
const keyNames: Record<
'esc' | 'space' | 'up' | 'left' | 'right' | 'down' | 'delete',
string
> = {
esc: 'escape',
space: ' ',
up: 'arrow-up',
@ -69,7 +82,7 @@ const keyNames = {
right: 'arrow-right',
down: 'arrow-down',
delete: 'backspace',
} satisfies Record<string, string | string[]>
}
/**
* @private
@ -77,7 +90,7 @@ const keyNames = {
export const withKeys = <T extends (event: KeyboardEvent) => any>(
fn: T & { _withKeys?: { [k: string]: T } },
modifiers: string[],
) => {
): T => {
let globalKeyCodes: LegacyConfig['keyCodes']
let instance: ComponentInternalInstance | null = null
if (__COMPAT__) {

View File

@ -1,7 +1,7 @@
import type { ObjectDirective } from '@vue/runtime-core'
export const vShowOriginalDisplay = Symbol('_vod')
export const vShowHidden = Symbol('_vsh')
export const vShowOriginalDisplay: unique symbol = Symbol('_vod')
export const vShowHidden: unique symbol = Symbol('_vsh')
export interface VShowElement extends HTMLElement {
// _vod = vue original display
@ -56,7 +56,7 @@ function setDisplay(el: VShowElement, value: unknown): void {
// SSR vnode transforms, only used when user includes client-oriented render
// function in SSR
export function initVShowForSSR() {
export function initVShowForSSR(): void {
vShow.getSSRProps = ({ value }) => {
if (!value) {
return { style: { display: 'none' } }

View File

@ -11,12 +11,12 @@ import {
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared'
export const CSS_VAR_TEXT = Symbol(__DEV__ ? 'CSS_VAR_TEXT' : '')
export const CSS_VAR_TEXT: unique symbol = Symbol(__DEV__ ? 'CSS_VAR_TEXT' : '')
/**
* Runtime helper for SFC's CSS variable injection feature.
* @private
*/
export function useCssVars(getter: (ctx: any) => Record<string, string>) {
export function useCssVars(getter: (ctx: any) => Record<string, string>): void {
if (!__BROWSER__ && !__TEST__) return
const instance = getCurrentInstance()

Some files were not shown because too many files have changed in this diff Show More