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