UNPKG

16.2 kBTypeScriptView Raw
1import * as lru_cache_min from 'lru-cache/min';
2import * as _babel_types from '@babel/types';
3import { Statement, Expression, TSType, Program, CallExpression, Node, ObjectPattern, TSModuleDeclaration, TSPropertySignature, TSMethodSignature, TSCallSignatureDeclaration, TSFunctionType } from '@babel/types';
4import { CompilerOptions, CodegenResult, ParserOptions, RootNode, CompilerError, SourceLocation, ElementNode, BindingMetadata as BindingMetadata$1 } from '@vue/compiler-core';
5export { BindingMetadata, CompilerError, CompilerOptions, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, walkIdentifiers } from '@vue/compiler-core';
6import { RawSourceMap } from 'source-map-js';
7import { ParserPlugin } from '@babel/parser';
8export { parse as babelParse } from '@babel/parser';
9import { Result, LazyResult } from 'postcss';
10import MagicString from 'magic-string';
11export { default as MagicString } from 'magic-string';
12import TS from 'typescript';
13export { shouldTransform as shouldTransformRef, transform as transformRef, transformAST as transformRefAST } from '@vue/reactivity-transform';
14
15export interface AssetURLTagConfig {
16 [name: string]: string[];
17}
18export interface AssetURLOptions {
19 /**
20 * If base is provided, instead of transforming relative asset urls into
21 * imports, they will be directly rewritten to absolute urls.
22 */
23 base?: string | null;
24 /**
25 * If true, also processes absolute urls.
26 */
27 includeAbsolute?: boolean;
28 tags?: AssetURLTagConfig;
29}
30
31export interface TemplateCompiler {
32 compile(template: string, options: CompilerOptions): CodegenResult;
33 parse(template: string, options: ParserOptions): RootNode;
34}
35export interface SFCTemplateCompileResults {
36 code: string;
37 ast?: RootNode;
38 preamble?: string;
39 source: string;
40 tips: string[];
41 errors: (string | CompilerError)[];
42 map?: RawSourceMap;
43}
44export interface SFCTemplateCompileOptions {
45 source: string;
46 filename: string;
47 id: string;
48 scoped?: boolean;
49 slotted?: boolean;
50 isProd?: boolean;
51 ssr?: boolean;
52 ssrCssVars?: string[];
53 inMap?: RawSourceMap;
54 compiler?: TemplateCompiler;
55 compilerOptions?: CompilerOptions;
56 preprocessLang?: string;
57 preprocessOptions?: any;
58 /**
59 * In some cases, compiler-sfc may not be inside the project root (e.g. when
60 * linked or globally installed). In such cases a custom `require` can be
61 * passed to correctly resolve the preprocessors.
62 */
63 preprocessCustomRequire?: (id: string) => any;
64 /**
65 * Configure what tags/attributes to transform into asset url imports,
66 * or disable the transform altogether with `false`.
67 */
68 transformAssetUrls?: AssetURLOptions | AssetURLTagConfig | boolean;
69}
70export declare function compileTemplate(options: SFCTemplateCompileOptions): SFCTemplateCompileResults;
71
72export interface SFCScriptCompileOptions {
73 /**
74 * Scope ID for prefixing injected CSS variables.
75 * This must be consistent with the `id` passed to `compileStyle`.
76 */
77 id: string;
78 /**
79 * Production mode. Used to determine whether to generate hashed CSS variables
80 */
81 isProd?: boolean;
82 /**
83 * Enable/disable source map. Defaults to true.
84 */
85 sourceMap?: boolean;
86 /**
87 * https://babeljs.io/docs/en/babel-parser#plugins
88 */
89 babelParserPlugins?: ParserPlugin[];
90 /**
91 * A list of files to parse for global types to be made available for type
92 * resolving in SFC macros. The list must be fully resolved file system paths.
93 */
94 globalTypeFiles?: string[];
95 /**
96 * Compile the template and inline the resulting render function
97 * directly inside setup().
98 * - Only affects `<script setup>`
99 * - This should only be used in production because it prevents the template
100 * from being hot-reloaded separately from component state.
101 */
102 inlineTemplate?: boolean;
103 /**
104 * Generate the final component as a variable instead of default export.
105 * This is useful in e.g. @vitejs/plugin-vue where the script needs to be
106 * placed inside the main module.
107 */
108 genDefaultAs?: string;
109 /**
110 * Options for template compilation when inlining. Note these are options that
111 * would normally be passed to `compiler-sfc`'s own `compileTemplate()`, not
112 * options passed to `compiler-dom`.
113 */
114 templateOptions?: Partial<SFCTemplateCompileOptions>;
115 /**
116 * Hoist <script setup> static constants.
117 * - Only enables when one `<script setup>` exists.
118 * @default true
119 */
120 hoistStatic?: boolean;
121 /**
122 * (**Experimental**) Enable macro `defineModel`
123 * @default false
124 */
125 defineModel?: boolean;
126 /**
127 * (**Experimental**) Enable reactive destructure for `defineProps`
128 * @default false
129 */
130 propsDestructure?: boolean;
131 /**
132 * File system access methods to be used when resolving types
133 * imported in SFC macros. Defaults to ts.sys in Node.js, can be overwritten
134 * to use a virtual file system for use in browsers (e.g. in REPLs)
135 */
136 fs?: {
137 fileExists(file: string): boolean;
138 readFile(file: string): string | undefined;
139 };
140 /**
141 * (Experimental) Enable syntax transform for using refs without `.value` and
142 * using destructured props with reactivity
143 * @deprecated the Reactivity Transform proposal has been dropped. This
144 * feature will be removed from Vue core in 3.4. If you intend to continue
145 * using it, disable this and switch to the [Vue Macros implementation](https://vue-macros.sxzz.moe/features/reactivity-transform.html).
146 */
147 reactivityTransform?: boolean;
148}
149interface ImportBinding {
150 isType: boolean;
151 imported: string;
152 local: string;
153 source: string;
154 isFromSetup: boolean;
155 isUsedInTemplate: boolean;
156}
157/**
158 * Compile `<script setup>`
159 * It requires the whole SFC descriptor because we need to handle and merge
160 * normal `<script>` + `<script setup>` if both are present.
161 */
162export declare function compileScript(sfc: SFCDescriptor, options: SFCScriptCompileOptions): SFCScriptBlock;
163
164export interface SFCParseOptions {
165 filename?: string;
166 sourceMap?: boolean;
167 sourceRoot?: string;
168 pad?: boolean | 'line' | 'space';
169 ignoreEmpty?: boolean;
170 compiler?: TemplateCompiler;
171}
172export interface SFCBlock {
173 type: string;
174 content: string;
175 attrs: Record<string, string | true>;
176 loc: SourceLocation;
177 map?: RawSourceMap;
178 lang?: string;
179 src?: string;
180}
181export interface SFCTemplateBlock extends SFCBlock {
182 type: 'template';
183 ast: ElementNode;
184}
185export interface SFCScriptBlock extends SFCBlock {
186 type: 'script';
187 setup?: string | boolean;
188 bindings?: BindingMetadata$1;
189 imports?: Record<string, ImportBinding>;
190 scriptAst?: _babel_types.Statement[];
191 scriptSetupAst?: _babel_types.Statement[];
192 warnings?: string[];
193 /**
194 * Fully resolved dependency file paths (unix slashes) with imported types
195 * used in macros, used for HMR cache busting in @vitejs/plugin-vue and
196 * vue-loader.
197 */
198 deps?: string[];
199}
200export interface SFCStyleBlock extends SFCBlock {
201 type: 'style';
202 scoped?: boolean;
203 module?: string | boolean;
204}
205export interface SFCDescriptor {
206 filename: string;
207 source: string;
208 template: SFCTemplateBlock | null;
209 script: SFCScriptBlock | null;
210 scriptSetup: SFCScriptBlock | null;
211 styles: SFCStyleBlock[];
212 customBlocks: SFCBlock[];
213 cssVars: string[];
214 /**
215 * whether the SFC uses :slotted() modifier.
216 * this is used as a compiler optimization hint.
217 */
218 slotted: boolean;
219 /**
220 * compare with an existing descriptor to determine whether HMR should perform
221 * a reload vs. re-render.
222 *
223 * Note: this comparison assumes the prev/next script are already identical,
224 * and only checks the special case where <script setup lang="ts"> unused import
225 * pruning result changes due to template changes.
226 */
227 shouldForceReload: (prevImports: Record<string, ImportBinding>) => boolean;
228}
229export interface SFCParseResult {
230 descriptor: SFCDescriptor;
231 errors: (CompilerError | SyntaxError)[];
232}
233export declare const parseCache: Map<string, SFCParseResult> | lru_cache_min.LRUCache<string, SFCParseResult, unknown>;
234export declare function parse(source: string, { sourceMap, filename, sourceRoot, pad, ignoreEmpty, compiler }?: SFCParseOptions): SFCParseResult;
235
236type PreprocessLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus';
237
238export interface SFCStyleCompileOptions {
239 source: string;
240 filename: string;
241 id: string;
242 scoped?: boolean;
243 trim?: boolean;
244 isProd?: boolean;
245 inMap?: RawSourceMap;
246 preprocessLang?: PreprocessLang;
247 preprocessOptions?: any;
248 preprocessCustomRequire?: (id: string) => any;
249 postcssOptions?: any;
250 postcssPlugins?: any[];
251 /**
252 * @deprecated use `inMap` instead.
253 */
254 map?: RawSourceMap;
255}
256/**
257 * Aligns with postcss-modules
258 * https://github.com/css-modules/postcss-modules
259 */
260interface CSSModulesOptions {
261 scopeBehaviour?: 'global' | 'local';
262 generateScopedName?: string | ((name: string, filename: string, css: string) => string);
263 hashPrefix?: string;
264 localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
265 exportGlobals?: boolean;
266 globalModulePaths?: RegExp[];
267}
268export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
269 isAsync?: boolean;
270 modules?: boolean;
271 modulesOptions?: CSSModulesOptions;
272}
273export interface SFCStyleCompileResults {
274 code: string;
275 map: RawSourceMap | undefined;
276 rawResult: Result | LazyResult | undefined;
277 errors: Error[];
278 modules?: Record<string, string>;
279 dependencies: Set<string>;
280}
281export declare function compileStyle(options: SFCStyleCompileOptions): SFCStyleCompileResults;
282export declare function compileStyleAsync(options: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults>;
283
284export declare function rewriteDefault(input: string, as: string, parserPlugins?: ParserPlugin[]): string;
285/**
286 * Utility for rewriting `export default` in a script block into a variable
287 * declaration so that we can inject things into it
288 */
289export declare function rewriteDefaultAST(ast: Statement[], s: MagicString, as: string): void;
290
291type PropsDestructureBindings = Record<string, // public prop key
292{
293 local: string;
294 default?: Expression;
295}>;
296
297interface ModelDecl {
298 type: TSType | undefined;
299 options: string | undefined;
300 identifier: string | undefined;
301}
302
303declare const enum BindingTypes {
304 /**
305 * returned from data()
306 */
307 DATA = "data",
308 /**
309 * declared as a prop
310 */
311 PROPS = "props",
312 /**
313 * a local alias of a `<script setup>` destructured prop.
314 * the original is stored in __propsAliases of the bindingMetadata object.
315 */
316 PROPS_ALIASED = "props-aliased",
317 /**
318 * a let binding (may or may not be a ref)
319 */
320 SETUP_LET = "setup-let",
321 /**
322 * a const binding that can never be a ref.
323 * these bindings don't need `unref()` calls when processed in inlined
324 * template expressions.
325 */
326 SETUP_CONST = "setup-const",
327 /**
328 * a const binding that does not need `unref()`, but may be mutated.
329 */
330 SETUP_REACTIVE_CONST = "setup-reactive-const",
331 /**
332 * a const binding that may be a ref.
333 */
334 SETUP_MAYBE_REF = "setup-maybe-ref",
335 /**
336 * bindings that are guaranteed to be refs
337 */
338 SETUP_REF = "setup-ref",
339 /**
340 * declared by other options, e.g. computed, inject
341 */
342 OPTIONS = "options",
343 /**
344 * a literal constant, e.g. 'foo', 1, true
345 */
346 LITERAL_CONST = "literal-const"
347}
348type BindingMetadata = {
349 [key: string]: BindingTypes | undefined;
350} & {
351 __isScriptSetup?: boolean;
352 __propsAliases?: Record<string, string>;
353};
354
355export declare class ScriptCompileContext {
356 descriptor: SFCDescriptor;
357 options: Partial<SFCScriptCompileOptions>;
358 isJS: boolean;
359 isTS: boolean;
360 scriptAst: Program | null;
361 scriptSetupAst: Program | null;
362 source: string;
363 filename: string;
364 s: MagicString;
365 startOffset: number | undefined;
366 endOffset: number | undefined;
367 scope?: TypeScope;
368 globalScopes?: TypeScope[];
369 userImports: Record<string, ImportBinding>;
370 hasDefinePropsCall: boolean;
371 hasDefineEmitCall: boolean;
372 hasDefineExposeCall: boolean;
373 hasDefaultExportName: boolean;
374 hasDefaultExportRender: boolean;
375 hasDefineOptionsCall: boolean;
376 hasDefineSlotsCall: boolean;
377 hasDefineModelCall: boolean;
378 propsCall: CallExpression | undefined;
379 propsDecl: Node | undefined;
380 propsRuntimeDecl: Node | undefined;
381 propsTypeDecl: Node | undefined;
382 propsDestructureDecl: ObjectPattern | undefined;
383 propsDestructuredBindings: PropsDestructureBindings;
384 propsDestructureRestId: string | undefined;
385 propsRuntimeDefaults: Node | undefined;
386 emitsRuntimeDecl: Node | undefined;
387 emitsTypeDecl: Node | undefined;
388 emitDecl: Node | undefined;
389 modelDecls: Record<string, ModelDecl>;
390 optionsRuntimeDecl: Node | undefined;
391 bindingMetadata: BindingMetadata;
392 helperImports: Set<string>;
393 helper(key: string): string;
394 /**
395 * to be exposed on compiled script block for HMR cache busting
396 */
397 deps?: Set<string>;
398 /**
399 * cache for resolved fs
400 */
401 fs?: NonNullable<SFCScriptCompileOptions['fs']>;
402 constructor(descriptor: SFCDescriptor, options: Partial<SFCScriptCompileOptions>);
403 getString(node: Node, scriptSetup?: boolean): string;
404 error(msg: string, node: Node, scope?: TypeScope): never;
405}
406
407/**
408 * TypeResolveContext is compatible with ScriptCompileContext
409 * but also allows a simpler version of it with minimal required properties
410 * when resolveType needs to be used in a non-SFC context, e.g. in a babel
411 * plugin. The simplest context can be just:
412 * ```ts
413 * const ctx: SimpleTypeResolveContext = {
414 * filename: '...',
415 * source: '...',
416 * options: {},
417 * error() {},
418 * ast: []
419 * }
420 * ```
421 */
422export type SimpleTypeResolveContext = Pick<ScriptCompileContext, 'source' | 'filename' | 'error' | 'options'> & Partial<Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'>> & {
423 ast: Statement[];
424};
425export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext;
426type Import = Pick<ImportBinding, 'source' | 'imported'>;
427interface WithScope {
428 _ownerScope: TypeScope;
429}
430type ScopeTypeNode = Node & WithScope & {
431 _ns?: TSModuleDeclaration & WithScope;
432};
433declare class TypeScope {
434 filename: string;
435 source: string;
436 offset: number;
437 imports: Record<string, Import>;
438 types: Record<string, ScopeTypeNode>;
439 declares: Record<string, ScopeTypeNode>;
440 constructor(filename: string, source: string, offset?: number, imports?: Record<string, Import>, types?: Record<string, ScopeTypeNode>, declares?: Record<string, ScopeTypeNode>);
441 resolvedImportSources: Record<string, string>;
442 exportedTypes: Record<string, ScopeTypeNode>;
443 exportedDeclares: Record<string, ScopeTypeNode>;
444}
445interface MaybeWithScope {
446 _ownerScope?: TypeScope;
447}
448interface ResolvedElements {
449 props: Record<string, (TSPropertySignature | TSMethodSignature) & {
450 _ownerScope: TypeScope;
451 }>;
452 calls?: (TSCallSignatureDeclaration | TSFunctionType)[];
453}
454/**
455 * Resolve arbitrary type node to a list of type elements that can be then
456 * mapped to runtime props or emits.
457 */
458export declare function resolveTypeElements(ctx: TypeResolveContext, node: Node & MaybeWithScope & {
459 _resolvedElements?: ResolvedElements;
460}, scope?: TypeScope): ResolvedElements;
461/**
462 * @private
463 */
464export declare function registerTS(_loadTS: () => typeof TS): void;
465/**
466 * @private
467 */
468export declare function invalidateTypeCache(filename: string): void;
469export declare function inferRuntimeType(ctx: TypeResolveContext, node: Node & MaybeWithScope, scope?: TypeScope): string[];
470
471export declare const version: string;
472
473export declare const walk: any;
474
475
\No newline at end of file