-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathindex.ts
More file actions
437 lines (377 loc) · 16.6 KB
/
Copy pathindex.ts
File metadata and controls
437 lines (377 loc) · 16.6 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import QuickLRU from '@alloc/quick-lru'
import {
compileAst,
env,
Features,
Instrumentation,
optimize as optimizeCss,
Polyfills,
} from '@tailwindcss/node'
import { clearRequireCache } from '@tailwindcss/node/require-cache'
import { Scanner } from '@tailwindcss/oxide'
import fs from 'node:fs'
import path, { relative } from 'node:path'
import type { AcceptedPlugin, PluginCreator, Postcss, Root } from 'postcss'
import { toCss, type AstNode } from '../../tailwindcss/src/ast'
import { cssAstToPostCssAst, postCssAstToCssAst } from './ast'
import fixRelativePathsPlugin from './postcss-fix-relative-paths'
const DEBUG = env.DEBUG
interface CacheEntry {
mtimes: Map<string, number>
inputCss: string
compiler: null | ReturnType<typeof compileAst>
scanner: null | Scanner
tailwindCssAst: AstNode[]
cachedPostCssAst: Root
optimizedPostCssAst: Root
fullRebuildPaths: string[]
}
const cache = new QuickLRU<string, CacheEntry>({ maxSize: 50 })
function getContextFromCache(postcss: Postcss, inputFile: string, opts: PluginOptions): CacheEntry {
let key = `${inputFile}:${opts.base ?? ''}:${JSON.stringify(opts.optimize)}`
if (cache.has(key)) return cache.get(key)!
let entry = {
mtimes: new Map<string, number>(),
inputCss: '',
compiler: null,
scanner: null,
tailwindCssAst: [],
cachedPostCssAst: postcss.root(),
optimizedPostCssAst: postcss.root(),
fullRebuildPaths: [] as string[],
}
cache.set(key, entry)
return entry
}
export type PluginOptions = {
/**
* The base directory to scan for class candidates.
*
* Defaults to the current working directory.
*/
base?: string
/**
* Optimize and minify the output CSS.
*/
optimize?: boolean | { minify?: boolean }
/**
* Enable or disable asset URL rewriting.
*
* Defaults to `true`.
*/
transformAssetUrls?: boolean
}
function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
let base = opts.base ?? process.cwd()
let optimize = opts.optimize ?? process.env.NODE_ENV === 'production'
let shouldRewriteUrls = opts.transformAssetUrls ?? true
return {
postcssPlugin: '@tailwindcss/postcss',
plugins: [
// We need to handle the case where `postcss-import` might have run before
// the Tailwind CSS plugin is run. In this case, we need to manually fix
// relative paths before processing it in core.
fixRelativePathsPlugin(),
{
postcssPlugin: 'tailwindcss',
async Once(root, { result, postcss }) {
using I = new Instrumentation()
let inputFile = result.opts.from ?? ''
let isCSSModuleFile = inputFile.endsWith('.module.css')
DEBUG && I.start(`[@tailwindcss/postcss] ${relative(base, inputFile)}`)
// Bail out early if this is guaranteed to be a non-Tailwind CSS file.
{
DEBUG && I.start('Quick bail check')
let canBail = true
root.walkAtRules((node) => {
if (
node.name === 'import' ||
node.name === 'reference' ||
node.name === 'theme' ||
node.name === 'variant' ||
node.name === 'config' ||
node.name === 'plugin' ||
node.name === 'apply' ||
node.name === 'tailwind'
) {
canBail = false
return false
}
})
if (canBail) return
DEBUG && I.end('Quick bail check')
}
let context = getContextFromCache(postcss, inputFile, opts)
let inputBasePath = inputFile ? path.dirname(path.resolve(inputFile)) : base
// Whether this is the first build or not, if it is, then we can
// optimize the build by not creating the compiler until we need it.
let isInitialBuild = context.compiler === null
async function createCompiler() {
DEBUG && I.start('Setup compiler')
if (context.fullRebuildPaths.length > 0 && !isInitialBuild) {
clearRequireCache(context.fullRebuildPaths)
}
context.fullRebuildPaths = []
DEBUG && I.start('PostCSS AST -> Tailwind CSS AST')
let ast = postCssAstToCssAst(root)
DEBUG && I.end('PostCSS AST -> Tailwind CSS AST')
DEBUG && I.start('Create compiler')
let compiler = await compileAst(ast, {
from: result.opts.from,
base: inputBasePath,
shouldRewriteUrls,
onDependency: (path) => context.fullRebuildPaths.push(path),
// In CSS Module files, we have to disable the `@property` polyfill since these will
// emit global `*` rules which are considered to be non-pure and will cause builds
// to fail.
polyfills: isCSSModuleFile ? Polyfills.All ^ Polyfills.AtProperty : Polyfills.All,
})
DEBUG && I.end('Create compiler')
DEBUG && I.end('Setup compiler')
return compiler
}
try {
// Setup the compiler if it doesn't exist yet. This way we can
// guarantee a `build()` function is available.
context.compiler ??= createCompiler()
if ((await context.compiler).features === Features.None) {
return
}
let rebuildStrategy: 'full' | 'incremental' = 'incremental'
// Track file modification times to CSS files
DEBUG && I.start('Register full rebuild paths')
{
for (let file of context.fullRebuildPaths) {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(file),
parent: result.opts.from,
})
}
let files = result.messages.flatMap((message) => {
if (message.type !== 'dependency') return []
return message.file
})
files.push(inputFile)
for (let file of files) {
let changedTime = fs.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? null
if (changedTime === null) {
if (file === inputFile) {
rebuildStrategy = 'full'
}
continue
}
let prevTime = context.mtimes.get(file)
if (prevTime === changedTime) continue
rebuildStrategy = 'full'
context.mtimes.set(file, changedTime)
}
// The mtimes above only track files on disk. When the input CSS is
// generated by another tool (e.g. Sass) and passed to `process()`,
// it can change without any tracked file's mtime changing, so also
// rebuild when the input CSS itself differs from the last build.
let inputCss = root.source?.input.css ?? root.toString()
if (context.inputCss !== inputCss) {
rebuildStrategy = 'full'
context.inputCss = inputCss
}
}
DEBUG && I.end('Register full rebuild paths')
if (
rebuildStrategy === 'full' &&
// We can reuse the compiler if it was created during the
// initial build. If it wasn't, we need to create a new one.
!isInitialBuild
) {
context.compiler = createCompiler()
}
let compiler = await context.compiler
if (context.scanner === null || rebuildStrategy === 'full') {
DEBUG && I.start('Setup scanner')
let sources = (() => {
// Disable auto source detection
if (compiler.root === 'none') {
return []
}
// No root specified, use the base directory
if (compiler.root === null) {
return [{ base, pattern: '**/*', negated: false }]
}
// Use the specified root
return [{ ...compiler.root, negated: false }]
})().concat(compiler.sources)
// Look for candidates used to generate the CSS
context.scanner = new Scanner({ sources })
DEBUG && I.end('Setup scanner')
}
DEBUG && I.start('Scan for candidates')
let candidates = compiler.features & Features.Utilities ? context.scanner.scan() : []
DEBUG && I.end('Scan for candidates')
if (compiler.features & Features.Utilities) {
DEBUG && I.start('Register dependency messages')
// Add all found files as direct dependencies
// Note: With Turbopack, the input file might not be a resolved path
let resolvedInputFile = path.resolve(base, inputFile)
for (let file of context.scanner.files) {
let absolutePath = path.resolve(file)
// The CSS file cannot be a dependency of itself
if (absolutePath === resolvedInputFile) {
continue
}
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: absolutePath,
parent: result.opts.from,
})
}
// Register dependencies so changes in `base` cause a rebuild while
// giving tools like Vite or Parcel a glob that can be used to limit
// the files that cause a rebuild to only those that match it.
for (let { base: globBase, pattern } of context.scanner.globs) {
// Avoid adding a dependency on the base directory itself, since it
// causes Next.js to start an endless recursion if the `distDir` is
// configured to anything other than the default `.next` dir.
if (pattern === '*' && base === globBase) {
continue
}
if (pattern === '') {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(globBase),
parent: result.opts.from,
})
} else {
result.messages.push({
type: 'dir-dependency',
plugin: '@tailwindcss/postcss',
dir: path.resolve(globBase),
glob: pattern,
parent: result.opts.from,
})
}
}
DEBUG && I.end('Register dependency messages')
}
DEBUG && I.start('Build utilities')
let tailwindCssAst = compiler.build(candidates)
DEBUG && I.end('Build utilities')
if (context.tailwindCssAst !== tailwindCssAst) {
if (optimize) {
DEBUG && I.start('Optimization')
DEBUG && I.start('AST -> CSS')
let css = toCss(tailwindCssAst)
DEBUG && I.end('AST -> CSS')
DEBUG && I.start('Lightning CSS')
let optimized = optimizeCss(css, {
minify: typeof optimize === 'object' ? optimize.minify : true,
})
DEBUG && I.end('Lightning CSS')
DEBUG && I.start('CSS -> PostCSS AST')
context.optimizedPostCssAst = postcss.parse(optimized.code, result.opts)
DEBUG && I.end('CSS -> PostCSS AST')
DEBUG && I.end('Optimization')
} else {
// Convert our AST to a PostCSS AST
DEBUG && I.start('Transform Tailwind CSS AST into PostCSS AST')
context.cachedPostCssAst = cssAstToPostCssAst(postcss, tailwindCssAst, root.source)
DEBUG && I.end('Transform Tailwind CSS AST into PostCSS AST')
}
}
context.tailwindCssAst = tailwindCssAst
DEBUG && I.start('Update PostCSS AST')
root.removeAll()
root.append(
optimize
? context.optimizedPostCssAst.clone().nodes
: context.cachedPostCssAst.clone().nodes,
)
// Trick PostCSS into thinking the indent is 2 spaces, so it uses that
// as the default instead of 4.
root.raws.indent = ' '
DEBUG && I.end('Update PostCSS AST')
DEBUG && I.end(`[@tailwindcss/postcss] ${relative(base, inputFile)}`)
} catch (error) {
// An error requires a full rebuild to fix
context.compiler = null
// Ensure all dependencies we have collected thus far are included so that the rebuild
// is correctly triggered. This may run before we ever got to register the CSS import
// graph (`context.fullRebuildPaths`) and/or the candidate-scanning dependencies
// (`context.scanner`) for *this* build, e.g. when the failure happens while resolving
// `@import`/`@reference` targets, before scanning even starts. Re-report whatever we
// still know from the last successful build so watchers don't lose track of files that
// haven't changed.
let resolvedInputFile = path.resolve(base, inputFile)
for (let file of context.fullRebuildPaths) {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(file),
parent: result.opts.from,
})
}
if (context.scanner) {
for (let file of context.scanner.files) {
let absolutePath = path.resolve(file)
if (absolutePath === resolvedInputFile) continue
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: absolutePath,
parent: result.opts.from,
})
}
for (let { base: globBase, pattern } of context.scanner.globs) {
if (pattern === '*' && base === globBase) continue
if (pattern === '') {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(globBase),
parent: result.opts.from,
})
} else {
result.messages.push({
type: 'dir-dependency',
plugin: '@tailwindcss/postcss',
dir: path.resolve(globBase),
glob: pattern,
parent: result.opts.from,
})
}
}
}
console.error(error)
let message =
error && typeof error === 'object' && 'message' in error ? `${error.message}` : `${error}`
// In optimized (typically production) builds we want compilation errors to fail
// the build outright so broken CSS never ships.
//
// Otherwise, we avoid throwing here. Throwing causes PostCSS's `process()` promise
// to reject instead of resolve. Tools that rely on `result.messages` to register
// file dependencies (e.g. `postcss-loader`/webpack) only ever read `result.messages`
// from a *resolved* result, so on rejection none of the dependency messages above —
// or from any previously successful build — are seen. That drops every file in the
// CSS import graph from the watcher, not just the one that failed, and nothing
// recompiles again until some other, still-watched file happens to change.
//
// We instead report the error as a warning so `result` still resolves and dependency
// tracking keeps working. We keep serving the last known-good output (if any) rather
// than clearing the stylesheet, so a broken edit doesn't strip all styling while it's
// being fixed.
if (optimize) {
throw root.error(message)
}
result.warn(message, { plugin: '@tailwindcss/postcss' })
root.removeAll()
root.append(context.cachedPostCssAst.clone().nodes)
root.raws.indent = ' '
}
},
},
],
}
}
export default Object.assign(tailwindcss, { postcss: true }) as PluginCreator<PluginOptions>