UNPKG

weapp-tailwindcss

Version:

把 tailwindcss 原子化样式思想,带给小程序开发者们! bring tailwindcss to miniprogram developers!

1,132 lines (1,100 loc) 40.2 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _chunkFMBPNII7js = require('./chunk-FMBPNII7.js'); var _chunkMB4BR57Ejs = require('./chunk-MB4BR57E.js'); // src/logger/index.ts var _logger = require('@weapp-tailwindcss/logger'); // src/context/workspace.ts var _fs = require('fs'); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var IGNORED_WORKSPACE_DIRS = /* @__PURE__ */ new Set([ "node_modules", ".git", ".hg", ".svn", ".turbo", ".output", ".next", "dist", "build" ]); function findWorkspaceRoot(startDir) { if (!startDir) { return void 0; } let current = _path2.default.resolve(startDir); while (true) { const workspaceFile = _path2.default.join(current, "pnpm-workspace.yaml"); if (_fs.existsSync.call(void 0, workspaceFile)) { return current; } const parent = _path2.default.dirname(current); if (parent === current) { return void 0; } current = parent; } } function findNearestPackageRoot(startDir) { if (!startDir) { return void 0; } let current = _path2.default.resolve(startDir); while (true) { const pkgPath = _path2.default.join(current, "package.json"); if (_fs.existsSync.call(void 0, pkgPath)) { return current; } const parent = _path2.default.dirname(current); if (parent === current) { return void 0; } current = parent; } } function findWorkspacePackageDir(rootDir, packageName) { const visited = /* @__PURE__ */ new Set(); const queue = [_path2.default.resolve(rootDir)]; while (queue.length > 0) { const current = queue.shift(); const normalized = _path2.default.normalize(current); if (visited.has(normalized)) { continue; } visited.add(normalized); try { const pkgPath = _path2.default.join(normalized, "package.json"); if (_fs.existsSync.call(void 0, pkgPath)) { const pkg = JSON.parse(_fs.readFileSync.call(void 0, pkgPath, "utf8")); if (_optionalChain([pkg, 'optionalAccess', _ => _.name]) === packageName) { return normalized; } } } catch (e) { } let entries; try { entries = _fs.readdirSync.call(void 0, normalized, { withFileTypes: true }); } catch (e2) { continue; } for (const entry of entries) { if (!entry.isDirectory() || IGNORED_WORKSPACE_DIRS.has(entry.name) || _optionalChain([entry, 'access', _2 => _2.isSymbolicLink, 'optionalCall', _3 => _3()])) { continue; } queue.push(_path2.default.join(normalized, entry.name)); } } return void 0; } // src/tailwindcss/v4/config.ts var DEFAULT_CSS_CALC_CUSTOM_PROPERTIES = []; function includesToken(list, token) { return list.some((candidate) => { if (typeof token === "string") { if (typeof candidate === "string") { return candidate === token; } candidate.lastIndex = 0; return candidate.test(token); } if (typeof candidate === "string") { token.lastIndex = 0; return token.test(candidate); } return candidate.source === token.source && candidate.flags === token.flags; }); } function ensureDefaultsIncluded(value) { if (value === true) { return { includeCustomProperties: [...DEFAULT_CSS_CALC_CUSTOM_PROPERTIES] }; } if (Array.isArray(value)) { if (!DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.length) { return value; } const missing = DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.filter((token) => !includesToken(value, token)); return missing.length > 0 ? [...value, ...missing] : value; } if (value && typeof value === "object") { const include = value.includeCustomProperties; if (!Array.isArray(include)) { return { ...value, includeCustomProperties: [...DEFAULT_CSS_CALC_CUSTOM_PROPERTIES] }; } if (!DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.length) { return value; } const missing = DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.filter((token) => !includesToken(include, token)); return missing.length > 0 ? { ...value, includeCustomProperties: [...include, ...missing] } : value; } return value; } function normalizeCssEntriesConfig(entries) { if (!entries) { return void 0; } if (typeof entries === "string") { const trimmed = entries.trim(); return trimmed ? [trimmed] : void 0; } if (!Array.isArray(entries)) { return void 0; } const normalized = entries.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry.length > 0); return normalized.length > 0 ? normalized : void 0; } function hasConfiguredCssEntries(ctx) { if (normalizeCssEntriesConfig(ctx.cssEntries)) { return true; } if (normalizeCssEntriesConfig(_optionalChain([ctx, 'access', _4 => _4.tailwindcss, 'optionalAccess', _5 => _5.v4, 'optionalAccess', _6 => _6.cssEntries]))) { return true; } const patcherOptions = ctx.tailwindcssPatcherOptions; if (patcherOptions) { if (normalizeCssEntriesConfig(_optionalChain([patcherOptions, 'access', _7 => _7.tailwind, 'optionalAccess', _8 => _8.v4, 'optionalAccess', _9 => _9.cssEntries]))) { return true; } if (normalizeCssEntriesConfig(_optionalChain([patcherOptions, 'access', _10 => _10.patch, 'optionalAccess', _11 => _11.tailwindcss, 'optionalAccess', _12 => _12.v4, 'optionalAccess', _13 => _13.cssEntries]))) { return true; } } return false; } var hasWarnedMissingCssEntries = false; function warnMissingCssEntries(ctx, patcher) { if (hasWarnedMissingCssEntries) { return; } if (_optionalChain([patcher, 'optionalAccess', _14 => _14.majorVersion]) !== 4) { return; } if (hasConfiguredCssEntries(ctx)) { return; } hasWarnedMissingCssEntries = true; _logger.logger.warn( '[tailwindcss@4] \u672A\u68C0\u6D4B\u5230 cssEntries \u914D\u7F6E\u3002\u8BF7\u4F20\u5165\u5305\u542B tailwindcss \u5F15\u7528\u7684 CSS \u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4F8B\u5982 cssEntries: ["/absolute/path/to/src/app.css"]\uFF0C\u5426\u5219 tailwindcss \u751F\u6210\u7684\u7C7B\u540D\u4E0D\u4F1A\u53C2\u4E0E\u8F6C\u8BD1\u3002' ); } function applyV4CssCalcDefaults(cssCalc, patcher) { const cssCalcOptions = _nullishCoalesce(cssCalc, () => ( _optionalChain([patcher, 'optionalAccess', _15 => _15.majorVersion]) === 4)); if (_optionalChain([patcher, 'optionalAccess', _16 => _16.majorVersion]) === 4 && cssCalcOptions) { return ensureDefaultsIncluded(cssCalcOptions); } return cssCalcOptions; } // src/tailwindcss/v4/patcher.ts // src/tailwindcss/patcher.ts var _module = require('module'); var _process = require('process'); var _process2 = _interopRequireDefault(_process); var _url = require('url'); var _shared = require('@weapp-tailwindcss/shared'); var _tailwindcsspatch = require('tailwindcss-patch'); var GENERIC_RELATIVE_SPECIFIERS = [".", ".."]; var DEFAULT_TAILWIND_CONFIG_SPECIFIERS = [ "stubs/config.full.js", "defaultConfig.js" ]; function isPathSpecifier(specifier) { if (!specifier) { return false; } if (specifier.startsWith("file://")) { return true; } if (_path2.default.isAbsolute(specifier)) { return true; } return GENERIC_RELATIVE_SPECIFIERS.some((prefix) => specifier.startsWith(`${prefix}/`) || specifier.startsWith(`${prefix}\\`)); } function resolveModuleFromPaths(specifier, paths) { if (!specifier || isPathSpecifier(specifier) || paths.length === 0) { return void 0; } try { const req = _module.createRequire.call(void 0, _chunkMB4BR57Ejs.importMetaUrl); return req.resolve(specifier, { paths }); } catch (e3) { return void 0; } } function resolveTailwindConfigFallback(packageName, paths) { if (!packageName) { return void 0; } for (const suffix of DEFAULT_TAILWIND_CONFIG_SPECIFIERS) { const candidate = `${packageName}/${suffix}`; const resolved = resolveModuleFromPaths(candidate, paths); if (resolved) { return resolved; } } return void 0; } function createFallbackTailwindcssPatcher() { const packageInfo = { name: "tailwindcss", version: void 0, rootPath: "", packageJsonPath: "", packageJson: {} }; return { packageInfo, async patch() { return { exposeContext: void 0, extendLengthUnits: void 0 }; }, async getClassSet() { return /* @__PURE__ */ new Set(); }, async extract(_options) { const classSet = /* @__PURE__ */ new Set(); return { classList: [], classSet }; }, async collectContentTokens() { return { entries: [], filesScanned: 0, sources: [], skippedFiles: [] }; } }; } var hasLoggedMissingTailwind = false; function appendNodeModules(paths, dir) { if (!dir) { return; } const nodeModulesDir = _path2.default.join(dir, "node_modules"); if (_fs.existsSync.call(void 0, nodeModulesDir)) { paths.add(nodeModulesDir); } } var TAILWIND_CONFIG_FILES = [ "tailwind.config.js", "tailwind.config.cjs", "tailwind.config.mjs", "tailwind.config.ts", "tailwind.config.cts", "tailwind.config.mts" ]; function findTailwindConfig(searchRoots) { for (const root of searchRoots) { for (const file of TAILWIND_CONFIG_FILES) { const candidate = _path2.default.resolve(root, file); if (_fs.existsSync.call(void 0, candidate)) { return candidate; } } } return void 0; } function createDefaultResolvePaths(basedir) { const paths = /* @__PURE__ */ new Set(); let fallbackCandidates = []; if (basedir) { const resolvedBase = _path2.default.resolve(basedir); appendNodeModules(paths, resolvedBase); fallbackCandidates.push(resolvedBase); const packageRoot = findNearestPackageRoot(resolvedBase); if (packageRoot) { appendNodeModules(paths, packageRoot); fallbackCandidates.push(packageRoot); } } const cwd = _process2.default.cwd(); appendNodeModules(paths, cwd); try { const modulePath = _url.fileURLToPath.call(void 0, _chunkMB4BR57Ejs.importMetaUrl); const candidate = _fs.existsSync.call(void 0, modulePath) && !_path2.default.extname(modulePath) ? modulePath : _path2.default.dirname(modulePath); paths.add(candidate); } catch (e4) { paths.add(_chunkMB4BR57Ejs.importMetaUrl); } if (paths.size === 0) { fallbackCandidates = fallbackCandidates.filter(Boolean); if (fallbackCandidates.length === 0) { fallbackCandidates.push(cwd); } for (const candidate of fallbackCandidates) { paths.add(candidate); } } return [...paths]; } function normalizeExtendLengthUnits(value) { if (value === false) { return false; } if (value === true) { return { enabled: true }; } if (value && typeof value === "object") { return { enabled: true, ...value }; } return void 0; } function normalizeTailwindcssPatcherOptions(options) { if (!options) { return void 0; } if ("patch" in options) { const { cache, patch } = options; const normalized = {}; if (cache !== void 0) { normalized.cache = cache; } if (_optionalChain([patch, 'optionalAccess', _17 => _17.overwrite]) !== void 0) { normalized.overwrite = patch.overwrite; } if (_optionalChain([patch, 'optionalAccess', _18 => _18.filter])) { normalized.filter = patch.filter; } const extendLengthUnits = normalizeExtendLengthUnits(_optionalChain([patch, 'optionalAccess', _19 => _19.applyPatches, 'optionalAccess', _20 => _20.extendLengthUnits])); const exposeContext = _optionalChain([patch, 'optionalAccess', _21 => _21.applyPatches, 'optionalAccess', _22 => _22.exportContext]); if (extendLengthUnits !== void 0 || exposeContext !== void 0) { normalized.features = { exposeContext, extendLengthUnits }; } const cwd = _nullishCoalesce(_optionalChain([patch, 'optionalAccess', _23 => _23.cwd]), () => ( _optionalChain([patch, 'optionalAccess', _24 => _24.basedir]))); if (cwd) { normalized.cwd = cwd; } const tailwindOptions = _optionalChain([patch, 'optionalAccess', _25 => _25.tailwindcss]) ? { ...patch.tailwindcss } : void 0; const legacyResolve = _optionalChain([patch, 'optionalAccess', _26 => _26.resolve]); let nextTailwindOptions = tailwindOptions; if (_optionalChain([nextTailwindOptions, 'optionalAccess', _27 => _27.version]) === 2 && !nextTailwindOptions.packageName) { nextTailwindOptions = { ...nextTailwindOptions, packageName: "@tailwindcss/postcss7-compat", postcssPlugin: nextTailwindOptions.postcssPlugin }; if (!nextTailwindOptions.postcssPlugin) { nextTailwindOptions.postcssPlugin = "@tailwindcss/postcss7-compat"; } } if (nextTailwindOptions || legacyResolve) { const resolveOptions = _optionalChain([nextTailwindOptions, 'optionalAccess', _28 => _28.resolve]); const mergedResolve = legacyResolve || resolveOptions ? { ..._nullishCoalesce(resolveOptions, () => ( {})), ..._nullishCoalesce(legacyResolve, () => ( {})) } : void 0; normalized.tailwind = { ..._nullishCoalesce(nextTailwindOptions, () => ( {})), ...mergedResolve ? { resolve: mergedResolve } : {} }; } return normalized; } return options; } function createTailwindcssPatcher(options) { const { basedir, cacheDir, supportCustomLengthUnitsPatch, tailwindcss, tailwindcssPatcherOptions } = options || {}; const cache = { driver: "memory" }; const normalizedBasedir = basedir ? _path2.default.resolve(basedir) : void 0; const cacheRoot = _nullishCoalesce(_nullishCoalesce(findNearestPackageRoot(normalizedBasedir), () => ( normalizedBasedir)), () => ( _process2.default.cwd())); if (cacheDir) { if (_path2.default.isAbsolute(cacheDir)) { cache.dir = cacheDir; } else if (normalizedBasedir) { cache.dir = _path2.default.resolve(normalizedBasedir, cacheDir); } else { cache.dir = _path2.default.resolve(_process2.default.cwd(), cacheDir); } } else { cache.dir = _path2.default.join(cacheRoot, "node_modules", ".cache", "tailwindcss-patch"); } if (normalizedBasedir) { cache.cwd = normalizedBasedir; } const resolvePaths = createDefaultResolvePaths(_nullishCoalesce(_nullishCoalesce(cache.cwd, () => ( normalizedBasedir)), () => ( _process2.default.cwd()))); const normalizedUserOptions = normalizeTailwindcssPatcherOptions(tailwindcssPatcherOptions); const extendLengthUnits = normalizeExtendLengthUnits(_nullishCoalesce(supportCustomLengthUnitsPatch, () => ( true))); const baseTailwindOptions = _shared.defuOverrideArray.call(void 0, _nullishCoalesce(tailwindcss, () => ( {})), { cwd: normalizedBasedir, resolve: { paths: resolvePaths } } ); if (baseTailwindOptions.version === 2) { if (!baseTailwindOptions.packageName) { baseTailwindOptions.packageName = "@tailwindcss/postcss7-compat"; } if (!baseTailwindOptions.postcssPlugin) { baseTailwindOptions.postcssPlugin = "@tailwindcss/postcss7-compat"; } } else if (!baseTailwindOptions.packageName) { baseTailwindOptions.packageName = "tailwindcss"; } if (!baseTailwindOptions.postcssPlugin) { baseTailwindOptions.postcssPlugin = baseTailwindOptions.version === 4 ? "@tailwindcss/postcss" : "tailwindcss"; } if (typeof baseTailwindOptions.postcssPlugin === "string") { const resolvedPlugin = resolveModuleFromPaths(baseTailwindOptions.postcssPlugin, resolvePaths); if (resolvedPlugin) { baseTailwindOptions.postcssPlugin = resolvedPlugin; } } const baseOptions = { cwd: normalizedBasedir, cache, tailwind: baseTailwindOptions, features: { exposeContext: true, extendLengthUnits } }; const resolvedOptions = _shared.defuOverrideArray.call(void 0, _nullishCoalesce(normalizedUserOptions, () => ( {})), baseOptions ); if (resolvedOptions.tailwind) { const existingResolve = _nullishCoalesce(resolvedOptions.tailwind.resolve, () => ( {})); const customPaths = Array.isArray(existingResolve.paths) && existingResolve.paths.length > 0; const sourcePaths = customPaths ? existingResolve.paths : resolvePaths; resolvedOptions.tailwind.resolve = { ...existingResolve, paths: Array.from(new Set(sourcePaths)) }; _logger.logger.debug("Tailwind resolve config %O", { packageName: resolvedOptions.tailwind.packageName, version: resolvedOptions.tailwind.version, resolve: resolvedOptions.tailwind.resolve, cwd: resolvedOptions.tailwind.cwd }); if (typeof resolvedOptions.tailwind.postcssPlugin === "string") { const resolvedPlugin = resolveModuleFromPaths( resolvedOptions.tailwind.postcssPlugin, _nullishCoalesce(_optionalChain([resolvedOptions, 'access', _29 => _29.tailwind, 'access', _30 => _30.resolve, 'optionalAccess', _31 => _31.paths]), () => ( resolvePaths)) ); if (resolvedPlugin) { resolvedOptions.tailwind.postcssPlugin = resolvedPlugin; } } const searchRoots = /* @__PURE__ */ new Set(); if (resolvedOptions.tailwind.cwd) { searchRoots.add(resolvedOptions.tailwind.cwd); } for (const resolvePath of _nullishCoalesce(_optionalChain([resolvedOptions, 'access', _32 => _32.tailwind, 'access', _33 => _33.resolve, 'optionalAccess', _34 => _34.paths]), () => ( []))) { const parentDir = _path2.default.dirname(resolvePath); searchRoots.add(parentDir); } const configPath = findTailwindConfig(searchRoots); if (!resolvedOptions.tailwind.config) { if (configPath) { resolvedOptions.tailwind.config = configPath; } else { const fallbackConfig = resolveTailwindConfigFallback( resolvedOptions.tailwind.packageName, _nullishCoalesce(resolvedOptions.tailwind.resolve.paths, () => ( resolvePaths)) ); if (fallbackConfig) { resolvedOptions.tailwind.config = fallbackConfig; } } } if (!resolvedOptions.tailwind.cwd && configPath) { resolvedOptions.tailwind.cwd = _path2.default.dirname(configPath); } } try { return new (0, _tailwindcsspatch.TailwindcssPatcher)(resolvedOptions); } catch (error) { const searchPaths = _optionalChain([resolvedOptions, 'access', _35 => _35.tailwind, 'optionalAccess', _36 => _36.resolve, 'optionalAccess', _37 => _37.paths]); if (error instanceof Error && /tailwindcss not found/i.test(error.message)) { if (!hasLoggedMissingTailwind) { _logger.logger.warn("Tailwind CSS \u672A\u5B89\u88C5\uFF0C\u5DF2\u8DF3\u8FC7 Tailwind \u76F8\u5173\u8865\u4E01\u3002\u82E5\u9700\u4F7F\u7528 Tailwind \u80FD\u529B\uFF0C\u8BF7\u5B89\u88C5 tailwindcss\u3002"); hasLoggedMissingTailwind = true; } return createFallbackTailwindcssPatcher(); } if (error instanceof Error && /unable to locate tailwind css package/i.test(error.message)) { _logger.logger.error('\u65E0\u6CD5\u5B9A\u4F4D Tailwind CSS \u5305 "%s"\uFF0C\u5DF2\u5C1D\u8BD5\u8DEF\u5F84: %O', _optionalChain([resolvedOptions, 'access', _38 => _38.tailwind, 'optionalAccess', _39 => _39.packageName]), searchPaths); } throw error; } } // src/tailwindcss/v4/patcher.ts function isLegacyTailwindcssPatcherOptions(options) { return typeof options === "object" && options !== null && "patch" in options; } function isModernTailwindcssPatchOptions(options) { return typeof options === "object" && options !== null && !("patch" in options); } function guessBasedirFromEntries(entries) { if (!entries) { return void 0; } for (const entry of entries) { if (typeof entry !== "string") { continue; } const trimmed = entry.trim(); if (!trimmed || !_path2.default.isAbsolute(trimmed)) { continue; } const entryDir = _path2.default.dirname(trimmed); const resolved = _nullishCoalesce(findNearestPackageRoot(entryDir), () => ( entryDir)); if (resolved) { return resolved; } } return void 0; } function normalizeCssEntries(entries, anchor) { if (!entries || entries.length === 0) { return void 0; } const normalized = /* @__PURE__ */ new Set(); for (const entry of entries) { if (typeof entry !== "string") { continue; } const trimmed = entry.trim(); if (trimmed.length === 0) { continue; } const resolved = _path2.default.isAbsolute(trimmed) ? _path2.default.normalize(trimmed) : _path2.default.normalize(_path2.default.resolve(anchor, trimmed)); normalized.add(resolved); } return normalized.size > 0 ? [...normalized] : void 0; } function isSubPath(parent, child) { if (!parent || !child) { return false; } const relative = _path2.default.relative(parent, child); return relative === "" || !relative.startsWith("..") && !_path2.default.isAbsolute(relative); } function resolveCssEntryBase(entryDir, options) { const normalizedDir = _path2.default.normalize(entryDir); const { preferredBaseDir, workspaceRoot } = options; if (preferredBaseDir && isSubPath(preferredBaseDir, normalizedDir)) { return preferredBaseDir; } if (workspaceRoot && isSubPath(workspaceRoot, normalizedDir)) { return workspaceRoot; } const packageRoot = findNearestPackageRoot(normalizedDir); if (packageRoot) { return _path2.default.normalize(packageRoot); } return normalizedDir; } function groupCssEntriesByBase(entries, options = {}) { const normalizedOptions = { preferredBaseDir: options.preferredBaseDir ? _path2.default.normalize(options.preferredBaseDir) : void 0, workspaceRoot: options.workspaceRoot ? _path2.default.normalize(options.workspaceRoot) : void 0 }; const groups = /* @__PURE__ */ new Map(); for (const entry of entries) { const entryDir = _path2.default.dirname(entry); const baseDir = resolveCssEntryBase(entryDir, normalizedOptions); const bucket = groups.get(baseDir); if (bucket) { bucket.push(entry); } else { groups.set(baseDir, [entry]); } } return groups; } function overrideTailwindcssPatcherOptionsForBase(options, baseDir, cssEntries) { if (!options) { return options; } if (isLegacyTailwindcssPatcherOptions(options)) { const patchOptions = options.patch; if (!patchOptions) { return options; } const nextPatch = { ...patchOptions, basedir: baseDir, cwd: _nullishCoalesce(patchOptions.cwd, () => ( baseDir)) }; if (patchOptions.tailwindcss) { nextPatch.tailwindcss = { ...patchOptions.tailwindcss, v4: { ..._nullishCoalesce(patchOptions.tailwindcss.v4, () => ( {})), base: baseDir, cssEntries } }; } return { ...options, patch: nextPatch }; } if (!isModernTailwindcssPatchOptions(options)) { return options; } if (!options.tailwind) { return options; } return { ...options, tailwind: { ...options.tailwind, v4: { ..._nullishCoalesce(options.tailwind.v4, () => ( {})), base: baseDir, cssEntries } } }; } function createPatcherForBase(baseDir, cssEntries, options) { const { tailwindcss, tailwindcssPatcherOptions, supportCustomLengthUnitsPatch } = options; const defaultTailwindcssConfig = { cwd: baseDir, v2: { cwd: baseDir }, v3: { cwd: baseDir }, v4: { base: baseDir, cssEntries } }; if (_optionalChain([cssEntries, 'optionalAccess', _40 => _40.length]) && (tailwindcss == null || tailwindcss.version == null)) { defaultTailwindcssConfig.version = 4; } const mergedTailwindOptions = _chunkFMBPNII7js.defuOverrideArray.call(void 0, _nullishCoalesce(tailwindcss, () => ( {})), defaultTailwindcssConfig ); if (!mergedTailwindOptions.v4) { mergedTailwindOptions.v4 = { base: baseDir, cssEntries: _nullishCoalesce(cssEntries, () => ( [])) }; } else { mergedTailwindOptions.v4.base = baseDir; if (_optionalChain([cssEntries, 'optionalAccess', _41 => _41.length])) { mergedTailwindOptions.v4.cssEntries = cssEntries; } else if (!mergedTailwindOptions.v4.cssEntries) { mergedTailwindOptions.v4.cssEntries = []; } } const patchedOptions = overrideTailwindcssPatcherOptionsForBase( tailwindcssPatcherOptions, baseDir, _nullishCoalesce(cssEntries, () => ( [])) ); const configuredPackageName = _optionalChain([tailwindcss, 'optionalAccess', _42 => _42.packageName]) || _optionalChain([tailwindcssPatcherOptions, 'optionalAccess', _43 => _43.tailwind, 'optionalAccess', _44 => _44.packageName]) || _optionalChain([tailwindcssPatcherOptions, 'optionalAccess', _45 => _45.patch, 'optionalAccess', _46 => _46.tailwindcss, 'optionalAccess', _47 => _47.packageName]); const configuredVersion = _optionalChain([tailwindcss, 'optionalAccess', _48 => _48.version]) || _optionalChain([tailwindcssPatcherOptions, 'optionalAccess', _49 => _49.tailwind, 'optionalAccess', _50 => _50.version]) || _optionalChain([tailwindcssPatcherOptions, 'optionalAccess', _51 => _51.patch, 'optionalAccess', _52 => _52.tailwindcss, 'optionalAccess', _53 => _53.version]) || mergedTailwindOptions.version; const isTailwindcss4Package = (packageName) => Boolean( packageName && (packageName === "tailwindcss4" || packageName === "@tailwindcss/postcss" || packageName.includes("tailwindcss4")) ); const isV4 = configuredVersion === 4 || mergedTailwindOptions.version === 4 || isTailwindcss4Package(_nullishCoalesce(configuredPackageName, () => ( mergedTailwindOptions.packageName))); const tailwindPackageConfigured = Boolean(configuredPackageName); const shouldPatchV4PostcssPackage = isV4 && !tailwindPackageConfigured; const packageCandidates = /* @__PURE__ */ new Set(); if (shouldPatchV4PostcssPackage) { packageCandidates.add("@tailwindcss/postcss"); } packageCandidates.add( _nullishCoalesce(_nullishCoalesce(mergedTailwindOptions.packageName, () => ( configuredPackageName)), () => ( "tailwindcss")) ); const patchers = Array.from(packageCandidates).map((packageName) => { const tailwindOptionsForPackage = { ...mergedTailwindOptions, packageName }; return createTailwindcssPatcher({ basedir: baseDir, supportCustomLengthUnitsPatch: _nullishCoalesce(supportCustomLengthUnitsPatch, () => ( true)), tailwindcss: tailwindOptionsForPackage, tailwindcssPatcherOptions: patchedOptions }); }); return patchers.length === 1 ? patchers[0] : createMultiTailwindcssPatcher(patchers); } function createMultiTailwindcssPatcher(patchers) { if (patchers.length <= 1) { return patchers[0]; } const [first] = patchers; const multiPatcher = { packageInfo: _optionalChain([first, 'optionalAccess', _54 => _54.packageInfo]), majorVersion: _optionalChain([first, 'optionalAccess', _55 => _55.majorVersion]), options: _optionalChain([first, 'optionalAccess', _56 => _56.options]), async patch() { let exposeContext; let extendLengthUnits; for (const patcher of patchers) { const result = await patcher.patch(); if (_optionalChain([result, 'optionalAccess', _57 => _57.exposeContext]) && exposeContext == null) { exposeContext = result.exposeContext; } if (_optionalChain([result, 'optionalAccess', _58 => _58.extendLengthUnits]) && extendLengthUnits == null) { extendLengthUnits = result.extendLengthUnits; } } return { exposeContext, extendLengthUnits }; }, async getClassSet() { const aggregated = /* @__PURE__ */ new Set(); for (const patcher of patchers) { const current = await patcher.getClassSet(); for (const className of current) { aggregated.add(className); } } return aggregated; }, async extract(options) { const aggregatedSet = /* @__PURE__ */ new Set(); const aggregatedList = []; let filename; for (const patcher of patchers) { const result = await patcher.extract(options); if (!result) { continue; } if (filename === void 0 && result.filename) { filename = result.filename; } if (result.classList) { for (const className of result.classList) { if (!aggregatedSet.has(className)) { aggregatedList.push(className); } aggregatedSet.add(className); } } if (result.classSet) { for (const className of result.classSet) { aggregatedSet.add(className); } } } return { classList: aggregatedList, classSet: aggregatedSet, filename }; } }; if (patchers.every((patcher) => typeof patcher.getClassSetSync === "function")) { multiPatcher.getClassSetSync = () => { const aggregated = /* @__PURE__ */ new Set(); for (const patcher of patchers) { const current = _optionalChain([patcher, 'access', _59 => _59.getClassSetSync, 'optionalCall', _60 => _60()]); if (!current) { continue; } for (const className of current) { aggregated.add(className); } } return aggregated; }; } return multiPatcher; } function tryCreateMultiTailwindcssPatcher(groups, options) { if (groups.size <= 1) { return void 0; } _logger.logger.debug("detected multiple Tailwind CSS entry bases: %O", [...groups.keys()]); const patchers = []; for (const [baseDir, entries] of groups) { patchers.push(createPatcherForBase(baseDir, entries, options)); } return createMultiTailwindcssPatcher(patchers); } // src/context/tailwindcss.ts var ENV_BASEDIR_KEYS = [ "WEAPP_TAILWINDCSS_BASEDIR", "WEAPP_TAILWINDCSS_BASE_DIR", "TAILWINDCSS_BASEDIR", "TAILWINDCSS_BASE_DIR", "UNI_INPUT_DIR", "UNI_INPUT_ROOT", "UNI_CLI_ROOT", "UNI_APP_INPUT_DIR", "INIT_CWD", "PWD" ]; var GENERIC_ENV_BASEDIR_KEYS = /* @__PURE__ */ new Set(["INIT_CWD", "PWD"]); function pickEnvBasedir() { for (const key of ENV_BASEDIR_KEYS) { const value = _process2.default.env[key]; if (value && _path2.default.isAbsolute(value)) { return { key, value }; } } return void 0; } function pickPackageEnvBasedir() { const packageJsonPath = _process2.default.env.npm_package_json; if (packageJsonPath) { const packageDir = _path2.default.dirname(packageJsonPath); if (packageDir && _path2.default.isAbsolute(packageDir)) { return packageDir; } } const localPrefix = _process2.default.env.npm_config_local_prefix; if (localPrefix && _path2.default.isAbsolute(localPrefix)) { return localPrefix; } return void 0; } function detectCallerBasedir() { const stack = new Error("resolveTailwindcssBasedir stack probe").stack; if (!stack) { return void 0; } if (_process2.default.env.WEAPP_TW_DEBUG_STACK === "1") { _logger.logger.debug("caller stack: %s", stack); } const lines = stack.split("\n"); for (const line of lines) { const match = _nullishCoalesce(line.match(/\(([^)]+)\)/u), () => ( line.match(/at\s+(\S.*)$/u))); const location = _optionalChain([match, 'optionalAccess', _61 => _61[1]]); if (!location) { continue; } let filePath = location; if (filePath.startsWith("file://")) { try { filePath = _url.fileURLToPath.call(void 0, filePath); } catch (e5) { continue; } } const [candidate] = filePath.split(":"); const resolvedPath = _path2.default.isAbsolute(filePath) ? filePath : candidate; if (!_path2.default.isAbsolute(resolvedPath)) { continue; } if (resolvedPath.includes("node_modules") && resolvedPath.includes("weapp-tailwindcss")) { continue; } try { return _path2.default.dirname(resolvedPath); } catch (e6) { continue; } } return void 0; } function resolveTailwindcssBasedir(basedir, fallback) { const envBasedirResult = pickEnvBasedir(); const envBasedir = _optionalChain([envBasedirResult, 'optionalAccess', _62 => _62.value]); const envBasedirKey = _optionalChain([envBasedirResult, 'optionalAccess', _63 => _63.key]); const envBasedirIsGeneric = envBasedirKey ? GENERIC_ENV_BASEDIR_KEYS.has(envBasedirKey) : false; const packageEnvBasedir = pickPackageEnvBasedir(); const shouldDetectCaller = !envBasedir || envBasedirIsGeneric; const callerBasedir = shouldDetectCaller ? detectCallerBasedir() : void 0; const cwd = _process2.default.cwd(); const anchor = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(envBasedir, () => ( packageEnvBasedir)), () => ( fallback)), () => ( callerBasedir)), () => ( cwd)); const resolveRelative = (value) => _path2.default.isAbsolute(value) ? _path2.default.normalize(value) : _path2.default.normalize(_path2.default.resolve(anchor, value)); if (_process2.default.env.WEAPP_TW_DEBUG_STACK === "1") { _logger.logger.debug("resolveTailwindcssBasedir anchor %O", { basedir, envBasedir, envBasedirKey, envBasedirIsGeneric, packageEnvBasedir, fallback, callerBasedir, npm_package_json: _process2.default.env.npm_package_json, cwd, anchor }); } if (basedir && basedir.trim().length > 0) { return resolveRelative(basedir); } if (envBasedir && !envBasedirIsGeneric) { return _path2.default.normalize(envBasedir); } if (fallback && fallback.trim().length > 0) { return resolveRelative(fallback); } if (packageEnvBasedir) { return _path2.default.normalize(packageEnvBasedir); } if (callerBasedir) { const normalizedCaller = _path2.default.normalize(callerBasedir); const librarySegment = `${_path2.default.sep}weapp-tailwindcss${_path2.default.sep}`; if (!normalizedCaller.includes(librarySegment)) { return normalizedCaller; } } const packageName = _process2.default.env.PNPM_PACKAGE_NAME; if (packageName) { try { const anchorRequire = _module.createRequire.call(void 0, _path2.default.join(anchor, "__resolve_tailwindcss_basedir__.cjs")); const packageJsonPath = anchorRequire.resolve(`${packageName}/package.json`); if (_process2.default.env.WEAPP_TW_DEBUG_STACK === "1") { _logger.logger.debug("package basedir resolved from PNPM_PACKAGE_NAME: %s", packageJsonPath); } return _path2.default.normalize(_path2.default.dirname(packageJsonPath)); } catch (e7) { if (_process2.default.env.WEAPP_TW_DEBUG_STACK === "1") { _logger.logger.debug("failed to resolve package json for %s", packageName); } const workspaceRoot = findWorkspaceRoot(anchor); if (workspaceRoot) { const packageDir = findWorkspacePackageDir(workspaceRoot, packageName); if (packageDir) { return packageDir; } } } } if (envBasedir) { return _path2.default.normalize(envBasedir); } return _path2.default.normalize(cwd); } function isRaxWorkspace(appType, baseDir) { if (appType === "rax") { return true; } try { const pkgPath = _path2.default.join(baseDir, "package.json"); if (!_fs.existsSync.call(void 0, pkgPath)) { return false; } const pkg = JSON.parse(_fs.readFileSync.call(void 0, pkgPath, "utf8")); const deps = { ..._nullishCoalesce(pkg.dependencies, () => ( {})), ..._nullishCoalesce(pkg.devDependencies, () => ( {})) }; if (deps["rax-app"] || deps.rax) { return true; } } catch (e8) { return false; } return false; } function collectRaxStyleEntries(baseDir) { const STYLE_CANDIDATES = [ "src/global.css", "src/global.scss", "src/global.less", "src/global.sass", "src/global.styl", "src/global.stylus" ]; const discovered = []; for (const relative of STYLE_CANDIDATES) { const candidate = _path2.default.resolve(baseDir, relative); if (_fs.existsSync.call(void 0, candidate)) { discovered.push(_path2.default.normalize(candidate)); } } return discovered; } function detectImplicitCssEntries(appType, baseDir) { const baseCandidates = /* @__PURE__ */ new Set(); baseCandidates.add(_path2.default.normalize(baseDir)); const envCandidates = [_process2.default.cwd(), _process2.default.env.INIT_CWD, _process2.default.env.PWD]; for (const candidate of envCandidates) { if (candidate) { baseCandidates.add(_path2.default.normalize(candidate)); } } for (const candidateBase of baseCandidates) { if (!isRaxWorkspace(appType, candidateBase)) { continue; } const entries = collectRaxStyleEntries(candidateBase); if (entries.length) { return entries; } } return void 0; } function createTailwindcssPatcherFromContext(ctx) { const { tailwindcssBasedir, supportCustomLengthUnitsPatch, tailwindcss, tailwindcssPatcherOptions, cssEntries: rawCssEntries, appType } = ctx; const absoluteCssEntryBasedir = guessBasedirFromEntries(rawCssEntries); const resolvedTailwindcssBasedir = resolveTailwindcssBasedir(tailwindcssBasedir, absoluteCssEntryBasedir); ctx.tailwindcssBasedir = resolvedTailwindcssBasedir; _logger.logger.debug("tailwindcss basedir resolved: %s", resolvedTailwindcssBasedir); let normalizedCssEntries = normalizeCssEntries(rawCssEntries, resolvedTailwindcssBasedir); if (!normalizedCssEntries) { normalizedCssEntries = detectImplicitCssEntries(ctx.appType, resolvedTailwindcssBasedir); } if (normalizedCssEntries) { ctx.cssEntries = normalizedCssEntries; } const patcherOptions = { tailwindcss, tailwindcssPatcherOptions, supportCustomLengthUnitsPatch, appType }; const workspaceRoot = _nullishCoalesce(findWorkspaceRoot(resolvedTailwindcssBasedir), () => ( (absoluteCssEntryBasedir ? findWorkspaceRoot(absoluteCssEntryBasedir) : void 0))); const groupedCssEntries = normalizedCssEntries ? groupCssEntriesByBase(normalizedCssEntries, { preferredBaseDir: resolvedTailwindcssBasedir, workspaceRoot }) : void 0; const multiPatcher = groupedCssEntries ? tryCreateMultiTailwindcssPatcher(groupedCssEntries, patcherOptions) : void 0; if (multiPatcher) { return multiPatcher; } if (_optionalChain([groupedCssEntries, 'optionalAccess', _64 => _64.size]) === 1) { const firstGroup = groupedCssEntries.entries().next().value; if (firstGroup) { const [baseDir, entries] = firstGroup; return createPatcherForBase(baseDir, entries, patcherOptions); } } const effectiveCssEntries = _nullishCoalesce(normalizedCssEntries, () => ( rawCssEntries)); return createPatcherForBase( resolvedTailwindcssBasedir, effectiveCssEntries, patcherOptions ); } exports.findWorkspaceRoot = findWorkspaceRoot; exports.findNearestPackageRoot = findNearestPackageRoot; exports.warnMissingCssEntries = warnMissingCssEntries; exports.applyV4CssCalcDefaults = applyV4CssCalcDefaults; exports.resolveTailwindcssBasedir = resolveTailwindcssBasedir; exports.createTailwindcssPatcherFromContext = createTailwindcssPatcherFromContext; exports.logger = _logger.logger;