tailwindcss 0.0.0-insiders.4e21639 → 0.0.0-insiders.4e62334

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +435 -3
  2. package/LICENSE +1 -2
  3. package/README.md +13 -6
  4. package/colors.d.ts +3 -0
  5. package/colors.js +2 -1
  6. package/defaultConfig.d.ts +3 -0
  7. package/defaultConfig.js +2 -1
  8. package/defaultTheme.d.ts +4 -0
  9. package/defaultTheme.js +2 -1
  10. package/lib/cli-peer-dependencies.js +20 -7
  11. package/lib/cli.js +460 -259
  12. package/lib/constants.js +27 -20
  13. package/lib/corePluginList.js +9 -3
  14. package/lib/corePlugins.js +1840 -1753
  15. package/lib/css/preflight.css +8 -9
  16. package/lib/featureFlags.js +29 -20
  17. package/lib/index.js +22 -11
  18. package/lib/lib/cacheInvalidation.js +90 -0
  19. package/lib/lib/collapseAdjacentRules.js +27 -9
  20. package/lib/lib/collapseDuplicateDeclarations.js +58 -4
  21. package/lib/lib/defaultExtractor.js +231 -0
  22. package/lib/lib/detectNesting.js +13 -10
  23. package/lib/lib/evaluateTailwindFunctions.js +119 -52
  24. package/lib/lib/expandApplyAtRules.js +440 -161
  25. package/lib/lib/expandTailwindAtRules.js +130 -128
  26. package/lib/lib/generateRules.js +410 -171
  27. package/lib/lib/getModuleDependencies.js +11 -8
  28. package/lib/lib/normalizeTailwindDirectives.js +43 -32
  29. package/lib/lib/offsets.js +199 -0
  30. package/lib/lib/partitionApplyAtRules.js +56 -0
  31. package/lib/lib/regex.js +60 -0
  32. package/lib/lib/resolveDefaultsAtRules.js +91 -55
  33. package/lib/lib/setupContextUtils.js +453 -347
  34. package/lib/lib/setupTrackingContext.js +52 -44
  35. package/lib/lib/sharedState.js +48 -9
  36. package/lib/lib/substituteScreenAtRules.js +13 -8
  37. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  38. package/lib/postcss-plugins/nesting/index.js +19 -0
  39. package/lib/postcss-plugins/nesting/plugin.js +87 -0
  40. package/lib/processTailwindFeatures.js +36 -25
  41. package/lib/public/colors.js +247 -245
  42. package/lib/public/create-plugin.js +6 -4
  43. package/lib/public/default-config.js +7 -5
  44. package/lib/public/default-theme.js +7 -5
  45. package/lib/public/resolve-config.js +8 -5
  46. package/lib/util/bigSign.js +4 -1
  47. package/lib/util/buildMediaQuery.js +16 -25
  48. package/lib/util/cloneDeep.js +7 -6
  49. package/lib/util/cloneNodes.js +21 -3
  50. package/lib/util/color.js +54 -40
  51. package/lib/util/configurePlugins.js +4 -1
  52. package/lib/util/createPlugin.js +6 -6
  53. package/lib/util/createUtilityPlugin.js +12 -14
  54. package/lib/util/dataTypes.js +119 -102
  55. package/lib/util/defaults.js +10 -1
  56. package/lib/util/escapeClassName.js +7 -4
  57. package/lib/util/escapeCommas.js +5 -2
  58. package/lib/util/flattenColorPalette.js +9 -12
  59. package/lib/util/formatVariantSelector.js +223 -40
  60. package/lib/util/getAllConfigs.js +27 -8
  61. package/lib/util/hashConfig.js +6 -3
  62. package/lib/util/isKeyframeRule.js +5 -2
  63. package/lib/util/isPlainObject.js +5 -2
  64. package/lib/util/isValidArbitraryValue.js +72 -0
  65. package/lib/util/log.js +22 -12
  66. package/lib/util/nameClass.js +17 -8
  67. package/lib/util/negateValue.js +22 -7
  68. package/lib/util/normalizeConfig.js +99 -54
  69. package/lib/util/normalizeScreens.js +73 -0
  70. package/lib/util/parseAnimationValue.js +42 -40
  71. package/lib/util/parseBoxShadowValue.js +30 -23
  72. package/lib/util/parseDependency.js +18 -15
  73. package/lib/util/parseObjectStyles.js +10 -7
  74. package/lib/util/pluginUtils.js +51 -42
  75. package/lib/util/prefixSelector.js +10 -8
  76. package/lib/util/removeAlphaVariables.js +29 -0
  77. package/lib/util/resolveConfig.js +91 -66
  78. package/lib/util/resolveConfigPath.js +11 -9
  79. package/lib/util/responsive.js +8 -5
  80. package/lib/util/splitAtTopLevelOnly.js +43 -0
  81. package/lib/util/tap.js +4 -1
  82. package/lib/util/toColorValue.js +5 -3
  83. package/lib/util/toPath.js +24 -3
  84. package/lib/util/transformThemeValue.js +37 -29
  85. package/lib/util/validateConfig.js +24 -0
  86. package/lib/util/withAlphaVariable.js +23 -15
  87. package/nesting/index.js +2 -12
  88. package/package.json +43 -43
  89. package/peers/index.js +11543 -8114
  90. package/plugin.d.ts +11 -0
  91. package/plugin.js +2 -1
  92. package/resolveConfig.d.ts +3 -0
  93. package/resolveConfig.js +2 -1
  94. package/scripts/generate-types.js +105 -0
  95. package/scripts/type-utils.js +27 -0
  96. package/src/cli-peer-dependencies.js +7 -1
  97. package/src/cli.js +293 -36
  98. package/src/corePluginList.js +1 -1
  99. package/src/corePlugins.js +428 -285
  100. package/src/css/preflight.css +8 -9
  101. package/src/featureFlags.js +9 -5
  102. package/src/index.js +14 -6
  103. package/src/lib/cacheInvalidation.js +52 -0
  104. package/src/lib/collapseAdjacentRules.js +21 -2
  105. package/src/lib/collapseDuplicateDeclarations.js +66 -1
  106. package/src/lib/defaultExtractor.js +208 -0
  107. package/src/lib/evaluateTailwindFunctions.js +84 -10
  108. package/src/lib/expandApplyAtRules.js +488 -153
  109. package/src/lib/expandTailwindAtRules.js +82 -80
  110. package/src/lib/generateRules.js +352 -120
  111. package/src/lib/normalizeTailwindDirectives.js +7 -1
  112. package/src/lib/offsets.js +239 -0
  113. package/src/lib/partitionApplyAtRules.js +52 -0
  114. package/src/lib/regex.js +74 -0
  115. package/src/lib/resolveDefaultsAtRules.js +59 -17
  116. package/src/lib/setupContextUtils.js +337 -174
  117. package/src/lib/setupTrackingContext.js +13 -8
  118. package/src/lib/sharedState.js +42 -4
  119. package/src/lib/substituteScreenAtRules.js +6 -3
  120. package/src/postcss-plugins/nesting/README.md +42 -0
  121. package/src/postcss-plugins/nesting/index.js +13 -0
  122. package/src/postcss-plugins/nesting/plugin.js +80 -0
  123. package/src/processTailwindFeatures.js +12 -2
  124. package/src/util/buildMediaQuery.js +14 -18
  125. package/src/util/cloneNodes.js +19 -2
  126. package/src/util/color.js +31 -14
  127. package/src/util/dataTypes.js +28 -19
  128. package/src/util/defaults.js +6 -0
  129. package/src/util/formatVariantSelector.js +237 -23
  130. package/src/util/getAllConfigs.js +19 -0
  131. package/src/util/isValidArbitraryValue.js +61 -0
  132. package/src/util/log.js +11 -7
  133. package/src/util/nameClass.js +1 -1
  134. package/src/util/negateValue.js +10 -2
  135. package/src/util/normalizeConfig.js +16 -3
  136. package/src/util/normalizeScreens.js +45 -0
  137. package/src/util/parseBoxShadowValue.js +4 -3
  138. package/src/util/pluginUtils.js +14 -2
  139. package/src/util/prefixSelector.js +7 -5
  140. package/src/util/removeAlphaVariables.js +24 -0
  141. package/src/util/resolveConfig.js +71 -17
  142. package/src/util/splitAtTopLevelOnly.js +45 -0
  143. package/src/util/toPath.js +23 -1
  144. package/src/util/transformThemeValue.js +13 -3
  145. package/src/util/validateConfig.js +13 -0
  146. package/src/util/withAlphaVariable.js +1 -1
  147. package/stubs/defaultConfig.stub.js +24 -3
  148. package/stubs/simpleConfig.stub.js +1 -0
  149. package/types/config.d.ts +334 -0
  150. package/types/generated/.gitkeep +0 -0
  151. package/types/generated/colors.d.ts +276 -0
  152. package/types/generated/corePluginList.d.ts +1 -0
  153. package/types/generated/default-theme.d.ts +331 -0
  154. package/types/index.d.ts +7 -0
  155. package/lib/lib/setupWatchingContext.js +0 -288
  156. package/nesting/plugin.js +0 -41
  157. package/src/lib/setupWatchingContext.js +0 -311
package/src/cli.js CHANGED
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { postcss, lazyCssnano, lazyAutoprefixer } from '../peers/index.js'
3
+ import { lazyPostcss, lazyPostcssImport, lazyCssnano, lazyAutoprefixer } from '../peers/index.js'
4
4
 
5
5
  import chokidar from 'chokidar'
6
6
  import path from 'path'
7
7
  import arg from 'arg'
8
8
  import fs from 'fs'
9
9
  import postcssrc from 'postcss-load-config'
10
- import { cosmiconfig } from 'cosmiconfig'
10
+ import { lilconfig } from 'lilconfig'
11
11
  import loadPlugins from 'postcss-load-config/src/plugins' // Little bit scary, looking at private/internal API
12
+ import loadOptions from 'postcss-load-config/src/options' // Little bit scary, looking at private/internal API
12
13
  import tailwind from './processTailwindFeatures'
13
14
  import resolveConfigInternal from '../resolveConfig'
14
15
  import fastGlob from 'fast-glob'
@@ -16,11 +17,34 @@ import getModuleDependencies from './lib/getModuleDependencies'
16
17
  import log from './util/log'
17
18
  import packageJson from '../package.json'
18
19
  import normalizePath from 'normalize-path'
20
+ import micromatch from 'micromatch'
21
+ import { validateConfig } from './util/validateConfig.js'
19
22
 
20
23
  let env = {
21
24
  DEBUG: process.env.DEBUG !== undefined && process.env.DEBUG !== '0',
22
25
  }
23
26
 
27
+ function isESM() {
28
+ const pkgPath = path.resolve('./package.json')
29
+
30
+ try {
31
+ let pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
32
+ return pkg.type && pkg.type === 'module'
33
+ } catch (err) {
34
+ return false
35
+ }
36
+ }
37
+
38
+ let configs = isESM()
39
+ ? {
40
+ tailwind: 'tailwind.config.cjs',
41
+ postcss: 'postcss.config.cjs',
42
+ }
43
+ : {
44
+ tailwind: 'tailwind.config.js',
45
+ postcss: 'postcss.config.js',
46
+ }
47
+
24
48
  // ---
25
49
 
26
50
  function indentRecursive(node, indent = 0) {
@@ -41,6 +65,26 @@ function formatNodes(root) {
41
65
  }
42
66
  }
43
67
 
68
+ async function outputFile(file, contents) {
69
+ if (fs.existsSync(file) && (await fs.promises.readFile(file, 'utf8')) === contents) {
70
+ return // Skip writing the file
71
+ }
72
+
73
+ // Write the file
74
+ await fs.promises.writeFile(file, contents, 'utf8')
75
+ }
76
+
77
+ function drainStdin() {
78
+ return new Promise((resolve, reject) => {
79
+ let result = ''
80
+ process.stdin.on('data', (chunk) => {
81
+ result += chunk
82
+ })
83
+ process.stdin.on('end', () => resolve(result))
84
+ process.stdin.on('error', (err) => reject(err))
85
+ })
86
+ }
87
+
44
88
  function help({ message, usage, commands, options }) {
45
89
  let indent = 2
46
90
 
@@ -125,12 +169,21 @@ function oneOf(...options) {
125
169
  )
126
170
  }
127
171
 
172
+ function loadPostcss() {
173
+ // Try to load a local `postcss` version first
174
+ try {
175
+ return require('postcss')
176
+ } catch {}
177
+
178
+ return lazyPostcss()
179
+ }
180
+
128
181
  let commands = {
129
182
  init: {
130
183
  run: init,
131
184
  args: {
132
- '--full': { type: Boolean, description: 'Initialize a full `tailwind.config.js` file' },
133
- '--postcss': { type: Boolean, description: 'Initialize a `postcss.config.js` file' },
185
+ '--full': { type: Boolean, description: `Initialize a full \`${configs.tailwind}\` file` },
186
+ '--postcss': { type: Boolean, description: `Initialize a \`${configs.postcss}\` file` },
134
187
  '-f': '--full',
135
188
  '-p': '--postcss',
136
189
  },
@@ -141,6 +194,10 @@ let commands = {
141
194
  '--input': { type: String, description: 'Input file' },
142
195
  '--output': { type: String, description: 'Output file' },
143
196
  '--watch': { type: Boolean, description: 'Watch for changes and rebuild as needed' },
197
+ '--poll': {
198
+ type: Boolean,
199
+ description: 'Use polling instead of filesystem events when watching',
200
+ },
144
201
  '--content': {
145
202
  type: String,
146
203
  description: 'Content paths to use for removing unused classes',
@@ -167,6 +224,7 @@ let commands = {
167
224
  '-o': '--output',
168
225
  '-m': '--minify',
169
226
  '-w': '--watch',
227
+ '-p': '--poll',
170
228
  },
171
229
  },
172
230
  }
@@ -300,7 +358,7 @@ run()
300
358
  function init() {
301
359
  let messages = []
302
360
 
303
- let tailwindConfigLocation = path.resolve(args['_'][1] ?? './tailwind.config.js')
361
+ let tailwindConfigLocation = path.resolve(args['_'][1] ?? `./${configs.tailwind}`)
304
362
  if (fs.existsSync(tailwindConfigLocation)) {
305
363
  messages.push(`${path.basename(tailwindConfigLocation)} already exists.`)
306
364
  } else {
@@ -320,7 +378,7 @@ function init() {
320
378
  }
321
379
 
322
380
  if (args['--postcss']) {
323
- let postcssConfigLocation = path.resolve('./postcss.config.js')
381
+ let postcssConfigLocation = path.resolve(`./${configs.postcss}`)
324
382
  if (fs.existsSync(postcssConfigLocation)) {
325
383
  messages.push(`${path.basename(postcssConfigLocation)} already exists.`)
326
384
  } else {
@@ -347,15 +405,21 @@ async function build() {
347
405
  let input = args['--input']
348
406
  let output = args['--output']
349
407
  let shouldWatch = args['--watch']
408
+ let shouldPoll = args['--poll']
409
+ let shouldCoalesceWriteEvents = shouldPoll || process.platform === 'win32'
350
410
  let includePostCss = args['--postcss']
351
411
 
412
+ // Polling interval in milliseconds
413
+ // Used only when polling or coalescing add/change events on Windows
414
+ let pollInterval = 10
415
+
352
416
  // TODO: Deprecate this in future versions
353
417
  if (!input && args['_'][1]) {
354
418
  console.error('[deprecation] Running tailwindcss without -i, please provide an input file.')
355
419
  input = args['--input'] = args['_'][1]
356
420
  }
357
421
 
358
- if (input && !fs.existsSync((input = path.resolve(input)))) {
422
+ if (input && input !== '-' && !fs.existsSync((input = path.resolve(input)))) {
359
423
  console.error(`Specified input file ${args['--input']} does not exist.`)
360
424
  process.exit(9)
361
425
  }
@@ -368,17 +432,17 @@ async function build() {
368
432
  let configPath = args['--config']
369
433
  ? args['--config']
370
434
  : ((defaultPath) => (fs.existsSync(defaultPath) ? defaultPath : null))(
371
- path.resolve('./tailwind.config.js')
435
+ path.resolve(`./${configs.tailwind}`)
372
436
  )
373
437
 
374
438
  async function loadPostCssPlugins() {
375
439
  let customPostCssPath = typeof args['--postcss'] === 'string' ? args['--postcss'] : undefined
376
- let { plugins: configPlugins } = customPostCssPath
440
+ let config = customPostCssPath
377
441
  ? await (async () => {
378
442
  let file = path.resolve(customPostCssPath)
379
443
 
380
- // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.0.1/src/index.js
381
- let { config = {} } = await cosmiconfig('postcss').load(file)
444
+ // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
445
+ let { config = {} } = await lilconfig('postcss').load(file)
382
446
  if (typeof config === 'function') {
383
447
  config = config()
384
448
  } else {
@@ -389,10 +453,16 @@ async function build() {
389
453
  config.plugins = []
390
454
  }
391
455
 
392
- return { plugins: loadPlugins(config, file) }
456
+ return {
457
+ file,
458
+ plugins: loadPlugins(config, file),
459
+ options: loadOptions(config, file),
460
+ }
393
461
  })()
394
462
  : await postcssrc()
395
463
 
464
+ let configPlugins = config.plugins
465
+
396
466
  let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
397
467
  if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
398
468
  return true
@@ -412,12 +482,50 @@ async function build() {
412
482
  ? configPlugins
413
483
  : configPlugins.slice(configPluginTailwindIdx + 1)
414
484
 
415
- return [beforePlugins, afterPlugins]
485
+ return [beforePlugins, afterPlugins, config.options]
486
+ }
487
+
488
+ function loadBuiltinPostcssPlugins() {
489
+ let postcss = loadPostcss()
490
+ let IMPORT_COMMENT = '__TAILWIND_RESTORE_IMPORT__: '
491
+ return [
492
+ [
493
+ (root) => {
494
+ root.walkAtRules('import', (rule) => {
495
+ if (rule.params.slice(1).startsWith('tailwindcss/')) {
496
+ rule.after(postcss.comment({ text: IMPORT_COMMENT + rule.params }))
497
+ rule.remove()
498
+ }
499
+ })
500
+ },
501
+ (() => {
502
+ try {
503
+ return require('postcss-import')
504
+ } catch {}
505
+
506
+ return lazyPostcssImport()
507
+ })(),
508
+ (root) => {
509
+ root.walkComments((rule) => {
510
+ if (rule.text.startsWith(IMPORT_COMMENT)) {
511
+ rule.after(
512
+ postcss.atRule({
513
+ name: 'import',
514
+ params: rule.text.replace(IMPORT_COMMENT, ''),
515
+ })
516
+ )
517
+ rule.remove()
518
+ }
519
+ })
520
+ },
521
+ ],
522
+ [],
523
+ {},
524
+ ]
416
525
  }
417
526
 
418
527
  function resolveConfig() {
419
528
  let config = configPath ? require(configPath) : {}
420
- let resolvedConfig = resolveConfigInternal(config)
421
529
 
422
530
  if (args['--purge']) {
423
531
  log.warn('purge-flag-deprecated', [
@@ -430,9 +538,15 @@ async function build() {
430
538
  }
431
539
 
432
540
  if (args['--content']) {
433
- resolvedConfig.content.files = args['--content'].split(/(?<!{[^}]+),/)
541
+ let files = args['--content'].split(/(?<!{[^}]+),/)
542
+ let resolvedConfig = resolveConfigInternal(config, { content: { files } })
543
+ resolvedConfig.content.files = files
544
+ resolvedConfig = validateConfig(resolvedConfig)
545
+ return resolvedConfig
434
546
  }
435
547
 
548
+ let resolvedConfig = resolveConfigInternal(config)
549
+ resolvedConfig = validateConfig(resolvedConfig)
436
550
  return resolvedConfig
437
551
  }
438
552
 
@@ -494,7 +608,9 @@ async function build() {
494
608
 
495
609
  tailwindPlugin.postcss = true
496
610
 
497
- let [beforePlugins, afterPlugins] = includePostCss ? await loadPostCssPlugins() : [[], []]
611
+ let [beforePlugins, afterPlugins, postcssOptions] = includePostCss
612
+ ? await loadPostCssPlugins()
613
+ : loadBuiltinPostcssPlugins()
498
614
 
499
615
  let plugins = [
500
616
  ...beforePlugins,
@@ -523,21 +639,23 @@ async function build() {
523
639
  })(),
524
640
  ].filter(Boolean)
525
641
 
642
+ let postcss = loadPostcss()
526
643
  let processor = postcss(plugins)
527
644
 
528
645
  function processCSS(css) {
529
646
  let start = process.hrtime.bigint()
530
647
  return Promise.resolve()
531
648
  .then(() => (output ? fs.promises.mkdir(path.dirname(output), { recursive: true }) : null))
532
- .then(() => processor.process(css, { from: input, to: output }))
649
+ .then(() => processor.process(css, { ...postcssOptions, from: input, to: output }))
533
650
  .then((result) => {
534
651
  if (!output) {
535
652
  return process.stdout.write(result.css)
536
653
  }
654
+
537
655
  return Promise.all(
538
656
  [
539
- fs.promises.writeFile(output, result.css, () => true),
540
- result.map && fs.writeFile(output + '.map', result.map.toString(), () => true),
657
+ outputFile(output, result.css),
658
+ result.map && outputFile(output + '.map', result.map.toString()),
541
659
  ].filter(Boolean)
542
660
  )
543
661
  })
@@ -548,9 +666,21 @@ async function build() {
548
666
  })
549
667
  }
550
668
 
551
- let css = input
552
- ? fs.readFileSync(path.resolve(input), 'utf8')
553
- : '@tailwind base; @tailwind components; @tailwind utilities'
669
+ let css = await (() => {
670
+ // Piping in data, let's drain the stdin
671
+ if (input === '-') {
672
+ return drainStdin()
673
+ }
674
+
675
+ // Input file has been provided
676
+ if (input) {
677
+ return fs.readFileSync(path.resolve(input), 'utf8')
678
+ }
679
+
680
+ // No input file provided, fallback to default atrules
681
+ return '@tailwind base; @tailwind components; @tailwind utilities'
682
+ })()
683
+
554
684
  return processCSS(css)
555
685
  }
556
686
 
@@ -580,7 +710,9 @@ async function build() {
580
710
  return resolveConfig()
581
711
  }
582
712
 
583
- let [beforePlugins, afterPlugins] = includePostCss ? await loadPostCssPlugins() : [[], []]
713
+ let [beforePlugins, afterPlugins] = includePostCss
714
+ ? await loadPostCssPlugins()
715
+ : loadBuiltinPostcssPlugins()
584
716
 
585
717
  let plugins = [
586
718
  ...beforePlugins,
@@ -643,6 +775,7 @@ async function build() {
643
775
  let tailwindPluginIdx = plugins.indexOf('__TAILWIND_PLUGIN_POSITION__')
644
776
  let copy = plugins.slice()
645
777
  copy.splice(tailwindPluginIdx, 1, tailwindPlugin)
778
+ let postcss = loadPostcss()
646
779
  let processor = postcss(copy)
647
780
 
648
781
  function processCSS(css) {
@@ -664,10 +797,10 @@ async function build() {
664
797
  return process.stdout.write(result.css)
665
798
  }
666
799
 
667
- await Promise.all(
800
+ return Promise.all(
668
801
  [
669
- fs.promises.writeFile(output, result.css, () => true),
670
- result.map && fs.writeFile(output + '.map', result.map.toString(), () => true),
802
+ outputFile(output, result.css),
803
+ result.map && outputFile(output + '.map', result.map.toString()),
671
804
  ].filter(Boolean)
672
805
  )
673
806
  })
@@ -684,38 +817,75 @@ async function build() {
684
817
  })
685
818
  }
686
819
 
687
- let css = input
688
- ? fs.readFileSync(path.resolve(input), 'utf8')
689
- : '@tailwind base; @tailwind components; @tailwind utilities'
820
+ let css = await (() => {
821
+ // Piping in data, let's drain the stdin
822
+ if (input === '-') {
823
+ return drainStdin()
824
+ }
825
+
826
+ // Input file has been provided
827
+ if (input) {
828
+ return fs.readFileSync(path.resolve(input), 'utf8')
829
+ }
830
+
831
+ // No input file provided, fallback to default atrules
832
+ return '@tailwind base; @tailwind components; @tailwind utilities'
833
+ })()
834
+
690
835
  let result = await processCSS(css)
691
836
  env.DEBUG && console.timeEnd('Finished in')
692
837
  return result
693
838
  }
694
839
 
695
840
  let config = refreshConfig(configPath)
841
+ let contentPatterns = refreshContentPatterns(config)
842
+
843
+ /**
844
+ * @param {import('../types/config.js').RequiredConfig} config
845
+ * @return {{all: string[], dynamic: string[], static: string[]}}
846
+ **/
847
+ function refreshContentPatterns(config) {
848
+ let globs = extractFileGlobs(config)
849
+ let tasks = fastGlob.generateTasks(globs, { absolute: true })
850
+ let dynamicPatterns = tasks.filter((task) => task.dynamic).flatMap((task) => task.patterns)
851
+ let staticPatterns = tasks.filter((task) => !task.dynamic).flatMap((task) => task.patterns)
852
+
853
+ return {
854
+ all: [...staticPatterns, ...dynamicPatterns],
855
+ dynamic: dynamicPatterns,
856
+ }
857
+ }
696
858
 
697
859
  if (input) {
698
860
  contextDependencies.add(path.resolve(input))
699
861
  }
700
862
 
701
863
  watcher = chokidar.watch([...contextDependencies, ...extractFileGlobs(config)], {
864
+ // Force checking for atomic writes in all situations
865
+ // This causes chokidar to wait up to 100ms for a file to re-added after it's been unlinked
866
+ // This only works when watching directories though
867
+ atomic: true,
868
+
869
+ usePolling: shouldPoll,
870
+ interval: shouldPoll ? pollInterval : undefined,
702
871
  ignoreInitial: true,
703
- awaitWriteFinish:
704
- process.platform === 'win32'
705
- ? {
706
- stabilityThreshold: 50,
707
- pollInterval: 10,
708
- }
709
- : false,
872
+ awaitWriteFinish: shouldCoalesceWriteEvents
873
+ ? {
874
+ stabilityThreshold: 50,
875
+ pollInterval: pollInterval,
876
+ }
877
+ : false,
710
878
  })
711
879
 
712
880
  let chain = Promise.resolve()
881
+ let pendingRebuilds = new Set()
713
882
 
714
883
  watcher.on('change', async (file) => {
715
884
  if (contextDependencies.has(file)) {
716
885
  env.DEBUG && console.time('Resolve config')
717
886
  context = null
718
887
  config = refreshConfig(configPath)
888
+ contentPatterns = refreshContentPatterns(config)
719
889
  env.DEBUG && console.timeEnd('Resolve config')
720
890
 
721
891
  env.DEBUG && console.time('Watch new files')
@@ -740,6 +910,93 @@ async function build() {
740
910
  }
741
911
  })
742
912
 
913
+ /**
914
+ * When rapidly saving files atomically a couple of situations can happen:
915
+ * - The file is missing since the external program has deleted it by the time we've gotten around to reading it from the earlier save.
916
+ * - The file is being written to by the external program by the time we're going to read it and is thus treated as busy because a lock is held.
917
+ *
918
+ * To work around this we retry reading the file a handful of times with a delay between each attempt
919
+ *
920
+ * @param {string} path
921
+ * @param {number} tries
922
+ * @returns {string}
923
+ * @throws {Error} If the file is still missing or busy after the specified number of tries
924
+ */
925
+ async function readFileWithRetries(path, tries = 5) {
926
+ for (let n = 0; n <= tries; n++) {
927
+ try {
928
+ return await fs.promises.readFile(path, 'utf8')
929
+ } catch (err) {
930
+ if (n !== tries) {
931
+ if (err.code === 'ENOENT' || err.code === 'EBUSY') {
932
+ await new Promise((resolve) => setTimeout(resolve, 10))
933
+
934
+ continue
935
+ }
936
+ }
937
+
938
+ throw err
939
+ }
940
+ }
941
+ }
942
+
943
+ // Restore watching any files that are "removed"
944
+ // This can happen when a file is pseudo-atomically replaced (a copy is created, overwritten, the old one is unlinked, and the new one is renamed)
945
+ // TODO: An an optimization we should allow removal when the config changes
946
+ watcher.on('unlink', (file) => {
947
+ file = normalizePath(file)
948
+
949
+ // Only re-add the file if it's not covered by a dynamic pattern
950
+ if (!micromatch.some([file], contentPatterns.dynamic)) {
951
+ watcher.add(file)
952
+ }
953
+ })
954
+
955
+ // Some applications such as Visual Studio (but not VS Code)
956
+ // will only fire a rename event for atomic writes and not a change event
957
+ // This is very likely a chokidar bug but it's one we need to work around
958
+ // We treat this as a change event and rebuild the CSS
959
+ watcher.on('raw', (evt, filePath, meta) => {
960
+ if (evt !== 'rename') {
961
+ return
962
+ }
963
+
964
+ let watchedPath = meta.watchedPath
965
+
966
+ // Watched path might be the file itself
967
+ // Or the directory it is in
968
+ filePath = watchedPath.endsWith(filePath) ? watchedPath : path.join(watchedPath, filePath)
969
+
970
+ // Skip this event since the files it is for does not match any of the registered content globs
971
+ if (!micromatch.some([filePath], contentPatterns.all)) {
972
+ return
973
+ }
974
+
975
+ // Skip since we've already queued a rebuild for this file that hasn't happened yet
976
+ if (pendingRebuilds.has(filePath)) {
977
+ return
978
+ }
979
+
980
+ pendingRebuilds.add(filePath)
981
+
982
+ chain = chain.then(async () => {
983
+ let content
984
+
985
+ try {
986
+ content = await readFileWithRetries(path.resolve(filePath))
987
+ } finally {
988
+ pendingRebuilds.delete(filePath)
989
+ }
990
+
991
+ changedContent.push({
992
+ content,
993
+ extension: path.extname(filePath).slice(1),
994
+ })
995
+
996
+ await rebuild(config)
997
+ })
998
+ })
999
+
743
1000
  watcher.on('add', async (file) => {
744
1001
  chain = chain.then(async () => {
745
1002
  changedContent.push({
@@ -1 +1 @@
1
- export default ["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","display","aspectRatio","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","borderCollapse","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","whitespace","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","content"]
1
+ export default ["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","display","aspectRatio","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","borderCollapse","borderSpacing","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","whitespace","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","textDecorationStyle","textDecorationThickness","textUnderlineOffset","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","content"]