Skip to content

Add compile-time platform flags across TSRX builders - #98

Merged
leonidaz merged 4 commits into
mainfrom
feat/platform-flags-95
Sep 11, 2026
Merged

leonidaz merged 4 commits into
mainfrom
feat/platform-flags-95

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #95.

Summary

  • add the shared web, ios, and android platform option and compatible import.meta.env.platform typing
  • specialize exact ordinary-if platform guards immediately after parsing and before TSRX semantic analysis, CSS extraction, target lowering, source mapping, and virtual TypeScript generation
  • resolve tsrx.platform through inherited, nested, and project-referenced TypeScript configs, including config refreshes and dot completion
  • make every in-repo builder read the project tsconfig automatically, while retaining a validated explicit override/fallback that must agree with tsconfig
  • define the same three boolean paths in every React, Preact, Solid, and Vue Vite/Rspack/Bun integration
  • add equivalent replacement rules to the existing React Turbopack integration, preserving and composing upstream source maps
  • reject invalid platform values and conflicting Vite, Rspack, or Bun definitions
  • document the ordinary-if versus runtime @if boundary

Builder coverage

  • Vite: React, Preact, Solid, Vue; nearest/referenced config or plugin tsconfig override
  • Rspack: React, Preact, Solid, Vue; context plus resolve.tsConfig
  • Bun: React, Preact, Solid, Vue; build root plus build.tsconfig
  • Turbopack: React (the integration currently present); Next typescript.tsconfigPath or Turbopack root

Validation

  • pnpm test — 96 files, 4,155 passed, 33 skipped
  • pnpm typecheck
  • pnpm changeset:check
  • pnpm install --frozen-lockfile
  • pnpm --filter tsrx-website build

Cursor Bugbot findings from earlier revisions were addressed with regression coverage: chained Turbopack source maps, broader Rspack DefinePlugin conflict detection, and solution-style project-reference resolution.

The local all-files formatting check also inspected machine-generated IntelliJ cache files that are absent from a clean checkout; all touched source and documentation files are formatted.

@vercel

vercel Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
tsrx-website Ready Ready Preview Sep 11, 2026 7:53am UTC
tsrx-website-mcp Ready Ready Preview Sep 11, 2026 7:53am UTC

Request Review

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Turbopack loader clobbers source maps
    • The platform loader now forwards the previous loader map into replacePlatformFlags, which passes it through unchanged or composes it so debugging still points at the original .tsrx source.
  • ✅ Fixed: Rspack conflict check misses plugins
    • Rspack plugins now read DefinePlugin definitions from definitions, options, or _args and identify plugins by name or constructor, so conflicting import.meta.env.platform.* values throw.

Create PR

Or push these changes by commenting:

@cursor push 2f75925ffd
Preview (2f75925ffd)
diff --git a/.changeset/compose-platform-loader-maps.md b/.changeset/compose-platform-loader-maps.md
new file mode 100644
--- /dev/null
+++ b/.changeset/compose-platform-loader-maps.md
@@ -1,0 +1,10 @@
+---
+'@tsrx/core': patch
+'@tsrx/turbopack-plugin-react': patch
+'@tsrx/rspack-plugin-react': patch
+'@tsrx/rspack-plugin-preact': patch
+'@tsrx/rspack-plugin-solid': patch
+'@tsrx/rspack-plugin-vue': patch
+---
+
+Compose incoming source maps in the Turbopack platform loader and detect webpack-shaped Rspack DefinePlugin conflicts.

diff --git a/packages/rspack-plugin-preact/src/index.js b/packages/rspack-plugin-preact/src/index.js
--- a/packages/rspack-plugin-preact/src/index.js
+++ b/packages/rspack-plugin-preact/src/index.js
@@ -18,14 +18,31 @@
 const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
 const CSS_QUERY_PATTERN = /tsrx-css/;
 
+/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
+function get_define_plugin_definitions(plugin) {
+	if (plugin == null || typeof plugin !== 'object') return undefined;
+	const name = plugin.name ?? plugin.constructor?.name;
+	if (name !== 'DefinePlugin') return undefined;
+
+	if (plugin.definitions && typeof plugin.definitions === 'object') {
+		return plugin.definitions;
+	}
+	if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
+		return plugin._args[0];
+	}
+	if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
+		return plugin.options;
+	}
+	return undefined;
+}
+
 /** @param {Compiler} compiler @param {Platform | undefined} platform */
 function apply_platform_definitions(compiler, platform) {
 	if (platform === undefined) return;
 	const compiler_with_definitions = /** @type {any} */ (compiler);
 	for (const plugin of compiler_with_definitions.options.plugins ?? []) {
-		if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
-		const definitions = plugin._args[0];
-		if (definitions && typeof definitions === 'object') {
+		const definitions = get_define_plugin_definitions(plugin);
+		if (definitions) {
 			mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
 		}
 	}

diff --git a/packages/rspack-plugin-react/src/index.js b/packages/rspack-plugin-react/src/index.js
--- a/packages/rspack-plugin-react/src/index.js
+++ b/packages/rspack-plugin-react/src/index.js
@@ -14,15 +14,32 @@
 const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
 const CSS_QUERY_PATTERN = /tsrx-css/;
 
+/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
+function get_define_plugin_definitions(plugin) {
+	if (plugin == null || typeof plugin !== 'object') return undefined;
+	const name = plugin.name ?? plugin.constructor?.name;
+	if (name !== 'DefinePlugin') return undefined;
+
+	if (plugin.definitions && typeof plugin.definitions === 'object') {
+		return plugin.definitions;
+	}
+	if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
+		return plugin._args[0];
+	}
+	if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
+		return plugin.options;
+	}
+	return undefined;
+}
+
 /** @param {Compiler} compiler @param {Platform | undefined} platform */
 function apply_platform_definitions(compiler, platform) {
 	if (platform === undefined) return;
 
 	const compiler_with_definitions = /** @type {any} */ (compiler);
 	for (const plugin of compiler_with_definitions.options.plugins ?? []) {
-		if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
-		const definitions = plugin._args[0];
-		if (definitions && typeof definitions === 'object') {
+		const definitions = get_define_plugin_definitions(plugin);
+		if (definitions) {
 			mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
 		}
 	}

diff --git a/packages/rspack-plugin-solid/src/index.js b/packages/rspack-plugin-solid/src/index.js
--- a/packages/rspack-plugin-solid/src/index.js
+++ b/packages/rspack-plugin-solid/src/index.js
@@ -21,14 +21,31 @@
 const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
 const CSS_QUERY_PATTERN = /tsrx-css/;
 
+/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
+function get_define_plugin_definitions(plugin) {
+	if (plugin == null || typeof plugin !== 'object') return undefined;
+	const name = plugin.name ?? plugin.constructor?.name;
+	if (name !== 'DefinePlugin') return undefined;
+
+	if (plugin.definitions && typeof plugin.definitions === 'object') {
+		return plugin.definitions;
+	}
+	if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
+		return plugin._args[0];
+	}
+	if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
+		return plugin.options;
+	}
+	return undefined;
+}
+
 /** @param {Compiler} compiler @param {Platform | undefined} platform */
 function apply_platform_definitions(compiler, platform) {
 	if (platform === undefined) return;
 	const compiler_with_definitions = /** @type {any} */ (compiler);
 	for (const plugin of compiler_with_definitions.options.plugins ?? []) {
-		if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
-		const definitions = plugin._args[0];
-		if (definitions && typeof definitions === 'object') {
+		const definitions = get_define_plugin_definitions(plugin);
+		if (definitions) {
 			mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
 		}
 	}

diff --git a/packages/rspack-plugin-vue/src/index.js b/packages/rspack-plugin-vue/src/index.js
--- a/packages/rspack-plugin-vue/src/index.js
+++ b/packages/rspack-plugin-vue/src/index.js
@@ -17,14 +17,31 @@
 const CSS_QUERY_PATTERN = /tsrx-css/;
 const SOURCE_EXTENSION_PATTERN = /\.[cm]?[jt]sx?$/;
 
+/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
+function get_define_plugin_definitions(plugin) {
+	if (plugin == null || typeof plugin !== 'object') return undefined;
+	const name = plugin.name ?? plugin.constructor?.name;
+	if (name !== 'DefinePlugin') return undefined;
+
+	if (plugin.definitions && typeof plugin.definitions === 'object') {
+		return plugin.definitions;
+	}
+	if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
+		return plugin._args[0];
+	}
+	if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
+		return plugin.options;
+	}
+	return undefined;
+}
+
 /** @param {Compiler} compiler @param {Platform | undefined} platform */
 function apply_platform_definitions(compiler, platform) {
 	if (platform === undefined) return;
 	const compiler_with_definitions = /** @type {any} */ (compiler);
 	for (const plugin of compiler_with_definitions.options.plugins ?? []) {
-		if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
-		const definitions = plugin._args[0];
-		if (definitions && typeof definitions === 'object') {
+		const definitions = get_define_plugin_definitions(plugin);
+		if (definitions) {
 			mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
 		}
 	}

diff --git a/packages/tsrx/src/transform/platform.js b/packages/tsrx/src/transform/platform.js
--- a/packages/tsrx/src/transform/platform.js
+++ b/packages/tsrx/src/transform/platform.js
@@ -1,6 +1,7 @@
 /** @import * as AST from 'estree' */
 /** @import { CompileError, Platform, PlatformSpecializationOptions } from '../../types/index' */
 
+import { decode, encode } from '@jridgewell/sourcemap-codec';
 import MagicString from 'magic-string';
 import { DIAGNOSTIC_CODES } from '../diagnostics.js';
 import { error } from '../errors.js';
@@ -327,22 +328,124 @@
 }
 
 /**
+ * @param {unknown} map
+ * @returns {import('source-map').RawSourceMap | undefined}
+ */
+function normalize_source_map(map) {
+	if (map == null) return undefined;
+	const parsed = typeof map === 'string' ? JSON.parse(map) : map;
+	if (parsed && typeof parsed === 'object' && typeof parsed.mappings === 'string') {
+		return /** @type {import('source-map').RawSourceMap} */ (parsed);
+	}
+	return undefined;
+}
+
+/**
+ * Chain a follow-up MagicString map through an incoming compile map so the
+ * result still names the original file and content, not the intermediate source.
+ *
+ * @param {import('source-map').RawSourceMap} input_map
+ * @param {import('source-map').RawSourceMap} output_map
+ * @returns {import('source-map').RawSourceMap}
+ */
+function compose_source_maps(input_map, output_map) {
+	const input_decoded = decode(input_map.mappings);
+	const output_decoded = decode(output_map.mappings);
+
+	/**
+	 * @param {number} line
+	 * @param {number} column
+	 * @returns {{ source_index: number, line: number, column: number, name_index?: number } | null}
+	 */
+	function original_position_for(line, column) {
+		const segments = input_decoded[line];
+		if (!segments || segments.length === 0) return null;
+
+		let low = 0;
+		let high = segments.length - 1;
+		let found = -1;
+		while (low <= high) {
+			const mid = (low + high) >> 1;
+			if (segments[mid][0] <= column) {
+				found = mid;
+				low = mid + 1;
+			} else {
+				high = mid - 1;
+			}
+		}
+		if (found === -1) return null;
+
+		const segment = segments[found];
+		if (segment.length < 4) return null;
+
+		return {
+			source_index: segment[1],
+			line: segment[2],
+			column: segment[3],
+			name_index: segment.length > 4 ? segment[4] : undefined,
+		};
+	}
+
+	/** @typedef {[number] | [number, number, number, number] | [number, number, number, number, number]} SourceMapSegment */
+	/** @type {SourceMapSegment[][]} */
+	const composed = [];
+	for (const line of output_decoded) {
+		/** @type {SourceMapSegment[]} */
+		const next_line = [];
+		for (const segment of line) {
+			if (segment.length < 4) {
+				next_line.push([segment[0]]);
+				continue;
+			}
+
+			const original = original_position_for(segment[2], segment[3]);
+			if (!original) continue;
+
+			next_line.push(
+				original.name_index === undefined
+					? [segment[0], original.source_index, original.line, original.column]
+					: [
+							segment[0],
+							original.source_index,
+							original.line,
+							original.column,
+							original.name_index,
+						],
+			);
+		}
+		composed.push(next_line);
+	}
+
+	return {
+		...input_map,
+		file: output_map.file ?? input_map.file,
+		mappings: encode(composed),
+	};
+}
+
+/**
  * Replace exact platform flag expressions in a JavaScript/TypeScript module.
  * This is used by integrations without a native `define` facility. It does not
  * perform dead-code elimination; the downstream bundler sees literal booleans
  * and owns that optimization.
  *
+ * When `input_map` is supplied, the returned map is composed through that map
+ * so loader chains keep pointing at the original file instead of the
+ * intermediate source that this pass rewrites.
+ *
  * @param {string} source
  * @param {string} filename
  * @param {unknown} platform_value
+ * @param {import('source-map').RawSourceMap | string | null} [input_map]
  * @returns {{ code: string, map: import('source-map').RawSourceMap }}
  */
-export function replace_platform_flags(source, filename, platform_value) {
+export function replace_platform_flags(source, filename, platform_value, input_map) {
 	const platform = validate_platform(platform_value);
 	if (platform === undefined) {
 		throw new TypeError('Replacing TSRX platform flags requires a configured platform.');
 	}
 
+	const incoming = normalize_source_map(input_map);
 	const ast = parse_module(source, filename);
 	const output = new MagicString(source);
 
@@ -358,8 +461,13 @@
 	}
 
 	visit(ast);
+	if (!output.hasChanged() && incoming) {
+		return { code: source, map: incoming };
+	}
+
+	const map = output.generateMap({ source: filename, includeContent: true, hires: true });
 	return {
 		code: output.toString(),
-		map: output.generateMap({ source: filename, includeContent: true, hires: true }),
+		map: incoming ? compose_source_maps(incoming, map) : map,
 	};
 }

diff --git a/packages/tsrx/tests/utils/platform.test.js b/packages/tsrx/tests/utils/platform.test.js
--- a/packages/tsrx/tests/utils/platform.test.js
+++ b/packages/tsrx/tests/utils/platform.test.js
@@ -1,3 +1,4 @@
+import { encode } from '@jridgewell/sourcemap-codec';
 import { describe, expect, it } from 'vitest';
 import {
 	createPlatformDefinitions,
@@ -61,5 +62,40 @@
 		expect(result.code).toContain("'import.meta.env.platform.ios'");
 		expect(result.code).toContain('const active = true;');
 		expect(result.map.sources).toEqual(['flags.ts']);
+		expect(result.map.sourcesContent?.[0]).toBe(source);
 	});
+
+	it('keeps an incoming compile map when no flags are rewritten', () => {
+		const source = 'export const ready = true;';
+		const incoming = {
+			version: 3,
+			sources: ['App.tsrx'],
+			sourcesContent: ['export function App() @{ true }'],
+			names: [],
+			mappings: 'AAAA',
+		};
+
+		const result = replacePlatformFlags(source, 'App.tsrx', 'web', incoming);
+
+		expect(result.code).toBe(source);
+		expect(result.map).toBe(incoming);
+	});
+
+	it('composes an incoming map instead of treating the rewritten source as the original file', () => {
+		const intermediate = 'const active = import.meta.env.platform.android;\n';
+		const incoming = {
+			version: 3,
+			file: 'App.js',
+			sources: ['App.tsrx'],
+			sourcesContent: ['const active = FLAG;\n'],
+			names: [],
+			mappings: encode([[[0, 0, 0, 0]]]),
+		};
+
+		const result = replacePlatformFlags(intermediate, 'App.tsrx', 'android', incoming);
+
+		expect(result.code).toContain('const active = true;');
+		expect(result.map.sources).toEqual(['App.tsrx']);
+		expect(result.map.sourcesContent).toEqual(['const active = FLAG;\n']);
+	});
 });

diff --git a/packages/tsrx/types/index.d.ts b/packages/tsrx/types/index.d.ts
--- a/packages/tsrx/types/index.d.ts
+++ b/packages/tsrx/types/index.d.ts
@@ -2395,6 +2395,7 @@
 	source: string,
 	filename: string,
 	platform: unknown,
+	inputMap?: import('source-map').RawSourceMap | string | null,
 ): { code: string; map: import('source-map').RawSourceMap };
 
 /**

diff --git a/packages/turbopack-plugin-react/src/platform-loader.js b/packages/turbopack-plugin-react/src/platform-loader.js
--- a/packages/turbopack-plugin-react/src/platform-loader.js
+++ b/packages/turbopack-plugin-react/src/platform-loader.js
@@ -15,11 +15,16 @@
  * pruned exact ordinary-if guards; this pass handles flags left in runtime
  * expressions and ordinary JavaScript/TypeScript modules.
  *
+ * Webpack-compatible loaders receive the previous loader's source map. That map
+ * must be forwarded so this pass does not treat compiled TSX as the original
+ * `.tsrx` file.
+ *
  * @this {LoaderContext}
  * @param {string} source
+ * @param {import('source-map').RawSourceMap | string | undefined} [input_map]
  * @returns {void}
  */
-export default function tsrx_react_turbopack_platform_loader(source) {
+export default function tsrx_react_turbopack_platform_loader(source, input_map) {
 	const callback = this.async();
 
 	try {
@@ -27,6 +32,7 @@
 			source,
 			this.resourcePath,
 			this.getOptions?.().platform,
+			input_map,
 		);
 		callback(null, code, map);
 	} catch (/** @type {any} */ error) {

diff --git a/packages/turbopack-plugin-react/tests/platform-builders.test.js b/packages/turbopack-plugin-react/tests/platform-builders.test.js
--- a/packages/turbopack-plugin-react/tests/platform-builders.test.js
+++ b/packages/turbopack-plugin-react/tests/platform-builders.test.js
@@ -1,4 +1,5 @@
 import { describe, expect, it } from 'vitest';
+import { compile } from '@tsrx/react';
 import { tsrxReact as viteReact } from '../../vite-plugin-react/src/index.js';
 import { tsrxPreact as vitePreact } from '../../vite-plugin-preact/src/index.js';
 import { tsrxSolid as viteSolid } from '../../vite-plugin-solid/src/index.js';
@@ -113,12 +114,21 @@
 		expect(compiler.options.module.rules[rule_index].use.at(-1).options.platform).toBe('ios');
 	});
 
-	it('reports conflicting Rspack definitions', () => {
+	it.each([
+		['Rspack _args', { name: 'DefinePlugin', _args: [{ 'import.meta.env.platform.web': true }] }],
+		[
+			'webpack definitions',
+			{ name: 'DefinePlugin', definitions: { 'import.meta.env.platform.web': true } },
+		],
+		['plugin options', { name: 'DefinePlugin', options: { 'import.meta.env.platform.web': true } }],
+		[
+			'constructor name',
+			new (class DefinePlugin {
+				definitions = { 'import.meta.env.platform.web': true };
+			})(),
+		],
+	])('reports conflicting Rspack definitions from %s', (_, conflict) => {
 		const plugin = new TsrxReactRspackPlugin({ platform: 'ios' });
-		const conflict = {
-			name: 'DefinePlugin',
-			_args: [{ 'import.meta.env.platform.web': true }],
-		};
 		const compiler = {
 			options: {
 				plugins: [conflict],
@@ -183,4 +193,52 @@
 		expect(transformed.output).toContain('[false, true]');
 		expect(transformed.map).toBeTruthy();
 	});
+
+	it('preserves the TSRX compile map when no runtime flags remain', async () => {
+		const source = `export function App() @{
+				<div>{'Hello world'}</div>
+			}`;
+		const compiled = compile(source, '/virtual/App.tsrx', { platform: 'ios' });
+		const transformed = await new Promise((resolve) => {
+			turbopackPlatformLoader.call(
+				{
+					resourcePath: '/virtual/App.tsrx',
+					getOptions: () => ({ platform: 'ios' }),
+					async: () => (error, output, map) => resolve({ error, output, map }),
+				},
+				compiled.code,
+				compiled.map,
+			);
+		});
+
+		expect(transformed.error).toBeNull();
+		expect(transformed.output).toBe(compiled.code);
+		expect(transformed.map).toBe(compiled.map);
+		expect(transformed.map.sourcesContent?.[0]).toBe(source);
+	});
+
+	it('composes the TSRX compile map when runtime flags are rewritten', async () => {
+		const source = `export function App() @{
+				<div>{import.meta.env.platform.ios ? 'ios' : 'other'}</div>
+			}`;
+		const compiled = compile(source, '/virtual/App.tsrx', { platform: 'ios' });
+		expect(compiled.code).toContain('import.meta.env.platform.ios');
+
+		const transformed = await new Promise((resolve) => {
+			turbopackPlatformLoader.call(
+				{
+					resourcePath: '/virtual/App.tsrx',
+					getOptions: () => ({ platform: 'ios' }),
+					async: () => (error, output, map) => resolve({ error, output, map }),
+				},
+				compiled.code,
+				compiled.map,
+			);
+		});
+
+		expect(transformed.error).toBeNull();
+		expect(transformed.output).toContain("true ? 'ios' : 'other'");
+		expect(transformed.map.sourcesContent?.[0]).toBe(source);
+		expect(transformed.map.sourcesContent?.[0]).not.toBe(compiled.code);
+	});
 });

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Builders miss referenced tsconfig platforms
    • resolveBuildPlatform now walks TypeScript project references after the nearest tsconfig extends chain, so Vite-style tsconfig.app.json platform settings are applied at build time.

Create PR

Or push these changes by commenting:

@cursor push 4a42fed6b3
Preview (4a42fed6b3)
diff --git a/packages/tsrx/src/config.js b/packages/tsrx/src/config.js
--- a/packages/tsrx/src/config.js
+++ b/packages/tsrx/src/config.js
@@ -1,5 +1,6 @@
 /** @import { Platform } from '../types/index' */
 
+import fs from 'node:fs';
 import path from 'node:path';
 import { findTsconfig, getExtendsChain } from 'get-tsconfig';
 import { validate_platform } from './transform/platform.js';
@@ -12,6 +13,18 @@
  * @property {string} [integration]
  */
 
+/**
+ * @typedef {object} TsconfigLayer
+ * @property {string} path
+ * @property {unknown} config
+ */
+
+/**
+ * @typedef {object} DeclaredPlatform
+ * @property {Platform} platform
+ * @property {string} path
+ */
+
 /** @param {unknown} value @returns {string} */
 function render_value(value) {
 	try {
@@ -52,47 +65,127 @@
 }
 
 /**
- * Resolve `tsrx.platform` for a builder from the same nearest/configured
- * tsconfig and explicit `extends` graph used by the project. An explicit
- * builder option is retained as an escape hatch, but it must agree with a
- * tsconfig declaration when both exist.
+ * TypeScript project references use `.json` files as-is and otherwise look for
+ * `tsconfig.json` inside the referenced directory.
  *
- * @param {BuildPlatformResolutionOptions} [options]
- * @returns {Platform | undefined}
+ * @param {string} from_config_path
+ * @param {string} reference_path
+ * @returns {string}
  */
-export function resolveBuildPlatform(options = {}) {
-	const integration = options.integration ?? 'build integration';
-	const explicit_platform = validate_platform(options.platform, `${integration} platform option`);
-	const root = path.resolve(options.root ?? process.cwd());
-	const config_path = options.tsconfig
-		? path.resolve(root, options.tsconfig)
-		: findTsconfig(root, { cache: new Map() });
+function resolve_reference_config_path(from_config_path, reference_path) {
+	const resolved = path.resolve(path.dirname(from_config_path), reference_path);
+	return path.extname(resolved) === '.json' ? resolved : path.join(resolved, 'tsconfig.json');
+}
 
-	if (!config_path) return explicit_platform;
+/**
+ * @param {unknown} config
+ * @param {string} from_config_path
+ * @returns {string[]}
+ */
+function get_reference_config_paths(config, from_config_path) {
+	if (!config || typeof config !== 'object' || Array.isArray(config)) return [];
+	const references = /** @type {Record<string, unknown>} */ (config).references;
+	if (!Array.isArray(references)) return [];
 
+	/** @type {string[]} */
+	const paths = [];
+	for (const reference of references) {
+		if (!reference || typeof reference !== 'object' || Array.isArray(reference)) continue;
+		const reference_path = /** @type {Record<string, unknown>} */ (reference).path;
+		if (typeof reference_path !== 'string' || reference_path === '') continue;
+		paths.push(resolve_reference_config_path(from_config_path, reference_path));
+	}
+	return paths;
+}
+
+/**
+ * @param {TsconfigLayer[]} layers
+ * @returns {DeclaredPlatform | undefined}
+ */
+function read_chain_platform(layers) {
+	for (const layer of layers) {
+		const declared = read_layer_platform(layer);
+		if (declared !== undefined) return { platform: declared, path: layer.path };
+	}
+	return undefined;
+}
+
+/**
+ * Resolve a project's own `extends` graph first, then fall through to nested
+ * `references`. A solution tsconfig that only lists referenced projects, the
+ * default Vite layout, therefore still finds `tsrx.platform` on
+ * `tsconfig.app.json`.
+ *
+ * @param {string} config_path
+ * @param {string} integration
+ * @param {Map<string, unknown>} cache
+ * @param {Set<string>} seen
+ * @param {boolean} [allow_missing]
+ * @returns {DeclaredPlatform | undefined}
+ */
+function read_project_platform(config_path, integration, cache, seen, allow_missing = false) {
+	const normalized = path.resolve(config_path);
+	if (seen.has(normalized)) return undefined;
+	seen.add(normalized);
+	if (allow_missing && !fs.existsSync(normalized)) return undefined;
+
 	let layers;
 	try {
 		// get-tsconfig returns the root first, followed by extended configs in
 		// precedence order. The first own platform declaration is therefore the
 		// effective value, while a sibling `tsrx.compiler` key can still inherit.
-		layers = getExtendsChain(config_path, { cache: new Map() });
+		layers = getExtendsChain(normalized, { cache });
 	} catch (error) {
 		throw new Error(
-			`Unable to resolve TSRX platform from ${config_path} for ${integration}: ${error instanceof Error ? error.message : String(error)}`,
+			`Unable to resolve TSRX platform from ${normalized} for ${integration}: ${error instanceof Error ? error.message : String(error)}`,
 			{ cause: error },
 		);
 	}
 
-	/** @type {Platform | undefined} */
-	let configured_platform;
-	for (const layer of layers) {
-		const declared = read_layer_platform(layer);
-		if (declared !== undefined) {
-			configured_platform = declared;
-			break;
+	const own = read_chain_platform(layers);
+	if (own) return own;
+
+	const start = layers[0];
+	if (!start) return undefined;
+
+	/** @type {DeclaredPlatform | undefined} */
+	let referenced;
+	for (const reference_path of get_reference_config_paths(start.config, start.path)) {
+		const nested = read_project_platform(reference_path, integration, cache, seen, true);
+		if (!nested) continue;
+		if (referenced && referenced.platform !== nested.platform) {
+			throw new Error(
+				`TSRX platform mismatch for ${integration}: ${referenced.path} selects ${JSON.stringify(referenced.platform)}, but ${nested.path} selects ${JSON.stringify(nested.platform)}.`,
+			);
 		}
+		referenced = nested;
 	}
+	return referenced;
+}
 
+/**
+ * Resolve `tsrx.platform` for a builder from the same nearest/configured
+ * tsconfig, explicit `extends` graph, and TypeScript project `references` used
+ * by the project. An explicit builder option is retained as an escape hatch,
+ * but it must agree with a tsconfig declaration when both exist.
+ *
+ * @param {BuildPlatformResolutionOptions} [options]
+ * @returns {Platform | undefined}
+ */
+export function resolveBuildPlatform(options = {}) {
+	const integration = options.integration ?? 'build integration';
+	const explicit_platform = validate_platform(options.platform, `${integration} platform option`);
+	const root = path.resolve(options.root ?? process.cwd());
+	const cache = new Map();
+	const config_path = options.tsconfig
+		? path.resolve(root, options.tsconfig)
+		: findTsconfig(root, { cache });
+
+	if (!config_path) return explicit_platform;
+
+	const configured = read_project_platform(config_path, integration, cache, new Set());
+	const configured_platform = configured?.platform;
+
 	if (
 		explicit_platform !== undefined &&
 		configured_platform !== undefined &&

diff --git a/packages/tsrx/tests/utils/config.test.js b/packages/tsrx/tests/utils/config.test.js
--- a/packages/tsrx/tests/utils/config.test.js
+++ b/packages/tsrx/tests/utils/config.test.js
@@ -85,4 +85,63 @@
 		write_config('tsconfig.json', { tsrx: { platform } });
 		expect(() => resolveBuildPlatform({ root: directory })).toThrow(/Invalid TSRX platform/);
 	});
+
+	it('reads platform from a referenced project such as tsconfig.app.json', () => {
+		write_config('tsconfig.app.json', { tsrx: { compiler: '@tsrx/react', platform: 'ios' } });
+		write_config('tsconfig.node.json', { include: ['vite.config.ts'] });
+		write_config('tsconfig.json', {
+			files: [],
+			references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.node.json' }],
+		});
+
+		expect(resolveBuildPlatform({ root: directory })).toBe('ios');
+	});
+
+	it('follows extends inside a referenced project', () => {
+		write_config('tsconfig.base.json', { tsrx: { platform: 'android' } });
+		write_config('tsconfig.app.json', {
+			extends: './tsconfig.base.json',
+			tsrx: { compiler: '@tsrx/react' },
+		});
+		write_config('tsconfig.json', {
+			files: [],
+			references: [{ path: './tsconfig.app.json' }],
+		});
+
+		expect(resolveBuildPlatform({ root: directory })).toBe('android');
+	});
+
+	it('prefers the solution tsconfig over a referenced project', () => {
+		write_config('tsconfig.app.json', { tsrx: { platform: 'ios' } });
+		write_config('tsconfig.json', {
+			files: [],
+			references: [{ path: './tsconfig.app.json' }],
+			tsrx: { platform: 'web' },
+		});
+
+		expect(resolveBuildPlatform({ root: directory })).toBe('web');
+	});
+
+	it('resolves a directory project reference to its tsconfig.json', () => {
+		write_config('app/tsconfig.json', { tsrx: { platform: 'web' } });
+		write_config('tsconfig.json', {
+			files: [],
+			references: [{ path: './app' }],
+		});
+
+		expect(resolveBuildPlatform({ root: directory })).toBe('web');
+	});
+
+	it('rejects conflicting platforms across referenced projects', () => {
+		write_config('tsconfig.app.json', { tsrx: { platform: 'ios' } });
+		write_config('tsconfig.node.json', { tsrx: { platform: 'web' } });
+		write_config('tsconfig.json', {
+			files: [],
+			references: [{ path: './tsconfig.app.json' }, { path: './tsconfig.node.json' }],
+		});
+
+		expect(() => resolveBuildPlatform({ root: directory, integration: 'test builder' })).toThrow(
+			/platform mismatch.*tsconfig\.app\.json selects "ios".*tsconfig\.node\.json selects "web"/i,
+		);
+	});
 });

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 99d5890. Configure here.

Comment thread packages/tsrx/src/config.js Resolved

This branch was successfully deployed

2 active deployments
Preview – tsrx-website — ebec0264 Deployed Sep 11, 2026 by vercel[bot]
Preview – tsrx-website-mcp — ebec0264 Deployed Sep 11, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Add compile-time import.meta.env.platform flags for web, iOS, and Android

1 participant