Skip to content

Track source locations through @plugin and @config #18329

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 36 additions & 9 deletions packages/tailwindcss/src/compat/apply-compat-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Features } from '..'
import { styleRule, toCss, walk, WalkAction, type AstNode } from '../ast'
import type { DesignSystem } from '../design-system'
import type { SourceLocation } from '../source-maps/source'
import { segment } from '../utils/segment'
import { applyConfigToTheme } from './apply-config-to-theme'
import { applyKeyframesToTheme } from './apply-keyframes-to-theme'
Expand Down Expand Up @@ -38,9 +39,16 @@ export async function applyCompatibilityHooks({
sources: { base: string; pattern: string; negated: boolean }[]
}) {
let features = Features.None
let pluginPaths: [{ id: string; base: string; reference: boolean }, CssPluginOptions | null][] =
[]
let configPaths: { id: string; base: string; reference: boolean }[] = []
let pluginPaths: [
{ id: string; base: string; reference: boolean; src: SourceLocation | undefined },
CssPluginOptions | null,
][] = []
let configPaths: {
id: string
base: string
reference: boolean
src: SourceLocation | undefined
}[] = []

walk(ast, (node, { parent, replaceWith, context }) => {
if (node.kind !== 'at-rule') return
Expand Down Expand Up @@ -100,7 +108,12 @@ export async function applyCompatibilityHooks({
}

pluginPaths.push([
{ id: pluginPath, base: context.base as string, reference: !!context.reference },
{
id: pluginPath,
base: context.base as string,
reference: !!context.reference,
src: node.src,
},
Object.keys(options).length > 0 ? options : null,
])

Expand All @@ -123,6 +136,7 @@ export async function applyCompatibilityHooks({
id: node.params.slice(1, -1),
base: context.base as string,
reference: !!context.reference,
src: node.src,
})
replaceWith([])
features |= Features.JsPluginCompat
Expand Down Expand Up @@ -162,25 +176,27 @@ export async function applyCompatibilityHooks({

let [configs, pluginDetails] = await Promise.all([
Promise.all(
configPaths.map(async ({ id, base, reference }) => {
configPaths.map(async ({ id, base, reference, src }) => {
let loaded = await loadModule(id, base, 'config')
return {
path: id,
base: loaded.base,
config: loaded.module as UserConfig,
reference,
src,
}
}),
),
Promise.all(
pluginPaths.map(async ([{ id, base, reference }, pluginOptions]) => {
pluginPaths.map(async ([{ id, base, reference, src }, pluginOptions]) => {
let loaded = await loadModule(id, base, 'plugin')
return {
path: id,
base: loaded.base,
plugin: loaded.module as Plugin,
options: pluginOptions,
reference,
src,
}
}),
),
Expand Down Expand Up @@ -215,13 +231,15 @@ function upgradeToFullPluginSupport({
base: string
config: UserConfig
reference: boolean
src: SourceLocation | undefined
}[]
pluginDetails: {
path: string
base: string
plugin: Plugin
options: CssPluginOptions | null
reference: boolean
src: SourceLocation | undefined
}[]
}) {
let features = Features.None
Expand All @@ -231,6 +249,7 @@ function upgradeToFullPluginSupport({
config: { plugins: [detail.plugin] },
base: detail.base,
reference: detail.reference,
src: detail.src,
}
}

Expand All @@ -239,6 +258,7 @@ function upgradeToFullPluginSupport({
config: { plugins: [detail.plugin(detail.options)] },
base: detail.base,
reference: detail.reference,
src: detail.src,
}
}

Expand All @@ -248,9 +268,9 @@ function upgradeToFullPluginSupport({
let userConfig = [...pluginConfigs, ...configs]

let { resolvedConfig } = resolveConfig(designSystem, [
{ config: createCompatConfig(designSystem.theme), base, reference: true },
{ config: createCompatConfig(designSystem.theme), base, reference: true, src: undefined },
...userConfig,
{ config: { plugins: [darkModePlugin] }, base, reference: true },
{ config: { plugins: [darkModePlugin] }, base, reference: true, src: undefined },
])
let { resolvedConfig: resolvedUserConfig, replacedThemeKeys } = resolveConfig(
designSystem,
Expand Down Expand Up @@ -285,6 +305,7 @@ function upgradeToFullPluginSupport({
}
}

let currentSrc: SourceLocation | undefined = undefined
let pluginApiConfig = {
designSystem,
ast,
Expand All @@ -294,12 +315,18 @@ function upgradeToFullPluginSupport({
features |= value
},
},
srcRef: {
get current() {
return currentSrc
},
},
}

let pluginApi = buildPluginApi({ ...pluginApiConfig, referenceMode: false })
let referenceModePluginApi = undefined

for (let { handler, reference } of resolvedConfig.plugins) {
for (let { handler, reference, src } of resolvedConfig.plugins) {
currentSrc = src
if (reference) {
referenceModePluginApi ||= buildPluginApi({ ...pluginApiConfig, referenceMode: true })
handler(referenceModePluginApi)
Expand Down
20 changes: 14 additions & 6 deletions packages/tailwindcss/src/compat/config/resolve-config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { DesignSystem } from '../../design-system'
import type { SourceLocation } from '../../source-maps/source'
import colors from '../colors'
import type { PluginWithConfig } from '../plugin-api'
import { createThemeFn } from '../plugin-functions'
Expand All @@ -16,6 +17,7 @@ export interface ConfigFile {
base: string
config: UserConfig
reference: boolean
src: SourceLocation | undefined
}

interface ResolutionContext {
Expand Down Expand Up @@ -131,7 +133,7 @@ export type PluginUtils = {

function extractConfigs(
ctx: ResolutionContext,
{ config, base, path, reference }: ConfigFile,
{ config, base, path, reference, src }: ConfigFile,
): void {
let plugins: PluginWithConfig[] = []

Expand All @@ -140,17 +142,17 @@ function extractConfigs(
if ('__isOptionsFunction' in plugin) {
// Happens with `plugin.withOptions()` when no options were passed:
// e.g. `require("my-plugin")` instead of `require("my-plugin")(options)`
plugins.push({ ...plugin(), reference })
plugins.push({ ...plugin(), reference, src })
} else if ('handler' in plugin) {
// Happens with `plugin(…)`:
// e.g. `require("my-plugin")`
//
// or with `plugin.withOptions()` when the user passed options:
// e.g. `require("my-plugin")(options)`
plugins.push({ ...plugin, reference })
plugins.push({ ...plugin, reference, src })
} else {
// Just a plain function without using the plugin(…) API
plugins.push({ handler: plugin, reference })
plugins.push({ handler: plugin, reference, src })
}
}

Expand All @@ -162,15 +164,21 @@ function extractConfigs(
}

for (let preset of config.presets ?? []) {
extractConfigs(ctx, { path, base, config: preset, reference })
extractConfigs(ctx, { path, base, config: preset, reference, src })
}

// Apply configs from plugins
for (let plugin of plugins) {
ctx.plugins.push(plugin)

if (plugin.config) {
extractConfigs(ctx, { path, base, config: plugin.config, reference: !!plugin.reference })
extractConfigs(ctx, {
path,
base,
config: plugin.config,
reference: !!plugin.reference,
src: plugin.src ?? src,
})
}
}

Expand Down
10 changes: 9 additions & 1 deletion packages/tailwindcss/src/compat/plugin-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Candidate, CandidateModifier, NamedUtilityValue } from '../candida
import { substituteFunctions } from '../css-functions'
import * as CSS from '../css-parser'
import type { DesignSystem } from '../design-system'
import type { SourceLocation } from '../source-maps/source'
import { withAlpha } from '../utilities'
import { DefaultMap } from '../utils/default-map'
import { escape } from '../utils/escape'
Expand All @@ -24,6 +25,7 @@ export type PluginWithConfig = {

/** @internal */
reference?: boolean
src?: SourceLocation | undefined
}
export type PluginWithOptions<T> = {
(options?: T): PluginWithConfig
Expand Down Expand Up @@ -93,19 +95,25 @@ export function buildPluginApi({
resolvedConfig,
featuresRef,
referenceMode,
srcRef,
}: {
designSystem: DesignSystem
ast: AstNode[]
resolvedConfig: ResolvedConfig
featuresRef: { current: Features }
referenceMode: boolean
srcRef: { current: SourceLocation | undefined }
}): PluginAPI {
let api: PluginAPI = {
addBase(css) {
if (referenceMode) return
let baseNodes = objectToAst(css)
featuresRef.current |= substituteFunctions(baseNodes, designSystem)
ast.push(atRule('@layer', 'base', baseNodes))
let rule = atRule('@layer', 'base', baseNodes)
walk([rule], (node) => {
node.src = srcRef.current
})
ast.push(rule)
},

addVariant(name, variant) {
Expand Down
52 changes: 52 additions & 0 deletions packages/tailwindcss/src/source-maps/source-map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,3 +419,55 @@ test('license comments with new lines preserve source locations', async ({ expec
'input.css: 2:11 <- 2:11',
])
})

test('Source locations for `addBase` point to the `@plugin` that generated them', async ({
expect,
}) => {
let { sources, annotations } = await run({
input: dedent`
@plugin "./plugin.js";
@config "./config.js";
`,
options: {
async loadModule(id, base) {
if (id === './plugin.js') {
return {
module: createPlugin(({ addBase }) => {
addBase({ body: { color: 'red' } })
}),
base,
path: '',
}
}

if (id === './config.js') {
return {
module: {
plugins: [
createPlugin(({ addBase }) => {
addBase({ body: { color: 'green' } })
}),
],
},
base,
path: '',
}
}

throw new Error(`unknown module ${id}`)
},
},
})

expect(sources).toEqual(['input.css'])

expect(annotations).toEqual([
//
'input.css: 1:0-12 <- 1:0-21',
'input.css: 2:2-7 <- 1:0-21',
'input.css: 3:4-14 <- 1:0-21',
'input.css: 6:0-12 <- 2:0-21',
'input.css: 7:2-7 <- 2:0-21',
'input.css: 8:4-16 <- 2:0-21',
])
})