-
-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathcreate-plugin.ts
More file actions
247 lines (203 loc) · 6.36 KB
/
create-plugin.ts
File metadata and controls
247 lines (203 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import type { Parser, ParserOptions, Plugin, Printer } from 'prettier'
import { getTailwindConfig } from './config'
import { createMatcher } from './options'
import { loadIfExists, maybeResolve } from './resolve'
import type { TransformOptions } from './transform'
import type { TransformerEnv } from './types'
import { isAbsolute } from 'path'
export function createPlugin(transforms: TransformOptions<any>[]) {
// Prettier parsers and printers may be async functions at definition time.
// They'll be awaited when the plugin is loaded but must also be swapped out
// with the resolved value before returning as later Prettier internals
// assume that parsers and printers are objects and not functions.
type Init<T> = (() => Promise<T | undefined>) | T | undefined
let parsers: Record<string, Init<Parser<any>>> = Object.create(null)
let printers: Record<string, Init<Printer<any>>> = Object.create(null)
for (let opts of transforms) {
for (let [name, meta] of Object.entries(opts.parsers)) {
parsers[name] = async () => {
let plugin = await loadPlugins(meta.load ?? opts.load ?? [])
let original = plugin.parsers?.[name]
if (!original) return
parsers[name] = await createParser({
name,
original,
opts,
})
return parsers[name]
}
}
for (let [name, _meta] of Object.entries(opts.printers ?? {})) {
printers[name] = async () => {
let plugin = await loadPlugins(opts.load ?? [])
let original = plugin.printers?.[name]
if (!original) return
printers[name] = createPrinter({
original,
opts,
})
return printers[name]
}
}
}
return { parsers, printers }
}
async function createParser({
name,
original,
opts,
}: {
name: string
original: Parser<any>
opts: TransformOptions<any>
}) {
let parser: Parser<any> = { ...original }
async function load(options: ParserOptions<any>) {
let parser: Parser<any> = { ...original }
for (const pluginName of opts.compatible || []) {
let plugin = await findEnabledPlugin(options, pluginName)
if (plugin?.parsers?.[name]) Object.assign(parser, plugin.parsers[name])
}
return parser
}
parser.preprocess = async (code: string, options: ParserOptions) => {
let parser = await load(options)
return parser.preprocess ? parser.preprocess(code, options) : code
}
parser.parse = async (code, options) => {
let original = await load(options)
// @ts-expect-error: `options` is passed twice for compat with older plugins that were written
// for Prettier v2 but still work with v3.
//
// Currently only the Twig plugin requires this.
let ast = await original.parse(code, options, options)
let env = await loadTailwindCSS({ opts, options })
transformAst({
ast,
env,
opts,
options,
})
options.__tailwindcss__ = env
return ast
}
return parser
}
function createPrinter({
original,
opts,
}: {
original: Printer<any>
opts: TransformOptions<any>
}) {
let printer: Printer<any> = { ...original }
let reprint = opts.reprint
// Hook into the preprocessing phase to load the config
if (reprint) {
printer.print = new Proxy(original.print, {
apply(target, thisArg, args) {
let [path, options] = args as Parameters<typeof original.print>
let env = options.__tailwindcss__ as TransformerEnv
reprint(path, { ...env, options: options })
return Reflect.apply(target, thisArg, args)
},
})
if (original.embed) {
printer.embed = new Proxy(original.embed, {
apply(target, thisArg, args) {
let [path, options] = args as Parameters<typeof original.embed>
let env = options.__tailwindcss__ as TransformerEnv
reprint(path, { ...env, options: options as any })
return Reflect.apply(target, thisArg, args)
},
})
}
}
return printer
}
type PluginLoad = string | Plugin<any>
async function loadPlugins<T>(fns: PluginLoad[]) {
let plugin: Plugin<T> = {
parsers: Object.create(null),
printers: Object.create(null),
options: Object.create(null),
defaultOptions: Object.create(null),
languages: [],
}
for (let moduleName of fns) {
let loaded = typeof moduleName === 'string' ? await loadIfExistsESM(moduleName) : moduleName
Object.assign(plugin.parsers!, loaded.parsers ?? {})
Object.assign(plugin.printers!, loaded.printers ?? {})
Object.assign(plugin.options!, loaded.options ?? {})
Object.assign(plugin.defaultOptions!, loaded.defaultOptions ?? {})
plugin.languages = [...(plugin.languages ?? []), ...(loaded.languages ?? [])]
}
return plugin
}
async function loadIfExistsESM(name: string): Promise<Plugin<any>> {
let mod = await loadIfExists<Plugin<any>>(name)
return (
mod ?? {
parsers: {},
printers: {},
languages: [],
options: {},
defaultOptions: {},
}
)
}
function findEnabledPlugin(options: ParserOptions<any>, name: string) {
for (let plugin of options.plugins) {
if (plugin instanceof URL) {
if (plugin.protocol !== 'file:') continue
if (plugin.hostname !== '') continue
plugin = plugin.pathname
} if (typeof plugin !== 'string') {
if (!plugin.name) {
continue
}
plugin = plugin.name
}
if (plugin === name || (isAbsolute(plugin) && plugin.includes(name) && maybeResolve(name) === plugin)) {
return loadIfExistsESM(name)
}
}
}
async function loadTailwindCSS<T = any>({
options,
opts,
}: {
options: ParserOptions<T>
opts: TransformOptions<T>
}): Promise<TransformerEnv> {
let parsers = opts.parsers
let parser = options.parser as string
let context = await getTailwindConfig(options)
let matcher = createMatcher(options, parser, {
staticAttrs: new Set(parsers[parser]?.staticAttrs ?? opts.staticAttrs ?? []),
dynamicAttrs: new Set(parsers[parser]?.dynamicAttrs ?? opts.dynamicAttrs ?? []),
functions: new Set(),
staticAttrsRegex: [],
dynamicAttrsRegex: [],
functionsRegex: [],
})
return {
context,
matcher,
options,
changes: [],
}
}
function transformAst<T = any>({
ast,
env,
opts,
}: {
ast: T
env: TransformerEnv
options: ParserOptions<T>
opts: TransformOptions<T>
}) {
let transform = opts.transform
if (transform) transform(ast, env)
}