@tsrx/bun-plugin-react 0.1.110 → 0.1.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +14 -2
  2. package/package.json +5 -4
  3. package/src/index.js +167 -64
package/README.md CHANGED
@@ -25,6 +25,13 @@ The plugin compiles `.tsrx` modules with `@tsrx/react`, runs Bun's TSX transform
25
25
  for React's automatic JSX runtime, and emits sibling-scoped `<style>` blocks (each
26
26
  styles its siblings and everything below them) as virtual CSS modules.
27
27
 
28
+ Bun selects the development or production JSX runtime for each build, as it does
29
+ for `.tsx` files. Production builds need an automatic JSX setting such as
30
+ `"jsx": "react-jsx"` in the tsconfig Bun applies: the nearest one for `Bun.build`,
31
+ the working directory's for `Bun.plugin()`. Under the classic `"jsx": "react"`,
32
+ the plugin keeps the automatic runtime, but Bun then always uses
33
+ `react/jsx-dev-runtime`, which React's production build does not provide.
34
+
28
35
  For `bun:test`, register it from a preload:
29
36
 
30
37
  ```ts
@@ -41,9 +48,14 @@ Bun.plugin(tsrxReact());
41
48
  - `platform`: optional override/fallback for the compile-time platform. Normally
42
49
  the plugin reads `tsrx.platform` from Bun's selected/nearest tsconfig, including
43
50
  `extends`. An override must match tsconfig. For `Bun.build`, all three exact
44
- flags are defined and conflicting definitions are rejected.
51
+ flags are defined and conflicting definitions are rejected. With `Bun.plugin()`,
52
+ including `bun:test` preloads, flags left in compiled `.tsrx` output are
53
+ replaced with their values.
45
54
  - `emitCss`: whether to emit virtual CSS imports (default: `true`).
46
- - `include`, `exclude`: regex filters for source files.
55
+ - `include`, `exclude`: regex filters for source files. Under `Bun.plugin()`, an
56
+ instance hands a `.tsrx` file it leaves out to the first registered TSRX plugin
57
+ instance that includes it. When no instance includes the file, Bun loads it as
58
+ it would without a plugin.
47
59
 
48
60
  When using `runtimeImports: 'direct'`, install the runtime as a direct production
49
61
  dependency of the package that owns the compiled modules:
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Bun plugin for @tsrx/react (.tsrx modules)",
4
4
  "license": "MIT",
5
5
  "author": "Dominic Gannaway",
6
- "version": "0.1.110",
6
+ "version": "0.1.111",
7
7
  "type": "module",
8
8
  "publishConfig": {
9
9
  "access": "public"
@@ -20,8 +20,8 @@
20
20
  }
21
21
  },
22
22
  "dependencies": {
23
- "@tsrx/core": "0.5.5",
24
- "@tsrx/react": "0.4.5"
23
+ "@tsrx/core": "0.6.0",
24
+ "@tsrx/react": "0.5.0"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "bun": "^1.0.0",
@@ -37,6 +37,7 @@
37
37
  "types"
38
38
  ],
39
39
  "scripts": {
40
- "test": "pnpm -w test --project bun-plugin-react"
40
+ "test": "pnpm -w test --project bun-plugin-react",
41
+ "test:native": "bun test tests/native.test.ts"
41
42
  }
42
43
  }
package/src/index.js CHANGED
@@ -1,10 +1,12 @@
1
- /** @import { BunPlugin, Target, Transpiler } from 'bun' */
1
+ /** @import { BunPlugin, OnLoadResult } from 'bun' */
2
2
  /** @import { Platform, RuntimeImportMode } from '@tsrx/react' */
3
3
 
4
+ import { existsSync } from 'node:fs';
4
5
  import { readFile } from 'node:fs/promises';
6
+ import path from 'node:path';
5
7
  import { compile } from '@tsrx/react';
6
- import { mergePlatformDefinitions, validatePlatform } from '@tsrx/core';
7
- import { resolveBuildPlatform } from '@tsrx/core/config';
8
+ import { mergePlatformDefinitions, replacePlatformFlags, validatePlatform } from '@tsrx/core';
9
+ import { resolveBuildPlatform, resolveTsconfigJsx } from '@tsrx/core/config';
8
10
 
9
11
  const DEFAULT_INCLUDE = /\.tsrx$/;
10
12
  const CSS_QUERY = '?tsrx-css&lang.css';
@@ -62,26 +64,98 @@ function to_css_id(file_path) {
62
64
  return file_path + CSS_QUERY;
63
65
  }
64
66
 
67
+ const RUNTIME_STATE = Symbol.for('@tsrx/bun-plugin.runtime.v1');
68
+
69
+ /**
70
+ * @typedef {{
71
+ * loaders: Array<{ compiles: (file_path: string) => boolean, load: (file_path: string) => Promise<OnLoadResult> }>,
72
+ * css: Map<string, string>,
73
+ * }} RuntimeState
74
+ */
75
+
76
+ /**
77
+ * State that every TSRX Bun plugin instance registered with Bun.plugin()
78
+ * shares. There Bun calls only the first onLoad hook whose filter matches and
79
+ * needs an object back, so the instance it calls serves the stylesheets any
80
+ * instance compiled and hands on the `.tsrx` files it leaves out. The key has
81
+ * a version, so a later change to this shape can take a new key without
82
+ * breaking older plugins installed alongside. `Bun.plugin.clearAll()` doesn't
83
+ * tell plugins, so instances registered before it stay in the list.
84
+ *
85
+ * @returns {RuntimeState}
86
+ */
87
+ function get_runtime_state() {
88
+ const scope = /** @type {any} */ (globalThis);
89
+ return (scope[RUNTIME_STATE] ??= { loaders: [], css: new Map() });
90
+ }
91
+
65
92
  /**
93
+ * Loads a `.tsrx` file this instance leaves out under Bun.plugin(): with the
94
+ * first registered instance that compiles it, or else the way Bun loads it
95
+ * without a plugin, as a module whose default export is the file's path.
96
+ *
97
+ * @param {RuntimeState} runtime
98
+ * @param {string} file_path
99
+ * @returns {OnLoadResult | Promise<OnLoadResult>}
100
+ */
101
+ function load_elsewhere(runtime, file_path) {
102
+ const owner = runtime.loaders.find((loader) => loader.compiles(file_path));
103
+ return owner ? owner.load(file_path) : { exports: { default: file_path }, loader: 'object' };
104
+ }
105
+
106
+ /**
107
+ * Directory the tsconfig lookup starts from. Without `root`, Bun builds from
108
+ * the common ancestor directory of the entrypoints, or from the working
109
+ * directory when every entrypoint is an in-memory `files` entry. The nearest
110
+ * tsconfig is searched from there. A relative `tsconfig` option resolves from
111
+ * the working directory.
112
+ *
113
+ * @param {{ root?: string, tsconfig?: unknown, entrypoints?: unknown[], files?: object }} build_config
114
+ * @returns {string}
115
+ */
116
+ function get_tsconfig_base(build_config) {
117
+ if (build_config.root) return build_config.root;
118
+ const entrypoints = (build_config.entrypoints ?? []).filter(
119
+ (entrypoint) => typeof entrypoint === 'string',
120
+ );
121
+ const virtual_files = new Set(
122
+ Object.keys(build_config.files ?? {}).map((file) => path.resolve(file)),
123
+ );
124
+ if (
125
+ typeof build_config.tsconfig === 'string' ||
126
+ entrypoints.every((entrypoint) => virtual_files.has(path.resolve(entrypoint)))
127
+ ) {
128
+ return process.cwd();
129
+ }
130
+
131
+ let base = path.dirname(path.resolve(entrypoints[0]));
132
+ for (const entrypoint of entrypoints) {
133
+ const file_path = path.resolve(entrypoint);
134
+ while (/^\.\.(?:[/\\]|$)/.test(path.relative(base, file_path))) {
135
+ base = path.dirname(base);
136
+ }
137
+ }
138
+ return base;
139
+ }
140
+
141
+ /**
142
+ * Prefix compiled TSX with the pragma that selects the JSX import source, so
143
+ * Bun's own TSX transform picks the development or production runtime for the
144
+ * build. Bun ignores a lone `@jsxImportSource` under a classic `"jsx": "react"`
145
+ * tsconfig. There `@jsxRuntime automatic` keeps the automatic runtime, which
146
+ * Bun then takes from the development entry point in every build.
147
+ *
148
+ * @param {string} code
66
149
  * @param {string} jsx_import_source
67
- * @param {Target | undefined} target
68
- * @returns {Transpiler | null}
150
+ * @param {boolean} classic
151
+ * @returns {string}
69
152
  */
70
- function create_transpiler(jsx_import_source, target) {
71
- const Transpiler = globalThis.Bun?.Transpiler;
72
- if (typeof Transpiler !== 'function') return null;
73
-
74
- return new Transpiler({
75
- loader: 'tsx',
76
- target,
77
- autoImportJSX: true,
78
- tsconfig: {
79
- compilerOptions: {
80
- jsx: 'react-jsx',
81
- jsxImportSource: jsx_import_source,
82
- },
83
- },
84
- });
153
+ function add_jsx_pragma(code, jsx_import_source, classic) {
154
+ const runtime = classic ? '@jsxRuntime automatic ' : '';
155
+ const pragma = `/** ${runtime}@jsxImportSource ${jsx_import_source} */\n`;
156
+ // A shebang has to stay on the first line.
157
+ const shebang_end = code.startsWith('#!') ? code.indexOf('\n') + 1 || code.length : 0;
158
+ return code.slice(0, shebang_end) + pragma + code.slice(shebang_end);
85
159
  }
86
160
 
87
161
  /**
@@ -108,7 +182,7 @@ export function tsrxReact(options = {}) {
108
182
  // via Bun.plugin(), including bun:test preloads, does not provide it.
109
183
  const build_config = build.config ?? {};
110
184
  const platform = resolveBuildPlatform({
111
- root: build_config.root ?? process.cwd(),
185
+ root: get_tsconfig_base(build_config),
112
186
  tsconfig: typeof build_config.tsconfig === 'string' ? build_config.tsconfig : undefined,
113
187
  platform: explicit_platform,
114
188
  integration: '@tsrx/bun-plugin-react',
@@ -122,49 +196,78 @@ export function tsrxReact(options = {}) {
122
196
  })
123
197
  );
124
198
  }
125
- const transpiler = create_transpiler(jsx_import_source, build_config.target);
126
-
127
- build.onResolve({ filter: CSS_QUERY_PATTERN }, (args) => ({
128
- path: args.path,
129
- }));
130
-
131
- build.onLoad({ filter: CSS_QUERY_PATTERN }, (args) => ({
132
- contents: css_cache.get(args.path) ?? '',
133
- loader: 'css',
134
- }));
135
-
136
- build.onLoad(
137
- { filter: options.include ?? DEFAULT_INCLUDE, namespace: 'file' },
138
- async (args) => {
139
- if (!should_compile(options, args.path)) return undefined;
140
-
141
- const source = await readFile(args.path, 'utf-8');
142
- const { code, css } = compile(source, args.path, compile_options);
143
- const css_id = to_css_id(args.path);
144
-
145
- let output = code;
146
- if (emit_css && css) {
147
- css_cache.set(css_id, css);
148
- // After the module's own imports so imported themes' sheets load first
149
- // and a rule in the applying module wins at equal specificity.
150
- output = `${code}\nimport ${JSON.stringify(css_id)};\n`;
151
- } else {
152
- css_cache.delete(css_id);
153
- }
154
-
155
- if (transpiler) {
156
- return {
157
- contents: transpiler.transformSync(output),
158
- loader: 'js',
159
- };
160
- }
161
-
162
- return {
163
- contents: output,
164
- loader: 'tsx',
165
- };
166
- },
167
- );
199
+ // Bun.plugin() registration has no `define`, so the flags left in compiled
200
+ // output get their values written in directly.
201
+ const inline_platform = build.config ? undefined : platform;
202
+ /** @type {Map<string, unknown>} */
203
+ const tsconfig_cache = new Map();
204
+ // Bun.build() applies the tsconfig nearest each file. Bun.plugin()
205
+ // registration applies the working directory's own tsconfig, if any, to
206
+ // every file, without searching parent folders.
207
+ const runtime_classic_jsx =
208
+ !build.config &&
209
+ existsSync(path.join(process.cwd(), 'tsconfig.json')) &&
210
+ resolveTsconfigJsx(process.cwd(), tsconfig_cache) === 'react';
211
+ /** @param {string} file_path */
212
+ const uses_classic_jsx = (file_path) =>
213
+ build.config
214
+ ? resolveTsconfigJsx(file_path, tsconfig_cache) === 'react'
215
+ : runtime_classic_jsx;
216
+
217
+ const runtime = build.config ? undefined : get_runtime_state();
218
+ const stylesheets = runtime ? runtime.css : css_cache;
219
+
220
+ // Every instance sees every virtual CSS request. Leave the ones another
221
+ // instance compiled to that instance, except under Bun.plugin(), where
222
+ // the first instance has to answer and every instance shares the sheets.
223
+ build.onResolve({ filter: CSS_QUERY_PATTERN }, (args) => {
224
+ if (!stylesheets.has(args.path)) return undefined;
225
+ return { path: args.path };
226
+ });
227
+
228
+ build.onLoad({ filter: CSS_QUERY_PATTERN }, (args) => {
229
+ const css = stylesheets.get(args.path);
230
+ if (css !== undefined) return { contents: css, loader: 'css' };
231
+ return runtime ? { contents: '', loader: 'css' } : undefined;
232
+ });
233
+
234
+ /**
235
+ * @param {string} file_path
236
+ * @returns {Promise<OnLoadResult>}
237
+ */
238
+ const load_tsrx = async (file_path) => {
239
+ const source = await readFile(file_path, 'utf-8');
240
+ const { code: compiled, css } = compile(source, file_path, compile_options);
241
+ const code =
242
+ inline_platform === undefined
243
+ ? compiled
244
+ : replacePlatformFlags(compiled, file_path, inline_platform).code;
245
+ const css_id = to_css_id(file_path);
246
+
247
+ let output = code;
248
+ if (emit_css && css) {
249
+ stylesheets.set(css_id, css);
250
+ // After the module's own imports so imported themes' sheets load first
251
+ // and a rule in the applying module wins at equal specificity.
252
+ output = `${code}\nimport ${JSON.stringify(css_id)};\n`;
253
+ } else {
254
+ stylesheets.delete(css_id);
255
+ }
256
+
257
+ return {
258
+ contents: add_jsx_pragma(output, jsx_import_source, uses_classic_jsx(file_path)),
259
+ loader: 'tsx',
260
+ };
261
+ };
262
+ runtime?.loaders.push({
263
+ compiles: (file_path) => should_compile(options, file_path),
264
+ load: load_tsrx,
265
+ });
266
+
267
+ build.onLoad({ filter: options.include ?? DEFAULT_INCLUDE, namespace: 'file' }, (args) => {
268
+ if (should_compile(options, args.path)) return load_tsrx(args.path);
269
+ return runtime ? load_elsewhere(runtime, args.path) : undefined;
270
+ });
168
271
  },
169
272
  };
170
273
  }