UNPKG

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