@unframework.dev/unplugin 0.1.4 → 0.3.0

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.
package/README.md CHANGED
@@ -88,14 +88,15 @@ integration harness does (`sourceUtilities` in `tests/integration/harness/stylef
88
88
 
89
89
  ## Options
90
90
 
91
- | Option | Meaning |
92
- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
93
- | `target` | A built-in target's name (`"react"`, `"vue"`, `"svelte"`, `"solid"`, `"angular"`, `"qwik"`, `"astro"`) or a third-party `Target`. Optional on Vite, which detects a built-in target. Required on every other bundler. |
94
- | `extension` | What module ids append to the `.uf.tsx` path. Built-in targets have one; a third-party target must set it. |
95
- | `onCompile` | Called each time a module loads, with `{ id, file, target, files, diagnostics }`. Returning a string (or a promise of one) fails that module with it: the integration harness's golden guard. |
96
- | `plugins` | Compiler plugins, passed to `compile()` (the harness's canaries). |
97
- | `format` | Formats the output with oxfmt. Defaults to `true`, so a module's code equals the golden file byte for byte. |
98
- | `passThrough` | The specifier prefixes whose imports pass through to every output as written, passed to `compile()`. Defaults to `["virtual:"]`; a list replaces it, as `["virtual:", "styled-system/"]` adds an engine that generates files. A prefix that is empty, relative or absolute fails when the plugin is created. |
91
+ | Option | Meaning |
92
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
93
+ | `target` | A built-in target's name (`"react"`, `"vue"`, `"svelte"`, `"solid"`, `"angular"`, `"qwik"`, `"astro"`), `"solid@2"`, or a third-party `Target`. Optional on Vite, which detects a built-in target. Required on every other bundler. |
94
+ | `extension` | What module ids append to the `.uf.tsx` path. Built-in targets have one; a third-party target must set it. |
95
+ | `onCompile` | Called each time a module loads, with `{ id, file, target, files, diagnostics }`. Returning a string (or a promise of one) fails that module with it: the integration harness's golden guard. |
96
+ | `transformSource` | Called with a `.uf.tsx` or `.uf.ts` file's absolute path, with forward slashes, and its text, each time the plugin reads it, on the first load and on a hot update alike. The string it returns (or a promise of one) is what compiles, and `undefined` compiles the file as written. A hook that throws fails that load, with an error that names the file and the hook's message. `unframework preview` binds its controls to an example's components this way (ADR-0113). |
97
+ | `plugins` | Compiler plugins, passed to `compile()` (the harness's canaries). |
98
+ | `format` | Formats the output with oxfmt. Defaults to `true`, so a module's code equals the golden file byte for byte. |
99
+ | `passThrough` | The specifier prefixes whose imports pass through to every output as written, passed to `compile()`. Defaults to `["virtual:"]`; a list replaces it, as `["virtual:", "styled-system/"]` adds an engine that generates files. A prefix that is empty, relative or absolute fails when the plugin is created. |
99
100
 
100
101
  ## The dev server's allow list
101
102
 
@@ -123,6 +124,7 @@ name matches as this table writes it, so `vite:vue-jsx` and `vite-plugin-qwik-po
123
124
  | Svelte | `vite-plugin-svelte` | `@sveltejs/vite-plugin-svelte` |
124
125
  | React | `vite:react-*` | `@vitejs/plugin-react` |
125
126
  | Solid | `solid` | `vite-plugin-solid` |
127
+ | Solid 2 | `solid`, with `solid-js` 2 | `@solidjs/vite-plugin` |
126
128
  | Qwik | `vite-plugin-qwik` | `qwikVite` from Qwik |
127
129
  | Astro | `astro:*` | Astro's own plugins |
128
130
  | Angular | `@analogjs/vite-plugin-angular` | `@analogjs/vite-plugin-angular` |
package/dist/detect.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { createRequire } from "node:module";
2
+ import { join } from "node:path";
1
3
  import { readFileSync, realpathSync, statSync } from "node:fs";
2
4
  import { createDiagnostic, formatDiagnostic } from "@unframework.dev/diagnostics";
3
5
  // src/detect.ts
@@ -9,6 +11,7 @@ const FRAMEWORK_PLUGINS = {
9
11
  vue: (name) => name === VUE_PLUGIN,
10
12
  svelte: (name) => name === "vite-plugin-svelte",
11
13
  solid: (name) => name === "solid",
14
+ solid2: (name) => name === "solid",
12
15
  angular: (name) => name === "@analogjs/vite-plugin-angular",
13
16
  qwik: (name) => name === "vite-plugin-qwik",
14
17
  astro: (name) => name.startsWith("astro:")
@@ -18,17 +21,39 @@ const NO_SPAN = {
18
21
  end: 0
19
22
  };
20
23
  /**
24
+ * The major of the `solid-js` that resolves from `root`, or `undefined` when none does. Read from
25
+ * its `package.json`, so neither Solid build loads.
26
+ */
27
+ function solidMajor(root) {
28
+ try {
29
+ const manifest = createRequire(join(root, "package.json")).resolve("solid-js/package.json");
30
+ const { version } = JSON.parse(readFileSync(manifest, "utf8"));
31
+ const major = typeof version === "string" ? Number.parseInt(version, 10) : NaN;
32
+ return Number.isNaN(major) ? void 0 : major;
33
+ } catch {
34
+ return;
35
+ }
36
+ }
37
+ /**
21
38
  * The one target whose framework's plugin is among `plugins`, or the UF7005 or UF7006 message that
22
- * says why there isn't one. `file` names the configuration in the message.
39
+ * says why there isn't one. `file` names the configuration in the message. The `"solid"` plugin is
40
+ * Solid 2's when the `solid-js` that resolves from `root` is 2.x, and Solid 1's otherwise, as it
41
+ * was before `solid@2` (ADR-0102).
23
42
  */
24
- function detectTarget(plugins, file) {
43
+ function detectTarget(plugins, file, root = process.cwd()) {
25
44
  const names = plugins.flatMap(({ name }) => typeof name === "string" ? [name] : []);
45
+ let solid;
26
46
  const found = Object.entries(FRAMEWORK_PLUGINS).flatMap(([target, belongs]) => {
27
47
  const plugin = names.find((name) => belongs(name));
28
- return plugin ? [{
48
+ if (!plugin) return [];
49
+ if (target === "solid" || target === "solid2") {
50
+ solid ??= solidMajor(root) === 2 ? "solid2" : "solid";
51
+ if (target !== solid) return [];
52
+ }
53
+ return [{
29
54
  target,
30
55
  plugin
31
- }] : [];
56
+ }];
32
57
  });
33
58
  if (found.length === 1) return { target: found[0].target };
34
59
  const diagnostic = found.length ? createDiagnostic("UF7006", {
@@ -113,4 +138,4 @@ function fillVueScriptFs(plugins) {
113
138
  }
114
139
  };
115
140
  }
116
- export { NODE_SCRIPT_FS, detectTarget, fillVueScriptFs, hostOptionWarning };
141
+ export { NODE_SCRIPT_FS, detectTarget, fillVueScriptFs, hostOptionWarning, solidMajor };
package/dist/ids.js CHANGED
@@ -29,6 +29,7 @@ const ID_SUFFIXES = {
29
29
  vue: ".vue",
30
30
  svelte: ".svelte",
31
31
  solid: "",
32
+ solid2: "",
32
33
  angular: ".ts",
33
34
  qwik: "",
34
35
  astro: ".astro"
@@ -47,6 +48,7 @@ const COMPOSABLE_ID_SUFFIXES = {
47
48
  vue: "",
48
49
  svelte: ".svelte.ts",
49
50
  solid: "",
51
+ solid2: "",
50
52
  angular: ".ts",
51
53
  qwik: "",
52
54
  astro: ""
package/dist/plugin.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CompilerPlugin, TargetName, UfModule } from "@unframework.dev/compiler";
1
+ import { CompilerPlugin, TargetSelector, UfModule } from "@unframework.dev/compiler";
2
2
  import { Diagnostic } from "@unframework.dev/diagnostics";
3
3
  import { UnpluginInstance } from "unplugin";
4
4
  import { OutputFile, Target } from "@unframework.dev/codegen";
@@ -23,11 +23,11 @@ export interface CompileEvent {
23
23
  /** Options of the unframework plugin. */
24
24
  export interface UnframeworkOptions {
25
25
  /**
26
- * The framework to compile to: a built-in target's name, or a third-party target. On Vite it may
27
- * be left out, and the framework's plugin in the configuration decides (ADR-0075). Every other
28
- * bundler needs it.
26
+ * The framework to compile to: a built-in target's selector, such as `"solid@2"` (ADR-0102), or a
27
+ * third-party target. On Vite it may be left out, and the framework's plugin in the configuration
28
+ * decides (ADR-0075). Every other bundler needs it.
29
29
  */
30
- target?: TargetName | Target;
30
+ target?: TargetSelector | Target;
31
31
  /**
32
32
  * What module ids append to the `.uf.tsx` path: the extension the framework's own Vite plugin
33
33
  * claims, such as `".vue"`, or `""` to keep the `.uf.tsx` id. Defaults to the built-in
@@ -42,6 +42,14 @@ export interface UnframeworkOptions {
42
42
  * errors fails anyway, with the message after its diagnostics.
43
43
  */
44
44
  onCompile?(event: CompileEvent): string | void | Promise<string | void>;
45
+ /**
46
+ * Gives the source to compile for a `.uf.tsx` or `.uf.ts` file, in place of its text on disk:
47
+ * called with the file's absolute path, with forward slashes, and its text, each time the plugin
48
+ * reads it, on the first load and on a hot update alike. `undefined` compiles the file as
49
+ * written. `unframework preview` binds its controls to an example's components this way
50
+ * (ADR-0113). None by default.
51
+ */
52
+ transformSource?(file: string, source: string): string | undefined | Promise<string | undefined>;
45
53
  /** Compiler plugins, passed to `compile()` (the harness's canaries). */
46
54
  plugins?: readonly CompilerPlugin[];
47
55
  /** Formats the output with oxfmt. Defaults to `true`, so modules equal the golden files. */
package/dist/plugin.js CHANGED
@@ -3,7 +3,7 @@ import { chainQwikSegments, chainSvelteOnce } from "./chain.js";
3
3
  import { detectTarget, fillVueScriptFs, hostOptionWarning } from "./detect.js";
4
4
  import { COMPONENT_ID_FILTER, COMPOSABLE_EXTENSION, COMPOSABLE_ID_SUFFIXES, ID_SUFFIXES, SCAN_ID_PREFIX, SOURCE_EXTENSION, componentId, composableFilter, composableId, composableIdSuffix, idSuffix, moduleId, moduleIdCandidates, moduleIdFilter, parseComponentId, parseComposableId, parseModuleId, specifierFilter } from "./ids.js";
5
5
  import { basename, extname, isAbsolute, posix, relative, sep } from "node:path";
6
- import { checkPassThrough, createProject, createSyntacticOracle, resolveTarget } from "@unframework.dev/compiler";
6
+ import { checkPassThrough, createProject, createSyntacticOracle, isTargetSelector, resolveTarget, targetName } from "@unframework.dev/compiler";
7
7
  import { existsSync, readFileSync } from "node:fs";
8
8
  import { readFile } from "node:fs/promises";
9
9
  import { formatDiagnostic, formatDiagnostics } from "@unframework.dev/diagnostics";
@@ -85,7 +85,8 @@ const factory = (options = {}, meta) => {
85
85
  let extension;
86
86
  let joins;
87
87
  let subRequest;
88
- const selectTarget = (selected) => {
88
+ const selectTarget = (selector) => {
89
+ const selected = typeof selector === "string" && isTargetSelector(selector) ? targetName(selector) : selector;
89
90
  target = resolveTarget(selected);
90
91
  suffix = idSuffix(selected, options.extension);
91
92
  composableSuffix = composableIdSuffix(selected);
@@ -111,8 +112,18 @@ const factory = (options = {}, meta) => {
111
112
  ];
112
113
  let root = toPosix(process.cwd());
113
114
  const seen = /* @__PURE__ */ new Map();
114
- const read = async (path) => {
115
+ const readSource = async (path) => {
115
116
  const text = await readFile(path, "utf8").catch(() => void 0);
117
+ if (text === void 0 || !options.transformSource || !isSource(path)) return text;
118
+ try {
119
+ return await options.transformSource(path, text) ?? text;
120
+ } catch (error) {
121
+ const reason = error instanceof Error ? error.message : String(error);
122
+ throw new Error(`transformSource threw while reading ${path}: ${reason}`, { cause: error });
123
+ }
124
+ };
125
+ const read = async (path) => {
126
+ const text = await readSource(path);
116
127
  if (!seen.has(path)) seen.set(path, text);
117
128
  return text;
118
129
  };
@@ -195,6 +206,7 @@ const factory = (options = {}, meta) => {
195
206
  };
196
207
  };
197
208
  let queue = Promise.resolve();
209
+ let generation = 0;
198
210
  const exclusive = (task) => {
199
211
  const run = queue.then(task);
200
212
  queue = run.catch(() => void 0);
@@ -281,12 +293,13 @@ const factory = (options = {}, meta) => {
281
293
  const changed = /* @__PURE__ */ new Map();
282
294
  for (const path of paths) {
283
295
  if (!seen.has(path)) continue;
284
- const text = await readFile(path, "utf8").catch(() => void 0);
296
+ const text = await readSource(path);
285
297
  if (text !== seen.get(path)) changed.set(path, text);
286
298
  }
287
299
  if (!changed.size) return false;
288
300
  const before = new Map([...changed.keys()].map((path) => [path, seen.get(path)]));
289
301
  for (const [path, text] of changed) seen.set(path, text);
302
+ generation += 1;
290
303
  try {
291
304
  for (const graph of graphs.values()) {
292
305
  const names = [...changed.keys()].flatMap((path) => namesOf(graph, path));
@@ -302,14 +315,18 @@ const factory = (options = {}, meta) => {
302
315
  } catch (error) {
303
316
  for (const [path, text] of before) seen.set(path, text);
304
317
  throw error;
318
+ } finally {
319
+ generation += 1;
305
320
  }
306
321
  return true;
307
322
  };
308
- /** Hands the project every change it has not seen among what a module reached. */
309
- const refresh = (graph, filename) => {
323
+ /** The paths of every file a module's output depends on, its own included. */
324
+ const reachedPaths = (graph, filename) => {
310
325
  const { files, packages } = reachedFrom(graph, filename);
311
- return handOver(/* @__PURE__ */ new Set([...files.map((file) => `${graph.root}/${file}`), ...packageFiles(packages)]));
326
+ return /* @__PURE__ */ new Set([...files.map((file) => `${graph.root}/${file}`), ...packageFiles(packages)]);
312
327
  };
328
+ /** Hands the project every change it has not seen among what a module reached. */
329
+ const refresh = (graph, filename) => handOver(reachedPaths(graph, filename));
313
330
  /**
314
331
  * The current compile of a `.uf.tsx` file or a `.uf.ts` module, shared by every id that loads
315
332
  * it, and the source it compiled. The changes the project has not seen go through its `update`
@@ -319,7 +336,14 @@ const factory = (options = {}, meta) => {
319
336
  * compile is taken again. The result's outputs hold the copies of the shared `.ts` modules it
320
337
  * reaches, as `compile()`'s do (ADR-0070): the golden guard judges them.
321
338
  */
322
- const compileFile = (file) => exclusive(async () => {
339
+ const compileFile = async (file) => await currentCompile(file) ?? exclusive(async () => {
340
+ const done = await compileNow(file);
341
+ await warmReach(file, done.result);
342
+ return done;
343
+ });
344
+ const compiles = /* @__PURE__ */ new Map();
345
+ /** The body of `compileFile`, which only a task of `exclusive` runs. */
346
+ const compileNow = async (file) => {
323
347
  const { graph, filename } = locate(file);
324
348
  const { project } = graph;
325
349
  await refresh(graph, filename);
@@ -327,22 +351,74 @@ const factory = (options = {}, meta) => {
327
351
  if (await refresh(graph, filename)) result = await project.compile(filename);
328
352
  const source = seen.get(`${graph.root}/${filename}`) ?? "";
329
353
  const files = result.outputs[target.name] ?? [];
330
- if (!files.length) return {
331
- result,
332
- source
333
- };
334
- const outputs = {
354
+ const outputs = files.length ? {
335
355
  ...result.outputs,
336
356
  [target.name]: [...files, ...project.copies(filename)]
337
- };
338
- return {
339
- result: {
357
+ } : void 0;
358
+ const done = {
359
+ result: outputs ? {
340
360
  ...result,
341
361
  outputs
342
- },
362
+ } : result,
343
363
  source
344
364
  };
345
- });
365
+ compiles.set(file, {
366
+ compiled: done,
367
+ generation
368
+ });
369
+ return done;
370
+ };
371
+ /**
372
+ * The file's last compile, without waiting for `exclusive`, if it is still what `compileNow`
373
+ * would give: no change has been handed over since, and none waits on disk among the files it
374
+ * reached, which `refresh` would hand over. Anything else waits its turn. Qwik loads a
375
+ * component's segments inside a test (ADR-0050), and each resolves its imports through
376
+ * `childId`, so a request that queued behind every other file's compile on a busy server
377
+ * outran the test's timeout.
378
+ */
379
+ const currentCompile = async (file) => {
380
+ const kept = compiles.get(file);
381
+ if (kept?.generation !== generation) return void 0;
382
+ const { graph, filename } = locate(file);
383
+ const paths = [...reachedPaths(graph, filename)].filter((path) => seen.has(path));
384
+ const texts = await Promise.all(paths.map((path) => readFile(path, "utf8").catch(() => void 0)));
385
+ if (paths.some((path, index) => texts[index] !== seen.get(path))) return void 0;
386
+ return compiles.get(file) === kept && kept.generation === generation ? kept.compiled : void 0;
387
+ };
388
+ /**
389
+ * Compiles every `.uf.tsx` and `.uf.ts` file a module's IR imports reach, its children's
390
+ * children too, in the module's own task, so a request for them finds them current. A module's
391
+ * load runs as its importer is imported, while Qwik's segments, the first to import the
392
+ * children, load inside a test (ADR-0050). A file that is gone, or whose compile throws, is
393
+ * left to its own request, which reports it.
394
+ */
395
+ const warmReach = async (file, result) => {
396
+ const visited = /* @__PURE__ */ new Set([file]);
397
+ const pending = [{
398
+ file,
399
+ result
400
+ }];
401
+ for (let next = pending.pop(); next; next = pending.pop()) for (const entry of next.result.ir?.imports ?? []) {
402
+ const child = posix.join(posix.dirname(next.file), entry.file);
403
+ if (visited.has(child)) continue;
404
+ visited.add(child);
405
+ if (!existsSync(child)) continue;
406
+ const kept = compiles.get(child);
407
+ if (kept?.generation === generation) {
408
+ pending.push({
409
+ file: child,
410
+ result: kept.compiled.result
411
+ });
412
+ continue;
413
+ }
414
+ try {
415
+ pending.push({
416
+ file: child,
417
+ result: (await compileNow(child)).result
418
+ });
419
+ } catch {}
420
+ }
421
+ };
346
422
  /** The guard's verdict on a load: the message that fails the module, if any. */
347
423
  const guard = async (event) => {
348
424
  if (!options.onCompile) return void 0;
@@ -473,7 +549,7 @@ const factory = (options = {}, meta) => {
473
549
  compiled.set(id, assembly.code);
474
550
  if (verdict === void 0) failed.delete(id);
475
551
  else {
476
- const names = (result.ir?.composables ?? []).map(({ name }) => name);
552
+ const names = [...result.ir?.composables ?? [], ...(result.ir?.directives ?? []).filter((directive) => directive.exported)].map(({ name }) => name);
477
553
  failed.set(id, {
478
554
  message: verdict,
479
555
  exports: names
@@ -757,7 +833,7 @@ const factory = (options = {}, meta) => {
757
833
  resolveBare = import("vite").then(({ createIdResolver }) => createIdResolver(config));
758
834
  const file = config.configFile ? filenameOf(config.configFile) : "inline Vite configuration";
759
835
  if (options.target === void 0) {
760
- const detected = detectTarget(config.plugins, file);
836
+ const detected = detectTarget(config.plugins, file, config.root);
761
837
  if ("error" in detected) this.error(detected.error);
762
838
  else selectTarget(detected.target);
763
839
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unframework.dev/unplugin",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "description": "The Unframework bundler plugin: imports of .uf.tsx files compile to the selected framework, and that framework's own plugin finishes the job.",
5
5
  "keywords": [
6
6
  "astro",
@@ -79,22 +79,22 @@
79
79
  "access": "public"
80
80
  },
81
81
  "dependencies": {
82
- "@unframework.dev/codegen": "0.1.3",
83
- "@unframework.dev/compiler": "0.2.3",
84
- "@unframework.dev/diagnostics": "0.2.0",
82
+ "@unframework.dev/codegen": "0.2.1",
83
+ "@unframework.dev/compiler": "0.3.1",
84
+ "@unframework.dev/diagnostics": "0.3.1",
85
85
  "@unframework.dev/parser": "0.1.1",
86
86
  "magic-string": "^1.4.2",
87
87
  "unplugin": "^3.4.0"
88
88
  },
89
89
  "devDependencies": {
90
- "@qwik.dev/core": "2.0.0-beta.47",
90
+ "@qwik.dev/core": "2.0.0-rc.5",
91
91
  "@types/node": "^24.19.0",
92
- "@unframework.dev/target-angular": "0.1.3",
93
- "@unframework.dev/target-qwik": "0.1.3",
94
- "@unframework.dev/target-react": "0.1.3",
95
- "@unframework.dev/target-solid": "0.1.3",
96
- "@unframework.dev/target-svelte": "0.1.3",
97
- "@unframework.dev/target-vue": "0.1.3",
92
+ "@unframework.dev/target-angular": "0.2.1",
93
+ "@unframework.dev/target-qwik": "0.2.1",
94
+ "@unframework.dev/target-react": "0.2.1",
95
+ "@unframework.dev/target-solid": "0.2.1",
96
+ "@unframework.dev/target-svelte": "0.2.1",
97
+ "@unframework.dev/target-vue": "0.2.1",
98
98
  "@uxfront/typescript-config": "^0.1.0",
99
99
  "astro": "7.3.5",
100
100
  "react": "19.3.0",