Allow parser.preprocess to return a Promise (#17679)

This commit is contained in:
fisker Cheung authored and GitHub committed 2025-09-12 05:03:05 +08:00
1 parent 0e4baf561d
commit afd57d3247
7 files changed
+45 -4

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
#### Allow `plugin.parser.preprocess()` to return a `Promise` (#17679 by @fisker)
Align with [`plugin.printer.preprocess()`](https://prettier.io/docs/plugins#optional-preprocess), which allows to return a `Promise`.
We still suggest move your async work into `plugin.parser.parse()`, which already allow to return a `Promise`, we may remove support for `plugin.parser.preprocess()` in future.
+1 -1
View File
@@ -149,7 +149,7 @@ function hasIgnorePragma(text: string): boolean;
_(Optional)_ The preprocess function can process the input text before passing into `parse` function.
```ts
function preprocess(text: string, options: object): string;
function preprocess(text: string, options: object): string | Promise<string>;
```
### `printers`
+1 -1
View File
@@ -480,7 +480,7 @@ export interface Parser<T = any> {
locStart: (node: T) => number;
locEnd: (node: T) => number;
preprocess?:
| ((text: string, options: ParserOptions<T>) => string)
| ((text: string, options: ParserOptions<T>) => string | Promise<string>)
| undefined;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { resolveParser } from "./parser-and-printer.js";
async function parse(originalText, options) {
const parser = await resolveParser(options);
const text = parser.preprocess
? parser.preprocess(originalText, options)
? await parser.preprocess(originalText, options)
: originalText;
options.originalText = text;
@@ -7,4 +7,16 @@ describe("parser preprocess function is used to reshape input text", () => {
status: 0,
write: [],
});
runCli(
"plugins/preprocess",
["*.foo", "--plugin=./plugin-with-async-preprocess.cjs"],
{
ignoreLineEndings: true,
},
).test({
stdout: "preprocessed:async:contents",
stderr: "",
status: 0,
write: [],
});
});
@@ -0,0 +1,24 @@
"use strict";
module.exports = {
languages: [
{
name: "foo",
parsers: ["foo-parser"],
extensions: [".foo"],
since: "1.0.0",
},
],
parsers: {
"foo-parser": {
preprocess: (text) => Promise.resolve(`preprocessed:async:${text}`),
parse: (text) => ({ text }),
astFormat: "foo-ast",
},
},
printers: {
"foo-ast": {
print: ({ node }) => node.text,
},
},
};
@@ -18,7 +18,7 @@ module.exports = {
},
printers: {
"foo-ast": {
print: (path) => path.getValue().text,
print: ({ node }) => node.text,
},
},
};