solid-optimizer 1.0.0-next.0 → 1.0.0-next.2

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/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-BRCj4UN7.mjs";
1
+ import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-CwH9mvHD.mjs";
2
2
  export { type CompileOptions, type CompileResult, type ImportedConstants, type ModuleConstants, type Primitive, type Skip, type SkipPass, compile, readModuleConstants };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as readModuleConstants, t as compile } from "./compile-Cz6hbiQv.mjs";
1
+ import { n as readModuleConstants, t as compile } from "./compile-sCZdwEKG.mjs";
2
2
  export { compile, readModuleConstants };
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { s as Skip, t as CompileOptions } from "./compile-BRCj4UN7.mjs";
1
+ import { s as Skip, t as CompileOptions } from "./compile-CwH9mvHD.mjs";
2
2
  import { Options as Options$1 } from "@solidjs/vite-plugin";
3
3
  import { Plugin } from "vite";
4
4
  //#region src/vite/report.d.ts
@@ -35,6 +35,16 @@ export interface OptimizerOptions extends Pick<CompileOptions, 'fold' | 'inline'
35
35
  * @default false
36
36
  */
37
37
  report?: boolean | ((report: OptimizerReport) => void);
38
+ /**
39
+ * Packages whose components can be copied into the modules that use
40
+ * them, like `['@kobalte/core']`. A package has to publish its JSX, as
41
+ * most Solid libraries do through the `solid` export condition. A copy
42
+ * lets the bundler drop the original, and the runtime code only it used,
43
+ * even when the package lands in another chunk.
44
+ *
45
+ * @default []
46
+ */
47
+ packages?: readonly string[];
38
48
  }
39
49
  export interface Options extends Partial<Options$1> {
40
50
  /** Set to `false` to use `@solidjs/vite-plugin` as it is. */
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.mts","names":["SolidPluginOptions"],"sources":["../src/vite/report.ts","../src/vite/index.ts"],"mappings":";;;;;UAUiB;;WAEN;WACA,gBAAgB;;;;iBCwCV,yBAAyB,KACxC;;;;;;;;;EAWA;;;;;;EAMA;;;;;;;;;EASA,qBAAqB,QAAQ;;iBAKd,gBAAgB,QAAQA;;EAEvC,YAAY;;wBAuIU,eAAe,UAAS,UAAe"}
1
+ {"version":3,"file":"vite.d.mts","names":["SolidPluginOptions"],"sources":["../src/vite/report.ts","../src/vite/index.ts"],"mappings":";;;;;UAUiB;;WAEN;WACA,gBAAgB;;;;iBCyCV,yBAAyB,KACxC;;;;;;;;;EAWA;;;;;;EAMA;;;;;;;;;EASA,qBAAqB,QAAQ;;;;;;;;;;EAU7B;;iBAKe,gBAAgB,QAAQA;;EAEvC,YAAY;;wBAwKU,eAAe,UAAS,UAAe"}
package/dist/vite.mjs CHANGED
@@ -1,12 +1,13 @@
1
- import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-Cz6hbiQv.mjs";
1
+ import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-sCZdwEKG.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import MagicString from "magic-string";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { readFile } from "node:fs/promises";
7
7
  import path from "node:path";
8
+ import { gzipSync } from "node:zlib";
8
9
  import solidPlugin from "@solidjs/vite-plugin";
9
- import { createFilter, transformWithOxc } from "vite";
10
+ import { createFilter, minifySync, transformWithOxc } from "vite";
10
11
  //#region src/vite/globals.ts
11
12
  /**
12
13
  * The `define` entries and `import.meta.env` values that are the same in
@@ -400,6 +401,42 @@ function functionOf(binding) {
400
401
  }
401
402
  }
402
403
  /**
404
+ * The binding a top-level alias like `const Button = ButtonRoot` names, or
405
+ * the binding itself when it is not one. Libraries often export a component
406
+ * under such a second name.
407
+ */
408
+ function aliasedBinding(binding) {
409
+ let current = binding;
410
+ for (let depth = 0; depth < 8; depth += 1) {
411
+ const { declaration } = current;
412
+ if (declaration.type !== "VariableDeclarator" || current.kind !== "const" || current.mutated || declaration.id !== current.identifier || !declaration.init) return current;
413
+ const init = unwrap(declaration.init);
414
+ const target = init.type === "Identifier" ? current.scope.bindings.get(init.name) : void 0;
415
+ if (!target || target === current || target.mutated) return current;
416
+ current = target;
417
+ }
418
+ return current;
419
+ }
420
+ /**
421
+ * Where a module re-exports `exportName` from, like
422
+ * `export { t as Separator } from './chunk.jsx'`, or `undefined` when it
423
+ * does not re-export it by name.
424
+ */
425
+ function readReexport(code, filename, exportName) {
426
+ const program = parse(filename, code);
427
+ for (const statement of program.body) {
428
+ if (statement.type !== "ExportNamedDeclaration" || !statement.source || statement.exportKind === "type") continue;
429
+ for (const specifier of statement.specifiers) {
430
+ const exported = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
431
+ const local = specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value;
432
+ if (exported === exportName && specifier.exportKind !== "type") return {
433
+ source: statement.source.value,
434
+ imported: local
435
+ };
436
+ }
437
+ }
438
+ }
439
+ /**
403
440
  * The names a module exports, each with the top-level binding it exports.
404
441
  */
405
442
  function exportsOf(program, scopes) {
@@ -494,7 +531,8 @@ function readExportedComponent(code, filename, exportName, moduleSources) {
494
531
  const program = parse(filename, code);
495
532
  const scopes = analyzeScopes(program);
496
533
  const exports = exportsOf(program, scopes);
497
- const binding = exports.get(exportName);
534
+ const named = exports.get(exportName);
535
+ const binding = named ? aliasedBinding(named) : void 0;
498
536
  const component = binding ? functionOf(binding) : void 0;
499
537
  if (!binding || !component) return;
500
538
  const exportNames = /* @__PURE__ */ new Map();
@@ -908,20 +946,27 @@ const LAZY_PLACEHOLDER = /"__SOLID_LAZY_MODULE__:([^"]+)"/g;
908
946
  * The common kinds of attribute: a class, any other attribute, events, and
909
947
  * children. Inlining a component turns a spread onto an element into
910
948
  * attributes like these, in a module that may not use their helpers itself.
911
- * A rarer kind, like `style`, can still need a helper no module imports.
912
- * The chunk is then lowered without optimizing it.
949
+ * A `ref` can come through a spread too, and a link with a dynamic attribute
950
+ * claims its element. A rarer kind, like `style`, can still need a helper no
951
+ * module imports. The chunk is then lowered without optimizing it.
913
952
  */
914
953
  const ATTRIBUTE_SAMPLE = `const a = () => 0;
915
954
  export const Sample = () => (
916
- <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
955
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>
956
+ {a()}
957
+ <a href="/" title={a()} ref={a} />
958
+ </div>
917
959
  );`;
918
- /** Whether the code spreads anything onto an intrinsic element. */
960
+ /**
961
+ * Whether the code spreads anything onto an intrinsic element, or onto
962
+ * `<Dynamic>`, which becomes one once its `component` is known.
963
+ */
919
964
  function spreadsOntoElement(code, filename) {
920
965
  if (!code.includes("...")) return false;
921
966
  let found = false;
922
967
  const visit = (node) => {
923
968
  if (found) return;
924
- if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && isIntrinsicTag(node.name.name) && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
969
+ if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && (isIntrinsicTag(node.name.name) || node.name.name === "Dynamic") && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
925
970
  found = true;
926
971
  return;
927
972
  }
@@ -930,6 +975,23 @@ function spreadsOntoElement(code, filename) {
930
975
  visit(parse(filename, code));
931
976
  return found;
932
977
  }
978
+ /**
979
+ * How many bytes a chunk takes once minified and gzipped. Minifying drops
980
+ * the runtime code nothing calls anymore, which is what the comparison is
981
+ * for, so it counts even when the build does not minify.
982
+ */
983
+ function shippedSize(candidate, filename) {
984
+ const minified = minifySync(filename, candidate.linked.code, {
985
+ module: true,
986
+ compress: true,
987
+ mangle: true
988
+ });
989
+ return gzipSync(minified.code).length;
990
+ }
991
+ /** Whether a module, or the module of a copy's key, is in `node_modules`. */
992
+ function isPackageModule(id) {
993
+ return stripQuery(id).replaceAll("\\", "/").includes("/node_modules/");
994
+ }
933
995
  function loadCompiler() {
934
996
  const require = createRequire(import.meta.url);
935
997
  return createRequire(require.resolve("@solidjs/vite-plugin"))("@solidjs/compiler");
@@ -1009,8 +1071,8 @@ function solidOptimizer(options = {}) {
1009
1071
  };
1010
1072
  /** What the final compile of each chunk or module left alone, by environment. */
1011
1073
  const skips = /* @__PURE__ */ new Map();
1012
- const addSkips = (context, list) => {
1013
- if (!list) return;
1074
+ const addSkips = (context, list, module) => {
1075
+ if (!list || module !== void 0 && isPackageModule(module)) return;
1014
1076
  const environment = context.environment?.name ?? "client";
1015
1077
  const entries = skips.get(environment) ?? [];
1016
1078
  entries.push(...list);
@@ -1393,26 +1455,63 @@ function solidOptimizer(options = {}) {
1393
1455
  return `import { ${imported} as ${local} } from ${from};`;
1394
1456
  }
1395
1457
  /**
1458
+ * Whether components can be copied from a module: one of the app's, or
1459
+ * one of a package listed in `optimizer.packages`.
1460
+ */
1461
+ const isCopyable = (id) => {
1462
+ const file = stripQuery(id).replaceAll("\\", "/");
1463
+ if (!file.includes("/node_modules/")) return true;
1464
+ return (optimizer.packages ?? []).some((name) => file.includes(`/node_modules/${name}/`));
1465
+ };
1466
+ /** The listed packages already warned about, by environment. */
1467
+ const warnedPackages = /* @__PURE__ */ new Set();
1468
+ /**
1469
+ * Warns once when a listed package is external, like a server build that
1470
+ * leaves it to Node. Its components are not copied there, so a build that
1471
+ * copies them would hydrate different markup.
1472
+ */
1473
+ const warnExternalPackage = (context, source) => {
1474
+ const name = (optimizer.packages ?? []).find((item) => source === item || source.startsWith(`${item}/`));
1475
+ const key = environmentKey(context, name ?? "");
1476
+ if (name === void 0 || warnedPackages.has(key)) return;
1477
+ warnedPackages.add(key);
1478
+ context.warn(`[solid-optimizer] ${name} is external in this build, so its components are not copied. Bundle it, like with \`ssr.noExternal\`, so every build copies the same components.`);
1479
+ };
1480
+ /**
1396
1481
  * Reads the component `source` exports as `imported`, and imports what it
1397
1482
  * needs into the importer. `undefined` when it cannot be copied.
1398
1483
  */
1399
- async function copyImported(context, id, source, imported, state) {
1484
+ async function copyImported(context, id, source, requested, state) {
1400
1485
  const skip = (reason) => {
1401
1486
  state.skips?.push({
1402
1487
  pass: "inline",
1403
1488
  reason,
1404
- name: `${imported} (${source})`
1489
+ name: `${requested} (${source})`
1405
1490
  });
1406
1491
  };
1407
- const resolved = await context.resolve(source, id);
1492
+ let imported = requested;
1493
+ let resolved = await context.resolve(source, id);
1408
1494
  if (!resolved || resolved.external) {
1495
+ warnExternalPackage(context, source);
1409
1496
  skip("copy-external");
1410
1497
  return;
1411
1498
  }
1412
- if (resolved.id.includes("/node_modules/")) {
1499
+ if (!isCopyable(resolved.id)) {
1413
1500
  skip("copy-package");
1414
1501
  return;
1415
1502
  }
1503
+ for (let depth = 0; depth < 8 && isJSXModule(resolved.id); depth += 1) {
1504
+ const code = await state.load(resolved.id);
1505
+ const reexport = code === void 0 ? void 0 : readReexport(code, stripQuery(resolved.id), imported);
1506
+ if (!reexport) break;
1507
+ const next = await context.resolve(reexport.source, resolved.id);
1508
+ if (!next || next.external || !isCopyable(next.id)) {
1509
+ skip("copy-package");
1510
+ return;
1511
+ }
1512
+ resolved = next;
1513
+ imported = reexport.imported;
1514
+ }
1416
1515
  if (resolved.id === id) return;
1417
1516
  if (!isJSXModule(resolved.id)) {
1418
1517
  skip("copy-not-jsx");
@@ -1529,8 +1628,10 @@ function solidOptimizer(options = {}) {
1529
1628
  if (copy && copySkips) copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
1530
1629
  if (copy) {
1531
1630
  const name = fresh(specifier.local.name);
1631
+ const fromPackage = isPackageModule(copy.key);
1532
1632
  copies.push({
1533
1633
  key: copy.key,
1634
+ fromPackage,
1534
1635
  name,
1535
1636
  tags,
1536
1637
  text: copy.text(name)
@@ -1553,7 +1654,8 @@ function solidOptimizer(options = {}) {
1553
1654
  filename,
1554
1655
  sourceMap: wantsMaps(),
1555
1656
  importedContexts: Object.fromEntries([...contexts].map(([module, exported]) => [module, [...exported]])),
1556
- sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1))
1657
+ sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1)),
1658
+ alwaysInlineComponents: copies.filter((copy) => copy.fromPackage).map((copy) => copy.name)
1557
1659
  });
1558
1660
  const left = analyzeScopes(parse(filename, result.code)).root.bindings;
1559
1661
  const stuck = copies.filter((copy) => left.has(copy.name));
@@ -1615,7 +1717,7 @@ function solidOptimizer(options = {}) {
1615
1717
  if (moduleCompileOptions.inline !== false) {
1616
1718
  const copySkips = compileOptions.report ? [] : void 0;
1617
1719
  const imported = await inlineImports(context, code, id, moduleCompileOptions, async (target) => loadModule(context, id, target), copySkips);
1618
- addSkips(context, copySkips);
1720
+ addSkips(context, copySkips, id);
1619
1721
  if (imported) {
1620
1722
  code = imported.code;
1621
1723
  maps.push(...imported.maps);
@@ -1713,7 +1815,7 @@ function solidOptimizer(options = {}) {
1713
1815
  if (isBuild() && sourceOptions.inline !== false) {
1714
1816
  const copySkips = compileOptions.report ? [] : void 0;
1715
1817
  const imported = await inlineImports(this, code, id, sourceOptions, async (target) => loadRecorded(this, id, target), copySkips);
1716
- addSkips(this, copySkips);
1818
+ addSkips(this, copySkips, id);
1717
1819
  if (imported) {
1718
1820
  code = imported.code;
1719
1821
  maps.push(...imported.maps);
@@ -1725,7 +1827,7 @@ function solidOptimizer(options = {}) {
1725
1827
  maps.push(exposed.map);
1726
1828
  }
1727
1829
  }
1728
- addSkips(this, skipped);
1830
+ addSkips(this, skipped, id);
1729
1831
  recorded.set(environmentKey(this, id), code);
1730
1832
  if (code === source) return null;
1731
1833
  return {
@@ -1766,23 +1868,45 @@ function solidOptimizer(options = {}) {
1766
1868
  filename: `${filename}.jsx`,
1767
1869
  sourceMap: wantsMaps()
1768
1870
  });
1769
- let optimized = compile(chunkCode, {
1871
+ const chunkOptions = {
1770
1872
  ...compileOptions,
1771
1873
  filename,
1772
1874
  sourceMap: wantsMaps(),
1773
1875
  constantVars: true,
1774
1876
  builtInAliases: runtime.builtInAliases
1775
- });
1877
+ };
1878
+ let missing;
1879
+ const lowerCandidate = (optimized) => {
1880
+ const lowered = lowerChunk(optimized.code);
1881
+ try {
1882
+ return {
1883
+ optimized,
1884
+ lowered,
1885
+ linked: linkHelpers(lowered.code, filename, moduleName, runtime.helpers)
1886
+ };
1887
+ } catch (error) {
1888
+ if (!(error instanceof MissingHelperError)) throw error;
1889
+ missing ??= error;
1890
+ return;
1891
+ }
1892
+ };
1893
+ let chosen = lowerCandidate(compile(chunkCode, chunkOptions));
1894
+ if (compileOptions.alwaysInline !== true) {
1895
+ const always = compile(chunkCode, {
1896
+ ...chunkOptions,
1897
+ alwaysInline: true
1898
+ });
1899
+ const other = always.code === chosen?.optimized.code ? void 0 : lowerCandidate(always);
1900
+ if (other && (!chosen || shippedSize(other, filename) < shippedSize(chosen, filename))) chosen = other;
1901
+ }
1902
+ let optimized;
1776
1903
  let linked;
1777
1904
  let lowered;
1778
- try {
1779
- lowered = lowerChunk(optimized.code);
1780
- linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1905
+ if (chosen) {
1906
+ ({optimized, lowered, linked} = chosen);
1781
1907
  addSkips(this, optimized.skipped);
1782
- } catch (error) {
1783
- if (!(error instanceof MissingHelperError)) throw error;
1784
- this.warn(`${error.message} ${filename} is not optimized.`);
1785
- optimized = void 0;
1908
+ } else {
1909
+ this.warn(`${missing?.message ?? ""} ${filename} is not optimized.`);
1786
1910
  addSkips(this, [{
1787
1911
  pass: "inline",
1788
1912
  reason: "missing-helper",