nitropack-nightly 2.10.0-28638494.93d002b7 → 3.0.0-beta-28638602.1fe7b893-nitro-nightly-mirror

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 (287) hide show
  1. package/README.md +1 -1
  2. package/cli.d.ts +1 -1
  3. package/config.d.ts +1 -1
  4. package/core.d.ts +1 -1
  5. package/dist/cli/index.d.mts +1 -1
  6. package/dist/cli/index.d.ts +1 -1
  7. package/dist/cli/index.mjs +1 -18
  8. package/dist/config/index.d.mts +1 -6
  9. package/dist/config/index.d.ts +1 -6
  10. package/dist/config/index.mjs +1 -5
  11. package/dist/core/index.d.mts +1 -69
  12. package/dist/core/index.d.ts +1 -69
  13. package/dist/core/index.mjs +1 -2435
  14. package/dist/kit/index.d.mts +1 -44
  15. package/dist/kit/index.d.ts +1 -44
  16. package/dist/kit/index.mjs +1 -71
  17. package/dist/meta/index.d.mts +1 -3
  18. package/dist/meta/index.d.ts +1 -3
  19. package/dist/meta/index.mjs +1 -3
  20. package/dist/presets/index.d.mts +1 -1
  21. package/dist/presets/index.d.ts +1 -2
  22. package/dist/presets/index.mjs +1 -1
  23. package/dist/rollup/index.d.mts +1 -5
  24. package/dist/rollup/index.d.ts +1 -5
  25. package/dist/rollup/index.mjs +1 -2033
  26. package/dist/runtime/index.d.mts +1 -0
  27. package/dist/runtime/index.d.ts +1 -12
  28. package/dist/runtime/index.mjs +1 -17
  29. package/dist/types/index.d.mts +1 -260
  30. package/dist/types/index.d.ts +1 -260
  31. package/dist/types/index.mjs +1 -1
  32. package/kit.d.ts +1 -1
  33. package/meta.d.ts +1 -1
  34. package/package.json +6 -172
  35. package/presets.d.ts +1 -1
  36. package/rollup.d.ts +1 -1
  37. package/runtime-meta.d.ts +1 -4
  38. package/runtime-meta.mjs +1 -30
  39. package/runtime.d.ts +1 -1
  40. package/types.d.ts +1 -1
  41. package/dist/cli/build.mjs +0 -47
  42. package/dist/cli/common.mjs +0 -13
  43. package/dist/cli/dev.mjs +0 -63
  44. package/dist/cli/index2.mjs +0 -14
  45. package/dist/cli/list.mjs +0 -28
  46. package/dist/cli/prepare.mjs +0 -21
  47. package/dist/cli/run.mjs +0 -57
  48. package/dist/presets/_all.gen.d.ts +0 -2
  49. package/dist/presets/_all.gen.mjs +0 -52
  50. package/dist/presets/_nitro/base-worker.d.ts +0 -2
  51. package/dist/presets/_nitro/base-worker.mjs +0 -25
  52. package/dist/presets/_nitro/nitro-dev.d.ts +0 -2
  53. package/dist/presets/_nitro/nitro-dev.mjs +0 -19
  54. package/dist/presets/_nitro/nitro-prerender.d.ts +0 -2
  55. package/dist/presets/_nitro/nitro-prerender.mjs +0 -17
  56. package/dist/presets/_nitro/preset.d.ts +0 -2
  57. package/dist/presets/_nitro/preset.mjs +0 -5
  58. package/dist/presets/_nitro/runtime/nitro-dev.d.ts +0 -1
  59. package/dist/presets/_nitro/runtime/nitro-dev.mjs +0 -86
  60. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.ts +0 -3
  61. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +0 -7
  62. package/dist/presets/_nitro/runtime/service-worker.d.ts +0 -1
  63. package/dist/presets/_nitro/runtime/service-worker.mjs +0 -31
  64. package/dist/presets/_nitro/service-worker.d.ts +0 -2
  65. package/dist/presets/_nitro/service-worker.mjs +0 -110
  66. package/dist/presets/_resolve.d.ts +0 -8
  67. package/dist/presets/_resolve.mjs +0 -44
  68. package/dist/presets/_static/preset.d.ts +0 -2
  69. package/dist/presets/_static/preset.mjs +0 -69
  70. package/dist/presets/_types.gen.d.ts +0 -16
  71. package/dist/presets/_types.gen.mjs +0 -0
  72. package/dist/presets/alwaysdata/preset.d.ts +0 -2
  73. package/dist/presets/alwaysdata/preset.mjs +0 -14
  74. package/dist/presets/aws-amplify/preset.d.ts +0 -3
  75. package/dist/presets/aws-amplify/preset.mjs +0 -27
  76. package/dist/presets/aws-amplify/runtime/aws-amplify.d.ts +0 -1
  77. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +0 -13
  78. package/dist/presets/aws-amplify/types.d.ts +0 -141
  79. package/dist/presets/aws-amplify/types.mjs +0 -0
  80. package/dist/presets/aws-amplify/utils.d.ts +0 -2
  81. package/dist/presets/aws-amplify/utils.mjs +0 -82
  82. package/dist/presets/aws-lambda/preset.d.ts +0 -2
  83. package/dist/presets/aws-lambda/preset.mjs +0 -21
  84. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.ts +0 -15
  85. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +0 -53
  86. package/dist/presets/aws-lambda/runtime/aws-lambda.d.ts +0 -4
  87. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +0 -45
  88. package/dist/presets/azure/preset.d.ts +0 -3
  89. package/dist/presets/azure/preset.mjs +0 -44
  90. package/dist/presets/azure/runtime/azure-functions.d.ts +0 -5
  91. package/dist/presets/azure/runtime/azure-functions.mjs +0 -24
  92. package/dist/presets/azure/runtime/azure-swa.d.ts +0 -5
  93. package/dist/presets/azure/runtime/azure-swa.mjs +0 -30
  94. package/dist/presets/azure/types.d.ts +0 -13
  95. package/dist/presets/azure/types.mjs +0 -0
  96. package/dist/presets/azure/utils.d.ts +0 -3
  97. package/dist/presets/azure/utils.mjs +0 -183
  98. package/dist/presets/bun/preset.d.ts +0 -2
  99. package/dist/presets/bun/preset.mjs +0 -17
  100. package/dist/presets/bun/runtime/bun.d.ts +0 -1
  101. package/dist/presets/bun/runtime/bun.mjs +0 -32
  102. package/dist/presets/cleavr/preset.d.ts +0 -2
  103. package/dist/presets/cleavr/preset.mjs +0 -12
  104. package/dist/presets/cloudflare/preset.d.ts +0 -3
  105. package/dist/presets/cloudflare/preset.mjs +0 -145
  106. package/dist/presets/cloudflare/runtime/cloudflare-module.d.ts +0 -13
  107. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +0 -102
  108. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.ts +0 -20
  109. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +0 -55
  110. package/dist/presets/cloudflare/runtime/cloudflare-worker.d.ts +0 -1
  111. package/dist/presets/cloudflare/runtime/cloudflare-worker.mjs +0 -63
  112. package/dist/presets/cloudflare/types.d.ts +0 -89
  113. package/dist/presets/cloudflare/types.mjs +0 -0
  114. package/dist/presets/cloudflare/types.wrangler.d.ts +0 -974
  115. package/dist/presets/cloudflare/types.wrangler.mjs +0 -0
  116. package/dist/presets/cloudflare/utils.d.ts +0 -3
  117. package/dist/presets/cloudflare/utils.mjs +0 -163
  118. package/dist/presets/deno/preset.d.ts +0 -2
  119. package/dist/presets/deno/preset.mjs +0 -148
  120. package/dist/presets/deno/runtime/_deno-env-polyfill.d.ts +0 -0
  121. package/dist/presets/deno/runtime/_deno-env-polyfill.mjs +0 -1
  122. package/dist/presets/deno/runtime/deno-deploy.d.ts +0 -2
  123. package/dist/presets/deno/runtime/deno-deploy.mjs +0 -32
  124. package/dist/presets/deno/runtime/deno-server.d.ts +0 -4
  125. package/dist/presets/deno/runtime/deno-server.mjs +0 -66
  126. package/dist/presets/digitalocean/preset.d.ts +0 -2
  127. package/dist/presets/digitalocean/preset.mjs +0 -11
  128. package/dist/presets/edgio/preset.d.ts +0 -2
  129. package/dist/presets/edgio/preset.mjs +0 -95
  130. package/dist/presets/firebase/preset.d.ts +0 -3
  131. package/dist/presets/firebase/preset.mjs +0 -51
  132. package/dist/presets/firebase/runtime/firebase-gen-1.d.ts +0 -2
  133. package/dist/presets/firebase/runtime/firebase-gen-1.mjs +0 -8
  134. package/dist/presets/firebase/runtime/firebase-gen-2.d.ts +0 -2
  135. package/dist/presets/firebase/runtime/firebase-gen-2.mjs +0 -15
  136. package/dist/presets/firebase/runtime/firebase-gen-default.d.ts +0 -1
  137. package/dist/presets/firebase/runtime/firebase-gen-default.mjs +0 -1
  138. package/dist/presets/firebase/types.d.ts +0 -37
  139. package/dist/presets/firebase/types.mjs +0 -0
  140. package/dist/presets/firebase/utils.d.ts +0 -3
  141. package/dist/presets/firebase/utils.mjs +0 -50
  142. package/dist/presets/flightcontrol/preset.d.ts +0 -2
  143. package/dist/presets/flightcontrol/preset.mjs +0 -11
  144. package/dist/presets/heroku/preset.d.ts +0 -2
  145. package/dist/presets/heroku/preset.mjs +0 -11
  146. package/dist/presets/iis/preset.d.ts +0 -2
  147. package/dist/presets/iis/preset.mjs +0 -32
  148. package/dist/presets/iis/utils.d.ts +0 -3
  149. package/dist/presets/iis/utils.mjs +0 -159
  150. package/dist/presets/koyeb/preset.d.ts +0 -2
  151. package/dist/presets/koyeb/preset.mjs +0 -11
  152. package/dist/presets/netlify/legacy/preset.d.ts +0 -2
  153. package/dist/presets/netlify/legacy/preset.mjs +0 -142
  154. package/dist/presets/netlify/legacy/runtime/_deno-env-polyfill.d.ts +0 -0
  155. package/dist/presets/netlify/legacy/runtime/_deno-env-polyfill.mjs +0 -1
  156. package/dist/presets/netlify/legacy/runtime/netlify-builder.d.ts +0 -3
  157. package/dist/presets/netlify/legacy/runtime/netlify-builder.mjs +0 -5
  158. package/dist/presets/netlify/legacy/runtime/netlify-edge.d.ts +0 -3
  159. package/dist/presets/netlify/legacy/runtime/netlify-edge.mjs +0 -26
  160. package/dist/presets/netlify/legacy/runtime/netlify-lambda.d.ts +0 -4
  161. package/dist/presets/netlify/legacy/runtime/netlify-lambda.mjs +0 -39
  162. package/dist/presets/netlify/legacy/runtime/netlify.d.ts +0 -4
  163. package/dist/presets/netlify/legacy/runtime/netlify.mjs +0 -22
  164. package/dist/presets/netlify/legacy/utils.d.ts +0 -4
  165. package/dist/presets/netlify/legacy/utils.mjs +0 -113
  166. package/dist/presets/netlify/preset.d.ts +0 -3
  167. package/dist/presets/netlify/preset.mjs +0 -127
  168. package/dist/presets/netlify/runtime/_deno-env-polyfill.d.ts +0 -0
  169. package/dist/presets/netlify/runtime/_deno-env-polyfill.mjs +0 -1
  170. package/dist/presets/netlify/runtime/netlify-edge.d.ts +0 -2
  171. package/dist/presets/netlify/runtime/netlify-edge.mjs +0 -25
  172. package/dist/presets/netlify/runtime/netlify.d.ts +0 -4
  173. package/dist/presets/netlify/runtime/netlify.mjs +0 -54
  174. package/dist/presets/netlify/types.d.ts +0 -12
  175. package/dist/presets/netlify/types.mjs +0 -0
  176. package/dist/presets/netlify/utils.d.ts +0 -5
  177. package/dist/presets/netlify/utils.mjs +0 -94
  178. package/dist/presets/node/preset.d.ts +0 -2
  179. package/dist/presets/node/preset.mjs +0 -49
  180. package/dist/presets/node/runtime/cli.d.ts +0 -1
  181. package/dist/presets/node/runtime/cli.mjs +0 -21
  182. package/dist/presets/node/runtime/cluster.d.ts +0 -1
  183. package/dist/presets/node/runtime/cluster.mjs +0 -60
  184. package/dist/presets/node/runtime/node-listener.d.ts +0 -6
  185. package/dist/presets/node/runtime/node-listener.mjs +0 -15
  186. package/dist/presets/node/runtime/node-server.d.ts +0 -3
  187. package/dist/presets/node/runtime/node-server.mjs +0 -44
  188. package/dist/presets/platform.sh/preset.d.ts +0 -2
  189. package/dist/presets/platform.sh/preset.mjs +0 -11
  190. package/dist/presets/render.com/preset.d.ts +0 -2
  191. package/dist/presets/render.com/preset.mjs +0 -11
  192. package/dist/presets/stormkit/preset.d.ts +0 -2
  193. package/dist/presets/stormkit/preset.mjs +0 -15
  194. package/dist/presets/stormkit/runtime/stormkit.d.ts +0 -21
  195. package/dist/presets/stormkit/runtime/stormkit.mjs +0 -32
  196. package/dist/presets/vercel/preset.d.ts +0 -3
  197. package/dist/presets/vercel/preset.mjs +0 -104
  198. package/dist/presets/vercel/runtime/vercel-edge.d.ts +0 -2
  199. package/dist/presets/vercel/runtime/vercel-edge.mjs +0 -22
  200. package/dist/presets/vercel/runtime/vercel.d.ts +0 -4
  201. package/dist/presets/vercel/runtime/vercel.mjs +0 -17
  202. package/dist/presets/vercel/types.d.ts +0 -78
  203. package/dist/presets/vercel/types.mjs +0 -0
  204. package/dist/presets/vercel/utils.d.ts +0 -5
  205. package/dist/presets/vercel/utils.mjs +0 -186
  206. package/dist/presets/winterjs/preset.d.ts +0 -2
  207. package/dist/presets/winterjs/preset.mjs +0 -20
  208. package/dist/presets/winterjs/runtime/winterjs.d.ts +0 -1
  209. package/dist/presets/winterjs/runtime/winterjs.mjs +0 -69
  210. package/dist/presets/zeabur/preset.d.ts +0 -2
  211. package/dist/presets/zeabur/preset.mjs +0 -70
  212. package/dist/presets/zeabur/runtime/zeabur.d.ts +0 -4
  213. package/dist/presets/zeabur/runtime/zeabur.mjs +0 -8
  214. package/dist/runtime/app.d.ts +0 -2
  215. package/dist/runtime/app.mjs +0 -1
  216. package/dist/runtime/cache.d.ts +0 -1
  217. package/dist/runtime/cache.mjs +0 -6
  218. package/dist/runtime/config.d.ts +0 -1
  219. package/dist/runtime/config.mjs +0 -1
  220. package/dist/runtime/context.d.ts +0 -1
  221. package/dist/runtime/context.mjs +0 -1
  222. package/dist/runtime/database.d.ts +0 -1
  223. package/dist/runtime/database.mjs +0 -1
  224. package/dist/runtime/error.d.ts +0 -1
  225. package/dist/runtime/error.mjs +0 -1
  226. package/dist/runtime/internal/app.d.ts +0 -3
  227. package/dist/runtime/internal/app.mjs +0 -152
  228. package/dist/runtime/internal/cache.d.ts +0 -8
  229. package/dist/runtime/internal/cache.mjs +0 -329
  230. package/dist/runtime/internal/client.d.ts +0 -1
  231. package/dist/runtime/internal/client.mjs +0 -4
  232. package/dist/runtime/internal/config.d.ts +0 -6
  233. package/dist/runtime/internal/config.mjs +0 -58
  234. package/dist/runtime/internal/context.d.ts +0 -12
  235. package/dist/runtime/internal/context.mjs +0 -17
  236. package/dist/runtime/internal/database.d.ts +0 -2
  237. package/dist/runtime/internal/database.mjs +0 -14
  238. package/dist/runtime/internal/debug.d.ts +0 -2
  239. package/dist/runtime/internal/debug.mjs +0 -5
  240. package/dist/runtime/internal/error.d.ts +0 -4
  241. package/dist/runtime/internal/error.mjs +0 -71
  242. package/dist/runtime/internal/index.d.ts +0 -6
  243. package/dist/runtime/internal/index.mjs +0 -16
  244. package/dist/runtime/internal/lib/http-graceful-shutdown.d.ts +0 -16
  245. package/dist/runtime/internal/lib/http-graceful-shutdown.mjs +0 -213
  246. package/dist/runtime/internal/meta.d.ts +0 -2
  247. package/dist/runtime/internal/meta.mjs +0 -3
  248. package/dist/runtime/internal/plugin.d.ts +0 -3
  249. package/dist/runtime/internal/plugin.mjs +0 -4
  250. package/dist/runtime/internal/renderer.d.ts +0 -2
  251. package/dist/runtime/internal/renderer.mjs +0 -38
  252. package/dist/runtime/internal/route-rules.d.ts +0 -14
  253. package/dist/runtime/internal/route-rules.mjs +0 -67
  254. package/dist/runtime/internal/routes/openapi.d.ts +0 -3
  255. package/dist/runtime/internal/routes/openapi.mjs +0 -85
  256. package/dist/runtime/internal/routes/scalar.d.ts +0 -2
  257. package/dist/runtime/internal/routes/scalar.mjs +0 -191
  258. package/dist/runtime/internal/routes/swagger.d.ts +0 -2
  259. package/dist/runtime/internal/routes/swagger.mjs +0 -39
  260. package/dist/runtime/internal/shutdown.d.ts +0 -10
  261. package/dist/runtime/internal/shutdown.mjs +0 -34
  262. package/dist/runtime/internal/static.d.ts +0 -2
  263. package/dist/runtime/internal/static.mjs +0 -89
  264. package/dist/runtime/internal/storage.d.ts +0 -2
  265. package/dist/runtime/internal/storage.mjs +0 -5
  266. package/dist/runtime/internal/task.d.ts +0 -17
  267. package/dist/runtime/internal/task.mjs +0 -73
  268. package/dist/runtime/internal/timing.d.ts +0 -2
  269. package/dist/runtime/internal/timing.mjs +0 -29
  270. package/dist/runtime/internal/utils.azure.d.ts +0 -2
  271. package/dist/runtime/internal/utils.azure.mjs +0 -51
  272. package/dist/runtime/internal/utils.d.ts +0 -23
  273. package/dist/runtime/internal/utils.env.d.ts +0 -7
  274. package/dist/runtime/internal/utils.env.mjs +0 -39
  275. package/dist/runtime/internal/utils.lambda.d.ts +0 -12
  276. package/dist/runtime/internal/utils.lambda.mjs +0 -30
  277. package/dist/runtime/internal/utils.mjs +0 -129
  278. package/dist/runtime/plugin.d.ts +0 -1
  279. package/dist/runtime/plugin.mjs +0 -1
  280. package/dist/runtime/storage.d.ts +0 -1
  281. package/dist/runtime/storage.mjs +0 -1
  282. package/dist/runtime/task.d.ts +0 -1
  283. package/dist/runtime/task.mjs +0 -1
  284. package/dist/runtime/utils.d.ts +0 -1
  285. package/dist/runtime/utils.mjs +0 -1
  286. package/dist/shared/nitro.DkCt8MDS.d.mts +0 -588
  287. package/dist/shared/nitro.DkCt8MDS.d.ts +0 -588
@@ -1,2033 +1 @@
1
- import { pathToFileURL } from 'node:url';
2
- import { builtinModules, createRequire } from 'node:module';
3
- import { resolve, dirname, normalize, isAbsolute, join, relative, extname } from 'pathe';
4
- import { defu } from 'defu';
5
- import commonjs from '@rollup/plugin-commonjs';
6
- import alias from '@rollup/plugin-alias';
7
- import json from '@rollup/plugin-json';
8
- import inject from '@rollup/plugin-inject';
9
- import { nodeResolve } from '@rollup/plugin-node-resolve';
10
- import { isWindows } from 'std-env';
11
- import { visualizer } from 'rollup-plugin-visualizer';
12
- import * as unenv from 'unenv';
13
- import { isValidNodeImport, normalizeid, parseNodeModulePath as parseNodeModulePath$1, lookupNodeModuleSubpath, resolvePath, sanitizeFilePath } from 'mlly';
14
- import unimportPlugin from 'unimport/unplugin';
15
- import { hash } from 'ohash';
16
- import { rollup } from 'unwasm/plugin';
17
- import _replace from '@rollup/plugin-replace';
18
- import { globby } from 'globby';
19
- import { genSafeVariableName, genImport } from 'knitwork';
20
- import { existsSync, promises } from 'node:fs';
21
- import { platform } from 'node:os';
22
- import { readPackageJSON, writePackageJSON } from 'pkg-types';
23
- import { nodeFileTrace } from '@vercel/nft';
24
- import semver from 'semver';
25
- import { isDirectory } from 'nitropack/kit';
26
- import { consola } from 'consola';
27
- import { withTrailingSlash } from 'ufo';
28
- import createEtag from 'etag';
29
- import mime from 'mime';
30
- import { normalizeKey, builtinDrivers } from 'unstorage';
31
- import { runtimeDir, runtimeDependencies } from 'nitropack/runtime/meta';
32
- import { readFile } from 'node:fs/promises';
33
- import { transform } from 'esbuild';
34
- import { createFilter } from '@rollup/pluginutils';
35
- import { connectors } from 'db0';
36
- import { camelCase } from 'scule';
37
-
38
- function resolveAliases(_aliases) {
39
- const aliases = Object.fromEntries(
40
- Object.entries(_aliases).sort(
41
- ([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length
42
- )
43
- );
44
- for (const key in aliases) {
45
- for (const alias in aliases) {
46
- if (!["~", "@", "#"].includes(alias[0])) {
47
- continue;
48
- }
49
- if (alias === "@" && !aliases[key].startsWith("@/")) {
50
- continue;
51
- }
52
- if (aliases[key].startsWith(alias)) {
53
- aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
54
- }
55
- }
56
- }
57
- return aliases;
58
- }
59
-
60
- const NO_REPLACE_RE = /ROLLUP_NO_REPLACE/;
61
- function replace(options) {
62
- const _plugin = _replace(options);
63
- return {
64
- ..._plugin,
65
- // https://github.com/rollup/plugins/blob/master/packages/replace/src/index.js#L94
66
- renderChunk(code, chunk, options2) {
67
- if (!NO_REPLACE_RE.test(code)) {
68
- return _plugin.renderChunk.call(this, code, chunk, options2);
69
- }
70
- }
71
- };
72
- }
73
-
74
- const PREFIX = "\0virtual:";
75
- function virtual(modules, cache = {}) {
76
- const _modules = /* @__PURE__ */ new Map();
77
- for (const [id, mod] of Object.entries(modules)) {
78
- cache[id] = mod;
79
- _modules.set(id, mod);
80
- _modules.set(resolve(id), mod);
81
- }
82
- return {
83
- name: "virtual",
84
- resolveId(id, importer) {
85
- if (id in modules) {
86
- return PREFIX + id;
87
- }
88
- if (importer) {
89
- const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
90
- const resolved = resolve(dirname(importerNoPrefix), id);
91
- if (_modules.has(resolved)) {
92
- return PREFIX + resolved;
93
- }
94
- }
95
- return null;
96
- },
97
- async load(id) {
98
- if (!id.startsWith(PREFIX)) {
99
- return null;
100
- }
101
- const idNoPrefix = id.slice(PREFIX.length);
102
- if (!_modules.has(idNoPrefix)) {
103
- return null;
104
- }
105
- let m = _modules.get(idNoPrefix);
106
- if (typeof m === "function") {
107
- m = await m();
108
- }
109
- if (!m) {
110
- return null;
111
- }
112
- cache[id.replace(PREFIX, "")] = m;
113
- return {
114
- code: m,
115
- map: null
116
- };
117
- }
118
- };
119
- }
120
-
121
- const PLUGIN_NAME = "dynamic-require";
122
- const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.mjs`;
123
- const DYNAMIC_REQUIRE_RE = /import\("\.\/" ?\+(.*)\).then/g;
124
- function dynamicRequire({ dir, ignore, inline }) {
125
- return {
126
- name: PLUGIN_NAME,
127
- transform(code, _id) {
128
- return {
129
- code: code.replace(
130
- DYNAMIC_REQUIRE_RE,
131
- `import('${HELPER_DYNAMIC}').then(r => r.default || r).then(dynamicRequire => dynamicRequire($1)).then`
132
- ),
133
- map: null
134
- };
135
- },
136
- resolveId(id) {
137
- return id === HELPER_DYNAMIC ? id : null;
138
- },
139
- // TODO: Async chunk loading over network!
140
- // renderDynamicImport () {
141
- // return {
142
- // left: 'fetch(', right: ')'
143
- // }
144
- // },
145
- async load(_id) {
146
- if (_id !== HELPER_DYNAMIC) {
147
- return null;
148
- }
149
- let files = [];
150
- try {
151
- const wpManifest = resolve(dir, "./server.manifest.json");
152
- files = await import(pathToFileURL(wpManifest).href).then(
153
- (r) => Object.keys(r.files).filter((file) => !ignore.includes(file))
154
- );
155
- } catch {
156
- files = await globby("**/*.{cjs,mjs,js}", {
157
- cwd: dir,
158
- absolute: false,
159
- ignore
160
- });
161
- }
162
- const chunks = (await Promise.all(
163
- files.map(async (id) => ({
164
- id,
165
- src: resolve(dir, id).replace(/\\/g, "/"),
166
- name: genSafeVariableName(id),
167
- meta: await getWebpackChunkMeta(resolve(dir, id))
168
- }))
169
- )).filter((chunk) => chunk.meta);
170
- return inline ? TMPL_INLINE({ chunks }) : TMPL_LAZY({ chunks });
171
- }
172
- };
173
- }
174
- async function getWebpackChunkMeta(src) {
175
- const chunk = await import(pathToFileURL(src).href).then(
176
- (r) => r.default || r || {}
177
- );
178
- const { id, ids, modules } = chunk;
179
- if (!id && !ids) {
180
- return null;
181
- }
182
- return {
183
- id,
184
- ids,
185
- moduleIds: Object.keys(modules || {})
186
- };
187
- }
188
- function TMPL_INLINE({ chunks }) {
189
- return `${chunks.map((i) => `import * as ${i.name} from '${i.src}'`).join("\n")}
190
- const dynamicChunks = {
191
- ${chunks.map((i) => ` ['${i.id}']: ${i.name}`).join(",\n")}
192
- };
193
-
194
- export default function dynamicRequire(id) {
195
- return Promise.resolve(dynamicChunks[id]);
196
- };`;
197
- }
198
- function TMPL_LAZY({ chunks }) {
199
- return `
200
- const dynamicChunks = {
201
- ${chunks.map((i) => ` ['${i.id}']: () => import('${i.src}')`).join(",\n")}
202
- };
203
-
204
- export default function dynamicRequire(id) {
205
- return dynamicChunks[id]();
206
- };`;
207
- }
208
-
209
- function externals$1(opts) {
210
- const trackedExternals = /* @__PURE__ */ new Set();
211
- const _resolveCache = /* @__PURE__ */ new Map();
212
- const _resolve = async (id) => {
213
- if (id.startsWith("\0")) {
214
- return id;
215
- }
216
- let resolved = _resolveCache.get(id);
217
- if (resolved) {
218
- return resolved;
219
- }
220
- resolved = await resolvePath(id, {
221
- conditions: opts.exportConditions,
222
- url: opts.moduleDirectories
223
- });
224
- _resolveCache.set(id, resolved);
225
- return resolved;
226
- };
227
- const inlineMatchers = (opts.inline || []).map((p) => normalizeMatcher(p)).sort((a, b) => (b.score || 0) - (a.score || 0));
228
- const externalMatchers = (opts.external || []).map((p) => normalizeMatcher(p)).sort((a, b) => (b.score || 0) - (a.score || 0));
229
- const isExplicitInline = (id, importer) => {
230
- if (id.startsWith("\0")) {
231
- return true;
232
- }
233
- const inlineMatch = inlineMatchers.find((m) => m(id, importer));
234
- const externalMatch = externalMatchers.find((m) => m(id, importer));
235
- if (inlineMatch && (!externalMatch || externalMatch && (inlineMatch.score || 0) > (externalMatch.score || 0))) {
236
- return true;
237
- }
238
- };
239
- return {
240
- name: "node-externals",
241
- async resolveId(originalId, importer, options) {
242
- if (!originalId || originalId.startsWith("\0") || originalId.includes("?") || originalId.startsWith("#")) {
243
- return null;
244
- }
245
- if (originalId.startsWith(".")) {
246
- return null;
247
- }
248
- const id = normalize(originalId);
249
- if (isExplicitInline(id, importer)) {
250
- return null;
251
- }
252
- const resolved = await this.resolve(originalId, importer, options) || {
253
- id
254
- };
255
- if (isExplicitInline(resolved.id, importer)) {
256
- return null;
257
- }
258
- if (!isAbsolute(resolved.id) || !existsSync(resolved.id) || await isDirectory(resolved.id)) {
259
- resolved.id = await _resolve(resolved.id).catch(() => resolved.id);
260
- }
261
- if (!await isValidNodeImport(resolved.id).catch(() => false)) {
262
- return null;
263
- }
264
- if (opts.trace === false) {
265
- return {
266
- ...resolved,
267
- id: isAbsolute(resolved.id) ? normalizeid(resolved.id) : resolved.id,
268
- external: true
269
- };
270
- }
271
- const { name: pkgName } = parseNodeModulePath$1(resolved.id);
272
- if (!pkgName) {
273
- return null;
274
- }
275
- if (pkgName !== originalId) {
276
- if (!isAbsolute(originalId)) {
277
- const fullPath = await _resolve(originalId);
278
- trackedExternals.add(fullPath);
279
- return {
280
- id: originalId,
281
- external: true
282
- };
283
- }
284
- const packageEntry = await _resolve(pkgName).catch(() => null);
285
- if (packageEntry !== id) {
286
- const guessedSubpath = await lookupNodeModuleSubpath(id).catch(() => null);
287
- const resolvedGuess = guessedSubpath && await _resolve(join(pkgName, guessedSubpath)).catch(() => null);
288
- if (resolvedGuess === id) {
289
- trackedExternals.add(resolvedGuess);
290
- return {
291
- id: join(pkgName, guessedSubpath),
292
- external: true
293
- };
294
- }
295
- return null;
296
- }
297
- }
298
- trackedExternals.add(resolved.id);
299
- return {
300
- id: pkgName,
301
- external: true
302
- };
303
- },
304
- async buildEnd() {
305
- if (opts.trace === false) {
306
- return;
307
- }
308
- for (const pkgName of opts.traceInclude || []) {
309
- const path = await this.resolve(pkgName);
310
- if (path?.id) {
311
- trackedExternals.add(path.id.replace(/\?.+/, ""));
312
- }
313
- }
314
- const _fileTrace = await nodeFileTrace([...trackedExternals], {
315
- // https://github.com/unjs/nitro/pull/1562
316
- conditions: (opts.exportConditions || []).filter(
317
- (c) => !["require", "import", "default"].includes(c)
318
- ),
319
- ...opts.traceOptions
320
- });
321
- const _resolveTracedPath = (p) => promises.realpath(resolve(opts.traceOptions?.base || ".", p));
322
- const tracedFiles = Object.fromEntries(
323
- await Promise.all(
324
- [..._fileTrace.reasons.entries()].map(async ([_path, reasons]) => {
325
- if (reasons.ignored) {
326
- return;
327
- }
328
- const path = await _resolveTracedPath(_path);
329
- if (!path.includes("node_modules")) {
330
- return;
331
- }
332
- if (!await isFile$1(path)) {
333
- return;
334
- }
335
- const {
336
- dir: baseDir,
337
- name: pkgName,
338
- subpath
339
- } = parseNodeModulePath$1(path);
340
- if (!baseDir || !pkgName) {
341
- return;
342
- }
343
- const pkgPath = join(baseDir, pkgName);
344
- const parents = await Promise.all(
345
- [...reasons.parents].map((p) => _resolveTracedPath(p))
346
- );
347
- const tracedFile = {
348
- path,
349
- parents,
350
- subpath,
351
- pkgName,
352
- pkgPath
353
- };
354
- return [path, tracedFile];
355
- })
356
- ).then((r) => r.filter(Boolean))
357
- );
358
- const tracedPackages = {};
359
- for (const tracedFile of Object.values(tracedFiles)) {
360
- const pkgName = tracedFile.pkgName;
361
- let tracedPackage = tracedPackages[pkgName];
362
- let pkgJSON = await readPackageJSON(tracedFile.pkgPath, {
363
- cache: true
364
- }).catch(
365
- () => {
366
- }
367
- // TODO: Only catch ENOENT
368
- );
369
- if (!pkgJSON) {
370
- pkgJSON = { name: pkgName, version: "0.0.0" };
371
- }
372
- if (!tracedPackage) {
373
- tracedPackage = {
374
- name: pkgName,
375
- versions: {}
376
- };
377
- tracedPackages[pkgName] = tracedPackage;
378
- }
379
- let tracedPackageVersion = tracedPackage.versions[pkgJSON.version || "0.0.0"];
380
- if (!tracedPackageVersion) {
381
- tracedPackageVersion = {
382
- path: tracedFile.pkgPath,
383
- files: [],
384
- pkgJSON
385
- };
386
- tracedPackage.versions[pkgJSON.version || "0.0.0"] = tracedPackageVersion;
387
- }
388
- tracedPackageVersion.files.push(tracedFile.path);
389
- tracedFile.pkgName = pkgName;
390
- if (pkgJSON.version) {
391
- tracedFile.pkgVersion = pkgJSON.version;
392
- }
393
- }
394
- const usedAliases = {};
395
- const writePackage = async (name, version, _pkgPath) => {
396
- const pkg = tracedPackages[name];
397
- const pkgPath = _pkgPath || pkg.name;
398
- for (const src of pkg.versions[version].files) {
399
- const { subpath } = parseNodeModulePath$1(src);
400
- if (!subpath) {
401
- continue;
402
- }
403
- const dst = join(opts.outDir, "node_modules", pkgPath, subpath);
404
- await promises.mkdir(dirname(dst), { recursive: true });
405
- await promises.copyFile(src, dst);
406
- }
407
- const pkgJSON = pkg.versions[version].pkgJSON;
408
- applyProductionCondition(pkgJSON.exports);
409
- const pkgJSONPath = join(
410
- opts.outDir,
411
- "node_modules",
412
- pkgPath,
413
- "package.json"
414
- );
415
- await promises.mkdir(dirname(pkgJSONPath), { recursive: true });
416
- await promises.writeFile(
417
- pkgJSONPath,
418
- JSON.stringify(pkgJSON, null, 2),
419
- "utf8"
420
- );
421
- if (opts.traceAlias && pkgPath in opts.traceAlias) {
422
- usedAliases[opts.traceAlias[pkgPath]] = version;
423
- await linkPackage(pkgPath, opts.traceAlias[pkgPath]);
424
- }
425
- };
426
- const isWindows = platform() === "win32";
427
- const linkPackage = async (from, to) => {
428
- const src = join(opts.outDir, "node_modules", from);
429
- const dst = join(opts.outDir, "node_modules", to);
430
- const dstStat = await promises.lstat(dst).catch(() => null);
431
- const exists = dstStat && dstStat.isSymbolicLink();
432
- if (exists) {
433
- return;
434
- }
435
- await promises.mkdir(dirname(dst), { recursive: true });
436
- await promises.symlink(
437
- relative(dirname(dst), src),
438
- dst,
439
- isWindows ? "junction" : "dir"
440
- ).catch((error) => {
441
- console.error("Cannot link", from, "to", to, error);
442
- });
443
- };
444
- const findPackageParents = (pkg, version) => {
445
- const versionFiles = pkg.versions[version].files.map(
446
- (path) => tracedFiles[path]
447
- );
448
- const parentPkgs = [
449
- ...new Set(
450
- versionFiles.flatMap(
451
- (file) => file.parents.map((parentPath) => {
452
- const parentFile = tracedFiles[parentPath];
453
- if (parentFile.pkgName === pkg.name) {
454
- return null;
455
- }
456
- return `${parentFile.pkgName}@${parentFile.pkgVersion}`;
457
- }).filter(Boolean)
458
- )
459
- )
460
- ];
461
- return parentPkgs;
462
- };
463
- const multiVersionPkgs = {};
464
- const singleVersionPackages = [];
465
- for (const tracedPackage of Object.values(tracedPackages)) {
466
- const versions = Object.keys(tracedPackage.versions);
467
- if (versions.length === 1) {
468
- singleVersionPackages.push(tracedPackage.name);
469
- continue;
470
- }
471
- multiVersionPkgs[tracedPackage.name] = {};
472
- for (const version of versions) {
473
- multiVersionPkgs[tracedPackage.name][version] = findPackageParents(
474
- tracedPackage,
475
- version
476
- );
477
- }
478
- }
479
- await Promise.all(
480
- singleVersionPackages.map((pkgName) => {
481
- const pkg = tracedPackages[pkgName];
482
- const version = Object.keys(pkg.versions)[0];
483
- return writePackage(pkgName, version);
484
- })
485
- );
486
- for (const [pkgName, pkgVersions] of Object.entries(multiVersionPkgs)) {
487
- const versionEntries = Object.entries(pkgVersions).sort(
488
- ([v1, p1], [v2, p2]) => {
489
- if (p1.length === 0) {
490
- return -1;
491
- }
492
- if (p2.length === 0) {
493
- return 1;
494
- }
495
- return compareVersions(v1, v2);
496
- }
497
- );
498
- for (const [version, parentPkgs] of versionEntries) {
499
- await writePackage(pkgName, version, `.nitro/${pkgName}@${version}`);
500
- await linkPackage(`.nitro/${pkgName}@${version}`, `${pkgName}`);
501
- for (const parentPkg of parentPkgs) {
502
- const parentPkgName = parentPkg.replace(/@[^@]+$/, "");
503
- await (multiVersionPkgs[parentPkgName] ? linkPackage(
504
- `.nitro/${pkgName}@${version}`,
505
- `.nitro/${parentPkg}/node_modules/${pkgName}`
506
- ) : linkPackage(
507
- `.nitro/${pkgName}@${version}`,
508
- `${parentPkgName}/node_modules/${pkgName}`
509
- ));
510
- }
511
- }
512
- }
513
- const userPkg = await readPackageJSON(
514
- opts.rootDir || process.cwd()
515
- ).catch(() => ({}));
516
- await writePackageJSON(resolve(opts.outDir, "package.json"), {
517
- name: (userPkg.name || "server") + "-prod",
518
- version: userPkg.version || "0.0.0",
519
- type: "module",
520
- private: true,
521
- dependencies: Object.fromEntries(
522
- [
523
- ...Object.values(tracedPackages).map((pkg) => [
524
- pkg.name,
525
- Object.keys(pkg.versions)[0]
526
- ]),
527
- ...Object.entries(usedAliases)
528
- ].sort(([a], [b]) => a.localeCompare(b))
529
- )
530
- });
531
- }
532
- };
533
- }
534
- function compareVersions(v1 = "0.0.0", v2 = "0.0.0") {
535
- try {
536
- return semver.lt(v1, v2, { loose: true }) ? 1 : -1;
537
- } catch {
538
- return v1.localeCompare(v2);
539
- }
540
- }
541
- function applyProductionCondition(exports) {
542
- if (!exports || typeof exports === "string") {
543
- return;
544
- }
545
- if (exports.production) {
546
- if (typeof exports.production === "string") {
547
- exports.default = exports.production;
548
- } else {
549
- Object.assign(exports, exports.production);
550
- }
551
- }
552
- for (const key in exports) {
553
- applyProductionCondition(exports[key]);
554
- }
555
- }
556
- async function isFile$1(file) {
557
- try {
558
- const stat = await promises.stat(file);
559
- return stat.isFile();
560
- } catch (error) {
561
- if (error?.code === "ENOENT") {
562
- return false;
563
- }
564
- throw error;
565
- }
566
- }
567
- function normalizeMatcher(input) {
568
- if (typeof input === "function") {
569
- input.score = input.score ?? 1e4;
570
- return input;
571
- }
572
- if (input instanceof RegExp) {
573
- const matcher = (id) => input.test(id);
574
- matcher.score = input.toString().length;
575
- Object.defineProperty(matcher, "name", { value: `match(${input})` });
576
- return matcher;
577
- }
578
- if (typeof input === "string") {
579
- const pattern = normalize(input);
580
- const matcher = (id) => {
581
- const idWithoutNodeModules = id.split("node_modules/").pop();
582
- return id.startsWith(pattern) || idWithoutNodeModules?.startsWith(pattern);
583
- };
584
- matcher.score = input.length;
585
- if (!isAbsolute(input) && input[0] !== ".") {
586
- matcher.score += 1e3;
587
- }
588
- Object.defineProperty(matcher, "name", { value: `match(${pattern})` });
589
- return matcher;
590
- }
591
- throw new Error(`Invalid matcher or pattern: ${input}`);
592
- }
593
-
594
- function externals(opts) {
595
- const trackedExternals = /* @__PURE__ */ new Set();
596
- const _resolveCache = /* @__PURE__ */ new Map();
597
- const _resolve = async (id) => {
598
- let resolved = _resolveCache.get(id);
599
- if (resolved) {
600
- return resolved;
601
- }
602
- resolved = await resolvePath(id, {
603
- conditions: opts.exportConditions,
604
- url: opts.moduleDirectories
605
- });
606
- _resolveCache.set(id, resolved);
607
- return resolved;
608
- };
609
- const inlineMatchers = (opts.inline || []).map((p) => normalizeMatcher(p));
610
- const externalMatchers = (opts.external || []).map(
611
- (p) => normalizeMatcher(p)
612
- );
613
- return {
614
- name: "node-externals",
615
- async resolveId(originalId, importer, options) {
616
- if (!originalId || originalId.startsWith("\0") || originalId.includes("?") || originalId.startsWith("#")) {
617
- return null;
618
- }
619
- if (originalId.startsWith(".")) {
620
- return null;
621
- }
622
- const id = normalize(originalId);
623
- for (const matcher of inlineMatchers) {
624
- if (matcher(id, importer)) {
625
- return null;
626
- }
627
- }
628
- for (const matcher of externalMatchers) {
629
- if (matcher(id, importer)) {
630
- return { id, external: true };
631
- }
632
- }
633
- const resolved = await this.resolve(originalId, importer, options) || {
634
- id
635
- };
636
- if (!isAbsolute(resolved.id) || !existsSync(resolved.id) || await isDirectory(resolved.id)) {
637
- resolved.id = await _resolve(resolved.id).catch(() => resolved.id);
638
- }
639
- if (!await isValidNodeImport(resolved.id).catch(() => false)) {
640
- return null;
641
- }
642
- if (opts.trace === false) {
643
- return {
644
- ...resolved,
645
- id: isAbsolute(resolved.id) ? normalizeid(resolved.id) : resolved.id,
646
- external: true
647
- };
648
- }
649
- const { pkgName, subpath } = parseNodeModulePath(resolved.id);
650
- if (!pkgName) {
651
- return null;
652
- }
653
- if (pkgName !== originalId) {
654
- if (!isAbsolute(originalId)) {
655
- const fullPath = await _resolve(originalId);
656
- trackedExternals.add(fullPath);
657
- return {
658
- id: originalId,
659
- external: true
660
- };
661
- }
662
- const packageEntry = await _resolve(pkgName).catch(() => null);
663
- if (packageEntry !== originalId) {
664
- const guessedSubpath = pkgName + subpath.replace(/\.[a-z]+$/, "");
665
- const resolvedGuess = await _resolve(guessedSubpath).catch(
666
- () => null
667
- );
668
- if (resolvedGuess === originalId) {
669
- trackedExternals.add(resolvedGuess);
670
- return {
671
- id: guessedSubpath,
672
- external: true
673
- };
674
- }
675
- return null;
676
- }
677
- }
678
- trackedExternals.add(resolved.id);
679
- return {
680
- id: pkgName,
681
- external: true
682
- };
683
- },
684
- async buildEnd() {
685
- if (opts.trace === false) {
686
- return;
687
- }
688
- for (const pkgName of opts.traceInclude || []) {
689
- const path = await this.resolve(pkgName);
690
- if (path?.id) {
691
- trackedExternals.add(path.id.replace(/\?.+/, ""));
692
- }
693
- }
694
- let tracedFiles = await nodeFileTrace(
695
- [...trackedExternals],
696
- opts.traceOptions
697
- ).then(
698
- (r) => [...r.fileList].map((f) => resolve(opts.traceOptions.base, f))
699
- ).then((r) => r.filter((file) => file.includes("node_modules")));
700
- tracedFiles = await Promise.all(
701
- tracedFiles.map((file) => promises.realpath(file))
702
- );
703
- const packageJSONCache = /* @__PURE__ */ new Map();
704
- const getPackageJson = async (pkgDir) => {
705
- if (packageJSONCache.has(pkgDir)) {
706
- return packageJSONCache.get(pkgDir);
707
- }
708
- const pkgJSON = JSON.parse(
709
- await promises.readFile(resolve(pkgDir, "package.json"), "utf8")
710
- );
711
- packageJSONCache.set(pkgDir, pkgJSON);
712
- return pkgJSON;
713
- };
714
- const tracedPackages = /* @__PURE__ */ new Map();
715
- const ignoreDirs = [];
716
- const ignoreWarns = /* @__PURE__ */ new Set();
717
- for (const file of tracedFiles) {
718
- const { baseDir, pkgName } = parseNodeModulePath(file);
719
- if (!pkgName) {
720
- continue;
721
- }
722
- let pkgDir = resolve(baseDir, pkgName);
723
- const existingPkgDir = tracedPackages.get(pkgName);
724
- if (existingPkgDir && existingPkgDir !== pkgDir) {
725
- const v1 = await getPackageJson(existingPkgDir).then(
726
- (r) => r.version
727
- );
728
- const v2 = await getPackageJson(pkgDir).then((r) => r.version);
729
- const isNewer = semver.gt(v2, v1);
730
- const getMajor = (v) => v.split(".").find((s) => s !== "0");
731
- if (getMajor(v1) !== getMajor(v2)) {
732
- const warn = `Multiple major versions of package \`${pkgName}\` are being externalized. Picking latest version:
733
-
734
- ` + [
735
- ` ${isNewer ? "-" : "+"} ` + existingPkgDir + "@" + v1,
736
- ` ${isNewer ? "+" : "-"} ` + pkgDir + "@" + v2
737
- ].join("\n");
738
- if (!ignoreWarns.has(warn)) {
739
- consola.warn(warn);
740
- ignoreWarns.add(warn);
741
- }
742
- }
743
- const [newerDir, olderDir] = isNewer ? [pkgDir, existingPkgDir] : [existingPkgDir, pkgDir];
744
- if (getMajor(v1) === getMajor(v2)) {
745
- tracedFiles = tracedFiles.map(
746
- (f) => f.startsWith(olderDir + "/") ? f.replace(olderDir, newerDir) : f
747
- );
748
- }
749
- ignoreDirs.push(olderDir + "/");
750
- pkgDir = newerDir;
751
- }
752
- tracedPackages.set(pkgName, pkgDir);
753
- }
754
- tracedFiles = tracedFiles.filter(
755
- (f) => !ignoreDirs.some((d) => f.startsWith(d))
756
- );
757
- tracedFiles = [...new Set(tracedFiles)];
758
- for (const pkgDir of tracedPackages.values()) {
759
- const pkgJSON = join(pkgDir, "package.json");
760
- if (!tracedFiles.includes(pkgJSON)) {
761
- tracedFiles.push(pkgJSON);
762
- }
763
- }
764
- const writeFile = async (file) => {
765
- if (!await isFile(file)) {
766
- return;
767
- }
768
- const src = resolve(opts.traceOptions.base, file);
769
- const { pkgName, subpath } = parseNodeModulePath(file);
770
- const dst = resolve(opts.outDir, `node_modules/${pkgName + subpath}`);
771
- await promises.mkdir(dirname(dst), { recursive: true });
772
- try {
773
- await promises.copyFile(src, dst);
774
- } catch {
775
- consola.warn(`Could not resolve \`${src}\`. Skipping.`);
776
- }
777
- };
778
- await Promise.all(
779
- tracedFiles.map((file) => retry(() => writeFile(file), 3))
780
- );
781
- await promises.writeFile(
782
- resolve(opts.outDir, "package.json"),
783
- JSON.stringify(
784
- {
785
- name: "nitro-output",
786
- version: "0.0.0",
787
- private: true,
788
- bundledDependencies: [...tracedPackages.keys()].sort()
789
- },
790
- null,
791
- 2
792
- ),
793
- "utf8"
794
- );
795
- }
796
- };
797
- }
798
- function parseNodeModulePath(path) {
799
- if (!path) {
800
- return {};
801
- }
802
- const match = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/.exec(
803
- normalize(path)
804
- );
805
- if (!match) {
806
- return {};
807
- }
808
- const [, baseDir, pkgName, subpath] = match;
809
- return {
810
- baseDir,
811
- pkgName,
812
- subpath
813
- };
814
- }
815
- async function isFile(file) {
816
- try {
817
- const stat = await promises.stat(file);
818
- return stat.isFile();
819
- } catch (error) {
820
- if (error.code === "ENOENT") {
821
- return false;
822
- }
823
- throw error;
824
- }
825
- }
826
- async function retry(fn, retries) {
827
- let retry2 = 0;
828
- let lastError;
829
- while (retry2++ < retries) {
830
- try {
831
- return await fn();
832
- } catch (error) {
833
- lastError = error;
834
- await new Promise((resolve2) => setTimeout(resolve2, 2));
835
- }
836
- }
837
- throw lastError;
838
- }
839
-
840
- const TIMING = "globalThis.__timing__";
841
- const iife = (code) => `(function() { ${code.trim()} })();`.replace(/\n/g, "");
842
- const HELPER = iife(`
843
- const start = () => Date.now();
844
- const end = s => Date.now() - s;
845
- const _s = {};
846
- const metrics = [];
847
- const logStart = id => { _s[id] = Date.now(); };
848
- const logEnd = id => { const t = end(_s[id]); delete _s[id]; metrics.push([id, t]); if (t > 0) { console.debug('>', id + ' (' + t + 'ms)'); } };
849
- ${TIMING} = { start, end, metrics, logStart, logEnd };
850
- `);
851
- const HELPERIMPORT = "import './timing.js';";
852
- function timing(_opts = {}) {
853
- return {
854
- name: "timing",
855
- generateBundle() {
856
- this.emitFile({
857
- type: "asset",
858
- fileName: "timing.js",
859
- source: HELPER
860
- });
861
- },
862
- renderChunk(code, chunk) {
863
- let name = chunk.fileName || "";
864
- name = name.replace(extname(name), "");
865
- const logName = name === "index" ? "Nitro Start" : "Load " + name;
866
- return {
867
- code: (chunk.isEntry ? HELPERIMPORT : "") + `${TIMING}.logStart('${logName}');` + code + `;${TIMING}.logEnd('${logName}');`,
868
- map: null
869
- };
870
- }
871
- };
872
- }
873
-
874
- const readAssetHandler = {
875
- true: "node",
876
- node: "node",
877
- false: "null",
878
- deno: "deno",
879
- inline: "inline"
880
- };
881
- function publicAssets(nitro) {
882
- return virtual(
883
- {
884
- // #nitro-internal-virtual/public-assets-data
885
- "#nitro-internal-virtual/public-assets-data": async () => {
886
- const assets = {};
887
- const files = await globby("**", {
888
- cwd: nitro.options.output.publicDir,
889
- absolute: false,
890
- dot: true
891
- });
892
- for (const id of files) {
893
- let mimeType = mime.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
894
- if (mimeType.startsWith("text")) {
895
- mimeType += "; charset=utf-8";
896
- }
897
- const fullPath = resolve(nitro.options.output.publicDir, id);
898
- const assetData = await promises.readFile(fullPath);
899
- const etag = createEtag(assetData);
900
- const stat = await promises.stat(fullPath);
901
- const assetId = "/" + decodeURIComponent(id);
902
- let encoding;
903
- if (id.endsWith(".gz")) {
904
- encoding = "gzip";
905
- } else if (id.endsWith(".br")) {
906
- encoding = "br";
907
- }
908
- assets[assetId] = {
909
- type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType,
910
- encoding,
911
- etag,
912
- mtime: stat.mtime.toJSON(),
913
- size: stat.size,
914
- path: relative(nitro.options.output.serverDir, fullPath),
915
- data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
916
- };
917
- }
918
- return `export default ${JSON.stringify(assets, null, 2)};`;
919
- },
920
- // #nitro-internal-virtual/public-assets-node
921
- "#nitro-internal-virtual/public-assets-node": () => {
922
- return `
923
- import { promises as fsp } from 'node:fs'
924
- import { fileURLToPath } from 'node:url'
925
- import { resolve, dirname } from 'pathe'
926
- import assets from '#nitro-internal-virtual/public-assets-data'
927
- export function readAsset (id) {
928
- const serverDir = dirname(fileURLToPath(import.meta.url))
929
- return fsp.readFile(resolve(serverDir, assets[id].path))
930
- }`;
931
- },
932
- // #nitro-internal-virtual/public-assets-deno
933
- "#nitro-internal-virtual/public-assets-deno": () => {
934
- return `
935
- import assets from '#nitro-internal-virtual/public-assets-data'
936
- export function readAsset (id) {
937
- // https://deno.com/deploy/docs/serve-static-assets
938
- const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
939
- return Deno.readFile(path);
940
- }`;
941
- },
942
- // #nitro-internal-virtual/public-assets-null
943
- "#nitro-internal-virtual/public-assets-null": () => {
944
- return `
945
- export function readAsset (id) {
946
- return Promise.resolve(null);
947
- }`;
948
- },
949
- // #nitro-internal-virtual/public-assets-inline
950
- "#nitro-internal-virtual/public-assets-inline": () => {
951
- return `
952
- import assets from '#nitro-internal-virtual/public-assets-data'
953
- export function readAsset (id) {
954
- if (!assets[id]) { return undefined }
955
- if (assets[id]._data) { return assets[id]._data }
956
- if (!assets[id].data) { return assets[id].data }
957
- assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
958
- return assets[id]._data
959
- }`;
960
- },
961
- // #nitro-internal-virtual/public-assets
962
- "#nitro-internal-virtual/public-assets": () => {
963
- const publicAssetBases = Object.fromEntries(
964
- nitro.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [
965
- withTrailingSlash(dir.baseURL),
966
- { maxAge: dir.maxAge }
967
- ])
968
- );
969
- const handlerName = readAssetHandler[nitro.options.serveStatic] || "null";
970
- const readAssetImport = `#nitro-internal-virtual/public-assets-${handlerName}`;
971
- return `
972
- import assets from '#nitro-internal-virtual/public-assets-data'
973
- export { readAsset } from "${readAssetImport}"
974
- export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
975
-
976
- export function isPublicAssetURL(id = '') {
977
- if (assets[id]) {
978
- return true
979
- }
980
- for (const base in publicAssetBases) {
981
- if (id.startsWith(base)) { return true }
982
- }
983
- return false
984
- }
985
-
986
- export function getPublicAssetMeta(id = '') {
987
- for (const base in publicAssetBases) {
988
- if (id.startsWith(base)) { return publicAssetBases[base] }
989
- }
990
- return {}
991
- }
992
-
993
- export function getAsset (id) {
994
- return assets[id]
995
- }
996
- `;
997
- }
998
- },
999
- nitro.vfs
1000
- );
1001
- }
1002
-
1003
- function serverAssets(nitro) {
1004
- if (nitro.options.dev || nitro.options.preset === "nitro-prerender") {
1005
- return virtual(
1006
- { "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) },
1007
- nitro.vfs
1008
- );
1009
- }
1010
- return virtual(
1011
- {
1012
- "#nitro-internal-virtual/server-assets": async () => {
1013
- const assets = {};
1014
- for (const asset of nitro.options.serverAssets) {
1015
- const files = await globby("**/*.*", {
1016
- cwd: asset.dir,
1017
- absolute: false,
1018
- ignore: asset.ignore
1019
- });
1020
- for (const _id of files) {
1021
- const fsPath = resolve(asset.dir, _id);
1022
- const id = asset.baseName + "/" + _id;
1023
- assets[id] = { fsPath, meta: {} };
1024
- let type = mime.getType(id) || "text/plain";
1025
- if (type.startsWith("text")) {
1026
- type += "; charset=utf-8";
1027
- }
1028
- const etag = createEtag(await promises.readFile(fsPath));
1029
- const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
1030
- assets[id].meta = { type, etag, mtime };
1031
- }
1032
- }
1033
- return getAssetProd(assets);
1034
- }
1035
- },
1036
- nitro.vfs
1037
- );
1038
- }
1039
- function getAssetsDev(nitro) {
1040
- return `
1041
- import { createStorage } from 'unstorage'
1042
- import fsDriver from 'unstorage/drivers/fs'
1043
-
1044
- const serverAssets = ${JSON.stringify(nitro.options.serverAssets)}
1045
-
1046
- export const assets = createStorage()
1047
-
1048
- for (const asset of serverAssets) {
1049
- assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
1050
- }`;
1051
- }
1052
- function getAssetProd(assets) {
1053
- return `
1054
- const _assets = {
1055
- ${Object.entries(assets).map(
1056
- ([id, asset]) => ` [${JSON.stringify(
1057
- normalizeKey(id)
1058
- )}]: {
1059
- import: () => import(${JSON.stringify(
1060
- "raw:" + asset.fsPath
1061
- )}).then(r => r.default || r),
1062
- meta: ${JSON.stringify(
1063
- asset.meta
1064
- )}
1065
- }`
1066
- ).join(",\n")}
1067
- }
1068
-
1069
- const normalizeKey = ${normalizeKey.toString()}
1070
-
1071
- export const assets = {
1072
- getKeys() {
1073
- return Promise.resolve(Object.keys(_assets))
1074
- },
1075
- hasItem (id) {
1076
- id = normalizeKey(id)
1077
- return Promise.resolve(id in _assets)
1078
- },
1079
- getItem (id) {
1080
- id = normalizeKey(id)
1081
- return Promise.resolve(_assets[id] ? _assets[id].import() : null)
1082
- },
1083
- getMeta (id) {
1084
- id = normalizeKey(id)
1085
- return Promise.resolve(_assets[id] ? _assets[id].meta : {})
1086
- }
1087
- }
1088
- `;
1089
- }
1090
-
1091
- function handlers(nitro) {
1092
- const getHandlers = () => {
1093
- const handlers2 = [
1094
- ...nitro.scannedHandlers,
1095
- ...nitro.options.handlers
1096
- ];
1097
- const envConditions = new Set(
1098
- [
1099
- nitro.options.dev ? "dev" : "prod",
1100
- nitro.options.preset,
1101
- nitro.options.preset === "nitro-prerender" ? "prerender" : void 0
1102
- ].filter(Boolean)
1103
- );
1104
- return handlers2.filter((h) => {
1105
- const envs = (Array.isArray(h.env) ? h.env : [h.env]).filter(
1106
- Boolean
1107
- );
1108
- return envs.length === 0 || envs.some((env) => envConditions.has(env));
1109
- });
1110
- };
1111
- return virtual(
1112
- {
1113
- "#nitro-internal-virtual/server-handlers": () => {
1114
- const handlers2 = getHandlers();
1115
- if (nitro.options.serveStatic) {
1116
- handlers2.unshift({
1117
- middleware: true,
1118
- handler: join(runtimeDir, "internal/static")
1119
- });
1120
- }
1121
- if (nitro.options.renderer) {
1122
- handlers2.push({
1123
- route: "/**",
1124
- lazy: true,
1125
- handler: nitro.options.renderer
1126
- });
1127
- }
1128
- extendMiddlewareWithRuleOverlaps(handlers2, nitro.options.routeRules);
1129
- const imports = unique(
1130
- handlers2.filter((h) => !h.lazy).map((h) => h.handler)
1131
- );
1132
- const lazyImports = unique(
1133
- handlers2.filter((h) => h.lazy).map((h) => h.handler)
1134
- );
1135
- const code = (
1136
- /* js */
1137
- `
1138
- ${imports.map((handler) => `import ${getImportId(handler)} from '${handler}';`).join("\n")}
1139
-
1140
- ${lazyImports.map(
1141
- (handler) => `const ${getImportId(handler, true)} = () => import('${handler}');`
1142
- ).join("\n")}
1143
-
1144
- export const handlers = [
1145
- ${handlers2.map(
1146
- (h) => ` { route: '${h.route || ""}', handler: ${getImportId(
1147
- h.handler,
1148
- h.lazy
1149
- )}, lazy: ${!!h.lazy}, middleware: ${!!h.middleware}, method: ${JSON.stringify(
1150
- h.method?.toLowerCase()
1151
- )} }`
1152
- ).join(",\n")}
1153
- ];
1154
- `.trim()
1155
- );
1156
- return code;
1157
- },
1158
- "#nitro-internal-virtual/server-handlers-meta": () => {
1159
- const handlers2 = getHandlers();
1160
- return (
1161
- /* js */
1162
- `
1163
- ${handlers2.map(
1164
- (h) => `import ${getImportId(h.handler)}Meta from "${h.handler}?meta";`
1165
- ).join("\n")}
1166
- export const handlersMeta = [
1167
- ${handlers2.map(
1168
- (h) => (
1169
- /* js */
1170
- `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(
1171
- h.method?.toLowerCase()
1172
- )}, meta: ${getImportId(h.handler)}Meta }`
1173
- )
1174
- ).join(",\n")}
1175
- ];
1176
- `
1177
- );
1178
- }
1179
- },
1180
- nitro.vfs
1181
- );
1182
- }
1183
- function unique(arr) {
1184
- return [...new Set(arr)];
1185
- }
1186
- function getImportId(p, lazy) {
1187
- return (lazy ? "_lazy_" : "_") + hash(p).slice(0, 6);
1188
- }
1189
- const WILDCARD_PATH_RE = /\/\*\*.*$/;
1190
- function extendMiddlewareWithRuleOverlaps(handlers2, routeRules) {
1191
- const rules = Object.entries(routeRules);
1192
- for (const [path, rule] of rules) {
1193
- if (!rule.cache) {
1194
- const isNested = rules.some(
1195
- ([p, r]) => r.cache && WILDCARD_PATH_RE.test(p) && path.startsWith(p.replace(WILDCARD_PATH_RE, ""))
1196
- );
1197
- if (!isNested) {
1198
- continue;
1199
- }
1200
- }
1201
- for (const [index, handler] of handlers2.entries()) {
1202
- if (!handler.route || handler.middleware) {
1203
- continue;
1204
- }
1205
- if (handler.route === path) {
1206
- break;
1207
- }
1208
- if (!WILDCARD_PATH_RE.test(handler.route)) {
1209
- continue;
1210
- }
1211
- if (!path.startsWith(handler.route.replace(WILDCARD_PATH_RE, ""))) {
1212
- continue;
1213
- }
1214
- handlers2.splice(index, 0, {
1215
- ...handler,
1216
- route: path
1217
- });
1218
- break;
1219
- }
1220
- }
1221
- }
1222
-
1223
- const virtualPrefix = "\0nitro-handler-meta:";
1224
- const esbuildLoaders = {
1225
- ".ts": "ts",
1226
- ".js": "js",
1227
- ".tsx": "tsx",
1228
- ".jsx": "jsx"
1229
- };
1230
- function handlersMeta(nitro) {
1231
- return {
1232
- name: "nitro:handlers-meta",
1233
- async resolveId(id) {
1234
- if (id.startsWith("\0")) {
1235
- return;
1236
- }
1237
- if (id.endsWith(`?meta`)) {
1238
- const resolved = await this.resolve(id.replace(`?meta`, ``));
1239
- if (!resolved) {
1240
- return;
1241
- }
1242
- return virtualPrefix + resolved.id;
1243
- }
1244
- },
1245
- load(id) {
1246
- if (id.startsWith(virtualPrefix)) {
1247
- const fullPath = id.slice(virtualPrefix.length);
1248
- return readFile(fullPath, { encoding: "utf8" });
1249
- }
1250
- },
1251
- async transform(code, id) {
1252
- if (!id.startsWith(virtualPrefix)) {
1253
- return;
1254
- }
1255
- let meta = null;
1256
- try {
1257
- const ext = extname(id);
1258
- const jsCode = await transform(code, {
1259
- loader: esbuildLoaders[ext]
1260
- }).then((r) => r.code);
1261
- const ast = this.parse(jsCode);
1262
- for (const node of ast.body) {
1263
- if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) {
1264
- meta = astToObject(node.expression.arguments[0]);
1265
- break;
1266
- }
1267
- }
1268
- } catch (error) {
1269
- console.warn(
1270
- `[nitro] [handlers-meta] Cannot extra route meta for: ${id}: ${error}`
1271
- );
1272
- }
1273
- return {
1274
- code: `export default ${JSON.stringify(meta)};`,
1275
- map: null
1276
- };
1277
- }
1278
- };
1279
- }
1280
- function astToObject(node) {
1281
- switch (node.type) {
1282
- case "ObjectExpression": {
1283
- const obj = {};
1284
- for (const prop of node.properties) {
1285
- if (prop.type === "Property") {
1286
- const key = prop.key.name;
1287
- obj[key] = astToObject(prop.value);
1288
- }
1289
- }
1290
- return obj;
1291
- }
1292
- case "ArrayExpression": {
1293
- return node.elements.map((el) => astToObject(el)).filter(Boolean);
1294
- }
1295
- case "Literal": {
1296
- return node.value;
1297
- }
1298
- }
1299
- }
1300
-
1301
- const defaultLoaders = {
1302
- ".ts": "ts",
1303
- ".js": "js",
1304
- ".tsx": "tsx",
1305
- ".jsx": "jsx"
1306
- };
1307
- function esbuild(options) {
1308
- const {
1309
- include,
1310
- exclude,
1311
- sourceMap,
1312
- loaders: loadersConfig,
1313
- minify,
1314
- ...transformOptions
1315
- } = options;
1316
- const loaders = { ...defaultLoaders };
1317
- if (loadersConfig) {
1318
- for (const key of Object.keys(loadersConfig)) {
1319
- const value = loadersConfig[key];
1320
- if (typeof value === "string") {
1321
- loaders[key] = value;
1322
- } else if (value === false) {
1323
- delete loaders[key];
1324
- }
1325
- }
1326
- }
1327
- const extensions = Object.keys(loaders);
1328
- const INCLUDE_REGEXP = new RegExp(
1329
- `\\.(${extensions.map((ext) => ext.slice(1)).join("|")})$`
1330
- );
1331
- const EXCLUDE_REGEXP = /node_modules/;
1332
- const filter = createFilter(
1333
- include || INCLUDE_REGEXP,
1334
- exclude || EXCLUDE_REGEXP
1335
- );
1336
- return {
1337
- name: "esbuild",
1338
- async transform(code, id) {
1339
- if (!filter(id)) {
1340
- return null;
1341
- }
1342
- const ext = extname(id);
1343
- const loader = loaders[ext];
1344
- if (!loader) {
1345
- return null;
1346
- }
1347
- const result = await transform(code, {
1348
- sourcemap: sourceMap === "hidden" ? "external" : sourceMap,
1349
- ...transformOptions,
1350
- loader,
1351
- sourcefile: id
1352
- });
1353
- printWarnings(id, result, this);
1354
- return result.code && {
1355
- code: result.code,
1356
- map: result.map || null
1357
- };
1358
- },
1359
- async renderChunk(code) {
1360
- if (minify) {
1361
- const result = await transform(code, {
1362
- loader: "js",
1363
- minify: true,
1364
- target: transformOptions.target
1365
- });
1366
- if (result.code) {
1367
- return {
1368
- code: result.code,
1369
- map: result.map || null
1370
- };
1371
- }
1372
- }
1373
- return null;
1374
- }
1375
- };
1376
- }
1377
- function printWarnings(id, result, plugin) {
1378
- if (result.warnings) {
1379
- for (const warning of result.warnings) {
1380
- let message = "[esbuild]";
1381
- if (warning.location) {
1382
- message += ` (${relative(process.cwd(), id)}:${warning.location.line}:${warning.location.column})`;
1383
- }
1384
- message += ` ${warning.text}`;
1385
- plugin.warn(message);
1386
- }
1387
- }
1388
- }
1389
-
1390
- const HELPER_ID = "\0raw-helpers";
1391
- function raw(opts = {}) {
1392
- const extensions = /* @__PURE__ */ new Set([
1393
- ".md",
1394
- ".mdx",
1395
- ".txt",
1396
- ".css",
1397
- ".htm",
1398
- ".html",
1399
- ...opts.extensions || []
1400
- ]);
1401
- return {
1402
- name: "raw",
1403
- async resolveId(id, importer) {
1404
- if (id === HELPER_ID) {
1405
- return id;
1406
- }
1407
- if (id[0] === "\0") {
1408
- return;
1409
- }
1410
- let isRawId = id.startsWith("raw:");
1411
- if (isRawId) {
1412
- id = id.slice(4);
1413
- } else if (extensions.has(extname(id))) {
1414
- isRawId = true;
1415
- }
1416
- if (!isRawId) {
1417
- return;
1418
- }
1419
- const resolvedId = (await this.resolve(id, importer, { skipSelf: true }))?.id;
1420
- if (!resolvedId || resolvedId.startsWith("\0")) {
1421
- return resolvedId;
1422
- }
1423
- return { id: "\0raw:" + resolvedId };
1424
- },
1425
- load(id) {
1426
- if (id === HELPER_ID) {
1427
- return getHelpers();
1428
- }
1429
- if (id.startsWith("\0raw:")) {
1430
- return promises.readFile(id.slice(5), isBinary(id) ? "binary" : "utf8");
1431
- }
1432
- },
1433
- transform(code, id) {
1434
- if (!id.startsWith("\0raw:")) {
1435
- return;
1436
- }
1437
- if (isBinary(id)) {
1438
- const serialized = Buffer.from(code, "binary").toString("base64");
1439
- return {
1440
- code: `// ROLLUP_NO_REPLACE
1441
- import {base64ToUint8Array } from "${HELPER_ID}"
1442
- export default base64ToUint8Array("${serialized}")`,
1443
- map: null
1444
- };
1445
- } else {
1446
- return {
1447
- code: `// ROLLUP_NO_REPLACE
1448
- export default ${JSON.stringify(
1449
- code
1450
- )}`,
1451
- map: null
1452
- };
1453
- }
1454
- }
1455
- };
1456
- }
1457
- function isBinary(id) {
1458
- const idMime = mime.getType(id) || "";
1459
- if (idMime.startsWith("text/")) {
1460
- return false;
1461
- }
1462
- if (/application\/(json|xml|yaml)/.test(idMime)) {
1463
- return false;
1464
- }
1465
- return true;
1466
- }
1467
- function getHelpers() {
1468
- const js = String.raw;
1469
- return js`
1470
- export function base64ToUint8Array(str) {
1471
- const data = atob(str);
1472
- const size = data.length;
1473
- const bytes = new Uint8Array(size);
1474
- for (let i = 0; i < size; i++) {
1475
- bytes[i] = data.charCodeAt(i);
1476
- }
1477
- return bytes;
1478
- }
1479
- `;
1480
- }
1481
-
1482
- function storage(nitro) {
1483
- const mounts = [];
1484
- const isDevOrPrerender = nitro.options.dev || nitro.options.preset === "nitro-prerender";
1485
- const storageMounts = isDevOrPrerender ? { ...nitro.options.storage, ...nitro.options.devStorage } : nitro.options.storage;
1486
- for (const path in storageMounts) {
1487
- const mount = storageMounts[path];
1488
- mounts.push({
1489
- path,
1490
- driver: builtinDrivers[mount.driver] || mount.driver,
1491
- opts: mount
1492
- });
1493
- }
1494
- const driverImports = [...new Set(mounts.map((m) => m.driver))];
1495
- const bundledStorageCode = `
1496
- import { prefixStorage } from 'unstorage'
1497
- import overlay from 'unstorage/drivers/overlay'
1498
- import memory from 'unstorage/drivers/memory'
1499
-
1500
- const bundledStorage = ${JSON.stringify(nitro.options.bundledStorage)}
1501
- for (const base of bundledStorage) {
1502
- storage.mount(base, overlay({
1503
- layers: [
1504
- memory(),
1505
- // TODO
1506
- // prefixStorage(storage, base),
1507
- prefixStorage(storage, 'assets:nitro:bundled:' + base)
1508
- ]
1509
- }))
1510
- }`;
1511
- return virtual(
1512
- {
1513
- "#nitro-internal-virtual/storage": `
1514
- import { createStorage } from 'unstorage'
1515
- import { assets } from '#nitro-internal-virtual/server-assets'
1516
-
1517
- ${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
1518
-
1519
- export const storage = createStorage({})
1520
-
1521
- storage.mount('/assets', assets)
1522
-
1523
- ${mounts.map(
1524
- (m) => `storage.mount('${m.path}', ${genSafeVariableName(
1525
- m.driver
1526
- )}(${JSON.stringify(m.opts)}))`
1527
- ).join("\n")}
1528
-
1529
- ${!isDevOrPrerender && nitro.options.bundledStorage.length > 0 ? bundledStorageCode : ""}
1530
- `
1531
- },
1532
- nitro.vfs
1533
- );
1534
- }
1535
-
1536
- function database(nitro) {
1537
- if (!nitro.options.experimental.database) {
1538
- return virtual(
1539
- {
1540
- "#nitro-internal-virtual/database": () => {
1541
- return (
1542
- /* js */
1543
- `export const connectionConfigs = {};`
1544
- );
1545
- }
1546
- },
1547
- nitro.vfs
1548
- );
1549
- }
1550
- const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database;
1551
- const connectorsNames = [
1552
- ...new Set(
1553
- Object.values(dbConfigs || {}).map((config) => config?.connector)
1554
- )
1555
- ].filter(Boolean);
1556
- for (const name of connectorsNames) {
1557
- if (!connectors[name]) {
1558
- throw new Error(`Database connector "${name}" is invalid.`);
1559
- }
1560
- }
1561
- return virtual(
1562
- {
1563
- "#nitro-internal-virtual/database": () => {
1564
- return `
1565
- ${connectorsNames.map(
1566
- (name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`
1567
- ).join("\n")}
1568
-
1569
- export const connectionConfigs = {
1570
- ${Object.entries(dbConfigs || {}).map(
1571
- ([name, { connector, options }]) => `${name}: {
1572
- connector: ${camelCase(connector)}Connector,
1573
- options: ${JSON.stringify(options)}
1574
- }`
1575
- ).join(",\n")}
1576
- };
1577
- `;
1578
- }
1579
- },
1580
- nitro.vfs
1581
- );
1582
- }
1583
-
1584
- const ImportMetaRe = /import\.meta|globalThis._importMeta_/;
1585
- function importMeta(nitro) {
1586
- return {
1587
- name: "import-meta",
1588
- renderChunk(code, chunk) {
1589
- const isEntry = chunk.isEntry;
1590
- if (!isEntry && (!ImportMetaRe.test(code) || code.includes("ROLLUP_NO_REPLACE"))) {
1591
- return;
1592
- }
1593
- const url = nitro.options.node && isEntry && !code.includes("ROLLUP_NO_REPLACE") ? "_import_meta_url_" : '"file:///_entry.js"';
1594
- const envImport = nitro.options.node ? "import process from 'node:process';" : "";
1595
- const env = nitro.options.node ? "process.env" : "{}";
1596
- const ref = "globalThis._importMeta_";
1597
- const stub = `{url:${url},env:${env}}`;
1598
- const stubInit = isEntry ? `${ref}=${stub};` : `${ref}=${ref}||${stub};`;
1599
- return {
1600
- code: envImport + stubInit + code,
1601
- map: null
1602
- };
1603
- }
1604
- };
1605
- }
1606
-
1607
- function appConfig(nitro) {
1608
- return virtual(
1609
- {
1610
- "#nitro-internal-virtual/app-config": () => `
1611
- import { defuFn } from 'defu';
1612
-
1613
- const inlineAppConfig = ${JSON.stringify(nitro.options.appConfig, null, 2)};
1614
-
1615
- ${nitro.options.appConfigFiles.map((file, i) => genImport(file, "appConfig" + i) + ";").join("\n")}
1616
-
1617
- export const appConfig = defuFn(${[
1618
- ...nitro.options.appConfigFiles.map((_, i) => "appConfig" + i),
1619
- "inlineAppConfig"
1620
- ].join(", ")});
1621
- `
1622
- },
1623
- nitro.vfs
1624
- );
1625
- }
1626
-
1627
- function sourcemapMininify() {
1628
- return {
1629
- name: "nitro:sourcemap-minify",
1630
- generateBundle(_options, bundle) {
1631
- for (const [key, asset] of Object.entries(bundle)) {
1632
- if (!key.endsWith(".map") || !("source" in asset) || typeof asset.source !== "string") {
1633
- continue;
1634
- }
1635
- const sourcemap = JSON.parse(asset.source);
1636
- if (!(sourcemap.sources || []).some((s) => s.includes("node_modules"))) {
1637
- continue;
1638
- }
1639
- sourcemap.mappings = "";
1640
- asset.source = JSON.stringify(sourcemap);
1641
- }
1642
- }
1643
- };
1644
- }
1645
-
1646
- const getRollupConfig = (nitro) => {
1647
- const extensions = [
1648
- ".ts",
1649
- ".mjs",
1650
- ".js",
1651
- ".json",
1652
- ".node",
1653
- ".tsx",
1654
- ".jsx"
1655
- ];
1656
- const nodePreset = nitro.options.node === false ? unenv.nodeless : unenv.node;
1657
- const builtinPreset = {
1658
- alias: {
1659
- // General
1660
- ...nitro.options.dev ? {} : {
1661
- debug: "unenv/runtime/npm/debug",
1662
- "consola/core": "consola/core",
1663
- consola: "unenv/runtime/npm/consola"
1664
- },
1665
- ...nitro.options.alias
1666
- }
1667
- };
1668
- const env = unenv.env(nodePreset, builtinPreset, nitro.options.unenv);
1669
- const buildServerDir = join(nitro.options.buildDir, "dist/server");
1670
- const chunkNamePrefixes = [
1671
- [nitro.options.buildDir, "build"],
1672
- [buildServerDir, "app"],
1673
- ["\0raw:", "raw"],
1674
- ["\0nitro-wasm:", "wasm"],
1675
- ["\0", "virtual"]
1676
- ];
1677
- function getChunkName(id) {
1678
- if (id.startsWith(runtimeDir)) {
1679
- return `chunks/runtime.mjs`;
1680
- }
1681
- for (const [dir, name] of chunkNamePrefixes) {
1682
- if (id.startsWith(dir)) {
1683
- return `chunks/${name}/[name].mjs`;
1684
- }
1685
- }
1686
- const routeHandler = nitro.options.handlers.find((h) => id.startsWith(h.handler)) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
1687
- if (routeHandler?.route) {
1688
- const path = routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/";
1689
- return `chunks/routes${path}/[name].mjs`;
1690
- }
1691
- const taskHandler = Object.entries(nitro.options.tasks).find(
1692
- ([_, task]) => task.handler === id
1693
- );
1694
- if (taskHandler) {
1695
- return `chunks/tasks/[name].mjs`;
1696
- }
1697
- return `chunks/_/[name].mjs`;
1698
- }
1699
- const rollupConfig = defu(nitro.options.rollupConfig, {
1700
- input: nitro.options.entry,
1701
- output: {
1702
- dir: nitro.options.output.serverDir,
1703
- entryFileNames: "index.mjs",
1704
- chunkFileNames(chunk) {
1705
- const lastModule = normalize(chunk.moduleIds.at(-1) || "");
1706
- return getChunkName(lastModule);
1707
- },
1708
- inlineDynamicImports: nitro.options.inlineDynamicImports,
1709
- format: "esm",
1710
- exports: "auto",
1711
- intro: "",
1712
- outro: "",
1713
- generatedCode: {
1714
- constBindings: true
1715
- },
1716
- sanitizeFileName: sanitizeFilePath,
1717
- sourcemap: nitro.options.sourceMap,
1718
- sourcemapExcludeSources: true,
1719
- sourcemapIgnoreList(relativePath, sourcemapPath) {
1720
- return relativePath.includes("node_modules");
1721
- }
1722
- },
1723
- external: env.external,
1724
- plugins: [],
1725
- onwarn(warning, rollupWarn) {
1726
- if (!["CIRCULAR_DEPENDENCY", "EVAL"].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) {
1727
- rollupWarn(warning);
1728
- }
1729
- },
1730
- treeshake: {
1731
- moduleSideEffects(id) {
1732
- const normalizedId = normalize(id);
1733
- const idWithoutNodeModules = normalizedId.split("node_modules/").pop();
1734
- if (!idWithoutNodeModules) {
1735
- return false;
1736
- }
1737
- if (normalizedId.startsWith(runtimeDir) || idWithoutNodeModules.startsWith(runtimeDir)) {
1738
- return true;
1739
- }
1740
- return nitro.options.moduleSideEffects.some(
1741
- (m) => normalizedId.startsWith(m) || idWithoutNodeModules.startsWith(m)
1742
- );
1743
- }
1744
- }
1745
- });
1746
- if (nitro.options.timing) {
1747
- rollupConfig.plugins.push(timing());
1748
- }
1749
- if (nitro.options.imports) {
1750
- rollupConfig.plugins.push(
1751
- unimportPlugin.rollup(nitro.options.imports)
1752
- );
1753
- }
1754
- rollupConfig.plugins.push(raw());
1755
- if (nitro.options.experimental.wasm) {
1756
- rollupConfig.plugins.push(rollup(nitro.options.wasm || {}));
1757
- }
1758
- let NODE_ENV = nitro.options.dev ? "development" : "production";
1759
- if (nitro.options.preset === "nitro-prerender") {
1760
- NODE_ENV = "prerender";
1761
- }
1762
- const buildEnvVars = {
1763
- NODE_ENV,
1764
- prerender: nitro.options.preset === "nitro-prerender",
1765
- server: true,
1766
- client: false,
1767
- dev: String(nitro.options.dev),
1768
- DEBUG: nitro.options.dev
1769
- };
1770
- const staticFlags = {
1771
- dev: nitro.options.dev,
1772
- preset: nitro.options.preset,
1773
- prerender: nitro.options.preset === "nitro-prerender",
1774
- server: true,
1775
- client: false,
1776
- nitro: true,
1777
- // @ts-expect-error
1778
- "versions.nitro": "",
1779
- "versions?.nitro": "",
1780
- // Internal
1781
- _asyncContext: nitro.options.experimental.asyncContext,
1782
- _websocket: nitro.options.experimental.websocket,
1783
- _tasks: nitro.options.experimental.tasks
1784
- };
1785
- rollupConfig.plugins.push(importMeta(nitro));
1786
- rollupConfig.plugins.push(
1787
- replace({
1788
- preventAssignment: true,
1789
- values: {
1790
- "typeof window": '"undefined"',
1791
- _import_meta_url_: "import.meta.url",
1792
- "globalThis.process.": "process.",
1793
- "process.env.RUNTIME_CONFIG": () => JSON.stringify(nitro.options.runtimeConfig, null, 2),
1794
- ...Object.fromEntries(
1795
- [".", ";", ")", "[", "]", "}", " "].map((d) => [
1796
- `import.meta${d}`,
1797
- `globalThis._importMeta_${d}`
1798
- ])
1799
- ),
1800
- ...Object.fromEntries(
1801
- [";", "(", "{", "}", " ", " ", "\n"].map((d) => [
1802
- `${d}global.`,
1803
- `${d}globalThis.`
1804
- ])
1805
- ),
1806
- ...Object.fromEntries(
1807
- Object.entries(buildEnvVars).map(([key, val]) => [
1808
- `process.env.${key}`,
1809
- JSON.stringify(val)
1810
- ])
1811
- ),
1812
- ...Object.fromEntries(
1813
- Object.entries(buildEnvVars).map(([key, val]) => [
1814
- `import.meta.env.${key}`,
1815
- JSON.stringify(val)
1816
- ])
1817
- ),
1818
- ...Object.fromEntries(
1819
- Object.entries(staticFlags).map(([key, val]) => [
1820
- `process.${key}`,
1821
- JSON.stringify(val)
1822
- ])
1823
- ),
1824
- ...Object.fromEntries(
1825
- Object.entries(staticFlags).map(([key, val]) => [
1826
- `import.meta.${key}`,
1827
- JSON.stringify(val)
1828
- ])
1829
- ),
1830
- ...nitro.options.replace
1831
- }
1832
- })
1833
- );
1834
- rollupConfig.plugins.push(
1835
- esbuild({
1836
- target: "es2019",
1837
- sourceMap: nitro.options.sourceMap,
1838
- ...nitro.options.esbuild?.options
1839
- })
1840
- );
1841
- rollupConfig.plugins.push(
1842
- dynamicRequire({
1843
- dir: resolve(nitro.options.buildDir, "dist/server"),
1844
- inline: nitro.options.node === false || nitro.options.inlineDynamicImports,
1845
- ignore: [
1846
- "client.manifest.mjs",
1847
- "server.js",
1848
- "server.cjs",
1849
- "server.mjs",
1850
- "server.manifest.mjs"
1851
- ]
1852
- })
1853
- );
1854
- rollupConfig.plugins.push(serverAssets(nitro));
1855
- rollupConfig.plugins.push(publicAssets(nitro));
1856
- rollupConfig.plugins.push(storage(nitro));
1857
- rollupConfig.plugins.push(database(nitro));
1858
- rollupConfig.plugins.push(appConfig(nitro));
1859
- rollupConfig.plugins.push(handlers(nitro));
1860
- if (nitro.options.experimental.openAPI) {
1861
- rollupConfig.plugins.push(handlersMeta());
1862
- }
1863
- rollupConfig.plugins.push(
1864
- virtual(
1865
- {
1866
- "#nitro-internal-pollyfills": env.polyfill.map((p) => `import '${p}';`).join("\n")
1867
- },
1868
- nitro.vfs
1869
- )
1870
- );
1871
- rollupConfig.plugins.push(virtual(nitro.options.virtual, nitro.vfs));
1872
- const nitroPlugins = [...new Set(nitro.options.plugins)];
1873
- rollupConfig.plugins.push(
1874
- virtual(
1875
- {
1876
- "#nitro-internal-virtual/plugins": `
1877
- ${nitroPlugins.map((plugin) => `import _${hash(plugin)} from '${plugin}';`).join("\n")}
1878
-
1879
- export const plugins = [
1880
- ${nitroPlugins.map((plugin) => `_${hash(plugin)}`).join(",\n")}
1881
- ]
1882
- `
1883
- },
1884
- nitro.vfs
1885
- )
1886
- );
1887
- let buildDir = nitro.options.buildDir;
1888
- if (isWindows && nitro.options.externals?.trace === false && nitro.options.dev) {
1889
- buildDir = pathToFileURL(buildDir).href;
1890
- }
1891
- rollupConfig.plugins.push(
1892
- alias({
1893
- entries: resolveAliases({
1894
- "#build": buildDir,
1895
- "#nitro-internal-virtual/error-handler": nitro.options.errorHandler,
1896
- "#internal/nitro": runtimeDir,
1897
- "nitro/runtime": runtimeDir,
1898
- "nitropack/runtime": runtimeDir,
1899
- "~": nitro.options.srcDir,
1900
- "@/": nitro.options.srcDir,
1901
- "~~": nitro.options.rootDir,
1902
- "@@/": nitro.options.rootDir,
1903
- ...env.alias
1904
- })
1905
- })
1906
- );
1907
- if (nitro.options.noExternals) {
1908
- rollupConfig.plugins.push({
1909
- name: "no-externals",
1910
- async resolveId(id, from, options) {
1911
- if (nitro.options.node && (id.startsWith("node:") || builtinModules.includes(id))) {
1912
- return { id, external: true };
1913
- }
1914
- const resolved = await this.resolve(id, from, options);
1915
- if (!resolved) {
1916
- const _resolved = await resolvePath(id, {
1917
- url: nitro.options.nodeModulesDirs,
1918
- conditions: [
1919
- "default",
1920
- nitro.options.dev ? "development" : "production",
1921
- "node",
1922
- "import",
1923
- "require"
1924
- ]
1925
- }).catch(() => null);
1926
- if (_resolved) {
1927
- return { id: _resolved, external: false };
1928
- }
1929
- }
1930
- if (!resolved || resolved.external && !id.endsWith(".wasm")) {
1931
- throw new Error(
1932
- `Cannot resolve ${JSON.stringify(id)} from ${JSON.stringify(
1933
- from
1934
- )} and externals are not allowed!`
1935
- );
1936
- }
1937
- }
1938
- });
1939
- } else {
1940
- const externalsPlugin = nitro.options.experimental.legacyExternals ? externals : externals$1;
1941
- rollupConfig.plugins.push(
1942
- externalsPlugin(
1943
- defu(nitro.options.externals, {
1944
- outDir: nitro.options.output.serverDir,
1945
- moduleDirectories: nitro.options.nodeModulesDirs,
1946
- external: [
1947
- ...nitro.options.dev ? [nitro.options.buildDir] : [],
1948
- ...nitro.options.nodeModulesDirs
1949
- ],
1950
- inline: [
1951
- "#",
1952
- "~",
1953
- "@/",
1954
- "~~",
1955
- "@@/",
1956
- "virtual:",
1957
- "nitro/runtime",
1958
- "nitropack/runtime",
1959
- dirname(nitro.options.entry),
1960
- ...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [],
1961
- runtimeDir,
1962
- nitro.options.srcDir,
1963
- ...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"),
1964
- ...nitro.options.dev || nitro.options.preset === "nitro-prerender" || nitro.options.experimental.bundleRuntimeDependencies === false ? [] : runtimeDependencies
1965
- ],
1966
- traceOptions: {
1967
- base: "/",
1968
- processCwd: nitro.options.rootDir,
1969
- exportsOnly: true
1970
- },
1971
- traceAlias: {
1972
- "h3-nightly": "h3",
1973
- ...nitro.options.externals?.traceAlias
1974
- },
1975
- exportConditions: nitro.options.exportConditions
1976
- })
1977
- )
1978
- );
1979
- }
1980
- rollupConfig.plugins.push(
1981
- nodeResolve({
1982
- extensions,
1983
- preferBuiltins: !!nitro.options.node,
1984
- rootDir: nitro.options.rootDir,
1985
- modulePaths: nitro.options.nodeModulesDirs,
1986
- // 'module' is intentionally not supported because of externals
1987
- mainFields: ["main"],
1988
- exportConditions: nitro.options.exportConditions
1989
- })
1990
- );
1991
- rollupConfig.plugins.push(
1992
- commonjs({
1993
- esmExternals: (id) => !id.startsWith("unenv/"),
1994
- requireReturnsDefault: "auto",
1995
- ...nitro.options.commonJS
1996
- })
1997
- );
1998
- rollupConfig.plugins.push(json());
1999
- rollupConfig.plugins.push(inject(env.inject));
2000
- if (nitro.options.minify) {
2001
- const _terser = createRequire(import.meta.url)("@rollup/plugin-terser");
2002
- const terser = _terser.default || _terser;
2003
- rollupConfig.plugins.push(
2004
- terser({
2005
- mangle: {
2006
- keep_fnames: true,
2007
- keep_classnames: true
2008
- },
2009
- format: {
2010
- comments: false
2011
- }
2012
- })
2013
- );
2014
- }
2015
- if (nitro.options.sourceMap && !nitro.options.dev && nitro.options.experimental.sourcemapMinify !== false) {
2016
- rollupConfig.plugins.push(sourcemapMininify());
2017
- }
2018
- if (nitro.options.analyze) {
2019
- rollupConfig.plugins.push(
2020
- visualizer({
2021
- ...nitro.options.analyze,
2022
- filename: (nitro.options.analyze.filename || "stats.html").replace(
2023
- "{name}",
2024
- "nitro"
2025
- ),
2026
- title: "Nitro Server bundle stats"
2027
- })
2028
- );
2029
- }
2030
- return rollupConfig;
2031
- };
2032
-
2033
- export { getRollupConfig };
1
+ export * from "nitro/rollup";