UNPKG

17.4 kBTypeScriptView Raw
1// Type definitions for prettier 2.0
2// Project: https://github.com/prettier/prettier, https://prettier.io
3// Definitions by: Ika <https://github.com/ikatyang>,
4// Ifiok Jr. <https://github.com/ifiokjr>,
5// Florian Keller <https://github.com/ffflorian>,
6// Sosuke Suzuki <https://github.com/sosukesuzuki>
7// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8// TypeScript Version: 2.8
9
10export type AST = any;
11export type Doc = doc.builders.Doc;
12
13// https://github.com/prettier/prettier/blob/master/src/common/fast-path.js
14export interface FastPath<T = any> {
15 stack: any[];
16 getName(): null | PropertyKey;
17 getValue(): T;
18 getNode(count?: number): null | T;
19 getParentNode(count?: number): null | T;
20 call<U>(callback: (path: this) => U, ...names: PropertyKey[]): U;
21 each(callback: (path: this) => void, ...names: PropertyKey[]): void;
22 map<U>(callback: (path: this, index: number) => U, ...names: PropertyKey[]): U[];
23}
24
25export type BuiltInParser = (text: string, options?: any) => AST;
26export type BuiltInParserName =
27 | 'babel'
28 | 'babel-flow'
29 | 'babel-ts'
30 | 'flow'
31 | 'typescript'
32 | 'css'
33 | 'less'
34 | 'scss'
35 | 'json'
36 | 'json5'
37 | 'json-stringify'
38 | 'graphql'
39 | 'markdown'
40 | 'vue'
41 | 'html'
42 | 'angular'
43 | 'mdx'
44 | 'yaml'
45 | 'lwc';
46
47export type CustomParser = (text: string, parsers: Record<BuiltInParserName, BuiltInParser>, options: Options) => AST;
48
49export interface Options extends Partial<RequiredOptions> {}
50export interface RequiredOptions extends doc.printer.Options {
51 /**
52 * Print semicolons at the ends of statements.
53 * @default true
54 */
55 semi: boolean;
56 /**
57 * Use single quotes instead of double quotes.
58 * @default false
59 */
60 singleQuote: boolean;
61 /**
62 * Use single quotes in JSX.
63 * @default false
64 */
65 jsxSingleQuote: boolean;
66 /**
67 * Print trailing commas wherever possible.
68 * @default 'es5'
69 */
70 trailingComma: 'none' | 'es5' | 'all';
71 /**
72 * Print spaces between brackets in object literals.
73 * @default true
74 */
75 bracketSpacing: boolean;
76 /**
77 * Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line.
78 * @default false
79 */
80 jsxBracketSameLine: boolean;
81 /**
82 * Format only a segment of a file.
83 * @default 0
84 */
85 rangeStart: number;
86 /**
87 * Format only a segment of a file.
88 * @default Infinity
89 */
90 rangeEnd: number;
91 /**
92 * Specify which parser to use.
93 */
94 parser: BuiltInParserName | CustomParser;
95 /**
96 * Specify the input filepath. This will be used to do parser inference.
97 */
98 filepath: string;
99 /**
100 * Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file.
101 * This is very useful when gradually transitioning large, unformatted codebases to prettier.
102 * @default false
103 */
104 requirePragma: boolean;
105 /**
106 * Prettier can insert a special @format marker at the top of files specifying that
107 * the file has been formatted with prettier. This works well when used in tandem with
108 * the --require-pragma option. If there is already a docblock at the top of
109 * the file then this option will add a newline to it with the @format marker.
110 * @default false
111 */
112 insertPragma: boolean;
113 /**
114 * By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer.
115 * In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out.
116 * @default 'preserve'
117 */
118 proseWrap: 'always' | 'never' | 'preserve';
119 /**
120 * Include parentheses around a sole arrow function parameter.
121 * @default 'always'
122 */
123 arrowParens: 'avoid' | 'always';
124 /**
125 * The plugin API is in a beta state.
126 */
127 plugins: Array<string | Plugin>;
128 /**
129 * How to handle whitespaces in HTML.
130 * @default 'css'
131 */
132 htmlWhitespaceSensitivity: 'css' | 'strict' | 'ignore';
133 /**
134 * Which end of line characters to apply.
135 * @default 'lf'
136 */
137 endOfLine: 'auto' | 'lf' | 'crlf' | 'cr';
138 /**
139 * Change when properties in objects are quoted.
140 * @default 'as-needed'
141 */
142 quoteProps: 'as-needed' | 'consistent' | 'preserve';
143 /**
144 * Whether or not to indent the code inside <script> and <style> tags in Vue files.
145 * @default false
146 */
147 vueIndentScriptAndStyle: boolean;
148}
149
150export interface ParserOptions extends RequiredOptions {
151 locStart: (node: any) => number;
152 locEnd: (node: any) => number;
153 originalText: string;
154}
155
156export interface Plugin {
157 languages?: SupportLanguage[];
158 parsers?: { [parserName: string]: Parser };
159 printers?: { [astFormat: string]: Printer };
160 options?: SupportOption[];
161 defaultOptions?: Partial<RequiredOptions>;
162}
163
164export interface Parser {
165 parse: (text: string, parsers: { [parserName: string]: Parser }, options: ParserOptions) => AST;
166 astFormat: string;
167 hasPragma?: (text: string) => boolean;
168 locStart: (node: any) => number;
169 locEnd: (node: any) => number;
170 preprocess?: (text: string, options: ParserOptions) => string;
171}
172
173export interface Printer {
174 print(path: FastPath, options: ParserOptions, print: (path: FastPath) => Doc): Doc;
175 embed?: (
176 path: FastPath,
177 print: (path: FastPath) => Doc,
178 textToDoc: (text: string, options: Options) => Doc,
179 options: ParserOptions,
180 ) => Doc | null;
181 insertPragma?: (text: string) => string;
182 /**
183 * @returns `null` if you want to remove this node
184 * @returns `void` if you want to use modified newNode
185 * @returns anything if you want to replace the node with it
186 */
187 massageAstNode?: (node: any, newNode: any, parent: any) => any;
188 hasPrettierIgnore?: (path: FastPath) => boolean;
189 canAttachComment?: (node: any) => boolean;
190 willPrintOwnComments?: (path: FastPath) => boolean;
191 printComments?: (path: FastPath, print: (path: FastPath) => Doc, options: ParserOptions, needsSemi: boolean) => Doc;
192 handleComments?: {
193 ownLine?: (commentNode: any, text: string, options: ParserOptions, ast: any, isLastComment: boolean) => boolean;
194 endOfLine?: (
195 commentNode: any,
196 text: string,
197 options: ParserOptions,
198 ast: any,
199 isLastComment: boolean,
200 ) => boolean;
201 remaining?: (
202 commentNode: any,
203 text: string,
204 options: ParserOptions,
205 ast: any,
206 isLastComment: boolean,
207 ) => boolean;
208 };
209}
210
211export interface CursorOptions extends Options {
212 /**
213 * Specify where the cursor is.
214 */
215 cursorOffset: number;
216 rangeStart?: never;
217 rangeEnd?: never;
218}
219
220export interface CursorResult {
221 formatted: string;
222 cursorOffset: number;
223}
224
225/**
226 * `format` is used to format text using Prettier. [Options](https://github.com/prettier/prettier#options) may be provided to override the defaults.
227 */
228export function format(source: string, options?: Options): string;
229
230/**
231 * `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
232 * This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
233 */
234export function check(source: string, options?: Options): boolean;
235
236/**
237 * `formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code.
238 * This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
239 *
240 * The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
241 */
242export function formatWithCursor(source: string, options: CursorOptions): CursorResult;
243
244export interface ResolveConfigOptions {
245 /**
246 * If set to `false`, all caching will be bypassed.
247 */
248 useCache?: boolean;
249 /**
250 * Pass directly the path of the config file if you don't wish to search for it.
251 */
252 config?: string;
253 /**
254 * If set to `true` and an `.editorconfig` file is in your project,
255 * Prettier will parse it and convert its properties to the corresponding prettier configuration.
256 * This configuration will be overridden by `.prettierrc`, etc. Currently,
257 * the following EditorConfig properties are supported:
258 * - indent_style
259 * - indent_size/tab_width
260 * - max_line_length
261 */
262 editorconfig?: boolean;
263}
264
265/**
266 * `resolveConfig` can be used to resolve configuration for a given source file,
267 * passing its path as the first argument. The config search will start at the
268 * file path and continue to search up the directory.
269 * (You can use `process.cwd()` to start searching from the current directory).
270 *
271 * A promise is returned which will resolve to:
272 *
273 * - An options object, providing a [config file](https://github.com/prettier/prettier#configuration-file) was found.
274 * - `null`, if no file was found.
275 *
276 * The promise will be rejected if there was an error parsing the configuration file.
277 */
278export function resolveConfig(filePath: string, options?: ResolveConfigOptions): Promise<null | Options>;
279export namespace resolveConfig {
280 function sync(filePath: string, options?: ResolveConfigOptions): null | Options;
281}
282
283/**
284 * `resolveConfigFile` can be used to find the path of the Prettier configuration file,
285 * that will be used when resolving the config (i.e. when calling `resolveConfig`).
286 *
287 * A promise is returned which will resolve to:
288 *
289 * - The path of the configuration file.
290 * - `null`, if no file was found.
291 *
292 * The promise will be rejected if there was an error parsing the configuration file.
293 */
294export function resolveConfigFile(filePath?: string): Promise<null | string>;
295export namespace resolveConfigFile {
296 function sync(filePath?: string): null | string;
297}
298
299/**
300 * As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache.
301 * Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
302 */
303export function clearConfigCache(): void;
304
305export interface SupportLanguage {
306 name: string;
307 since?: string;
308 parsers: BuiltInParserName[] | string[];
309 group?: string;
310 tmScope?: string;
311 aceMode?: string;
312 codemirrorMode?: string;
313 codemirrorMimeType?: string;
314 aliases?: string[];
315 extensions?: string[];
316 filenames?: string[];
317 linguistLanguageId?: number;
318 vscodeLanguageIds?: string[];
319}
320
321export interface SupportOptionDefault {
322 since: string;
323 value: SupportOptionValue;
324}
325
326export interface SupportOption {
327 since?: string;
328 type: 'int' | 'boolean' | 'choice' | 'path';
329 array?: boolean;
330 deprecated?: string;
331 redirect?: SupportOptionRedirect;
332 description: string;
333 oppositeDescription?: string;
334 default: SupportOptionValue | SupportOptionDefault[];
335 range?: SupportOptionRange;
336 choices?: SupportOptionChoice[];
337 category: string;
338}
339
340export interface SupportOptionRedirect {
341 options: string;
342 value: SupportOptionValue;
343}
344
345export interface SupportOptionRange {
346 start: number;
347 end: number;
348 step: number;
349}
350
351export interface SupportOptionChoice {
352 value: boolean | string;
353 description?: string;
354 since?: string;
355 deprecated?: string;
356 redirect?: SupportOptionValue;
357}
358
359export type SupportOptionValue = number | boolean | string;
360
361export interface SupportInfo {
362 languages: SupportLanguage[];
363 options: SupportOption[];
364}
365
366export interface FileInfoOptions {
367 ignorePath?: string;
368 withNodeModules?: boolean;
369 plugins?: string[];
370 resolveConfig?: boolean;
371}
372
373export interface FileInfoResult {
374 ignored: boolean;
375 inferredParser: string | null;
376}
377
378export function getFileInfo(filePath: string, options?: FileInfoOptions): Promise<FileInfoResult>;
379
380export namespace getFileInfo {
381 function sync(filePath: string, options?: FileInfoOptions): FileInfoResult;
382}
383
384/**
385 * Returns an object representing the parsers, languages and file types Prettier supports for the current version.
386 */
387export function getSupportInfo(): SupportInfo;
388
389/**
390 * `version` field in `package.json`
391 */
392export const version: string;
393
394// https://github.com/prettier/prettier/blob/master/src/common/util-shared.js
395export namespace util {
396 function isNextLineEmpty(text: string, node: any, locEnd: (node: any) => number): boolean;
397 function isNextLineEmptyAfterIndex(text: string, index: number): boolean;
398 function isPreviousLineEmpty(text: string, node: any, locStart: (node: any) => number): boolean;
399 function getNextNonSpaceNonCommentCharacterIndex(text: string, node: any, options: ParserOptions): number;
400 function makeString(rawContent: string, enclosingQuote: "'" | '"', unescapeUnnecessaryEscapes: boolean): string;
401 function addLeadingComment(node: any, commentNode: any): void;
402 function addDanglingComment(node: any, commentNode: any): void;
403 function addTrailingComment(node: any, commentNode: any): void;
404}
405
406// https://github.com/prettier/prettier/blob/master/src/doc/index.js
407export namespace doc {
408 namespace builders {
409 type Doc =
410 | string
411 | Align
412 | BreakParent
413 | Concat
414 | Fill
415 | Group
416 | IfBreak
417 | Indent
418 | Line
419 | LineSuffix
420 | LineSuffixBoundary;
421
422 interface Align {
423 type: 'align';
424 contents: Doc;
425 n: number | string | { type: 'root' };
426 }
427
428 interface BreakParent {
429 type: 'break-parent';
430 }
431
432 interface Concat {
433 type: 'concat';
434 parts: Doc[];
435 }
436
437 interface Fill {
438 type: 'fill';
439 parts: Doc[];
440 }
441
442 interface Group {
443 type: 'group';
444 contents: Doc;
445 break: boolean;
446 expandedStates: Doc[];
447 }
448
449 interface IfBreak {
450 type: 'if-break';
451 breakContents: Doc;
452 flatContents: Doc;
453 }
454
455 interface Indent {
456 type: 'indent';
457 contents: Doc;
458 }
459
460 interface Line {
461 type: 'line';
462 soft?: boolean;
463 hard?: boolean;
464 literal?: boolean;
465 }
466
467 interface LineSuffix {
468 type: 'line-suffix';
469 contents: Doc;
470 }
471
472 interface LineSuffixBoundary {
473 type: 'line-suffix-boundary';
474 }
475
476 function addAlignmentToDoc(doc: Doc, size: number, tabWidth: number): Doc;
477 function align(n: Align['n'], contents: Doc): Align;
478 const breakParent: BreakParent;
479 function concat(contents: Doc[]): Concat;
480 function conditionalGroup(states: Doc[], opts?: { shouldBreak: boolean }): Group;
481 function dedent(contents: Doc): Align;
482 function dedentToRoot(contents: Doc): Align;
483 function fill(parts: Doc[]): Fill;
484 function group(contents: Doc, opts?: { shouldBreak: boolean }): Group;
485 const hardline: Concat;
486 function ifBreak(breakContents: Doc, flatContents: Doc): IfBreak;
487 function indent(contents: Doc): Indent;
488 function join(separator: Doc, parts: Doc[]): Concat;
489 const line: Line;
490 function lineSuffix(contents: Doc): LineSuffix;
491 const lineSuffixBoundary: LineSuffixBoundary;
492 const literalline: Concat;
493 function markAsRoot(contents: Doc): Align;
494 const softline: Line;
495 }
496 namespace debug {
497 function printDocToDebug(doc: Doc): string;
498 }
499 namespace printer {
500 function printDocToString(
501 doc: Doc,
502 options: Options,
503 ): {
504 formatted: string;
505 cursorNodeStart?: number;
506 cursorNodeText?: string;
507 };
508 interface Options {
509 /**
510 * Specify the line length that the printer will wrap on.
511 * @default 80
512 */
513 printWidth: number;
514 /**
515 * Specify the number of spaces per indentation-level.
516 * @default 2
517 */
518 tabWidth: number;
519 /**
520 * Indent lines with tabs instead of spaces
521 * @default false
522 */
523 useTabs: boolean;
524 }
525 }
526 namespace utils {
527 function isEmpty(doc: Doc): boolean;
528 function isLineNext(doc: Doc): boolean;
529 function willBreak(doc: Doc): boolean;
530 function traverseDoc(
531 doc: Doc,
532 onEnter?: (doc: Doc) => void | boolean,
533 onExit?: (doc: Doc) => void,
534 shouldTraverseConditionalGroups?: boolean,
535 ): void;
536 function mapDoc<T>(doc: Doc, callback: (doc: Doc) => T): T;
537 function propagateBreaks(doc: Doc): void;
538 function removeLines(doc: Doc): Doc;
539 function stripTrailingHardline(doc: Doc): Doc;
540 }
541}