Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- An editor's source-tagging plugin runs natively in `oj dev` (the `lovable-tagger` package's `lovable-plugin`, 1.3.x, is the one oj knows). Config extraction asks the instance what it does, and oj does it: `react/jsx-dev-runtime` is answered with the plugin's own module, served at Vite's URL for its virtual id and compiled like any module so its import of the real runtime reaches the pre-bundle; and the app's resolved Tailwind theme is written to `src/tailwind.config.lov.json` at boot and when `tailwind.config.ts` or a v4 CSS entry changes, with the app's own `@tailwindcss/node` (v4) or esbuild and `tailwindcss/resolveConfig` (v3), off the boot's path. The plugin host leaves the plugin out, so an app whose other plugins are native (React's) boots no host at all. An instance with a hook oj does not know, and every build, keep the host as before.

### Changed

- The goldens and the TanStack Start fixture (`e2e/fixtures/start-app`) are recorded from Vite 8.4.0, the release, in place of 8.4.0-beta.1; rolldown stays 1.3.2, the crate oj builds with (8.4.0 declares `~1.3.2`; 8.4.1 declares `~1.3.4`, whose Rust crates are not published, and its build import analysis hands rolldown a field 1.3.2 rejects). Recorded from `/tmp`, so a recording carries no path depth of the machine it was made on.
Expand Down
30 changes: 30 additions & 0 deletions crates/oj_config/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,36 @@ pub struct OjConfig {
/// `recordStartImportProtection` writes.
#[serde(skip)]
pub vite_start_import_protection: Option<serde_json::Value>,
/// The config's source-tagging plugin (an editor's), from extraction
/// (not a config key): what oj does in its place in a serve.
#[serde(skip)]
pub vite_source_tagging: Option<SourceTagging>,
}

/// What a config's source-tagging plugin does in a serve, as config
/// extraction asked the instance (native-plugins.mjs `isSourceTaggingPlugin`):
/// oj serves the module and writes the theme itself and hosts no plugin for
/// it.
#[derive(Debug, Default, Clone, PartialEq, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SourceTagging {
/// The package the plugin ships in, whose own dependencies its theme
/// tools resolve from.
pub package: Option<String>,
/// The module it answers `react/jsx-dev-runtime` with, from every
/// importer but that module: its id (a `\0`-prefixed virtual id) and
/// its code. None: the feature is off (its `resolveId` passed).
pub jsx_dev_runtime: Option<JsxDevRuntime>,
/// It writes the app's resolved Tailwind theme to
/// `src/tailwind.config.lov.json` at boot and on a Tailwind config change.
pub tailwind_theme: bool,
}

/// A virtual module a plugin answers a specifier with: its id and its code.
#[derive(Debug, Default, Clone, PartialEq, Deserialize)]
pub struct JsxDevRuntime {
pub id: String,
pub code: String,
}

/// Vite's `worker` block, the part a build's worker bundles take.
Expand Down
40 changes: 40 additions & 0 deletions crates/oj_server/src/assets/native-plugins.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,46 @@ export const OJ_NATIVE_PLUGIN_NAMES = new Set([
// worker they spawn throws asynchronously; skip them outright.
export const OJ_UNSUPPORTED_PLUGIN_NAMES = new Set(["vite-plugin-checker"]);

// An editor's source-tagging plugin: a `pre` plugin whose work in a serve is
// two things oj does itself. It answers `react/jsx-dev-runtime` with a
// virtual module wrapping React's jsxDEV, which records each element's source
// on its DOM node for the editor (resolveId + load), and it writes the app's
// resolved Tailwind theme to `src/tailwind.config.lov.json` at boot and when
// the Tailwind config changes, for the editor's color picker (buildStart +
// configureServer). Known by plugin name, with the package the plugin ships
// in (where its own tools, esbuild and tailwindcss, resolve from). Config
// extraction asks the instance what it does (`sourceTagging` in
// vite-extract.mjs); the dev server serves the module and writes the file
// (oj_server's source_tagging). Only an instance with exactly these hooks is
// taken over: one with more (a later version's transform) stays hosted, and a
// build hosts it as before.
export const SOURCE_TAGGING_PLUGINS = new Map([["lovable-plugin", "lovable-tagger"]]);
const SOURCE_TAGGING_PLUGIN_HOOKS = new Set([
"name",
"enforce",
"configResolved",
"buildStart",
"configureServer",
"resolveId",
"load",
]);

export function isSourceTaggingPlugin(plugin) {
if (!plugin || typeof plugin !== "object" || !SOURCE_TAGGING_PLUGINS.has(plugin.name)) return false;
return Object.keys(plugin).every((key) => SOURCE_TAGGING_PLUGIN_HOOKS.has(key));
}

// The package a source-tagging plugin ships in.
export function sourceTaggingPackage(plugin) {
return SOURCE_TAGGING_PLUGINS.get(plugin && plugin.name) ?? null;
}

// Whether oj does `plugin`'s work itself under `command`, by its name: the
// host leaves such a plugin out, and config extraction does not count it.
export function nativeByName(plugin, command) {
return OJ_NATIVE_PLUGIN_NAMES.has(plugin && plugin.name) || (command === "serve" && isSourceTaggingPlugin(plugin));
}

// Start's router plugin: the code splitter pair it adds per environment
// (client and server, sharing one route list) and the router generator, whose
// run fills that list (`routesByFile`, the files the route tree imports).
Expand Down
7 changes: 4 additions & 3 deletions crates/oj_server/src/assets/plugin-host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
isReimplemented,
isRouteSplitting,
isStartManifest,
nativeByName,
isStartPostBuild,
} from "./native-plugins.mjs";
import { idFilterGlob, idFilterRegExp, loadViteGlobs, viteGlobs } from "./start/vite-globs.mjs";
Expand Down Expand Up @@ -2365,7 +2366,7 @@ function esbuildMinifyPlugin() {
// top-level list and what applyToEnvironment returns alike.
function ojRunsNatively(p, c = main) {
const name = p && p.name;
return OJ_NATIVE_PLUGIN_NAMES.has(name) || nativeImportProtection(name) || (c.leaveOut && startLeavesOut(name));
return nativeByName(p, command) || nativeImportProtection(name) || (c.leaveOut && startLeavesOut(name));
}
// Start's import protection (its resolve and transform-cache plugins), where
// oj checks imports itself (`ojNativeImportProtection`: a dev server whose
Expand Down Expand Up @@ -2406,7 +2407,7 @@ try {
// loads it; the hooks below run under the resolved one.
applyUserNodeEnv(userConfig);
allPlugins = (await flattenPlugins(list)).map(nativeStylexStandIn);
nativePlugins = allPlugins.filter((p) => OJ_NATIVE_PLUGIN_NAMES.has(p && p.name));
nativePlugins = allPlugins.filter((p) => nativeByName(p, command));
main.rawPlugins = allPlugins;
noteStartCompilerPosition(allPlugins);
main.plugins = hostedPlugins(allPlugins, userConfig);
Expand Down Expand Up @@ -6530,7 +6531,7 @@ async function openWorkerContainer(parent, bundleChain) {
bundleChain,
};
// As the app's: the natively run plugins stay listed (hooks unrun).
const native = raw.filter((p) => OJ_NATIVE_PLUGIN_NAMES.has(p && p.name));
const native = raw.filter((p) => nativeByName(p, command));
resolved.plugins = withCssPostShim(workerPlugins.concat(native), cssPostShimInto(c.pluginCss));
await runConfigResolved(workerPlugins, resolved, c);
c.resolvedConfig = resolved;
Expand Down
176 changes: 176 additions & 0 deletions crates/oj_server/src/assets/source-tagging-theme.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Raphael Amorim
//
// The source-tagging plugin's Tailwind theme (oj_server's source_tagging):
// the resolved theme of the app at `root`, written to
// src/tailwind.config.lov.json as the plugin writes it. Tailwind v4 first: a
// CSS entry that imports tailwindcss, read by the app's @tailwindcss/node,
// the theme namespaces with their `var()`s resolved from `:root`. Else v3:
// tailwind.config.ts bundled by esbuild, resolved by tailwindcss/resolveConfig,
// both from the plugin's `package` (its dependencies) or the app. `run`
// returns { wrote } (null when the app has neither) or { error }.
import { existsSync } from "node:fs";
import fs from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";

const V4_CSS_CANDIDATES = ["src/styles.css", "src/index.css", "src/globals.css", "src/app.css"];

const V4_NAMESPACES = {
colors: "--color",
screens: "--breakpoint",
spacing: "--spacing",
borderRadius: "--radius",
fontFamily: "--font",
opacity: "--opacity",
};

// The plugin resolves its tools from its own package (esbuild and tailwindcss
// are its dependencies; @tailwindcss/node an optional peer), so that comes
// first, then the app itself.
let anchors = [];
function setAnchors(root, pkg) {
const candidates = [pkg && path.join(root, "node_modules", pkg, "package.json"), path.join(root, "package.json")];
anchors = candidates.filter((anchor) => anchor && existsSync(anchor)).map((anchor) => createRequire(anchor));
}

function requirers() {
return anchors;
}

function resolveFrom(root, spec) {
for (const req of requirers(root)) {
try {
return req.resolve(spec);
} catch {
// Not from here; the next anchor may have it.
}
}
return null;
}

async function importFrom(root, spec) {
const resolved = resolveFrom(root, spec);
return resolved ? import(pathToFileURL(resolved).href) : null;
}

function requireFrom(root, spec) {
for (const req of requirers(root)) {
try {
return req(spec);
} catch (e) {
if (e && e.code !== "MODULE_NOT_FOUND") throw e;
}
}
return null;
}

async function findV4CssEntry(root) {
for (const candidate of V4_CSS_CANDIDATES) {
const abs = path.resolve(root, candidate);
try {
const contents = await fs.readFile(abs, "utf8");
if (/@import\s+["']tailwindcss/.test(contents)) return abs;
} catch {
// Not there; the next candidate may be.
}
}
return null;
}

// v4's `@theme inline { --color-primary: var(--primary) }` with
// `:root { --primary: oklch(...) }` leaves the namespace values as var()
// references; an editor's color picker wants the values, so `:root` is read
// and substituted. Scoped to the common shape, as the plugin's is.
export function parseRootVars(css) {
const vars = {};
const rootMatch = css.match(/:root\s*\{([^}]*)\}/s);
if (!rootMatch) return vars;
for (const decl of rootMatch[1].split(";")) {
const trimmed = decl.trim();
if (!trimmed.startsWith("--")) continue;
const colon = trimmed.indexOf(":");
if (colon === -1) continue;
const key = trimmed.slice(0, colon).trim();
const value = trimmed.slice(colon + 1).trim();
if (key && value) vars[key] = value;
}
return vars;
}

export function resolveVars(value, rootVars, depth = 0) {
if (depth > 8) return value;
return value.replace(/var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/g, (match, name, fallback) => {
const resolved = rootVars[name];
if (resolved !== undefined) return resolveVars(resolved, rootVars, depth + 1);
return fallback ?? match;
});
}

async function generateV4Config(cssEntry, outfile, load) {
const css = await fs.readFile(cssEntry, "utf8");
const ds = await load(css, { base: path.dirname(cssEntry) });
const rootVars = parseRootVars(css);
const theme = {};
for (const [configKey, namespace] of Object.entries(V4_NAMESPACES)) {
const entries = {};
for (const [key, rawValue] of ds.theme.namespace(namespace)) {
if (key === null) continue;
entries[key] = resolveVars(rawValue, rootVars);
}
theme[configKey] = entries;
}
await fs.mkdir(path.dirname(outfile), { recursive: true });
await fs.writeFile(outfile, JSON.stringify({ theme }, null, 2));
}

async function generateV3Config(root, configFile, outfile) {
const esbuild = await importFrom(root, "esbuild");
if (!esbuild) throw new Error("esbuild is not installed (the plugin's dependency)");
// Bundled beside the config, so its relative imports resolve as they do for
// the plugin; removed once imported.
const intermediate = path.resolve(root, "./.lov.tailwind.config.js");
await esbuild.build({
entryPoints: [configFile],
outfile: intermediate,
bundle: true,
format: "esm",
banner: {
js: 'import { createRequire } from "module"; const require = createRequire(import.meta.url);',
},
});
try {
const userConfig = await import(pathToFileURL(intermediate).href + "?update=" + Date.now());
if (!userConfig || !userConfig.default) throw new Error("Invalid Tailwind config structure");
const resolveConfigModule = requireFrom(root, "tailwindcss/resolveConfig.js");
if (!resolveConfigModule) throw new Error("tailwindcss/resolveConfig.js is not installed");
const resolveConfig = resolveConfigModule.default ?? resolveConfigModule;
await fs.mkdir(path.dirname(outfile), { recursive: true });
await fs.writeFile(outfile, JSON.stringify(resolveConfig(userConfig.default), null, 2));
} finally {
await fs.unlink(intermediate).catch(() => {});
}
}

export async function run({ root, package: pkg }) {
const outfile = path.resolve(root, "./src/tailwind.config.lov.json");
setAnchors(root, pkg);
try {
const cssEntry = await findV4CssEntry(root);
if (cssEntry) {
const tailwindNode = await importFrom(root, "@tailwindcss/node");
const load = tailwindNode && tailwindNode.__unstable__loadDesignSystem;
if (typeof load === "function") {
await generateV4Config(cssEntry, outfile, load);
return { wrote: outfile };
}
}
const v3ConfigFile = path.resolve(root, "./tailwind.config.ts");
if (!existsSync(v3ConfigFile)) return { wrote: null };
await generateV3Config(root, v3ConfigFile, outfile);
return { wrote: outfile };
} catch (e) {
return { error: String((e && e.stack) || e) };
}
}
55 changes: 54 additions & 1 deletion crates/oj_server/src/assets/vite-extract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import {
OJ_NATIVE_PLUGIN_NAMES,
OJ_UNSUPPORTED_PLUGIN_NAMES,
flattenPlugins,
isSourceTaggingPlugin,
sourceTaggingPackage,
isReimplemented,
nativeByName,
} from "./native-plugins.mjs";

// The slice of Vite's mergeConfigRecursively these assets need (twin copies:
Expand Down Expand Up @@ -2106,13 +2109,62 @@ async function activePluginCount(raw) {
if (!raw) return null;
try {
return (await flattenPlugins(raw.plugins)).filter(
(p) => !OJ_NATIVE_PLUGIN_NAMES.has(p.name) && !OJ_UNSUPPORTED_PLUGIN_NAMES.has(p.name),
(p) => !nativeByName(p, command) && !OJ_UNSUPPORTED_PLUGIN_NAMES.has(p.name),
).length;
} catch {
return null;
}
}

// What the config's source-tagging plugin (native-plugins.mjs) does in this
// serve, asked of the instance itself so no version of it is assumed: the
// module it answers `react/jsx-dev-runtime` with (its resolveId, then its
// load, from an importer of the app's), and whether it watches the Tailwind
// config (its configureServer registers a change listener only with that
// feature on, and the watcher calls are the hook's only effect, so a stand-in
// server sees them). null: no such plugin, or not a serve.
async function sourceTagging(raw) {
if (command !== "serve" || !raw) return null;
let plugin;
try {
plugin = (await flattenPlugins(raw.plugins)).find(isSourceTaggingPlugin);
} catch {
return null;
}
if (!plugin) return null;
const hook = (h) => (typeof h === "function" ? h : h && typeof h.handler === "function" ? h.handler : null);
let jsxDevRuntime = null;
try {
const resolveId = hook(plugin.resolveId);
const load = hook(plugin.load);
const answer =
resolveId &&
(await resolveId.call({}, "react/jsx-dev-runtime", appRoot + "/index.html", { ssr: false, isEntry: false }));
const id = typeof answer === "string" ? answer : answer && typeof answer.id === "string" ? answer.id : null;
const loaded = id && load ? await load.call({}, id) : null;
const code = typeof loaded === "string" ? loaded : loaded && typeof loaded.code === "string" ? loaded.code : null;
if (id && code != null) jsxDevRuntime = { id, code };
} catch (e) {
emitStderr(`oj: the source-tagging plugin's jsx-dev-runtime could not be read: ${(e && e.stack) || e}\n`);
}
let tailwindTheme = false;
try {
const configureServer = hook(plugin.configureServer);
if (configureServer) {
const watcher = {
add() {},
on(event) {
if (event === "change") tailwindTheme = true;
},
};
await configureServer.call({}, { watcher });
}
} catch {
// The plugin's own try/catch swallows a watcher error; so does this.
}
return { package: sourceTaggingPackage(plugin), jsxDevRuntime, tailwindTheme };
}

// Whether the config carries an editor's HMR gate plugin, which oj replaces
// with its native gate (native-plugins.mjs).
async function hasEditorHmrGate(raw) {
Expand Down Expand Up @@ -2409,6 +2461,7 @@ async function extractValues(input) {
resolveError: resolveFailure ? String((resolveFailure && resolveFailure.message) || resolveFailure) : null,
stylex: await stylexPlugin(raw),
editorHmrGate: await hasEditorHmrGate(raw),
sourceTagging: await sourceTagging(raw),
};
};
const out = await valuesOf(c);
Expand Down
Loading
Loading