@timber-js/app 0.2.0-alpha.223 → 0.2.0-alpha.225

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 (91) hide show
  1. package/dist/_chunks/{actions-7dTXYJfu.js → actions-B1xSIv32.js} +2 -2
  2. package/dist/_chunks/{actions-7dTXYJfu.js.map → actions-B1xSIv32.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-TDZ4hlDc.js → cache-api-DsSXA4Sp.js} +68 -47
  4. package/dist/_chunks/cache-api-DsSXA4Sp.js.map +1 -0
  5. package/dist/_chunks/{cli-check-Dv3f8d2j.js → cli-check-B33yhAPa.js} +2 -2
  6. package/dist/_chunks/{cli-check-Dv3f8d2j.js.map → cli-check-B33yhAPa.js.map} +1 -1
  7. package/dist/_chunks/cli-context-BPdyA7Fp.js +1 -0
  8. package/dist/_chunks/{cli-context-CbZp32SK.js → cli-context-CwTKMjVe.js} +10 -2
  9. package/dist/_chunks/cli-context-CwTKMjVe.js.map +1 -0
  10. package/dist/_chunks/{dev-server-C61GWpGg.js → dev-server-B7o4As0l.js} +15 -1
  11. package/dist/_chunks/dev-server-B7o4As0l.js.map +1 -0
  12. package/dist/_chunks/dev-server-hZzmbMvK.js +1 -0
  13. package/dist/_chunks/{error-boundary-DRQXGWCp.js → error-boundary-D3YyVVuP.js} +2 -2
  14. package/dist/_chunks/{error-boundary-DRQXGWCp.js.map → error-boundary-D3YyVVuP.js.map} +1 -1
  15. package/dist/_chunks/{singleflight-BChPMjwH.js → singleflight-CzoOVB9Y.js} +2 -3
  16. package/dist/_chunks/singleflight-CzoOVB9Y.js.map +1 -0
  17. package/dist/_chunks/{status-page-marker-XIQXlTOb.js → status-page-marker-C8POawuF.js} +2 -2
  18. package/dist/_chunks/{status-page-marker-XIQXlTOb.js.map → status-page-marker-C8POawuF.js.map} +1 -1
  19. package/dist/adapters/cloudflare-kv-cache.d.ts +0 -1
  20. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -1
  21. package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
  22. package/dist/cache/index.d.ts +5 -5
  23. package/dist/cache/index.d.ts.map +1 -1
  24. package/dist/cache/index.js +1 -1
  25. package/dist/cache/redis-handler.d.ts +0 -1
  26. package/dist/cache/redis-handler.d.ts.map +1 -1
  27. package/dist/cache/singleflight.d.ts +12 -2
  28. package/dist/cache/singleflight.d.ts.map +1 -1
  29. package/dist/cache/stable-stringify.d.ts +6 -0
  30. package/dist/cache/stable-stringify.d.ts.map +1 -1
  31. package/dist/cache/tag-aware-handler.d.ts +0 -1
  32. package/dist/cache/tag-aware-handler.d.ts.map +1 -1
  33. package/dist/cache/timber-cache.d.ts +1 -1
  34. package/dist/cache/timber-cache.d.ts.map +1 -1
  35. package/dist/cli-context.d.ts +8 -0
  36. package/dist/cli-context.d.ts.map +1 -1
  37. package/dist/cli.d.ts.map +1 -1
  38. package/dist/cli.js +9 -3
  39. package/dist/cli.js.map +1 -1
  40. package/dist/client/error-boundary.js +1 -1
  41. package/dist/client/internal.js +3 -3
  42. package/dist/config-types.d.ts +18 -0
  43. package/dist/config-types.d.ts.map +1 -1
  44. package/dist/config-validation.d.ts.map +1 -1
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +545 -9
  47. package/dist/index.js.map +1 -1
  48. package/dist/plugins/client-in-server-package-deps.d.ts +63 -0
  49. package/dist/plugins/client-in-server-package-deps.d.ts.map +1 -0
  50. package/dist/plugins/optimize-package-imports-defaults.d.ts +13 -0
  51. package/dist/plugins/optimize-package-imports-defaults.d.ts.map +1 -0
  52. package/dist/plugins/optimize-package-imports.d.ts +124 -0
  53. package/dist/plugins/optimize-package-imports.d.ts.map +1 -0
  54. package/dist/server/flight-injector-core.d.ts.map +1 -1
  55. package/dist/server/index.js +1 -1
  56. package/dist/server/internal.js +162 -33
  57. package/dist/server/internal.js.map +1 -1
  58. package/dist/server/pipeline-helpers.d.ts +5 -2
  59. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  60. package/dist/server/pipeline.d.ts.map +1 -1
  61. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  62. package/dist/server/response-framing.d.ts +43 -0
  63. package/dist/server/response-framing.d.ts.map +1 -0
  64. package/docs/api/34-api-config.mdx +20 -0
  65. package/package.json +2 -2
  66. package/src/adapters/cloudflare-kv-cache.ts +1 -5
  67. package/src/cache/index.ts +7 -27
  68. package/src/cache/redis-handler.ts +1 -5
  69. package/src/cache/singleflight.ts +17 -5
  70. package/src/cache/stable-stringify.ts +53 -0
  71. package/src/cache/tag-aware-handler.ts +1 -5
  72. package/src/cache/timber-cache.ts +55 -52
  73. package/src/cli-context.ts +9 -0
  74. package/src/cli.ts +16 -0
  75. package/src/config-types.ts +18 -0
  76. package/src/config-validation.ts +20 -0
  77. package/src/index.ts +4 -0
  78. package/src/plugins/client-in-server-package-deps.ts +139 -0
  79. package/src/plugins/optimize-package-imports-defaults.ts +88 -0
  80. package/src/plugins/optimize-package-imports.ts +439 -0
  81. package/src/server/flight-injector-core.ts +13 -9
  82. package/src/server/pipeline-helpers.ts +9 -5
  83. package/src/server/pipeline.ts +7 -0
  84. package/src/server/prebuilt-runtime.ts +125 -121
  85. package/src/server/response-framing.ts +59 -0
  86. package/dist/_chunks/cache-api-TDZ4hlDc.js.map +0 -1
  87. package/dist/_chunks/cli-context-CbZp32SK.js.map +0 -1
  88. package/dist/_chunks/cli-context-n5hmkdla.js +0 -1
  89. package/dist/_chunks/dev-server-C61GWpGg.js.map +0 -1
  90. package/dist/_chunks/dev-server-CBvvM7Lr.js +0 -1
  91. package/dist/_chunks/singleflight-BChPMjwH.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as formatMissingPeers, i as checkPeerDependencies, n as timberDevServer, o as reportConfigErrors, s as validateConfig } from "./_chunks/dev-server-C61GWpGg.js";
1
+ import { a as formatMissingPeers, i as checkPeerDependencies, n as timberDevServer, o as reportConfigErrors, s as validateConfig } from "./_chunks/dev-server-B7o4As0l.js";
2
2
  import { i as resolveRenderTimeoutMs } from "./_chunks/render-timeout-MrrqD1wd.js";
3
3
  import { t as writeFileAtomic } from "./_chunks/write-file-atomic-DW8m_Atv.js";
4
4
  import { d as collectInterceptionRewrites, l as getPrerenderExport, n as scanRoutes } from "./_chunks/scanner-CJC-ScJU.js";
@@ -12,6 +12,7 @@ import { n as rscPayloadPath, t as RSC_PAYLOAD_DIR } from "./_chunks/rsc-payload
12
12
  import { a as REDIRECTS_FILE, n as detectFsIdentity, o as RESERVED_OUTPUT_PATHS, r as fsKey, t as EXACT_FS_IDENTITY } from "./_chunks/fs-identity-BmQ_Agg-.js";
13
13
  import { t as EMPTY_BUILD_MANIFEST } from "./_chunks/build-manifest-Y4jl7nwU.js";
14
14
  import { t as fnv1aHash } from "./_chunks/fast-hash-DddxkU5Y.js";
15
+ import { i as detectDirective } from "./_chunks/classify--_kINHQV.js";
15
16
  import { t as formatSize } from "./_chunks/format-DuPOoXUP.js";
16
17
  import { createLogger, esmExternalRequirePlugin, isRunnableDevEnvironment, parseAst } from "vite";
17
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, win32 } from "node:path";
@@ -6893,7 +6894,7 @@ function addToMapSet(map, key, value) {
6893
6894
  if (existing) existing.add(value);
6894
6895
  else map.set(key, /* @__PURE__ */ new Set([value]));
6895
6896
  }
6896
- function nameOf(node) {
6897
+ function nameOf$1(node) {
6897
6898
  if (!node) return null;
6898
6899
  if (node.type === "Identifier") return node.name;
6899
6900
  if (node.type === "Literal" && typeof node.value === "string") return node.value;
@@ -6911,7 +6912,7 @@ function collectImportDeclaration(stmt, facts) {
6911
6912
  const source = stmt.source?.value;
6912
6913
  if (typeof source !== "string") return;
6913
6914
  for (const spec of stmt.specifiers ?? []) {
6914
- const local = nameOf(spec.local);
6915
+ const local = nameOf$1(spec.local);
6915
6916
  if (!local) continue;
6916
6917
  if (spec.type === "ImportNamespaceSpecifier") facts.importedBindings.set(local, {
6917
6918
  source,
@@ -6923,7 +6924,7 @@ function collectImportDeclaration(stmt, facts) {
6923
6924
  });
6924
6925
  else if (spec.type === "ImportSpecifier") facts.importedBindings.set(local, {
6925
6926
  source,
6926
- imported: nameOf(spec.imported) ?? local
6927
+ imported: nameOf$1(spec.imported) ?? local
6927
6928
  });
6928
6929
  }
6929
6930
  }
@@ -6942,8 +6943,8 @@ function collectExportNamed(stmt, facts) {
6942
6943
  const specifiers = stmt.specifiers ?? [];
6943
6944
  if (typeof source === "string") {
6944
6945
  for (const spec of specifiers) {
6945
- const imported = nameOf(spec.imported) ?? nameOf(spec.local);
6946
- const exported = nameOf(spec.exported);
6946
+ const imported = nameOf$1(spec.imported) ?? nameOf$1(spec.local);
6947
+ const exported = nameOf$1(spec.exported);
6947
6948
  if (imported && exported) facts.reExports.set(exported, {
6948
6949
  source,
6949
6950
  imported
@@ -6952,8 +6953,8 @@ function collectExportNamed(stmt, facts) {
6952
6953
  return;
6953
6954
  }
6954
6955
  for (const spec of specifiers) {
6955
- const local = nameOf(spec.local);
6956
- const exported = nameOf(spec.exported);
6956
+ const local = nameOf$1(spec.local);
6957
+ const exported = nameOf$1(spec.exported);
6957
6958
  if (local && exported) facts.localExports.set(exported, local);
6958
6959
  }
6959
6960
  const declaration = stmt.declaration;
@@ -6966,7 +6967,7 @@ function collectExportNamed(stmt, facts) {
6966
6967
  function collectExportAll(stmt, facts) {
6967
6968
  const source = stmt.source?.value;
6968
6969
  if (typeof source !== "string") return;
6969
- const exported = nameOf(stmt.exported);
6970
+ const exported = nameOf$1(stmt.exported);
6970
6971
  if (exported) facts.reExports.set(exported, {
6971
6972
  source,
6972
6973
  imported: "*"
@@ -7546,6 +7547,539 @@ function walkSegmentTree(node, fn) {
7546
7547
  if (node.children) for (const child of node.children) walkSegmentTree(child, fn);
7547
7548
  if (node.slots) for (const slot of Object.values(node.slots)) walkSegmentTree(slot, fn);
7548
7549
  }
7550
+ // src/plugins/optimize-package-imports-defaults.ts
7551
+ /**
7552
+ * Import specifiers whose barrel imports timber rewrites by default.
7553
+ *
7554
+ * Copied from Next.js's built-in `optimizePackageImports` list
7555
+ * (packages/next/src/server/config.ts, vercel/next.js@50bf604f2), so an app
7556
+ * moving from Next gets the same set without configuring it. Entries are exact
7557
+ * import specifiers, not package names: a package with several icon entry
7558
+ * points (`react-icons/fa`, `@heroicons/react/24/solid`) lists each one.
7559
+ *
7560
+ * See design/21-dev-server.md §"Barrel Import Optimization".
7561
+ */
7562
+ var DEFAULT_OPTIMIZE_PACKAGE_IMPORTS = [
7563
+ "lucide-react",
7564
+ "date-fns",
7565
+ "lodash-es",
7566
+ "ramda",
7567
+ "antd",
7568
+ "react-bootstrap",
7569
+ "ahooks",
7570
+ "@ant-design/icons",
7571
+ "@headlessui/react",
7572
+ "@headlessui-float/react",
7573
+ "@heroicons/react/20/solid",
7574
+ "@heroicons/react/24/solid",
7575
+ "@heroicons/react/24/outline",
7576
+ "@visx/visx",
7577
+ "@tremor/react",
7578
+ "rxjs",
7579
+ "@mui/material",
7580
+ "@mui/icons-material",
7581
+ "recharts",
7582
+ "react-use",
7583
+ "effect",
7584
+ "@effect/schema",
7585
+ "@effect/platform",
7586
+ "@effect/platform-node",
7587
+ "@effect/platform-browser",
7588
+ "@effect/platform-bun",
7589
+ "@effect/sql",
7590
+ "@effect/sql-mssql",
7591
+ "@effect/sql-mysql2",
7592
+ "@effect/sql-pg",
7593
+ "@effect/sql-sqlite-node",
7594
+ "@effect/sql-sqlite-bun",
7595
+ "@effect/sql-sqlite-wasm",
7596
+ "@effect/sql-sqlite-react-native",
7597
+ "@effect/rpc",
7598
+ "@effect/rpc-http",
7599
+ "@effect/typeclass",
7600
+ "@effect/experimental",
7601
+ "@effect/opentelemetry",
7602
+ "@material-ui/core",
7603
+ "@material-ui/icons",
7604
+ "@tabler/icons-react",
7605
+ "mui-core",
7606
+ "react-icons/ai",
7607
+ "react-icons/bi",
7608
+ "react-icons/bs",
7609
+ "react-icons/cg",
7610
+ "react-icons/ci",
7611
+ "react-icons/di",
7612
+ "react-icons/fa",
7613
+ "react-icons/fa6",
7614
+ "react-icons/fc",
7615
+ "react-icons/fi",
7616
+ "react-icons/gi",
7617
+ "react-icons/go",
7618
+ "react-icons/gr",
7619
+ "react-icons/hi",
7620
+ "react-icons/hi2",
7621
+ "react-icons/im",
7622
+ "react-icons/io",
7623
+ "react-icons/io5",
7624
+ "react-icons/lia",
7625
+ "react-icons/lib",
7626
+ "react-icons/lu",
7627
+ "react-icons/md",
7628
+ "react-icons/pi",
7629
+ "react-icons/ri",
7630
+ "react-icons/rx",
7631
+ "react-icons/si",
7632
+ "react-icons/sl",
7633
+ "react-icons/tb",
7634
+ "react-icons/tfi",
7635
+ "react-icons/ti",
7636
+ "react-icons/vsc",
7637
+ "react-icons/wi"
7638
+ ];
7639
+ // src/plugins/optimize-package-imports.ts
7640
+ /**
7641
+ * timber-optimize-package-imports — rewrites named imports from a listed
7642
+ * barrel package into imports of only the modules that define those names.
7643
+ *
7644
+ * In dev, `@vitejs/plugin-rsc` keeps packages with a `react` peer dependency
7645
+ * in the rsc and ssr module graphs without pre-bundling them, so on the server
7646
+ * `import { Play } from 'lucide-react'` enters lucide's barrel and Vite
7647
+ * transforms all ~2,000 icon modules it re-exports, once per environment. A
7648
+ * build loads all of them too, before tree-shaking. The
7649
+ * rewrite turns that import into one of the icon's own file:
7650
+ *
7651
+ * import { Play } from 'lucide-react'
7652
+ * → import { default as Play } from "/…/lucide-react/dist/esm/icons/play.mjs";
7653
+ *
7654
+ * Next.js does the same for its `optimizePackageImports` list
7655
+ * (next-barrel-loader.ts, optimize_barrel.rs). It applies to every environment
7656
+ * in builds; in dev, to the server environments and only for packages Vite
7657
+ * compiles itself (the client environment pre-bundles them; the server
7658
+ * environments hand most other packages to Node). See design/21-dev-server.md
7659
+ * §"Barrel Import Optimization".
7660
+ *
7661
+ * Every rule here leans toward leaving the import alone. A missed rewrite costs
7662
+ * compile time; a wrong one breaks the app. An import is rewritten only when
7663
+ * the barrel is a pure barrel (nothing but imports and re-exports) and every
7664
+ * imported name is in its export map with a target that resolves to a file.
7665
+ */
7666
+ /**
7667
+ * Merge the user's list with the defaults (Next's semantics: the user list
7668
+ * adds, never replaces). Config validation reports invalid entries without
7669
+ * stopping the dev server, so only the valid ones (non-empty strings) are used
7670
+ * here; a string list is not spread into characters, and an empty entry does
7671
+ * not match every quoted empty string.
7672
+ */
7673
+ function resolveOptimizedPackages(user) {
7674
+ const extra = Array.isArray(user) ? user.filter((entry) => typeof entry === "string" && entry.trim() !== "") : [];
7675
+ return /* @__PURE__ */ new Set([...DEFAULT_OPTIMIZE_PACKAGE_IMPORTS, ...extra]);
7676
+ }
7677
+ function nameOf(node) {
7678
+ return node.type === "Literal" ? node.value : node.name;
7679
+ }
7680
+ /**
7681
+ * Read a barrel's export map, or null when the file is not a pure barrel.
7682
+ *
7683
+ * A pure barrel holds only imports, re-exports, and `export { local }` of an
7684
+ * imported binding (`import * as icons from './icons'; export { icons }`, which
7685
+ * lucide-react's barrel opens with). Anything that runs code of its own, a
7686
+ * declaration, an expression, a bare side-effect import, makes it not a barrel:
7687
+ * importing past it would skip that code. So does any directive except
7688
+ * `'use strict'`: a `'use client'` or `'use server'` barrel is a boundary
7689
+ * plugin-rsc draws around the barrel module itself, and importing past it would
7690
+ * load the re-exported files on the wrong side of it.
7691
+ *
7692
+ * `export default local` is not followed even when `local` is imported: it
7693
+ * exports the value `local` held when the barrel ran, not a live binding, so
7694
+ * importing `local` directly would see later reassignments the barrel's
7695
+ * default never does. `export { local as default }` is live and is followed.
7696
+ *
7697
+ * A source-phase or deferred import, or import attributes, change what the
7698
+ * barrel's binding is, so a barrel using them is not followed. An
7699
+ * `export {} from` with no names only runs the module, like a bare import.
7700
+ *
7701
+ * `export * from` adds no entries. A name it might supply is not in the map, so
7702
+ * an import of that name falls back; explicit exports shadow star exports, so
7703
+ * every name that is in the map is exact.
7704
+ */
7705
+ function readBarrelExportMap(code, lang) {
7706
+ let program;
7707
+ try {
7708
+ program = parseAst(code, { lang });
7709
+ } catch {
7710
+ return null;
7711
+ }
7712
+ const imported = /* @__PURE__ */ new Map();
7713
+ for (const item of program.body) {
7714
+ if (item.type !== "ImportDeclaration" || item.importKind === "type") continue;
7715
+ const source = item.source.value;
7716
+ for (const spec of item.specifiers) if (spec.type === "ImportSpecifier") {
7717
+ if (spec.importKind === "type") continue;
7718
+ imported.set(spec.local.name, {
7719
+ source,
7720
+ imported: nameOf(spec.imported)
7721
+ });
7722
+ } else if (spec.type === "ImportDefaultSpecifier") imported.set(spec.local.name, {
7723
+ source,
7724
+ imported: "default"
7725
+ });
7726
+ else imported.set(spec.local.name, {
7727
+ source,
7728
+ imported: "*"
7729
+ });
7730
+ }
7731
+ const exports = /* @__PURE__ */ new Map();
7732
+ for (const item of program.body) switch (item.type) {
7733
+ case "ExpressionStatement":
7734
+ if ("directive" in item && item.directive === "use strict") continue;
7735
+ return null;
7736
+ case "ImportDeclaration":
7737
+ if (item.importKind === "type") continue;
7738
+ if (item.specifiers.length === 0 || item.phase !== null || item.attributes.length > 0) return null;
7739
+ continue;
7740
+ case "ExportAllDeclaration":
7741
+ if (item.exportKind === "type") continue;
7742
+ if (item.attributes.length > 0) return null;
7743
+ if (item.exported) exports.set(nameOf(item.exported), {
7744
+ source: item.source.value,
7745
+ imported: "*"
7746
+ });
7747
+ continue;
7748
+ case "ExportNamedDeclaration":
7749
+ if (item.exportKind === "type") continue;
7750
+ if (item.declaration || item.attributes.length > 0) return null;
7751
+ if (item.source && item.specifiers.length === 0) return null;
7752
+ for (const spec of item.specifiers) {
7753
+ if (spec.exportKind === "type") continue;
7754
+ const local = nameOf(spec.local);
7755
+ const origin = item.source ? {
7756
+ source: item.source.value,
7757
+ imported: local
7758
+ } : imported.get(local);
7759
+ if (!origin) return null;
7760
+ exports.set(nameOf(spec.exported), origin);
7761
+ }
7762
+ continue;
7763
+ case "TSInterfaceDeclaration":
7764
+ case "TSTypeAliasDeclaration": continue;
7765
+ default: return null;
7766
+ }
7767
+ return exports;
7768
+ }
7769
+ var IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
7770
+ /** An export name as it must be written in an import or export clause. */
7771
+ function clauseName(name) {
7772
+ return IDENTIFIER_RE.test(name) ? name : JSON.stringify(name);
7773
+ }
7774
+ /**
7775
+ * The bindings a statement takes from `source`, or null when the statement is
7776
+ * not a candidate: a namespace import, `import type`, an import attribute, a
7777
+ * source phase import, or a statement with no value bindings.
7778
+ */
7779
+ function statementBindings(item) {
7780
+ if (item.attributes.length > 0) return null;
7781
+ const bindings = [];
7782
+ if (item.type === "ImportDeclaration") {
7783
+ if (item.importKind === "type" || item.phase !== null) return null;
7784
+ for (const spec of item.specifiers) {
7785
+ if (spec.type === "ImportNamespaceSpecifier") return null;
7786
+ if (spec.type === "ImportDefaultSpecifier") bindings.push({
7787
+ barrelName: "default",
7788
+ as: spec.local.name
7789
+ });
7790
+ else if (spec.importKind !== "type") bindings.push({
7791
+ barrelName: nameOf(spec.imported),
7792
+ as: spec.local.name
7793
+ });
7794
+ }
7795
+ } else {
7796
+ if (item.exportKind === "type" || item.declaration) return null;
7797
+ for (const spec of item.specifiers) {
7798
+ if (spec.exportKind === "type") continue;
7799
+ bindings.push({
7800
+ barrelName: nameOf(spec.local),
7801
+ as: nameOf(spec.exported)
7802
+ });
7803
+ }
7804
+ }
7805
+ return bindings.length > 0 ? bindings : null;
7806
+ }
7807
+ /** The replacement statements for one candidate, or null to leave it alone. */
7808
+ async function rewriteStatement(item, barrel) {
7809
+ const bindings = statementBindings(item);
7810
+ if (!bindings) return null;
7811
+ const out = [];
7812
+ for (const { barrelName, as } of bindings) {
7813
+ const origin = barrel.exports.get(barrelName);
7814
+ if (!origin) return null;
7815
+ const target = await barrel.resolveTarget(origin.source);
7816
+ if (!target) return null;
7817
+ const from = JSON.stringify(target);
7818
+ if (item.type === "ImportDeclaration") out.push(origin.imported === "*" ? `import * as ${as} from ${from};` : `import { ${clauseName(origin.imported)} as ${as} } from ${from};`);
7819
+ else out.push(origin.imported === "*" ? `export * as ${clauseName(as)} from ${from};` : `export { ${clauseName(origin.imported)} as ${clauseName(as)} } from ${from};`);
7820
+ }
7821
+ return out.join(" ");
7822
+ }
7823
+ /**
7824
+ * Rewrite every import and `export { … } from` of a listed specifier whose
7825
+ * names the barrel's export map covers. Returns null when nothing changed.
7826
+ *
7827
+ * Replacements stay on the statement's own lines, so positions after it keep
7828
+ * their line numbers even before the source map is applied.
7829
+ */
7830
+ async function rewriteBarrelImports(code, packages, loadBarrel) {
7831
+ let program;
7832
+ try {
7833
+ program = parseAst(code, { lang: "js" });
7834
+ } catch {
7835
+ return null;
7836
+ }
7837
+ let s = null;
7838
+ const barrels = /* @__PURE__ */ new Map();
7839
+ for (const item of program.body) {
7840
+ if (item.type !== "ImportDeclaration" && item.type !== "ExportNamedDeclaration") continue;
7841
+ const specifier = item.source?.value;
7842
+ if (specifier === void 0 || !packages.has(specifier)) continue;
7843
+ let barrel = barrels.get(specifier);
7844
+ if (barrel === void 0) {
7845
+ barrel = await loadBarrel(specifier);
7846
+ barrels.set(specifier, barrel);
7847
+ }
7848
+ if (!barrel) continue;
7849
+ const replacement = await rewriteStatement(item, barrel);
7850
+ if (replacement === null) continue;
7851
+ s ??= new MagicString(code);
7852
+ const lineBreaks = code.slice(item.start, item.end).split("\n").length - 1;
7853
+ s.overwrite(item.start, item.end, replacement + "\n".repeat(lineBreaks));
7854
+ }
7855
+ return s;
7856
+ }
7857
+ /** The npm package a bare specifier names: `@scope/pkg/sub` → `@scope/pkg`. */
7858
+ function packageNameOf(specifier) {
7859
+ const parts = specifier.split("/");
7860
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
7861
+ }
7862
+ /**
7863
+ * Whether the environment loads `specifier` through Vite rather than handing
7864
+ * it to Node. Only those imports are rewritten.
7865
+ *
7866
+ * A server environment externalizes most of node_modules in dev: Node loads
7867
+ * the package natively, so its barrel costs nothing to compile. Rewriting such
7868
+ * an import to a file path would pull that file into Vite's module graph
7869
+ * while any other import of the package stayed external, two instances of one
7870
+ * module. In dev, plugin-rsc keeps packages with a `react` peer dependency
7871
+ * (lucide-react, the icon sets, the component libraries) out of
7872
+ * externalization, and timber's production build sets `noExternal: true`.
7873
+ *
7874
+ * Vite's own check is internal, so this is its conservative subset: the
7875
+ * package must match `resolve.noExternal` exactly (a string or a RegExp) and
7876
+ * `resolve.external` must not name it. A glob string in `noExternal` does
7877
+ * not match here, which only costs the optimization.
7878
+ */
7879
+ function isLoadedThroughVite(specifier, config) {
7880
+ const pkg = packageNameOf(specifier);
7881
+ const { noExternal, external } = config;
7882
+ if (external === true || external.includes(specifier) || external.includes(pkg)) return false;
7883
+ if (noExternal === true) return true;
7884
+ return (Array.isArray(noExternal) ? noExternal : [noExternal]).some((p) => typeof p === "string" ? p === pkg : p.test(pkg));
7885
+ }
7886
+ function langForFile(file) {
7887
+ if (file.endsWith(".tsx")) return "tsx";
7888
+ if (/\.[mc]?ts$/.test(file)) return "ts";
7889
+ if (file.endsWith(".jsx")) return "jsx";
7890
+ return "js";
7891
+ }
7892
+ /**
7893
+ * A resolved id as a plain file import, or null when it is not one (virtual,
7894
+ * relative, or carrying a query that changes what the module is).
7895
+ *
7896
+ * Vite's dev resolver appends `?v=<hash>` to files under node_modules, in the
7897
+ * server environments too, and appends the same query again when it resolves
7898
+ * the absolute path this rewrite emits. So the query is dropped, never copied:
7899
+ * the emitted path resolves to the same id the barrel's own import would, which
7900
+ * keeps one module instance per file.
7901
+ */
7902
+ function asFilePath(id) {
7903
+ const path = id.replace(/\?v=[\w.-]+$/, "");
7904
+ return isAbsolute(path) && !path.includes("?") && !path.includes("\0") ? path : null;
7905
+ }
7906
+ function escapeRegExp(text) {
7907
+ return text.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
7908
+ }
7909
+ function timberOptimizePackageImports(ctx) {
7910
+ let packages = /* @__PURE__ */ new Set();
7911
+ let isDev = false;
7912
+ let mentionsListed = /(?!)/;
7913
+ const exportMaps = /* @__PURE__ */ new Map();
7914
+ const targets = /* @__PURE__ */ new Map();
7915
+ const isInstalled = (path) => path.includes("/node_modules/");
7916
+ function exportMapFor(barrelPath) {
7917
+ const cached = exportMaps.get(barrelPath);
7918
+ if (cached !== void 0) return cached;
7919
+ let code;
7920
+ try {
7921
+ code = readFileSync(barrelPath, "utf8");
7922
+ } catch {
7923
+ return null;
7924
+ }
7925
+ const map = readBarrelExportMap(code, langForFile(barrelPath));
7926
+ if (isInstalled(barrelPath)) exportMaps.set(barrelPath, map);
7927
+ return map;
7928
+ }
7929
+ return {
7930
+ name: "timber-optimize-package-imports",
7931
+ configResolved(config) {
7932
+ isDev = config.command === "serve";
7933
+ packages = resolveOptimizedPackages(ctx.config.optimizePackageImports);
7934
+ const alternatives = [...packages].map(escapeRegExp).join("|");
7935
+ mentionsListed = new RegExp(`(["'])(?:${alternatives})\\1`);
7936
+ },
7937
+ async transform(code, id) {
7938
+ if (isDev && this.environment.config.consumer !== "server") return null;
7939
+ if (id.startsWith("\0") || !mentionsListed.test(code)) return null;
7940
+ const envName = this.environment.name;
7941
+ const { consumer, resolve } = this.environment.config;
7942
+ const s = await rewriteBarrelImports(code, packages, async (specifier) => {
7943
+ if (consumer === "server" && !isLoadedThroughVite(specifier, resolve)) return null;
7944
+ const resolved = await this.resolve(specifier, id);
7945
+ const barrelPath = resolved && !resolved.external ? asFilePath(resolved.id) : null;
7946
+ if (!barrelPath) return null;
7947
+ const installed = isInstalled(barrelPath);
7948
+ if (!installed) this.addWatchFile(barrelPath);
7949
+ const exports = exportMapFor(barrelPath);
7950
+ if (!exports) return null;
7951
+ return {
7952
+ exports,
7953
+ resolveTarget: async (source) => {
7954
+ if (!source.startsWith("./") && !source.startsWith("../")) return null;
7955
+ const key = `${envName}\0${barrelPath}\0${source}`;
7956
+ const cached = targets.get(key);
7957
+ if (cached !== void 0) return cached;
7958
+ const target = await this.resolve(source, barrelPath);
7959
+ const path = target && !target.external ? asFilePath(target.id) : null;
7960
+ if (installed) targets.set(key, path);
7961
+ return path;
7962
+ }
7963
+ };
7964
+ });
7965
+ if (!s) return null;
7966
+ return {
7967
+ code: s.toString(),
7968
+ map: s.generateMap({ hires: "boundary" })
7969
+ };
7970
+ }
7971
+ };
7972
+ }
7973
+ // src/plugins/client-in-server-package-deps.ts
7974
+ /**
7975
+ * timber-client-in-server-package-deps — in dev, the RSC environment resolves
7976
+ * a package's inner 'use client' file through its bare package path, so the
7977
+ * browser loads it from the client pre-bundle.
7978
+ *
7979
+ * plugin-rsc records a package source only for a file the RSC environment
7980
+ * reaches through a bare import. A server component that reaches a 'use
7981
+ * client' file through the package's own relative imports (lucide-react's
7982
+ * `icons/play.mjs` → `createLucideIcon.mjs` → `./Icon.mjs`, or
7983
+ * `@mui/material/Button` → `./Button.mjs`) gets a client reference whose
7984
+ * browser module re-exports the file's absolute path
7985
+ * (`client-in-server-package-proxy`). Vite serves that file, and everything it
7986
+ * imports, raw:
7987
+ *
7988
+ * - If an app client component also imports the package, the browser holds
7989
+ * two instances of those modules, the pre-bundled one and the raw one, so a
7990
+ * context the package provides (`LucideProvider`) does not reach icons
7991
+ * rendered by server components. plugin-rsc detects this and warns "client
7992
+ * component dependency is inconsistently optimized" on every dev start.
7993
+ * - If the file imports a CommonJS package (`prop-types`), the browser
7994
+ * cannot link it and the page fails (vitejs/vite-plugin-react#1538).
7995
+ *
7996
+ * This plugin resolves such an import as the bare specifier the file has from
7997
+ * the app root (`lucide-react/dist/esm/Icon.mjs`). plugin-rsc then records that
7998
+ * specifier as the file's package source and gives the browser
7999
+ * `client-package-proxy`, which imports the bare specifier. The client deps
8000
+ * optimizer pre-bundles it like any package import, splitting the modules it
8001
+ * shares with the package's own entry into one chunk, so the browser loads one
8002
+ * instance. No inconsistency remains, so plugin-rsc does not warn.
8003
+ *
8004
+ * Every rule leans toward leaving the import alone, which keeps plugin-rsc's
8005
+ * raw-file behavior:
8006
+ * - only in the RSC environment, in dev (a build has no proxy modules);
8007
+ * - only for a non-bare source (a bare one already gets a package source);
8008
+ * - only from a package file, or for an absolute path into `node_modules`
8009
+ * (what the barrel rewrite emits), so an app module's own relative imports
8010
+ * are not resolved twice;
8011
+ * - only when the resolved id is a plain file (no query but Vite's `?v=`; a
8012
+ * `?raw` or `?url` import asks for something other than the module), under
8013
+ * `node_modules`, whose directive prologue holds 'use client';
8014
+ * - only when the bare specifier resolves to the same file, from the importer
8015
+ * here and from the app root in plugin-rsc. A package whose `exports` hides
8016
+ * the file, or a transitive dependency the app cannot import by name, stays
8017
+ * as it is.
8018
+ *
8019
+ * A file found after startup is a new client dep, so the client optimizer
8020
+ * re-runs once, as for any import discovered late; Vite keeps it in the dep
8021
+ * cache for later starts. See design/21-dev-server.md §"Inner 'use client'
8022
+ * Files of Packages".
8023
+ *
8024
+ * Remove once plugin-rsc imports these files through the client pre-bundle
8025
+ * itself.
8026
+ */
8027
+ var NODE_MODULES = "/node_modules/";
8028
+ var BARE_IMPORT_RE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
8029
+ /**
8030
+ * The bare specifier `file` has as a package path, or null when the file is not
8031
+ * inside a package. The last `node_modules` segment is the package, so a pnpm
8032
+ * store path (`.pnpm/lucide-react@1.66.0/node_modules/lucide-react/…`) names
8033
+ * the package, not the store.
8034
+ */
8035
+ function packagePathOf(file) {
8036
+ const index = file.lastIndexOf(NODE_MODULES);
8037
+ if (index === -1) return null;
8038
+ const id = file.slice(index + 14);
8039
+ return id === "" || id.startsWith(".") ? null : id;
8040
+ }
8041
+ function timberClientInServerPackageDeps(rscEnvironmentName = "rsc") {
8042
+ const isClientFile = /* @__PURE__ */ new Map();
8043
+ function hasUseClient(file) {
8044
+ let cached = isClientFile.get(file);
8045
+ if (!cached) {
8046
+ cached = readFile(file, "utf8").then((code) => code.includes("use client") && detectDirective(code, file) === "use client", () => false);
8047
+ isClientFile.set(file, cached);
8048
+ }
8049
+ return cached;
8050
+ }
8051
+ return {
8052
+ name: "timber-client-in-server-package-deps",
8053
+ apply: "serve",
8054
+ resolveId: {
8055
+ order: "pre",
8056
+ async handler(source, importer, options) {
8057
+ if (this.environment.name !== rscEnvironmentName || !importer) return;
8058
+ if (BARE_IMPORT_RE.test(source) || source.startsWith("\0")) return;
8059
+ if (!importer.includes(NODE_MODULES) && !source.includes(NODE_MODULES)) return;
8060
+ const resolved = await this.resolve(source, importer, {
8061
+ ...options,
8062
+ skipSelf: true
8063
+ });
8064
+ if (!resolved || resolved.external) return resolved;
8065
+ const file = asFilePath(resolved.id);
8066
+ const bare = file && packagePathOf(file);
8067
+ if (!file || !bare || !await hasUseClient(file)) return resolved;
8068
+ let viaPackage;
8069
+ try {
8070
+ viaPackage = await this.resolve(bare, importer, {
8071
+ ...options,
8072
+ skipSelf: true
8073
+ });
8074
+ } catch {
8075
+ return resolved;
8076
+ }
8077
+ if (!viaPackage || asFilePath(viaPackage.id) !== file) return resolved;
8078
+ return viaPackage;
8079
+ }
8080
+ }
8081
+ };
8082
+ }
7549
8083
  // src/plugins/callsite-jsx.ts
7550
8084
  /**
7551
8085
  * Try to extract a static JSON-safe value from an AST expression node.
@@ -9827,6 +10361,8 @@ function timber(config) {
9827
10361
  timberBuildManifest(ctx),
9828
10362
  fonts,
9829
10363
  timberMdx(ctx),
10364
+ timberOptimizePackageImports(ctx),
10365
+ timberClientInServerPackageDeps(),
9830
10366
  timberRequestDep(ctx),
9831
10367
  timberCacheTransform(ctx),
9832
10368
  timberPrerenderSugar(ctx),