tailwindcss 0.0.0-insiders.ea80db2 → 0.0.0-insiders.eae2b7a

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 (213) hide show
  1. package/README.md +13 -9
  2. package/defaultTheme.d.ts +2 -1
  3. package/index.css +5 -0
  4. package/lib/cli/build/index.js +57 -0
  5. package/lib/cli/build/plugin.js +427 -0
  6. package/lib/cli/build/utils.js +88 -0
  7. package/lib/cli/build/watching.js +182 -0
  8. package/lib/cli/help/index.js +73 -0
  9. package/lib/cli/index.js +231 -0
  10. package/lib/cli/init/index.js +63 -0
  11. package/lib/cli.js +1 -759
  12. package/lib/corePluginList.js +12 -3
  13. package/lib/corePlugins.js +2308 -1739
  14. package/lib/css/preflight.css +13 -5
  15. package/lib/featureFlags.js +50 -25
  16. package/lib/index.js +1 -40
  17. package/lib/lib/cacheInvalidation.js +48 -25
  18. package/lib/lib/collapseAdjacentRules.js +17 -10
  19. package/lib/lib/collapseDuplicateDeclarations.js +13 -8
  20. package/lib/lib/content.js +207 -0
  21. package/lib/lib/defaultExtractor.js +232 -33
  22. package/lib/lib/detectNesting.js +21 -10
  23. package/lib/lib/evaluateTailwindFunctions.js +117 -50
  24. package/lib/lib/expandApplyAtRules.js +316 -215
  25. package/lib/lib/expandTailwindAtRules.js +167 -115
  26. package/lib/lib/findAtConfigPath.js +46 -0
  27. package/lib/lib/generateRules.js +444 -211
  28. package/lib/lib/getModuleDependencies.js +88 -37
  29. package/lib/lib/handleImportAtRules.js +50 -0
  30. package/lib/lib/load-config.js +42 -0
  31. package/lib/lib/normalizeTailwindDirectives.js +29 -39
  32. package/lib/lib/offsets.js +306 -0
  33. package/lib/lib/partitionApplyAtRules.js +13 -8
  34. package/lib/lib/regex.js +74 -0
  35. package/lib/lib/remap-bitfield.js +89 -0
  36. package/lib/lib/resolveDefaultsAtRules.js +96 -74
  37. package/lib/lib/setupContextUtils.js +672 -300
  38. package/lib/lib/setupTrackingContext.js +63 -68
  39. package/lib/lib/sharedState.js +44 -17
  40. package/lib/lib/substituteScreenAtRules.js +14 -10
  41. package/lib/plugin.js +160 -0
  42. package/lib/postcss-plugins/nesting/README.md +2 -2
  43. package/lib/postcss-plugins/nesting/index.js +10 -6
  44. package/lib/postcss-plugins/nesting/plugin.js +24 -20
  45. package/lib/processTailwindFeatures.js +34 -29
  46. package/lib/public/colors.js +272 -246
  47. package/lib/public/create-plugin.js +9 -5
  48. package/lib/public/default-config.js +10 -6
  49. package/lib/public/default-theme.js +10 -6
  50. package/lib/public/load-config.js +12 -0
  51. package/lib/public/resolve-config.js +11 -6
  52. package/lib/util/applyImportantSelector.js +36 -0
  53. package/lib/util/bigSign.js +6 -1
  54. package/lib/util/buildMediaQuery.js +13 -6
  55. package/lib/util/cloneDeep.js +9 -6
  56. package/lib/util/cloneNodes.js +12 -3
  57. package/lib/util/color.js +66 -50
  58. package/lib/util/colorNames.js +752 -0
  59. package/lib/util/configurePlugins.js +7 -2
  60. package/lib/util/createPlugin.js +8 -5
  61. package/lib/util/createUtilityPlugin.js +13 -9
  62. package/lib/util/dataTypes.js +182 -111
  63. package/lib/util/defaults.js +12 -7
  64. package/lib/util/escapeClassName.js +13 -8
  65. package/lib/util/escapeCommas.js +7 -2
  66. package/lib/util/flattenColorPalette.js +11 -10
  67. package/lib/util/formatVariantSelector.js +228 -151
  68. package/lib/util/getAllConfigs.js +33 -12
  69. package/lib/util/hashConfig.js +9 -4
  70. package/lib/util/isKeyframeRule.js +7 -2
  71. package/lib/util/isPlainObject.js +7 -2
  72. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +25 -15
  73. package/lib/util/log.js +40 -13
  74. package/lib/util/nameClass.js +27 -10
  75. package/lib/util/negateValue.js +25 -8
  76. package/lib/util/normalizeConfig.js +155 -87
  77. package/lib/util/normalizeScreens.js +127 -8
  78. package/lib/util/parseAnimationValue.js +44 -40
  79. package/lib/util/parseBoxShadowValue.js +33 -62
  80. package/lib/util/parseDependency.js +39 -55
  81. package/lib/util/parseGlob.js +36 -0
  82. package/lib/util/parseObjectStyles.js +15 -10
  83. package/lib/util/pluginUtils.js +154 -59
  84. package/lib/util/prefixSelector.js +29 -10
  85. package/lib/util/pseudoElements.js +209 -0
  86. package/lib/util/removeAlphaVariables.js +31 -0
  87. package/lib/util/resolveConfig.js +96 -95
  88. package/lib/util/resolveConfigPath.js +29 -10
  89. package/lib/util/responsive.js +11 -6
  90. package/lib/util/splitAtTopLevelOnly.js +51 -0
  91. package/lib/util/tap.js +6 -1
  92. package/lib/util/toColorValue.js +7 -2
  93. package/lib/util/toPath.js +22 -4
  94. package/lib/util/transformThemeValue.js +40 -26
  95. package/lib/util/validateConfig.js +48 -0
  96. package/lib/util/validateFormalSyntax.js +26 -0
  97. package/lib/util/withAlphaVariable.js +27 -15
  98. package/lib/value-parser/LICENSE +22 -0
  99. package/lib/value-parser/README.md +3 -0
  100. package/lib/value-parser/index.d.js +2 -0
  101. package/lib/value-parser/index.js +22 -0
  102. package/lib/value-parser/parse.js +259 -0
  103. package/lib/value-parser/stringify.js +38 -0
  104. package/lib/value-parser/unit.js +86 -0
  105. package/lib/value-parser/walk.js +16 -0
  106. package/loadConfig.d.ts +4 -0
  107. package/loadConfig.js +2 -0
  108. package/package.json +54 -52
  109. package/plugin.d.ts +10 -5
  110. package/resolveConfig.d.ts +12 -0
  111. package/scripts/generate-types.js +53 -0
  112. package/scripts/release-channel.js +18 -0
  113. package/scripts/release-notes.js +21 -0
  114. package/scripts/type-utils.js +27 -0
  115. package/src/cli/build/index.js +53 -0
  116. package/src/cli/build/plugin.js +465 -0
  117. package/src/cli/build/utils.js +76 -0
  118. package/src/cli/build/watching.js +229 -0
  119. package/src/cli/help/index.js +70 -0
  120. package/src/cli/index.js +217 -0
  121. package/src/cli/init/index.js +79 -0
  122. package/src/cli.js +1 -836
  123. package/src/corePluginList.js +1 -1
  124. package/src/corePlugins.js +576 -106
  125. package/src/css/preflight.css +13 -5
  126. package/src/featureFlags.js +17 -3
  127. package/src/index.js +1 -42
  128. package/src/lib/collapseAdjacentRules.js +5 -1
  129. package/src/lib/content.js +240 -0
  130. package/src/lib/defaultExtractor.js +202 -35
  131. package/src/lib/detectNesting.js +9 -1
  132. package/src/lib/evaluateTailwindFunctions.js +82 -8
  133. package/src/lib/expandApplyAtRules.js +322 -189
  134. package/src/lib/expandTailwindAtRules.js +82 -59
  135. package/src/lib/findAtConfigPath.js +48 -0
  136. package/src/lib/generateRules.js +413 -132
  137. package/src/lib/getModuleDependencies.js +70 -30
  138. package/src/lib/handleImportAtRules.js +34 -0
  139. package/src/lib/load-config.ts +31 -0
  140. package/src/lib/normalizeTailwindDirectives.js +0 -27
  141. package/src/lib/offsets.js +373 -0
  142. package/src/lib/regex.js +74 -0
  143. package/src/lib/remap-bitfield.js +82 -0
  144. package/src/lib/resolveDefaultsAtRules.js +53 -36
  145. package/src/lib/setupContextUtils.js +570 -151
  146. package/src/lib/setupTrackingContext.js +44 -58
  147. package/src/lib/sharedState.js +13 -4
  148. package/src/plugin.js +128 -0
  149. package/src/postcss-plugins/nesting/README.md +2 -2
  150. package/src/public/colors.js +22 -0
  151. package/src/public/default-config.js +1 -1
  152. package/src/public/default-theme.js +2 -2
  153. package/src/public/load-config.js +2 -0
  154. package/src/util/applyImportantSelector.js +27 -0
  155. package/src/util/buildMediaQuery.js +5 -3
  156. package/src/util/cloneNodes.js +5 -1
  157. package/src/util/color.js +34 -17
  158. package/src/util/colorNames.js +150 -0
  159. package/src/util/dataTypes.js +67 -23
  160. package/src/util/formatVariantSelector.js +264 -144
  161. package/src/util/getAllConfigs.js +21 -2
  162. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  163. package/src/util/log.js +25 -1
  164. package/src/util/nameClass.js +4 -0
  165. package/src/util/negateValue.js +11 -3
  166. package/src/util/normalizeConfig.js +78 -20
  167. package/src/util/normalizeScreens.js +99 -4
  168. package/src/util/parseBoxShadowValue.js +3 -50
  169. package/src/util/parseDependency.js +37 -42
  170. package/src/util/parseGlob.js +24 -0
  171. package/src/util/pluginUtils.js +118 -23
  172. package/src/util/prefixSelector.js +28 -10
  173. package/src/util/pseudoElements.js +167 -0
  174. package/src/util/removeAlphaVariables.js +24 -0
  175. package/src/util/resolveConfig.js +70 -62
  176. package/src/util/resolveConfigPath.js +12 -1
  177. package/src/util/splitAtTopLevelOnly.js +52 -0
  178. package/src/util/toPath.js +1 -1
  179. package/src/util/transformThemeValue.js +13 -3
  180. package/src/util/validateConfig.js +36 -0
  181. package/src/util/validateFormalSyntax.js +34 -0
  182. package/src/util/withAlphaVariable.js +1 -1
  183. package/src/value-parser/LICENSE +22 -0
  184. package/src/value-parser/README.md +3 -0
  185. package/src/value-parser/index.d.ts +177 -0
  186. package/src/value-parser/index.js +28 -0
  187. package/src/value-parser/parse.js +303 -0
  188. package/src/value-parser/stringify.js +41 -0
  189. package/src/value-parser/unit.js +118 -0
  190. package/src/value-parser/walk.js +18 -0
  191. package/stubs/.gitignore +1 -0
  192. package/stubs/.prettierrc.json +6 -0
  193. package/stubs/{defaultConfig.stub.js → config.full.js} +215 -165
  194. package/stubs/{simpleConfig.stub.js → config.simple.js} +1 -1
  195. package/stubs/{defaultPostCssConfig.stub.js → postcss.config.cjs} +0 -1
  196. package/stubs/postcss.config.js +5 -0
  197. package/stubs/tailwind.config.cjs +2 -0
  198. package/stubs/tailwind.config.js +2 -0
  199. package/stubs/tailwind.config.ts +3 -0
  200. package/types/config.d.ts +102 -56
  201. package/types/generated/colors.d.ts +22 -0
  202. package/types/generated/corePluginList.d.ts +1 -1
  203. package/types/generated/default-theme.d.ts +372 -0
  204. package/types/index.d.ts +7 -1
  205. package/CHANGELOG.md +0 -2099
  206. package/lib/cli-peer-dependencies.js +0 -15
  207. package/lib/constants.js +0 -37
  208. package/peers/index.js +0 -75156
  209. package/scripts/install-integrations.js +0 -27
  210. package/scripts/rebuildFixtures.js +0 -68
  211. package/src/cli-peer-dependencies.js +0 -9
  212. package/src/constants.js +0 -17
  213. package/types.d.ts +0 -1
package/src/cli.js CHANGED
@@ -1,838 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { postcss, lazyCssnano, lazyAutoprefixer } from '../peers/index.js'
4
-
5
- import chokidar from 'chokidar'
6
- import path from 'path'
7
- import arg from 'arg'
8
- import fs from 'fs'
9
- import postcssrc from 'postcss-load-config'
10
- import { lilconfig } from 'lilconfig'
11
- import loadPlugins from 'postcss-load-config/src/plugins' // Little bit scary, looking at private/internal API
12
- import tailwind from './processTailwindFeatures'
13
- import resolveConfigInternal from '../resolveConfig'
14
- import fastGlob from 'fast-glob'
15
- import getModuleDependencies from './lib/getModuleDependencies'
16
- import log from './util/log'
17
- import packageJson from '../package.json'
18
- import normalizePath from 'normalize-path'
19
-
20
- let env = {
21
- DEBUG: process.env.DEBUG !== undefined && process.env.DEBUG !== '0',
22
- }
23
-
24
- // ---
25
-
26
- function indentRecursive(node, indent = 0) {
27
- node.each &&
28
- node.each((child, i) => {
29
- if (!child.raws.before || !child.raws.before.trim() || child.raws.before.includes('\n')) {
30
- child.raws.before = `\n${node.type !== 'rule' && i > 0 ? '\n' : ''}${' '.repeat(indent)}`
31
- }
32
- child.raws.after = `\n${' '.repeat(indent)}`
33
- indentRecursive(child, indent + 1)
34
- })
35
- }
36
-
37
- function formatNodes(root) {
38
- indentRecursive(root)
39
- if (root.first) {
40
- root.first.raws.before = ''
41
- }
42
- }
43
-
44
- async function outputFile(file, contents) {
45
- if (fs.existsSync(file) && (await fs.promises.readFile(file, 'utf8')) === contents) {
46
- return // Skip writing the file
47
- }
48
-
49
- // Write the file
50
- await fs.promises.writeFile(file, contents, 'utf8')
51
- }
52
-
53
- function drainStdin() {
54
- return new Promise((resolve, reject) => {
55
- let result = ''
56
- process.stdin.on('data', (chunk) => {
57
- result += chunk
58
- })
59
- process.stdin.on('end', () => resolve(result))
60
- process.stdin.on('error', (err) => reject(err))
61
- })
62
- }
63
-
64
- function help({ message, usage, commands, options }) {
65
- let indent = 2
66
-
67
- // Render header
68
- console.log()
69
- console.log(`${packageJson.name} v${packageJson.version}`)
70
-
71
- // Render message
72
- if (message) {
73
- console.log()
74
- for (let msg of message.split('\n')) {
75
- console.log(msg)
76
- }
77
- }
78
-
79
- // Render usage
80
- if (usage && usage.length > 0) {
81
- console.log()
82
- console.log('Usage:')
83
- for (let example of usage) {
84
- console.log(' '.repeat(indent), example)
85
- }
86
- }
87
-
88
- // Render commands
89
- if (commands && commands.length > 0) {
90
- console.log()
91
- console.log('Commands:')
92
- for (let command of commands) {
93
- console.log(' '.repeat(indent), command)
94
- }
95
- }
96
-
97
- // Render options
98
- if (options) {
99
- let groupedOptions = {}
100
- for (let [key, value] of Object.entries(options)) {
101
- if (typeof value === 'object') {
102
- groupedOptions[key] = { ...value, flags: [key] }
103
- } else {
104
- groupedOptions[value].flags.push(key)
105
- }
106
- }
107
-
108
- console.log()
109
- console.log('Options:')
110
- for (let { flags, description, deprecated } of Object.values(groupedOptions)) {
111
- if (deprecated) continue
112
-
113
- if (flags.length === 1) {
114
- console.log(
115
- ' '.repeat(indent + 4 /* 4 = "-i, ".length */),
116
- flags.slice().reverse().join(', ').padEnd(20, ' '),
117
- description
118
- )
119
- } else {
120
- console.log(
121
- ' '.repeat(indent),
122
- flags.slice().reverse().join(', ').padEnd(24, ' '),
123
- description
124
- )
125
- }
126
- }
127
- }
128
-
129
- console.log()
130
- }
131
-
132
- function oneOf(...options) {
133
- return Object.assign(
134
- (value = true) => {
135
- for (let option of options) {
136
- let parsed = option(value)
137
- if (parsed === value) {
138
- return parsed
139
- }
140
- }
141
-
142
- throw new Error('...')
143
- },
144
- { manualParsing: true }
145
- )
146
- }
147
-
148
- let commands = {
149
- init: {
150
- run: init,
151
- args: {
152
- '--full': { type: Boolean, description: 'Initialize a full `tailwind.config.js` file' },
153
- '--postcss': { type: Boolean, description: 'Initialize a `postcss.config.js` file' },
154
- '--types': {
155
- type: Boolean,
156
- description: 'Add TypeScript types for the `tailwind.config.js` file',
157
- },
158
- '-f': '--full',
159
- '-p': '--postcss',
160
- },
161
- },
162
- build: {
163
- run: build,
164
- args: {
165
- '--input': { type: String, description: 'Input file' },
166
- '--output': { type: String, description: 'Output file' },
167
- '--watch': { type: Boolean, description: 'Watch for changes and rebuild as needed' },
168
- '--poll': {
169
- type: Boolean,
170
- description: 'Use polling instead of filesystem events when watching',
171
- },
172
- '--content': {
173
- type: String,
174
- description: 'Content paths to use for removing unused classes',
175
- },
176
- '--purge': {
177
- type: String,
178
- deprecated: true,
179
- },
180
- '--postcss': {
181
- type: oneOf(String, Boolean),
182
- description: 'Load custom PostCSS configuration',
183
- },
184
- '--minify': { type: Boolean, description: 'Minify the output' },
185
- '--config': {
186
- type: String,
187
- description: 'Path to a custom config file',
188
- },
189
- '--no-autoprefixer': {
190
- type: Boolean,
191
- description: 'Disable autoprefixer',
192
- },
193
- '-c': '--config',
194
- '-i': '--input',
195
- '-o': '--output',
196
- '-m': '--minify',
197
- '-w': '--watch',
198
- '-p': '--poll',
199
- },
200
- },
201
- }
202
-
203
- let sharedFlags = {
204
- '--help': { type: Boolean, description: 'Display usage information' },
205
- '-h': '--help',
206
- }
207
-
208
- if (
209
- process.stdout.isTTY /* Detect redirecting output to a file */ &&
210
- (process.argv[2] === undefined ||
211
- process.argv.slice(2).every((flag) => sharedFlags[flag] !== undefined))
212
- ) {
213
- help({
214
- usage: [
215
- 'tailwindcss [--input input.css] [--output output.css] [--watch] [options...]',
216
- 'tailwindcss init [--full] [--postcss] [--types] [options...]',
217
- ],
218
- commands: Object.keys(commands)
219
- .filter((command) => command !== 'build')
220
- .map((command) => `${command} [options]`),
221
- options: { ...commands.build.args, ...sharedFlags },
222
- })
223
- process.exit(0)
224
- }
225
-
226
- let command = ((arg = '') => (arg.startsWith('-') ? undefined : arg))(process.argv[2]) || 'build'
227
-
228
- if (commands[command] === undefined) {
229
- if (fs.existsSync(path.resolve(command))) {
230
- // TODO: Deprecate this in future versions
231
- // Check if non-existing command, might be a file.
232
- command = 'build'
233
- } else {
234
- help({
235
- message: `Invalid command: ${command}`,
236
- usage: ['tailwindcss <command> [options]'],
237
- commands: Object.keys(commands)
238
- .filter((command) => command !== 'build')
239
- .map((command) => `${command} [options]`),
240
- options: sharedFlags,
241
- })
242
- process.exit(1)
243
- }
244
- }
245
-
246
- // Execute command
247
- let { args: flags, run } = commands[command]
248
- let args = (() => {
249
- try {
250
- let result = arg(
251
- Object.fromEntries(
252
- Object.entries({ ...flags, ...sharedFlags })
253
- .filter(([_key, value]) => !value?.type?.manualParsing)
254
- .map(([key, value]) => [key, typeof value === 'object' ? value.type : value])
255
- ),
256
- { permissive: true }
257
- )
258
-
259
- // Manual parsing of flags to allow for special flags like oneOf(Boolean, String)
260
- for (let i = result['_'].length - 1; i >= 0; --i) {
261
- let flag = result['_'][i]
262
- if (!flag.startsWith('-')) continue
263
-
264
- let flagName = flag
265
- let handler = flags[flag]
266
-
267
- // Resolve flagName & handler
268
- while (typeof handler === 'string') {
269
- flagName = handler
270
- handler = flags[handler]
271
- }
272
-
273
- if (!handler) continue
274
-
275
- let args = []
276
- let offset = i + 1
277
-
278
- // Parse args for current flag
279
- while (result['_'][offset] && !result['_'][offset].startsWith('-')) {
280
- args.push(result['_'][offset++])
281
- }
282
-
283
- // Cleanup manually parsed flags + args
284
- result['_'].splice(i, 1 + args.length)
285
-
286
- // Set the resolved value in the `result` object
287
- result[flagName] = handler.type(
288
- args.length === 0 ? undefined : args.length === 1 ? args[0] : args,
289
- flagName
290
- )
291
- }
292
-
293
- // Ensure that the `command` is always the first argument in the `args`.
294
- // This is important so that we don't have to check if a default command
295
- // (build) was used or not from within each plugin.
296
- //
297
- // E.g.: tailwindcss input.css -> _: ['build', 'input.css']
298
- // E.g.: tailwindcss build input.css -> _: ['build', 'input.css']
299
- if (result['_'][0] !== command) {
300
- result['_'].unshift(command)
301
- }
302
-
303
- return result
304
- } catch (err) {
305
- if (err.code === 'ARG_UNKNOWN_OPTION') {
306
- help({
307
- message: err.message,
308
- usage: ['tailwindcss <command> [options]'],
309
- options: sharedFlags,
310
- })
311
- process.exit(1)
312
- }
313
- throw err
314
- }
315
- })()
316
-
317
- if (args['--help']) {
318
- help({
319
- options: { ...flags, ...sharedFlags },
320
- usage: [`tailwindcss ${command} [options]`],
321
- })
322
- process.exit(0)
323
- }
324
-
325
- run()
326
-
327
- // ---
328
-
329
- function init() {
330
- let messages = []
331
-
332
- let tailwindConfigLocation = path.resolve(args['_'][1] ?? './tailwind.config.js')
333
- if (fs.existsSync(tailwindConfigLocation)) {
334
- messages.push(`${path.basename(tailwindConfigLocation)} already exists.`)
335
- } else {
336
- let stubFile = fs.readFileSync(
337
- args['--full']
338
- ? path.resolve(__dirname, '../stubs/defaultConfig.stub.js')
339
- : path.resolve(__dirname, '../stubs/simpleConfig.stub.js'),
340
- 'utf8'
341
- )
342
-
343
- if (args['--types']) {
344
- let typesHeading = "/** @type {import('tailwindcss/types').Config} */"
345
- stubFile =
346
- stubFile.replace(`module.exports = `, `${typesHeading}\nconst config = `) +
347
- '\nmodule.exports = config'
348
- }
349
-
350
- // Change colors import
351
- stubFile = stubFile.replace('../colors', 'tailwindcss/colors')
352
-
353
- fs.writeFileSync(tailwindConfigLocation, stubFile, 'utf8')
354
-
355
- messages.push(`Created Tailwind CSS config file: ${path.basename(tailwindConfigLocation)}`)
356
- }
357
-
358
- if (args['--postcss']) {
359
- let postcssConfigLocation = path.resolve('./postcss.config.js')
360
- if (fs.existsSync(postcssConfigLocation)) {
361
- messages.push(`${path.basename(postcssConfigLocation)} already exists.`)
362
- } else {
363
- let stubFile = fs.readFileSync(
364
- path.resolve(__dirname, '../stubs/defaultPostCssConfig.stub.js'),
365
- 'utf8'
366
- )
367
-
368
- fs.writeFileSync(postcssConfigLocation, stubFile, 'utf8')
369
-
370
- messages.push(`Created PostCSS config file: ${path.basename(postcssConfigLocation)}`)
371
- }
372
- }
373
-
374
- if (messages.length > 0) {
375
- console.log()
376
- for (let message of messages) {
377
- console.log(message)
378
- }
379
- }
380
- }
381
-
382
- async function build() {
383
- let input = args['--input']
384
- let output = args['--output']
385
- let shouldWatch = args['--watch']
386
- let shouldPoll = args['--poll']
387
- let shouldCoalesceWriteEvents = shouldPoll || process.platform === 'win32'
388
- let includePostCss = args['--postcss']
389
-
390
- // Polling interval in milliseconds
391
- // Used only when polling or coalescing add/change events on Windows
392
- let pollInterval = 10
393
-
394
- // TODO: Deprecate this in future versions
395
- if (!input && args['_'][1]) {
396
- console.error('[deprecation] Running tailwindcss without -i, please provide an input file.')
397
- input = args['--input'] = args['_'][1]
398
- }
399
-
400
- if (input && input !== '-' && !fs.existsSync((input = path.resolve(input)))) {
401
- console.error(`Specified input file ${args['--input']} does not exist.`)
402
- process.exit(9)
403
- }
404
-
405
- if (args['--config'] && !fs.existsSync((args['--config'] = path.resolve(args['--config'])))) {
406
- console.error(`Specified config file ${args['--config']} does not exist.`)
407
- process.exit(9)
408
- }
409
-
410
- let configPath = args['--config']
411
- ? args['--config']
412
- : ((defaultPath) => (fs.existsSync(defaultPath) ? defaultPath : null))(
413
- path.resolve('./tailwind.config.js')
414
- )
415
-
416
- async function loadPostCssPlugins() {
417
- let customPostCssPath = typeof args['--postcss'] === 'string' ? args['--postcss'] : undefined
418
- let { plugins: configPlugins } = customPostCssPath
419
- ? await (async () => {
420
- let file = path.resolve(customPostCssPath)
421
-
422
- // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
423
- let { config = {} } = await lilconfig('postcss').load(file)
424
- if (typeof config === 'function') {
425
- config = config()
426
- } else {
427
- config = Object.assign({}, config)
428
- }
429
-
430
- if (!config.plugins) {
431
- config.plugins = []
432
- }
433
-
434
- return { plugins: loadPlugins(config, file) }
435
- })()
436
- : await postcssrc()
437
-
438
- let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
439
- if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
440
- return true
441
- }
442
-
443
- if (typeof plugin === 'object' && plugin !== null && plugin.postcssPlugin === 'tailwindcss') {
444
- return true
445
- }
446
-
447
- return false
448
- })
449
-
450
- let beforePlugins =
451
- configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx)
452
- let afterPlugins =
453
- configPluginTailwindIdx === -1
454
- ? configPlugins
455
- : configPlugins.slice(configPluginTailwindIdx + 1)
456
-
457
- return [beforePlugins, afterPlugins]
458
- }
459
-
460
- function resolveConfig() {
461
- let config = configPath ? require(configPath) : {}
462
-
463
- if (args['--purge']) {
464
- log.warn('purge-flag-deprecated', [
465
- 'The `--purge` flag has been deprecated.',
466
- 'Please use `--content` instead.',
467
- ])
468
- if (!args['--content']) {
469
- args['--content'] = args['--purge']
470
- }
471
- }
472
-
473
- if (args['--content']) {
474
- let files = args['--content'].split(/(?<!{[^}]+),/)
475
- let resolvedConfig = resolveConfigInternal(config, { content: { files } })
476
- resolvedConfig.content.files = files
477
- return resolvedConfig
478
- }
479
-
480
- return resolveConfigInternal(config)
481
- }
482
-
483
- function extractFileGlobs(config) {
484
- return config.content.files
485
- .filter((file) => {
486
- // Strings in this case are files / globs. If it is something else,
487
- // like an object it's probably a raw content object. But this object
488
- // is not watchable, so let's remove it.
489
- return typeof file === 'string'
490
- })
491
- .map((glob) => normalizePath(glob))
492
- }
493
-
494
- function extractRawContent(config) {
495
- return config.content.files.filter((file) => {
496
- return typeof file === 'object' && file !== null
497
- })
498
- }
499
-
500
- function getChangedContent(config) {
501
- let changedContent = []
502
-
503
- // Resolve globs from the content config
504
- let globs = extractFileGlobs(config)
505
- let files = fastGlob.sync(globs)
506
-
507
- for (let file of files) {
508
- changedContent.push({
509
- content: fs.readFileSync(path.resolve(file), 'utf8'),
510
- extension: path.extname(file).slice(1),
511
- })
512
- }
513
-
514
- // Resolve raw content in the tailwind config
515
- for (let { raw: content, extension = 'html' } of extractRawContent(config)) {
516
- changedContent.push({ content, extension })
517
- }
518
-
519
- return changedContent
520
- }
521
-
522
- async function buildOnce() {
523
- let config = resolveConfig()
524
- let changedContent = getChangedContent(config)
525
-
526
- let tailwindPlugin = () => {
527
- return {
528
- postcssPlugin: 'tailwindcss',
529
- Once(root, { result }) {
530
- tailwind(({ createContext }) => {
531
- return () => {
532
- return createContext(config, changedContent)
533
- }
534
- })(root, result)
535
- },
536
- }
537
- }
538
-
539
- tailwindPlugin.postcss = true
540
-
541
- let [beforePlugins, afterPlugins] = includePostCss ? await loadPostCssPlugins() : [[], []]
542
-
543
- let plugins = [
544
- ...beforePlugins,
545
- tailwindPlugin,
546
- !args['--minify'] && formatNodes,
547
- ...afterPlugins,
548
- !args['--no-autoprefixer'] &&
549
- (() => {
550
- // Try to load a local `autoprefixer` version first
551
- try {
552
- return require('autoprefixer')
553
- } catch {}
554
-
555
- return lazyAutoprefixer()
556
- })(),
557
- args['--minify'] &&
558
- (() => {
559
- let options = { preset: ['default', { cssDeclarationSorter: false }] }
560
-
561
- // Try to load a local `cssnano` version first
562
- try {
563
- return require('cssnano')
564
- } catch {}
565
-
566
- return lazyCssnano()(options)
567
- })(),
568
- ].filter(Boolean)
569
-
570
- let processor = postcss(plugins)
571
-
572
- function processCSS(css) {
573
- let start = process.hrtime.bigint()
574
- return Promise.resolve()
575
- .then(() => (output ? fs.promises.mkdir(path.dirname(output), { recursive: true }) : null))
576
- .then(() => processor.process(css, { from: input, to: output }))
577
- .then((result) => {
578
- if (!output) {
579
- return process.stdout.write(result.css)
580
- }
581
-
582
- return Promise.all(
583
- [
584
- outputFile(output, result.css),
585
- result.map && outputFile(output + '.map', result.map.toString()),
586
- ].filter(Boolean)
587
- )
588
- })
589
- .then(() => {
590
- let end = process.hrtime.bigint()
591
- console.error()
592
- console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
593
- })
594
- }
595
-
596
- let css = await (() => {
597
- // Piping in data, let's drain the stdin
598
- if (input === '-') {
599
- return drainStdin()
600
- }
601
-
602
- // Input file has been provided
603
- if (input) {
604
- return fs.readFileSync(path.resolve(input), 'utf8')
605
- }
606
-
607
- // No input file provided, fallback to default atrules
608
- return '@tailwind base; @tailwind components; @tailwind utilities'
609
- })()
610
-
611
- return processCSS(css)
612
- }
613
-
614
- let context = null
615
-
616
- async function startWatcher() {
617
- let changedContent = []
618
- let configDependencies = []
619
- let contextDependencies = new Set()
620
- let watcher = null
621
-
622
- function refreshConfig() {
623
- env.DEBUG && console.time('Module dependencies')
624
- for (let file of configDependencies) {
625
- delete require.cache[require.resolve(file)]
626
- }
627
-
628
- if (configPath) {
629
- configDependencies = getModuleDependencies(configPath).map(({ file }) => file)
630
-
631
- for (let dependency of configDependencies) {
632
- contextDependencies.add(dependency)
633
- }
634
- }
635
- env.DEBUG && console.timeEnd('Module dependencies')
636
-
637
- return resolveConfig()
638
- }
639
-
640
- let [beforePlugins, afterPlugins] = includePostCss ? await loadPostCssPlugins() : [[], []]
641
-
642
- let plugins = [
643
- ...beforePlugins,
644
- '__TAILWIND_PLUGIN_POSITION__',
645
- !args['--minify'] && formatNodes,
646
- ...afterPlugins,
647
- !args['--no-autoprefixer'] &&
648
- (() => {
649
- // Try to load a local `autoprefixer` version first
650
- try {
651
- return require('autoprefixer')
652
- } catch {}
653
-
654
- return lazyAutoprefixer()
655
- })(),
656
- args['--minify'] &&
657
- (() => {
658
- let options = { preset: ['default', { cssDeclarationSorter: false }] }
659
-
660
- // Try to load a local `cssnano` version first
661
- try {
662
- return require('cssnano')
663
- } catch {}
664
-
665
- return lazyCssnano()(options)
666
- })(),
667
- ].filter(Boolean)
668
-
669
- async function rebuild(config) {
670
- env.DEBUG && console.time('Finished in')
671
-
672
- let tailwindPlugin = () => {
673
- return {
674
- postcssPlugin: 'tailwindcss',
675
- Once(root, { result }) {
676
- env.DEBUG && console.time('Compiling CSS')
677
- tailwind(({ createContext }) => {
678
- console.error()
679
- console.error('Rebuilding...')
680
-
681
- return () => {
682
- if (context !== null) {
683
- context.changedContent = changedContent.splice(0)
684
- return context
685
- }
686
-
687
- env.DEBUG && console.time('Creating context')
688
- context = createContext(config, changedContent.splice(0))
689
- env.DEBUG && console.timeEnd('Creating context')
690
- return context
691
- }
692
- })(root, result)
693
- env.DEBUG && console.timeEnd('Compiling CSS')
694
- },
695
- }
696
- }
697
-
698
- tailwindPlugin.postcss = true
699
-
700
- let tailwindPluginIdx = plugins.indexOf('__TAILWIND_PLUGIN_POSITION__')
701
- let copy = plugins.slice()
702
- copy.splice(tailwindPluginIdx, 1, tailwindPlugin)
703
- let processor = postcss(copy)
704
-
705
- function processCSS(css) {
706
- let start = process.hrtime.bigint()
707
- return Promise.resolve()
708
- .then(() =>
709
- output ? fs.promises.mkdir(path.dirname(output), { recursive: true }) : null
710
- )
711
- .then(() => processor.process(css, { from: input, to: output }))
712
- .then(async (result) => {
713
- for (let message of result.messages) {
714
- if (message.type === 'dependency') {
715
- contextDependencies.add(message.file)
716
- }
717
- }
718
- watcher.add([...contextDependencies])
719
-
720
- if (!output) {
721
- return process.stdout.write(result.css)
722
- }
723
-
724
- return Promise.all(
725
- [
726
- outputFile(output, result.css),
727
- result.map && outputFile(output + '.map', result.map.toString()),
728
- ].filter(Boolean)
729
- )
730
- })
731
- .then(() => {
732
- let end = process.hrtime.bigint()
733
- console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
734
- })
735
- .catch((err) => {
736
- if (err.name === 'CssSyntaxError') {
737
- console.error(err.toString())
738
- } else {
739
- console.error(err)
740
- }
741
- })
742
- }
743
-
744
- let css = await (() => {
745
- // Piping in data, let's drain the stdin
746
- if (input === '-') {
747
- return drainStdin()
748
- }
749
-
750
- // Input file has been provided
751
- if (input) {
752
- return fs.readFileSync(path.resolve(input), 'utf8')
753
- }
754
-
755
- // No input file provided, fallback to default atrules
756
- return '@tailwind base; @tailwind components; @tailwind utilities'
757
- })()
758
-
759
- let result = await processCSS(css)
760
- env.DEBUG && console.timeEnd('Finished in')
761
- return result
762
- }
763
-
764
- let config = refreshConfig(configPath)
765
-
766
- if (input) {
767
- contextDependencies.add(path.resolve(input))
768
- }
769
-
770
- watcher = chokidar.watch([...contextDependencies, ...extractFileGlobs(config)], {
771
- usePolling: shouldPoll,
772
- interval: shouldPoll ? pollInterval : undefined,
773
- ignoreInitial: true,
774
- awaitWriteFinish: shouldCoalesceWriteEvents
775
- ? {
776
- stabilityThreshold: 50,
777
- pollInterval: pollInterval,
778
- }
779
- : false,
780
- })
781
-
782
- let chain = Promise.resolve()
783
-
784
- watcher.on('change', async (file) => {
785
- if (contextDependencies.has(file)) {
786
- env.DEBUG && console.time('Resolve config')
787
- context = null
788
- config = refreshConfig(configPath)
789
- env.DEBUG && console.timeEnd('Resolve config')
790
-
791
- env.DEBUG && console.time('Watch new files')
792
- let globs = extractFileGlobs(config)
793
- watcher.add(configDependencies)
794
- watcher.add(globs)
795
- env.DEBUG && console.timeEnd('Watch new files')
796
-
797
- chain = chain.then(async () => {
798
- changedContent.push(...getChangedContent(config))
799
- await rebuild(config)
800
- })
801
- } else {
802
- chain = chain.then(async () => {
803
- changedContent.push({
804
- content: fs.readFileSync(path.resolve(file), 'utf8'),
805
- extension: path.extname(file).slice(1),
806
- })
807
-
808
- await rebuild(config)
809
- })
810
- }
811
- })
812
-
813
- watcher.on('add', async (file) => {
814
- chain = chain.then(async () => {
815
- changedContent.push({
816
- content: fs.readFileSync(path.resolve(file), 'utf8'),
817
- extension: path.extname(file).slice(1),
818
- })
819
-
820
- await rebuild(config)
821
- })
822
- })
823
-
824
- chain = chain.then(() => {
825
- changedContent.push(...getChangedContent(config))
826
- return rebuild(config)
827
- })
828
- }
829
-
830
- if (shouldWatch) {
831
- /* Abort the watcher if stdin is closed to avoid zombie processes */
832
- process.stdin.on('end', () => process.exit(0))
833
- process.stdin.resume()
834
- startWatcher()
835
- } else {
836
- buildOnce()
837
- }
838
- }
3
+ module.exports = require('./cli/index')