vinext 1.0.0-beta.6 → 1.0.0-beta.8

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 (179) hide show
  1. package/README.md +47 -3
  2. package/dist/build/action-owner-manifest.d.ts +42 -0
  3. package/dist/build/action-owner-manifest.js +110 -0
  4. package/dist/build/clean-output.js +1 -4
  5. package/dist/build/client-build-config.js +10 -11
  6. package/dist/build/prerender.d.ts +1 -1
  7. package/dist/build/prerender.js +12 -6
  8. package/dist/build/report.d.ts +1 -1
  9. package/dist/build/route-classification-manifest.d.ts +1 -1
  10. package/dist/build/static-export.d.ts +1 -1
  11. package/dist/client/app-nav-failure-handler.js +1 -0
  12. package/dist/client/navigation-runtime.d.ts +5 -3
  13. package/dist/client/navigation-runtime.js +4 -8
  14. package/dist/entries/app-browser-entry.d.ts +1 -1
  15. package/dist/entries/app-rsc-entry.d.ts +2 -1
  16. package/dist/entries/app-rsc-entry.js +111 -8
  17. package/dist/entries/pages-client-entry.d.ts +1 -1
  18. package/dist/entries/pages-server-entry.d.ts +1 -1
  19. package/dist/index.d.ts +3 -0
  20. package/dist/index.js +119 -26
  21. package/dist/plugins/action-owner-manifest.d.ts +14 -0
  22. package/dist/plugins/action-owner-manifest.js +84 -0
  23. package/dist/plugins/ast-utils.d.ts +30 -1
  24. package/dist/plugins/ast-utils.js +76 -1
  25. package/dist/plugins/css-module-imports.d.ts +2 -2
  26. package/dist/plugins/css-module-imports.js +5 -13
  27. package/dist/plugins/dynamic-preload-metadata.js +13 -34
  28. package/dist/plugins/environment.d.ts +11 -0
  29. package/dist/plugins/environment.js +7 -0
  30. package/dist/plugins/extensionless-dynamic-import.js +11 -35
  31. package/dist/plugins/fonts.js +8 -12
  32. package/dist/plugins/ignore-dynamic-requests.d.ts +2 -4
  33. package/dist/plugins/ignore-dynamic-requests.js +29 -59
  34. package/dist/plugins/import-meta-url.d.ts +15 -9
  35. package/dist/plugins/import-meta-url.js +310 -85
  36. package/dist/plugins/instrumentation-client.js +4 -5
  37. package/dist/plugins/middleware-export-validation.js +5 -17
  38. package/dist/plugins/middleware-server-only.js +2 -2
  39. package/dist/plugins/og-asset-ownership.js +18 -26
  40. package/dist/plugins/og-assets.js +2 -4
  41. package/dist/plugins/optimize-imports.js +2 -4
  42. package/dist/plugins/pages-node-externals.js +13 -40
  43. package/dist/plugins/remove-console.js +2 -4
  44. package/dist/plugins/require-condition-resolution.d.ts +16 -0
  45. package/dist/plugins/require-condition-resolution.js +167 -0
  46. package/dist/plugins/require-context.js +11 -46
  47. package/dist/plugins/sass.js +1 -1
  48. package/dist/plugins/server-externals-manifest.js +1 -23
  49. package/dist/plugins/strip-server-exports.js +13 -19
  50. package/dist/plugins/styled-jsx.js +17 -19
  51. package/dist/plugins/transform-result.d.ts +10 -0
  52. package/dist/plugins/transform-result.js +10 -0
  53. package/dist/plugins/transitive-externals.js +7 -21
  54. package/dist/plugins/typeof-window.d.ts +3 -8
  55. package/dist/plugins/typeof-window.js +5 -15
  56. package/dist/plugins/use-cache-callable.js +12 -22
  57. package/dist/plugins/wasm-module-import.js +1 -1
  58. package/dist/plugins/worker-image-imports.d.ts +12 -0
  59. package/dist/plugins/worker-image-imports.js +136 -0
  60. package/dist/routing/app-route-graph.d.ts +3 -2
  61. package/dist/routing/app-route-graph.js +1 -1
  62. package/dist/routing/route-pattern.d.ts +8 -1
  63. package/dist/routing/route-pattern.js +28 -1
  64. package/dist/routing/route-validation.js +7 -1
  65. package/dist/server/accept-encoding.d.ts +1 -2
  66. package/dist/server/accept-encoding.js +1 -4
  67. package/dist/server/app-action-forwarding.d.ts +18 -0
  68. package/dist/server/app-action-forwarding.js +140 -0
  69. package/dist/server/app-browser-entry.js +231 -50
  70. package/dist/server/app-browser-error.d.ts +1 -2
  71. package/dist/server/app-browser-error.js +1 -5
  72. package/dist/server/app-browser-history-controller.d.ts +16 -1
  73. package/dist/server/app-browser-history-controller.js +135 -18
  74. package/dist/server/app-browser-navigation-abort.d.ts +16 -0
  75. package/dist/server/app-browser-navigation-abort.js +29 -0
  76. package/dist/server/app-browser-navigation-controller.d.ts +4 -0
  77. package/dist/server/app-browser-navigation-controller.js +22 -6
  78. package/dist/server/app-browser-navigation-response.d.ts +11 -0
  79. package/dist/server/app-browser-navigation-response.js +8 -0
  80. package/dist/server/app-browser-popstate.d.ts +6 -1
  81. package/dist/server/app-browser-popstate.js +6 -2
  82. package/dist/server/app-browser-server-action-client.js +1 -1
  83. package/dist/server/app-browser-state.d.ts +2 -2
  84. package/dist/server/app-browser-state.js +3 -3
  85. package/dist/server/app-browser-stream.d.ts +0 -2
  86. package/dist/server/app-browser-supplemental-refresh.d.ts +49 -0
  87. package/dist/server/app-browser-supplemental-refresh.js +190 -0
  88. package/dist/server/app-browser-visible-commit.js +23 -12
  89. package/dist/server/app-elements-wire.d.ts +2 -0
  90. package/dist/server/app-elements-wire.js +7 -0
  91. package/dist/server/app-history-state.d.ts +22 -1
  92. package/dist/server/app-history-state.js +93 -9
  93. package/dist/server/app-optimistic-routing.d.ts +22 -1
  94. package/dist/server/app-optimistic-routing.js +137 -12
  95. package/dist/server/app-page-cache-finalizer.d.ts +3 -1
  96. package/dist/server/app-page-cache-finalizer.js +6 -6
  97. package/dist/server/app-page-cache.d.ts +2 -1
  98. package/dist/server/app-page-cache.js +2 -2
  99. package/dist/server/app-page-dispatch.d.ts +4 -1
  100. package/dist/server/app-page-dispatch.js +10 -1
  101. package/dist/server/app-page-element-builder.d.ts +1 -0
  102. package/dist/server/app-page-element-builder.js +1 -0
  103. package/dist/server/app-page-ppr-runtime.js +3 -2
  104. package/dist/server/app-page-render.d.ts +2 -1
  105. package/dist/server/app-page-render.js +6 -3
  106. package/dist/server/app-page-request.d.ts +2 -33
  107. package/dist/server/app-page-request.js +1 -27
  108. package/dist/server/app-page-route-wiring.d.ts +1 -0
  109. package/dist/server/app-page-route-wiring.js +4 -0
  110. package/dist/server/app-page-segment-state.d.ts +2 -2
  111. package/dist/server/app-page-segment-state.js +14 -8
  112. package/dist/server/app-ppr-fallback-shell.d.ts +2 -2
  113. package/dist/server/app-ppr-fallback-shell.js +3 -6
  114. package/dist/server/app-route-handler-dispatch.js +4 -1
  115. package/dist/server/app-route-handler-execution.js +1 -1
  116. package/dist/server/app-rsc-cache-busting.d.ts +2 -1
  117. package/dist/server/app-rsc-cache-busting.js +34 -8
  118. package/dist/server/app-rsc-handler.d.ts +4 -2
  119. package/dist/server/app-rsc-handler.js +57 -9
  120. package/dist/server/app-rsc-request-normalization.d.ts +2 -0
  121. package/dist/server/app-rsc-request-normalization.js +5 -1
  122. package/dist/server/app-rsc-route-matching.d.ts +4 -3
  123. package/dist/server/app-rsc-route-matching.js +14 -42
  124. package/dist/server/app-server-action-execution.d.ts +3 -0
  125. package/dist/server/app-server-action-execution.js +77 -2
  126. package/dist/server/app-ssr-entry.js +6 -6
  127. package/dist/server/app-ssr-stream.d.ts +1 -1
  128. package/dist/server/app-ssr-stream.js +2 -2
  129. package/dist/server/app-visited-response-cache.d.ts +6 -1
  130. package/dist/server/app-visited-response-cache.js +18 -2
  131. package/dist/server/dev-route-files.js +2 -5
  132. package/dist/server/dev-server.d.ts +5 -13
  133. package/dist/server/dev-server.js +22 -22
  134. package/dist/server/dev-stack-sourcemap.d.ts +1 -2
  135. package/dist/server/dev-stack-sourcemap.js +1 -4
  136. package/dist/server/headers.d.ts +5 -1
  137. package/dist/server/headers.js +5 -1
  138. package/dist/server/isr-cache.d.ts +6 -14
  139. package/dist/server/isr-cache.js +6 -27
  140. package/dist/server/middleware.d.ts +3 -16
  141. package/dist/server/middleware.js +2 -19
  142. package/dist/server/navigation-planner.d.ts +1 -0
  143. package/dist/server/navigation-planner.js +57 -9
  144. package/dist/server/navigation-trace.d.ts +1 -0
  145. package/dist/server/navigation-trace.js +1 -0
  146. package/dist/server/pages-data-route.d.ts +1 -10
  147. package/dist/server/pages-data-route.js +1 -12
  148. package/dist/server/pages-node-compat.d.ts +1 -4
  149. package/dist/server/pages-node-compat.js +1 -7
  150. package/dist/server/pages-readiness.js +4 -4
  151. package/dist/server/prerender-route-params.d.ts +1 -2
  152. package/dist/server/prerender-route-params.js +1 -4
  153. package/dist/server/prod-server.js +3 -1
  154. package/dist/shims/cache-runtime.js +39 -22
  155. package/dist/shims/cache.d.ts +1 -1
  156. package/dist/shims/dynamic.d.ts +3 -3
  157. package/dist/shims/dynamic.js +4 -6
  158. package/dist/shims/error.js +1 -1
  159. package/dist/shims/fetch-cache.d.ts +3 -1
  160. package/dist/shims/fetch-cache.js +23 -4
  161. package/dist/shims/internal/app-route-prefetch-policy.d.ts +6 -7
  162. package/dist/shims/internal/app-route-prefetch-policy.js +5 -4
  163. package/dist/shims/link.js +1 -1
  164. package/dist/shims/navigation.d.ts +12 -3
  165. package/dist/shims/navigation.js +46 -11
  166. package/dist/shims/navigation.react-server.js +1 -1
  167. package/dist/shims/request-state-types.d.ts +1 -1
  168. package/dist/shims/router.js +75 -4
  169. package/dist/shims/unified-request-context.d.ts +1 -1
  170. package/dist/shims/unified-request-context.js +1 -0
  171. package/dist/utils/built-asset-url.d.ts +1 -1
  172. package/dist/utils/built-asset-url.js +4 -2
  173. package/dist/utils/package-name.d.ts +11 -0
  174. package/dist/utils/package-name.js +18 -0
  175. package/dist/utils/path.d.ts +8 -1
  176. package/dist/utils/path.js +21 -1
  177. package/dist/utils/react-compiler-support.d.ts +20 -0
  178. package/dist/utils/react-compiler-support.js +29 -0
  179. package/package.json +3 -2
@@ -1,13 +1,11 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { isPathInsideOrEqual, stripViteModuleQuery } from "../utils/path.js";
3
+ import { packageNameFromSpecifier } from "../utils/package-name.js";
2
4
  import fs from "node:fs";
3
5
  import { promisify } from "node:util";
4
6
  //#region src/plugins/og-asset-ownership.ts
5
7
  const promisifiedRealpathNative = promisify(fs.realpath.native);
6
8
  const realpathNative = async (target) => toSlash(await promisifiedRealpathNative(target));
7
- function isPathInside(root, target) {
8
- const relative = path.relative(root, target);
9
- return relative === "" || !path.isAbsolute(relative) && !relative.startsWith("../") && relative !== "..";
10
- }
11
9
  async function findPackageRoot(moduleDir, expectedPackageName) {
12
10
  let currentDir = moduleDir;
13
11
  while (true) {
@@ -23,12 +21,6 @@ async function findPackageRoot(moduleDir, expectedPackageName) {
23
21
  currentDir = parentDir;
24
22
  }
25
23
  }
26
- function getPackageNameFromSpecifier(specifier) {
27
- if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\0") || specifier.startsWith("#")) return null;
28
- const segments = specifier.split("/");
29
- if (specifier.startsWith("@")) return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : null;
30
- return segments[0] || null;
31
- }
32
24
  function getAliasedPackageName(value) {
33
25
  if (typeof value !== "string") return null;
34
26
  return value.match(/^(?:npm:|workspace:)(@[^/]+\/[^@]+|[^@*~^]+)(?:@|$)/)?.[1] ?? null;
@@ -44,7 +36,7 @@ function applyAlias(find, replacement, source) {
44
36
  return source.replace(find, replacement);
45
37
  }
46
38
  function getNodeModulesPackageRoot(logicalProjectRoot, logicalModulePath) {
47
- const isProjectPath = isPathInside(logicalProjectRoot, logicalModulePath);
39
+ const isProjectPath = isPathInsideOrEqual(logicalProjectRoot, logicalModulePath);
48
40
  const parsedPath = path.parse(logicalModulePath);
49
41
  const baseRoot = isProjectPath ? logicalProjectRoot : parsedPath.root;
50
42
  const segments = (isProjectPath ? path.relative(logicalProjectRoot, logicalModulePath) : logicalModulePath.slice(parsedPath.root.length)).split("/");
@@ -89,7 +81,7 @@ async function packageOwnsAliasDirectory(packageRoot, packageName, aliasDirector
89
81
  "module",
90
82
  "source",
91
83
  "browser"
92
- ].some((field) => typeof manifest[field] === "string" && isPathInside(aliasDirectory, path.resolve(packageRoot, manifest[field])));
84
+ ].some((field) => typeof manifest[field] === "string" && isPathInsideOrEqual(aliasDirectory, path.resolve(packageRoot, manifest[field])));
93
85
  } catch {
94
86
  return false;
95
87
  }
@@ -143,12 +135,12 @@ var OgAssetOwnership = class {
143
135
  }
144
136
  async recordResolvedImport(source, resolvedId) {
145
137
  const configuredAlias = this.findAlias(source);
146
- const sourcePackageName = getPackageNameFromSpecifier(source);
138
+ const sourcePackageName = packageNameFromSpecifier(source);
147
139
  const expectedPackageName = this.getExpectedPackageName(source);
148
140
  if (configuredAlias === void 0 && expectedPackageName === void 0) return;
149
141
  let realResolvedPath;
150
142
  try {
151
- realResolvedPath = await realpathNative(path.resolve(resolvedId.split("?")[0]));
143
+ realResolvedPath = await realpathNative(path.resolve(stripViteModuleQuery(resolvedId)));
152
144
  } catch {
153
145
  return;
154
146
  }
@@ -158,7 +150,7 @@ var OgAssetOwnership = class {
158
150
  if (packageRoot !== null) this.linkedPackageRoots.add(packageRoot);
159
151
  }
160
152
  async resolveModuleBoundary(moduleId) {
161
- const modulePath = path.resolve(moduleId.split("?")[0]);
153
+ const modulePath = path.resolve(stripViteModuleQuery(moduleId));
162
154
  let realProjectRoot;
163
155
  let realModulePath;
164
156
  try {
@@ -181,7 +173,7 @@ var OgAssetOwnership = class {
181
173
  } catch {
182
174
  return null;
183
175
  }
184
- if (isPathInside(realPackageRoot, realModulePath)) return {
176
+ if (isPathInsideOrEqual(realPackageRoot, realModulePath)) return {
185
177
  assetRoot: realPackageRoot,
186
178
  moduleDir
187
179
  };
@@ -197,11 +189,11 @@ var OgAssetOwnership = class {
197
189
  moduleDir
198
190
  };
199
191
  }
200
- if (isPathInside(realProjectRoot, realModulePath)) return {
192
+ if (isPathInsideOrEqual(realProjectRoot, realModulePath)) return {
201
193
  assetRoot: realProjectRoot,
202
194
  moduleDir
203
195
  };
204
- const linkedPackageRoot = [...this.linkedPackageRoots].filter((root) => isPathInside(root, realModulePath)).sort((a, b) => b.length - a.length)[0];
196
+ const linkedPackageRoot = [...this.linkedPackageRoots].filter((root) => isPathInsideOrEqual(root, realModulePath)).sort((a, b) => b.length - a.length)[0];
205
197
  if (linkedPackageRoot !== void 0) return {
206
198
  assetRoot: linkedPackageRoot,
207
199
  moduleDir
@@ -215,7 +207,7 @@ var OgAssetOwnership = class {
215
207
  async resolveContainedAsset(assetRoot, assetPath) {
216
208
  try {
217
209
  const realPath = await realpathNative(assetPath);
218
- return isPathInside(assetRoot, realPath) ? realPath : null;
210
+ return isPathInsideOrEqual(assetRoot, realPath) ? realPath : null;
219
211
  } catch {
220
212
  return null;
221
213
  }
@@ -224,7 +216,7 @@ var OgAssetOwnership = class {
224
216
  return [...this.stringAliasesByFirstCharacter.get(source[0] ?? "") ?? [], ...this.regularExpressionAliases].filter((alias) => aliasMatches(alias.find, source)).sort((a, b) => a.index - b.index)[0];
225
217
  }
226
218
  getExpectedPackageName(source) {
227
- const packageName = getPackageNameFromSpecifier(source);
219
+ const packageName = packageNameFromSpecifier(source);
228
220
  return packageName === null ? void 0 : this.dependencyPackageNames.get(packageName);
229
221
  }
230
222
  async resolveAliasPackageRoot(alias, source, sourcePackageName, realResolvedPath) {
@@ -242,11 +234,11 @@ var OgAssetOwnership = class {
242
234
  if (configuredDirectory !== null || aliasTargetStat.isDirectory()) {
243
235
  const aliasBoundary = configuredDirectory ?? realAliasTarget;
244
236
  const packageRoot = await findPackageRoot(path.dirname(realResolvedPath));
245
- if (packageRoot === null || !isPathInside(aliasBoundary, packageRoot) || !isPathInside(packageRoot, realResolvedPath)) return null;
237
+ if (packageRoot === null || !isPathInsideOrEqual(aliasBoundary, packageRoot) || !isPathInsideOrEqual(packageRoot, realResolvedPath)) return null;
246
238
  return packageRoot;
247
239
  }
248
240
  const packageRoot = await findPackageRoot(path.dirname(realResolvedPath));
249
- if (packageRoot === null || !await packageOwnsAliasFile(packageRoot, sourcePackageName, realAliasTarget) || !isPathInside(packageRoot, realResolvedPath)) return null;
241
+ if (packageRoot === null || !await packageOwnsAliasFile(packageRoot, sourcePackageName, realAliasTarget) || !isPathInsideOrEqual(packageRoot, realResolvedPath)) return null;
250
242
  return packageRoot;
251
243
  } catch {
252
244
  return null;
@@ -254,10 +246,10 @@ var OgAssetOwnership = class {
254
246
  }
255
247
  async resolveConfiguredAliasRoot(realModulePath) {
256
248
  const packageRoot = await findPackageRoot(path.dirname(realModulePath));
257
- if (packageRoot === null || !isPathInside(packageRoot, realModulePath)) return null;
249
+ if (packageRoot === null || !isPathInsideOrEqual(packageRoot, realModulePath)) return null;
258
250
  for (const alias of this.configuredAliases) {
259
251
  if (!path.isAbsolute(alias.replacement)) continue;
260
- const packageName = typeof alias.find === "string" ? getPackageNameFromSpecifier(alias.find) : null;
252
+ const packageName = typeof alias.find === "string" ? packageNameFromSpecifier(alias.find) : null;
261
253
  if (alias.replacement.indexOf("$") !== -1) {
262
254
  const packageManifestName = await readPackageName(packageRoot);
263
255
  if (packageManifestName === null || !aliasMatches(alias.find, packageManifestName)) continue;
@@ -266,14 +258,14 @@ var OgAssetOwnership = class {
266
258
  try {
267
259
  const realAliasTarget = await realpathNative(aliasTarget);
268
260
  const aliasTargetStat = await fs.promises.stat(realAliasTarget);
269
- if (aliasTargetStat.isDirectory() && isPathInside(realAliasTarget, realModulePath) || aliasTargetStat.isFile() && realAliasTarget === realModulePath) return packageRoot;
261
+ if (aliasTargetStat.isDirectory() && isPathInsideOrEqual(realAliasTarget, realModulePath) || aliasTargetStat.isFile() && realAliasTarget === realModulePath) return packageRoot;
270
262
  } catch {}
271
263
  continue;
272
264
  }
273
265
  try {
274
266
  const realReplacement = await realpathNative(alias.replacement);
275
267
  if ((await fs.promises.stat(realReplacement)).isDirectory()) {
276
- if (isPathInside(packageRoot, realReplacement) && isPathInside(realReplacement, realModulePath) && await packageOwnsAliasDirectory(packageRoot, packageName, realReplacement)) return packageRoot;
268
+ if (isPathInsideOrEqual(packageRoot, realReplacement) && isPathInsideOrEqual(realReplacement, realModulePath) && await packageOwnsAliasDirectory(packageRoot, packageName, realReplacement)) return packageRoot;
277
269
  continue;
278
270
  }
279
271
  if (realReplacement === realModulePath && await packageOwnsAliasFile(packageRoot, packageName, realReplacement)) return packageRoot;
@@ -1,4 +1,5 @@
1
1
  import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { magicStringTransformResult } from "./transform-result.js";
2
3
  import { OgAssetOwnership } from "./og-asset-ownership.js";
3
4
  import { createRequire } from "node:module";
4
5
  import fs from "node:fs";
@@ -88,10 +89,7 @@ function createOgInlineFetchAssetsPlugin() {
88
89
  didReplace = true;
89
90
  }
90
91
  if (!didReplace) return null;
91
- return {
92
- code: s.toString(),
93
- map: s.generateMap({ hires: "boundary" })
94
- };
92
+ return magicStringTransformResult(s);
95
93
  }
96
94
  }
97
95
  };
@@ -1,5 +1,6 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
2
  import { escapeRegExp } from "../utils/regex.js";
3
+ import { magicStringTransformResult } from "./transform-result.js";
3
4
  import { VIRTUAL_MODULE_ID_RE } from "../utils/virtual-module.js";
4
5
  import { getAstName } from "./ast-utils.js";
5
6
  import { createRequire } from "node:module";
@@ -574,10 +575,7 @@ function createOptimizeImportsPlugin(getNextConfig, getRoot) {
574
575
  hasChanges = true;
575
576
  }
576
577
  if (!hasChanges) return null;
577
- return {
578
- code: s.toString(),
579
- map: s.generateMap({ hires: "boundary" })
580
- };
578
+ return magicStringTransformResult(s);
581
579
  }
582
580
  }
583
581
  };
@@ -1,6 +1,8 @@
1
- import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { forEachAstChild, isAstRecord, mayContainDynamicImport, nodeArray } from "./ast-utils.js";
3
- import { stripViteModuleQuery } from "../utils/path.js";
1
+ import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { canonicalizeFilePath, isPathInsideOrEqual, stripViteModuleQuery } from "../utils/path.js";
3
+ import { SCRIPT_MODULE_ID_RE, isAstRecord, mayContainDynamicImport, scriptParserLanguage, staticStringValue, walkAst } from "./ast-utils.js";
4
+ import { packageNameFromSpecifier } from "../utils/package-name.js";
5
+ import { isServerEnvironment } from "./environment.js";
4
6
  import fs from "node:fs";
5
7
  import { parseAst } from "vite";
6
8
  //#region src/plugins/pages-node-externals.ts
@@ -14,22 +16,8 @@ const FRAMEWORK_PACKAGES = /* @__PURE__ */ new Set([
14
16
  "vite",
15
17
  "vinext"
16
18
  ]);
17
- function packageNameFromSpecifier(id) {
18
- const [first, second] = id.split("/");
19
- if (!first) return null;
20
- return first.startsWith("@") ? second ? `${first}/${second}` : null : first;
21
- }
22
19
  function canonicalFile(id) {
23
- const cleanId = toSlash(stripViteModuleQuery(id));
24
- try {
25
- return toSlash(fs.realpathSync.native(cleanId));
26
- } catch {
27
- return cleanId;
28
- }
29
- }
30
- function isInsideDirectory(directory, file) {
31
- const relative = path.relative(canonicalFile(directory), canonicalFile(file));
32
- return relative === "" || !relative.startsWith("../") && relative !== ".." && !path.isAbsolute(relative);
20
+ return canonicalizeFilePath(stripViteModuleQuery(id));
33
21
  }
34
22
  function findPackageJson(file) {
35
23
  let directory = path.dirname(file);
@@ -56,16 +44,10 @@ function canNodeImport(file) {
56
44
  function matchesAlias(id, aliases) {
57
45
  return Object.keys(aliases).some((alias) => id === alias || id.startsWith(`${alias}/`));
58
46
  }
59
- function parserLanguage(id) {
60
- const cleanId = stripViteModuleQuery(id).toLowerCase();
61
- if (cleanId.endsWith(".tsx")) return "tsx";
62
- if (cleanId.endsWith(".ts") || cleanId.endsWith(".mts") || cleanId.endsWith(".cts")) return "ts";
63
- return "jsx";
64
- }
65
47
  function moduleDependencySpecifiers(code, id) {
66
48
  let ast;
67
49
  try {
68
- ast = parseAst(code, { lang: parserLanguage(id) });
50
+ ast = parseAst(code, { lang: scriptParserLanguage(id) ?? "jsx" });
69
51
  } catch {
70
52
  return [];
71
53
  }
@@ -73,15 +55,7 @@ function moduleDependencySpecifiers(code, id) {
73
55
  const seen = /* @__PURE__ */ new Set();
74
56
  const sourceSpecifier = (source) => {
75
57
  if (!isAstRecord(source)) return null;
76
- if (source.type === "Literal") return typeof source.value === "string" ? source.value : null;
77
- if (source.type !== "TemplateLiteral" || nodeArray(source.expressions).length !== 0) return null;
78
- const quasis = nodeArray(source.quasis);
79
- if (quasis.length !== 1 || !isAstRecord(quasis[0]) || quasis[0].type !== "TemplateElement") return null;
80
- const value = quasis[0].value;
81
- if (typeof value !== "object" || value === null) return null;
82
- const cooked = Reflect.get(value, "cooked");
83
- const raw = Reflect.get(value, "raw");
84
- return typeof cooked === "string" ? cooked : typeof raw === "string" ? raw : null;
58
+ return staticStringValue(source);
85
59
  };
86
60
  const addStaticSource = (source) => {
87
61
  const specifier = sourceSpecifier(source);
@@ -98,9 +72,8 @@ function moduleDependencySpecifiers(code, id) {
98
72
  if (!mayContainDynamicImport(code)) return specifiers;
99
73
  const visitDynamicImports = (node) => {
100
74
  if (node.type === "ImportExpression") addStaticSource(node.source);
101
- forEachAstChild(node, visitDynamicImports);
102
75
  };
103
- for (const statement of ast.body) if (isAstRecord(statement)) visitDynamicImports(statement);
76
+ for (const statement of ast.body) walkAst(statement, visitDynamicImports);
104
77
  return specifiers;
105
78
  }
106
79
  /**
@@ -128,11 +101,11 @@ function createPagesNodeExternalsPlugin(options) {
128
101
  apply: "build",
129
102
  enforce: "pre",
130
103
  applyToEnvironment(environment) {
131
- return options.isEnabled() && options.getPagesDir() !== null && environment.name !== "client" && environment.config.consumer !== "client";
104
+ return options.isEnabled() && options.getPagesDir() !== null && isServerEnvironment(environment);
132
105
  },
133
106
  transform: {
134
107
  filter: { id: {
135
- include: /\.[cm]?[jt]sx?(?:\?.*)?$/,
108
+ include: SCRIPT_MODULE_ID_RE,
136
109
  exclude: /\/node_modules\//
137
110
  } },
138
111
  async handler(code, id) {
@@ -143,7 +116,7 @@ function createPagesNodeExternalsPlugin(options) {
143
116
  const cleanId = canonicalFile(id);
144
117
  if (!path.isAbsolute(cleanId) || cleanId.includes("/node_modules/")) return null;
145
118
  const pagesOwnedModules = pagesOwnedModulesFor(environment.name);
146
- if (!isInsideDirectory(pagesDir, cleanId) && !pagesOwnedModules.has(cleanId)) return null;
119
+ if (!isPathInsideOrEqual(canonicalFile(pagesDir), cleanId) && !pagesOwnedModules.has(cleanId)) return null;
147
120
  pagesOwnedModules.add(cleanId);
148
121
  for (const specifier of moduleDependencySpecifiers(code, cleanId)) {
149
122
  const resolved = await this.resolve(specifier, id, { skipSelf: true });
@@ -163,7 +136,7 @@ function createPagesNodeExternalsPlugin(options) {
163
136
  if (!pagesDir) return null;
164
137
  const pagesOwnedModules = pagesOwnedModulesFor(environment.name);
165
138
  const cleanImporter = canonicalFile(importer);
166
- if (!(path.isAbsolute(cleanImporter) && (isInsideDirectory(pagesDir, cleanImporter) || pagesOwnedModules.has(cleanImporter)))) return null;
139
+ if (!(path.isAbsolute(cleanImporter) && (isPathInsideOrEqual(canonicalFile(pagesDir), cleanImporter) || pagesOwnedModules.has(cleanImporter)))) return null;
167
140
  if (id.startsWith(".")) {
168
141
  const resolved = await this.resolve(id, importer, { skipSelf: true });
169
142
  if (resolved && !resolved.external) {
@@ -1,3 +1,4 @@
1
+ import { magicStringTransformResult } from "./transform-result.js";
1
2
  import { parseAst } from "vite";
2
3
  import MagicString from "magic-string";
3
4
  //#region src/plugins/remove-console.ts
@@ -168,10 +169,7 @@ function removeConsoleCalls(code, config) {
168
169
  }
169
170
  for (const node of ast.body) walk(node);
170
171
  if (!changed) return null;
171
- return {
172
- code: s.toString(),
173
- map: s.generateMap({ hires: "boundary" })
174
- };
172
+ return magicStringTransformResult(s);
175
173
  }
176
174
  //#endregion
177
175
  export { removeConsoleCalls };
@@ -0,0 +1,16 @@
1
+ import { Plugin, createIdResolver } from "vite";
2
+ //#region src/plugins/require-condition-resolution.d.ts
3
+ declare function isConditionalRequireScriptModuleId(id: string): boolean;
4
+ /**
5
+ * Resolve literal package `require()` calls while Vite still knows they are
6
+ * CommonJS references. `vite-plugin-commonjs` subsequently hoists each call
7
+ * into a static import; without this pre-resolution, Vite sees an
8
+ * `import-statement` and selects the package's `import` export condition. Use
9
+ * Vite's explicit `isRequire` resolver because the dev plugin container does
10
+ * not preserve a synthetic `kind: "require-call"` passed through `this.resolve`.
11
+ */
12
+ type IdResolverFactory = typeof createIdResolver;
13
+ type CommonJsTransformFilter = (id: string) => boolean | undefined;
14
+ declare function createRequireConditionResolutionPlugin(createResolver?: IdResolverFactory, commonjsTransformFilter?: CommonJsTransformFilter): Plugin;
15
+ //#endregion
16
+ export { createRequireConditionResolutionPlugin, isConditionalRequireScriptModuleId };
@@ -0,0 +1,167 @@
1
+ import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { stripViteModuleQuery } from "../utils/path.js";
3
+ import { magicStringTransformResult } from "./transform-result.js";
4
+ import { SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, hasRange, isAstRecord, isIdentifierNamed, nodeArray, scriptParserLanguage, staticStringValue, unwrapExpression } from "./ast-utils.js";
5
+ import { collectDirectScopeBindings, collectLoopScopeBindings, collectSwitchScopeBindings, collectVarScopeBindings, createAstScope, hasAstBinding, isFunctionNode } from "./ast-scope.js";
6
+ import { createIdResolver, parseAst } from "vite";
7
+ import { readFile } from "node:fs/promises";
8
+ import MagicString from "magic-string";
9
+ //#region src/plugins/require-condition-resolution.ts
10
+ const LITERAL_REQUIRE_RE = /\brequire\s*\(/;
11
+ const CONDITIONAL_REQUIRE_SCRIPT_ID_RE = /\.vinext-require\.(?:js|jsx|ts|tsx)$/i;
12
+ function isConditionalRequireScriptModuleId(id) {
13
+ return CONDITIONAL_REQUIRE_SCRIPT_ID_RE.test(stripViteModuleQuery(id));
14
+ }
15
+ function syntheticModuleType(id) {
16
+ const extension = path.extname(stripViteModuleQuery(id)).toLowerCase();
17
+ if (extension === ".json") return "json";
18
+ if (extension === ".jsx") return "jsx";
19
+ if (extension === ".tsx") return "tsx";
20
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") return "ts";
21
+ return "js";
22
+ }
23
+ function literalString(value) {
24
+ return staticStringValue(unwrapExpression(value));
25
+ }
26
+ function isPackageSpecifier(specifier) {
27
+ return specifier.startsWith("#") || !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("\\") && !/^[a-z][a-z\d+.-]*:/i.test(specifier);
28
+ }
29
+ function collectLiteralRequires(code, id) {
30
+ let ast;
31
+ try {
32
+ ast = parseAst(code, { lang: scriptParserLanguage(id) ?? "jsx" });
33
+ } catch {
34
+ return [];
35
+ }
36
+ const root = isAstRecord(ast) ? ast : null;
37
+ if (!root) return [];
38
+ const requires = [];
39
+ const rootScope = createAstScope(null);
40
+ collectDirectScopeBindings(root, rootScope);
41
+ collectVarScopeBindings(root, rootScope);
42
+ function visit(node, parentScope) {
43
+ let scope = parentScope;
44
+ if (isFunctionNode(node)) {
45
+ const parameterScope = createAstScope(parentScope);
46
+ collectBindingNames(node.id, parameterScope.bindings);
47
+ for (const parameter of nodeArray(node.params)) {
48
+ collectBindingNames(parameter, parameterScope.bindings);
49
+ if (isAstRecord(parameter)) visit(parameter, parameterScope);
50
+ }
51
+ const body = isAstRecord(node.body) ? node.body : null;
52
+ if (body) {
53
+ const bodyScope = createAstScope(parameterScope);
54
+ collectDirectScopeBindings(body, bodyScope);
55
+ collectVarScopeBindings(body, bodyScope);
56
+ if (body.type === "BlockStatement") {
57
+ for (const statement of nodeArray(body.body)) if (isAstRecord(statement)) visit(statement, bodyScope);
58
+ } else visit(body, bodyScope);
59
+ }
60
+ return;
61
+ }
62
+ if (node.type === "SwitchStatement") {
63
+ if (isAstRecord(node.discriminant)) visit(node.discriminant, parentScope);
64
+ const switchScope = createAstScope(parentScope);
65
+ collectSwitchScopeBindings(node, switchScope);
66
+ for (const switchCase of nodeArray(node.cases)) if (isAstRecord(switchCase)) visit(switchCase, switchScope);
67
+ return;
68
+ }
69
+ if (node.type === "BlockStatement" && node !== root || node.type === "StaticBlock" || node.type === "TSModuleBlock") {
70
+ scope = createAstScope(parentScope);
71
+ collectDirectScopeBindings(node, scope);
72
+ if (node.type === "StaticBlock" || node.type === "TSModuleBlock") collectVarScopeBindings(node, scope);
73
+ } else if (node.type === "CatchClause") {
74
+ scope = createAstScope(parentScope);
75
+ collectBindingNames(node.param, scope.bindings);
76
+ } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
77
+ scope = createAstScope(parentScope);
78
+ collectLoopScopeBindings(node, scope);
79
+ } else if (node.type === "ClassExpression" && node.id) {
80
+ scope = createAstScope(parentScope);
81
+ collectBindingNames(node.id, scope.bindings);
82
+ }
83
+ if (node.type === "CallExpression") {
84
+ const callee = unwrapExpression(node.callee);
85
+ const args = nodeArray(node.arguments);
86
+ const argument = unwrapExpression(args[0]);
87
+ const specifier = literalString(argument);
88
+ if (isIdentifierNamed(callee, "require") && !hasAstBinding(scope, "require") && args.length === 1 && argument && hasRange(argument) && specifier !== null && isPackageSpecifier(specifier)) {
89
+ requires.push({
90
+ argument,
91
+ specifier
92
+ });
93
+ return;
94
+ }
95
+ }
96
+ forEachAstChild(node, (child) => visit(child, scope));
97
+ }
98
+ for (const statement of nodeArray(root.body)) if (isAstRecord(statement)) visit(statement, rootScope);
99
+ return requires;
100
+ }
101
+ function createRequireConditionResolutionPlugin(createResolver = createIdResolver, commonjsTransformFilter) {
102
+ const virtualTargets = /* @__PURE__ */ new Map();
103
+ let resolveImport;
104
+ let resolveRequire;
105
+ return {
106
+ name: "vinext:require-condition-resolution",
107
+ enforce: "pre",
108
+ configResolved(config) {
109
+ resolveImport = createResolver(config, { isRequire: false });
110
+ resolveRequire = createResolver(config, { isRequire: true });
111
+ },
112
+ resolveId(source) {
113
+ if (virtualTargets.has(source)) return source;
114
+ },
115
+ async load(id) {
116
+ const target = virtualTargets.get(id);
117
+ if (!target) return;
118
+ this.addWatchFile(target.file);
119
+ try {
120
+ return {
121
+ code: await readFile(target.file, "utf8"),
122
+ moduleType: target.moduleType
123
+ };
124
+ } catch (error) {
125
+ const code = typeof error === "object" && error !== null && "code" in error ? Reflect.get(error, "code") : void 0;
126
+ if (code === "ENOENT" || code === "EISDIR") return;
127
+ throw error;
128
+ }
129
+ },
130
+ transform: {
131
+ filter: {
132
+ id: SCRIPT_MODULE_ID_RE,
133
+ code: LITERAL_REQUIRE_RE
134
+ },
135
+ async handler(code, id) {
136
+ const cleanId = stripViteModuleQuery(id);
137
+ const commonjsDisposition = commonjsTransformFilter?.(cleanId);
138
+ if (commonjsDisposition === false || commonjsDisposition !== true && cleanId.includes("node_modules")) return null;
139
+ const requires = collectLiteralRequires(code, id);
140
+ if (requires.length === 0 || !resolveImport || !resolveRequire) return null;
141
+ const output = new MagicString(code);
142
+ let changed = false;
143
+ for (const { argument, specifier } of requires) {
144
+ const [requireResolution, importResolution] = await Promise.all([resolveRequire(this.environment, specifier, id), resolveImport(this.environment, specifier, id)]);
145
+ if (!requireResolution || requireResolution === specifier || !path.isAbsolute(stripViteModuleQuery(requireResolution))) continue;
146
+ const requirePath = stripViteModuleQuery(requireResolution);
147
+ if (requirePath === (importResolution ? stripViteModuleQuery(importResolution) : importResolution)) continue;
148
+ const moduleType = syntheticModuleType(requirePath);
149
+ const virtualId = `${requirePath}.vinext-require.${moduleType}`;
150
+ virtualTargets.set(virtualId, {
151
+ file: requirePath,
152
+ moduleType
153
+ });
154
+ output.overwrite(argument.start, argument.end, JSON.stringify(virtualId));
155
+ changed = true;
156
+ }
157
+ if (!changed) return null;
158
+ return magicStringTransformResult(output, {
159
+ hires: "boundary",
160
+ source: id
161
+ });
162
+ }
163
+ }
164
+ };
165
+ }
166
+ //#endregion
167
+ export { createRequireConditionResolutionPlugin, isConditionalRequireScriptModuleId };
@@ -1,19 +1,11 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { forEachAstChild, hasRange, isAstRecord, nodeArray } from "./ast-utils.js";
2
+ import { stripViteModuleQuery } from "../utils/path.js";
3
+ import { magicStringTransformResult } from "./transform-result.js";
4
+ import { SCRIPT_MODULE_ID_RE, booleanLiteralValue, hasRange, isAstRecord, nodeArray, scriptParserLanguage, stringLiteralValue, walkAst } from "./ast-utils.js";
3
5
  import { parseAst } from "vite";
4
6
  import { readdir, realpath, stat } from "node:fs/promises";
5
7
  import MagicString from "magic-string";
6
8
  //#region src/plugins/require-context.ts
7
- const TRANSFORMABLE_EXTENSIONS = /* @__PURE__ */ new Set([
8
- ".js",
9
- ".jsx",
10
- ".ts",
11
- ".tsx",
12
- ".mjs",
13
- ".cjs",
14
- ".mts",
15
- ".cts"
16
- ]);
17
9
  function createRequireContextPlugin() {
18
10
  const watchedContexts = /* @__PURE__ */ new WeakMap();
19
11
  return {
@@ -21,7 +13,7 @@ function createRequireContextPlugin() {
21
13
  enforce: "pre",
22
14
  transform: {
23
15
  filter: {
24
- id: /\.(?:[cm]?[jt]s|[jt]sx)(?:\?.*)?$/i,
16
+ id: SCRIPT_MODULE_ID_RE,
25
17
  code: /\brequire\b[\s\S]*\.context/
26
18
  },
27
19
  async handler(code, id) {
@@ -60,7 +52,7 @@ function createRequireContextPlugin() {
60
52
  };
61
53
  }
62
54
  async function transformRequireContext(code, id) {
63
- const lang = langForId(id);
55
+ const lang = scriptParserLanguage(id);
64
56
  let ast;
65
57
  try {
66
58
  ast = parseAst(code, { lang });
@@ -86,38 +78,19 @@ async function transformRequireContext(code, id) {
86
78
  output.appendLeft(importOffset, importBlock);
87
79
  }
88
80
  return {
89
- code: output.toString(),
90
- map: output.generateMap({ hires: "boundary" }),
81
+ ...magicStringTransformResult(output),
91
82
  contexts
92
83
  };
93
84
  }
94
- function langForId(id) {
95
- const clean = id.split("?", 1)[0];
96
- const dot = clean.lastIndexOf(".");
97
- if (dot < 0) return null;
98
- const ext = clean.slice(dot).toLowerCase();
99
- if (!TRANSFORMABLE_EXTENSIONS.has(ext)) return null;
100
- switch (ext) {
101
- case ".ts":
102
- case ".cts":
103
- case ".mts": return "ts";
104
- case ".tsx": return "tsx";
105
- case ".jsx": return "jsx";
106
- default: return "jsx";
107
- }
108
- }
109
85
  function collectRequireContextCalls(ast) {
110
86
  const calls = [];
111
- function visit(value) {
112
- if (!isAstRecord(value)) return;
113
- const parsed = parseRequireContextCall(value);
87
+ walkAst(ast, (node) => {
88
+ const parsed = parseRequireContextCall(node);
114
89
  if (parsed) {
115
90
  calls.push(parsed);
116
- return;
91
+ return false;
117
92
  }
118
- forEachAstChild(value, visit);
119
- }
120
- visit(ast);
93
+ });
121
94
  return calls;
122
95
  }
123
96
  function findImportInsertionOffset(ast) {
@@ -184,14 +157,6 @@ function isRequireExpression(value) {
184
157
  function isPropertyNamed(value, name) {
185
158
  return isAstRecord(value) && value.type === "Identifier" && value.name === name;
186
159
  }
187
- function stringLiteralValue(value) {
188
- if (isAstRecord(value) && value.type === "Literal" && typeof value.value === "string") return value.value;
189
- return null;
190
- }
191
- function booleanLiteralValue(value) {
192
- if (isAstRecord(value) && value.type === "Literal" && typeof value.value === "boolean") return value.value;
193
- return null;
194
- }
195
160
  function regexLiteralValue(value) {
196
161
  if (!isAstRecord(value) || value.type !== "Literal") return null;
197
162
  const regex = value.regex;
@@ -223,7 +188,7 @@ function buildReplacement(call, modules) {
223
188
  ].join("\n");
224
189
  }
225
190
  async function resolveContextModules(id, call, bindingPrefix, callIndex) {
226
- const importer = toSlash(id.split("?", 1)[0]);
191
+ const importer = toSlash(stripViteModuleQuery(id));
227
192
  const directory = path.resolve(path.dirname(importer), call.dir);
228
193
  const context = {
229
194
  directory,
@@ -1,4 +1,5 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { NODE_MODULES_PATH_RE } from "../utils/path.js";
2
3
  import { markCssUrlAssetReferences, rebaseCssUrlAssetReferences } from "../build/css-url-assets.js";
3
4
  import { createRequire } from "node:module";
4
5
  import fs from "node:fs";
@@ -29,7 +30,6 @@ import { fileURLToPath, pathToFileURL } from "node:url";
29
30
  * @see https://vite.dev/config/shared-options.html#css-preprocessoroptions
30
31
  */
31
32
  const URL_SCHEME_RE = /^[A-Za-z][A-Za-z\d+.-]*:/;
32
- const NODE_MODULES_PATH_RE = /(?:^|\/)node_modules(?:\/|$)/;
33
33
  function matchSassTsconfigPathAlias(aliases, url) {
34
34
  for (const alias of aliases) if (!alias.find.includes("*") && alias.find === url) return {
35
35
  alias,
@@ -1,29 +1,7 @@
1
1
  import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { builtinModules } from "node:module";
2
+ import { packageNameFromSpecifier } from "../utils/package-name.js";
3
3
  import fs from "node:fs";
4
4
  //#region src/plugins/server-externals-manifest.ts
5
- const BUILTIN_MODULES = new Set(builtinModules.flatMap((name) => name.startsWith("node:") ? [name, name.slice(5)] : [name, `node:${name}`]));
6
- /**
7
- * Extract the npm package name from a bare module specifier.
8
- *
9
- * Returns null for:
10
- * - Relative imports ("./foo", "../bar")
11
- * - Absolute paths ("/abs/path")
12
- * - Node built-ins ("node:fs")
13
- * - Package self-references ("#imports")
14
- */
15
- function packageNameFromSpecifier(specifier) {
16
- if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\\") || specifier.startsWith("#")) return null;
17
- if (/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(specifier)) return null;
18
- if (specifier.startsWith("@")) {
19
- const parts = specifier.split("/");
20
- if (parts.length >= 2) return `${parts[0]}/${parts[1]}`;
21
- return null;
22
- }
23
- const packageName = specifier.split("/")[0] || null;
24
- if (!packageName || BUILTIN_MODULES.has(specifier) || BUILTIN_MODULES.has(packageName)) return null;
25
- return packageName;
26
- }
27
5
  /**
28
6
  * vinext:server-externals-manifest
29
7
  *