nitro-nightly 4.0.0-20251030-091344-d4418b98 → 4.0.0-20251030-121649-98b56dfe

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 (334) hide show
  1. package/dist/_build/common.mjs +763 -0
  2. package/dist/_build/rolldown.mjs +216 -0
  3. package/dist/_build/rollup.mjs +359 -0
  4. package/dist/_build/vite.build.mjs +67 -0
  5. package/dist/_build/vite.plugin.mjs +747 -0
  6. package/dist/_chunks/B-7HiF0V.mjs +1303 -0
  7. package/dist/_chunks/B3asVbT4.mjs +151 -0
  8. package/dist/_chunks/B5ooyfLk.mjs +372 -0
  9. package/dist/_chunks/DXMHy5ca.mjs +43 -0
  10. package/dist/_dev.d.mts +12 -0
  11. package/dist/_dev.mjs +675 -0
  12. package/dist/_libs/acorn.mjs +5034 -0
  13. package/dist/_libs/c12.mjs +2798 -0
  14. package/dist/_libs/chokidar.mjs +1560 -0
  15. package/dist/_libs/citty.mjs +333 -0
  16. package/dist/_libs/commondir.mjs +22 -0
  17. package/dist/_libs/compatx.mjs +46 -0
  18. package/dist/_libs/confbox.mjs +2920 -0
  19. package/dist/_libs/debug.mjs +848 -0
  20. package/dist/_libs/deepmerge.mjs +86 -0
  21. package/dist/_libs/depd.mjs +314 -0
  22. package/dist/_libs/dot-prop.mjs +138 -0
  23. package/dist/_libs/duplexer.mjs +71 -0
  24. package/dist/_libs/ee-first.mjs +68 -0
  25. package/dist/_libs/encodeurl.mjs +49 -0
  26. package/dist/_libs/escape-html.mjs +58 -0
  27. package/dist/_libs/escape-string-regexp.mjs +8 -0
  28. package/dist/_libs/estree-walker.mjs +330 -0
  29. package/dist/_libs/etag.mjs +75 -0
  30. package/dist/{_chunks/_deps → _libs}/fdir.mjs +49 -104
  31. package/dist/_libs/fresh.mjs +85 -0
  32. package/dist/_libs/function-bind.mjs +63 -0
  33. package/dist/_libs/gen-mapping.mjs +612 -0
  34. package/dist/_libs/giget.mjs +19076 -0
  35. package/dist/_libs/gzip-size.mjs +21 -0
  36. package/dist/_libs/hasown.mjs +14 -0
  37. package/dist/_libs/http-errors.mjs +436 -0
  38. package/dist/_libs/httpxy.mjs +410 -0
  39. package/dist/_libs/is-core-module.mjs +220 -0
  40. package/dist/_libs/is-module.mjs +13 -0
  41. package/dist/_libs/is-reference.mjs +32 -0
  42. package/dist/{_chunks/_deps → _libs}/js-tokens.mjs +83 -112
  43. package/dist/_libs/klona.mjs +90 -0
  44. package/dist/_libs/knitwork.mjs +124 -0
  45. package/dist/_libs/local-pkg.mjs +1686 -0
  46. package/dist/{_chunks/_deps → _libs}/magic-string.mjs +272 -629
  47. package/dist/_libs/mime-db.mjs +7642 -0
  48. package/dist/_libs/mime-types.mjs +162 -0
  49. package/dist/_libs/mime.mjs +1391 -0
  50. package/dist/_libs/node-fetch-native.mjs +173 -0
  51. package/dist/_libs/on-finished.mjs +170 -0
  52. package/dist/_libs/parseurl.mjs +103 -0
  53. package/dist/_libs/path-parse.mjs +47 -0
  54. package/dist/_libs/pathe.mjs +41 -0
  55. package/dist/_libs/picomatch.mjs +1673 -0
  56. package/dist/_libs/plugin-alias.mjs +64 -0
  57. package/dist/_libs/plugin-commonjs.mjs +1489 -0
  58. package/dist/_libs/plugin-inject.mjs +135 -0
  59. package/dist/_libs/plugin-json.mjs +36 -0
  60. package/dist/_libs/plugin-node-resolve.mjs +1553 -0
  61. package/dist/_libs/plugin-replace.mjs +104 -0
  62. package/dist/_libs/pretty-bytes.mjs +116 -0
  63. package/dist/_libs/range-parser.mjs +102 -0
  64. package/dist/_libs/remapping.mjs +117 -0
  65. package/dist/{_chunks/_deps → _libs}/rou3.mjs +7 -22
  66. package/dist/_libs/send.mjs +857 -0
  67. package/dist/_libs/serve-static.mjs +124 -0
  68. package/dist/_libs/std-env.mjs +158 -0
  69. package/dist/_libs/strip-literal.mjs +51 -0
  70. package/dist/{_chunks/_deps → _libs}/tinyglobby.mjs +32 -33
  71. package/dist/_libs/ultrahtml.mjs +138 -0
  72. package/dist/_libs/unimport.mjs +3520 -0
  73. package/dist/_libs/untyped.mjs +271 -0
  74. package/dist/_libs/unwasm.mjs +5825 -0
  75. package/dist/{_chunks/_deps/@pi0 → _libs}/vite-plugin-fullstack.mjs +28 -42
  76. package/dist/_presets.mjs +1723 -0
  77. package/dist/builder.d.mts +37 -35
  78. package/dist/builder.mjs +45 -117
  79. package/dist/cli/_chunks/build.mjs +43 -0
  80. package/dist/cli/_chunks/common.mjs +15 -0
  81. package/dist/cli/_chunks/detect-acorn.mjs +12 -0
  82. package/dist/cli/_chunks/dev.mjs +79 -0
  83. package/dist/cli/_chunks/dist.mjs +3 -0
  84. package/dist/cli/_chunks/dist2.mjs +4 -0
  85. package/dist/cli/_chunks/esm.mjs +3 -0
  86. package/dist/cli/_chunks/json5.mjs +4 -0
  87. package/dist/cli/_chunks/jsonc.mjs +4 -0
  88. package/dist/cli/_chunks/list.mjs +27 -0
  89. package/dist/cli/_chunks/multipart-parser.mjs +6 -0
  90. package/dist/cli/_chunks/prepare.mjs +19 -0
  91. package/dist/cli/_chunks/run.mjs +55 -0
  92. package/dist/cli/_chunks/task.mjs +16 -0
  93. package/dist/cli/_chunks/toml.mjs +4 -0
  94. package/dist/cli/_chunks/yaml.mjs +4 -0
  95. package/dist/cli/index.d.mts +1 -1
  96. package/dist/cli/index.mjs +19 -18
  97. package/dist/presets/_nitro/runtime/nitro-dev.d.mts +1 -0
  98. package/dist/presets/_nitro/runtime/nitro-dev.mjs +42 -33
  99. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.mts +2 -2
  100. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +4 -8
  101. package/dist/presets/_nitro/runtime/service-worker.d.mts +1 -0
  102. package/dist/presets/_nitro/runtime/service-worker.mjs +14 -11
  103. package/dist/presets/aws-amplify/runtime/aws-amplify.d.mts +1 -0
  104. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +6 -5
  105. package/dist/presets/aws-lambda/runtime/_utils.d.mts +8 -13
  106. package/dist/presets/aws-lambda/runtime/_utils.mjs +95 -81
  107. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +1 -2
  108. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +25 -27
  109. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +7 -7
  110. package/dist/presets/azure/runtime/_utils.mjs +43 -43
  111. package/dist/presets/azure/runtime/azure-swa.d.mts +2 -2
  112. package/dist/presets/azure/runtime/azure-swa.mjs +22 -21
  113. package/dist/presets/bun/runtime/bun.d.mts +1 -0
  114. package/dist/presets/bun/runtime/bun.mjs +18 -17
  115. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +10 -7
  116. package/dist/presets/cloudflare/runtime/_module-handler.mjs +78 -87
  117. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +6 -14
  118. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +53 -58
  119. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +1 -7
  120. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +12 -14
  121. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.mts +12 -12
  122. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +35 -39
  123. package/dist/presets/cloudflare/runtime/plugin.dev.d.mts +2 -2
  124. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +86 -76
  125. package/dist/presets/deno/runtime/deno-deploy.d.mts +1 -0
  126. package/dist/presets/deno/runtime/deno-deploy.mjs +12 -11
  127. package/dist/presets/deno/runtime/deno-server.d.mts +2 -1
  128. package/dist/presets/deno/runtime/deno-server.mjs +31 -39
  129. package/dist/presets/netlify/runtime/netlify-edge.d.mts +2 -1
  130. package/dist/presets/netlify/runtime/netlify-edge.mjs +14 -11
  131. package/dist/presets/netlify/runtime/netlify.mjs +11 -17
  132. package/dist/presets/node/runtime/node-cluster.mjs +49 -48
  133. package/dist/presets/node/runtime/node-middleware.d.mts +3 -2
  134. package/dist/presets/node/runtime/node-middleware.mjs +7 -6
  135. package/dist/presets/node/runtime/node-server.mjs +33 -23
  136. package/dist/presets/standard/runtime/server.d.mts +1 -3
  137. package/dist/presets/standard/runtime/server.mjs +1 -3
  138. package/dist/presets/stormkit/runtime/stormkit.d.mts +13 -13
  139. package/dist/presets/stormkit/runtime/stormkit.mjs +20 -20
  140. package/dist/presets/vercel/runtime/vercel.d.mts +3 -3
  141. package/dist/presets/vercel/runtime/vercel.mjs +15 -14
  142. package/dist/presets/winterjs/runtime/winterjs.d.mts +2 -0
  143. package/dist/presets/winterjs/runtime/winterjs.mjs +72 -68
  144. package/dist/presets/zeabur/runtime/zeabur.d.mts +1 -1
  145. package/dist/runtime/index.d.mts +12 -1
  146. package/dist/runtime/index.mjs +12 -7
  147. package/dist/runtime/internal/app.mjs +175 -162
  148. package/dist/runtime/internal/cache.d.mts +10 -4
  149. package/dist/runtime/internal/cache.mjs +247 -216
  150. package/dist/runtime/internal/context.d.mts +9 -9
  151. package/dist/runtime/internal/context.mjs +17 -10
  152. package/dist/runtime/internal/database.mjs +8 -10
  153. package/dist/runtime/internal/error/dev.d.mts +5 -4
  154. package/dist/runtime/internal/error/dev.mjs +106 -105
  155. package/dist/runtime/internal/error/prod.d.mts +2 -2
  156. package/dist/runtime/internal/error/prod.mjs +48 -52
  157. package/dist/runtime/internal/error/utils.d.mts +4 -4
  158. package/dist/runtime/internal/error/utils.mjs +1 -1
  159. package/dist/runtime/internal/index.d.mts +2 -0
  160. package/dist/runtime/internal/index.mjs +2 -0
  161. package/dist/runtime/internal/lib/http-graceful-shutdown.d.mts +14 -14
  162. package/dist/runtime/internal/lib/http-graceful-shutdown.mjs +248 -209
  163. package/dist/runtime/internal/meta.d.mts +1 -1
  164. package/dist/runtime/internal/meta.mjs +1 -1
  165. package/dist/runtime/internal/plugin.d.mts +2 -2
  166. package/dist/runtime/internal/plugin.mjs +1 -1
  167. package/dist/runtime/internal/renderer.mjs +39 -31
  168. package/dist/runtime/internal/route-rules.d.mts +8 -8
  169. package/dist/runtime/internal/route-rules.mjs +53 -51
  170. package/dist/runtime/internal/routes/dev-tasks.d.mts +1 -30
  171. package/dist/runtime/internal/routes/dev-tasks.mjs +15 -17
  172. package/dist/runtime/internal/routes/openapi.d.mts +1 -0
  173. package/dist/runtime/internal/routes/openapi.mjs +81 -87
  174. package/dist/runtime/internal/routes/renderer-template.d.mts +1 -1
  175. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +1 -2
  176. package/dist/runtime/internal/routes/renderer-template.dev.mjs +10 -17
  177. package/dist/runtime/internal/routes/renderer-template.mjs +1 -1
  178. package/dist/runtime/internal/routes/scalar.d.mts +1 -0
  179. package/dist/runtime/internal/routes/scalar.mjs +22 -23
  180. package/dist/runtime/internal/routes/swagger.d.mts +1 -0
  181. package/dist/runtime/internal/routes/swagger.mjs +9 -11
  182. package/dist/runtime/internal/runtime-config.d.mts +4 -4
  183. package/dist/runtime/internal/runtime-config.mjs +40 -35
  184. package/dist/runtime/internal/shutdown.d.mts +2 -7
  185. package/dist/runtime/internal/shutdown.mjs +30 -29
  186. package/dist/runtime/internal/static.mjs +63 -74
  187. package/dist/runtime/internal/storage.mjs +2 -2
  188. package/dist/runtime/internal/task.d.mts +6 -6
  189. package/dist/runtime/internal/task.mjs +56 -59
  190. package/dist/runtime/internal/utils.d.mts +1 -1
  191. package/dist/runtime/internal/utils.mjs +4 -10
  192. package/dist/types/index.d.mts +2566 -3851
  193. package/dist/types/index.mjs +1 -1
  194. package/dist/vite.d.mts +56 -52
  195. package/dist/vite.mjs +55 -132
  196. package/package.json +10 -10
  197. package/dist/_build/build.mjs +0 -368
  198. package/dist/_build/build2.mjs +0 -556
  199. package/dist/_build/info.mjs +0 -1002
  200. package/dist/_build/prepare.mjs +0 -1511
  201. package/dist/_build/snapshot.mjs +0 -185
  202. package/dist/_build/vite.mjs +0 -959
  203. package/dist/_build/vite2.mjs +0 -149
  204. package/dist/_chunks/_deps/@jridgewell/gen-mapping.mjs +0 -189
  205. package/dist/_chunks/_deps/@jridgewell/remapping.mjs +0 -137
  206. package/dist/_chunks/_deps/@jridgewell/resolve-uri.mjs +0 -231
  207. package/dist/_chunks/_deps/@jridgewell/sourcemap-codec.mjs +0 -173
  208. package/dist/_chunks/_deps/@jridgewell/trace-mapping.mjs +0 -170
  209. package/dist/_chunks/_deps/@rollup/plugin-alias.mjs +0 -89
  210. package/dist/_chunks/_deps/@rollup/plugin-commonjs.mjs +0 -2376
  211. package/dist/_chunks/_deps/@rollup/plugin-inject.mjs +0 -212
  212. package/dist/_chunks/_deps/@rollup/plugin-json.mjs +0 -37
  213. package/dist/_chunks/_deps/@rollup/plugin-node-resolve.mjs +0 -1386
  214. package/dist/_chunks/_deps/@rollup/plugin-replace.mjs +0 -133
  215. package/dist/_chunks/_deps/@rollup/pluginutils.mjs +0 -346
  216. package/dist/_chunks/_deps/acorn.mjs +0 -6225
  217. package/dist/_chunks/_deps/c12.mjs +0 -510
  218. package/dist/_chunks/_deps/chokidar.mjs +0 -1428
  219. package/dist/_chunks/_deps/citty.mjs +0 -460
  220. package/dist/_chunks/_deps/commondir.mjs +0 -77
  221. package/dist/_chunks/_deps/compatx.mjs +0 -76
  222. package/dist/_chunks/_deps/confbox.mjs +0 -300
  223. package/dist/_chunks/_deps/debug.mjs +0 -885
  224. package/dist/_chunks/_deps/deepmerge.mjs +0 -147
  225. package/dist/_chunks/_deps/depd.mjs +0 -550
  226. package/dist/_chunks/_deps/dot-prop.mjs +0 -282
  227. package/dist/_chunks/_deps/dotenv.mjs +0 -555
  228. package/dist/_chunks/_deps/duplexer.mjs +0 -1
  229. package/dist/_chunks/_deps/ee-first.mjs +0 -104
  230. package/dist/_chunks/_deps/encodeurl.mjs +0 -69
  231. package/dist/_chunks/_deps/escape-html.mjs +0 -87
  232. package/dist/_chunks/_deps/escape-string-regexp.mjs +0 -13
  233. package/dist/_chunks/_deps/estree-walker.mjs +0 -433
  234. package/dist/_chunks/_deps/etag.mjs +0 -147
  235. package/dist/_chunks/_deps/exsolve.mjs +0 -1416
  236. package/dist/_chunks/_deps/fresh.mjs +0 -145
  237. package/dist/_chunks/_deps/function-bind.mjs +0 -106
  238. package/dist/_chunks/_deps/giget.mjs +0 -451
  239. package/dist/_chunks/_deps/gzip-size.mjs +0 -19
  240. package/dist/_chunks/_deps/hasown.mjs +0 -19
  241. package/dist/_chunks/_deps/http-errors.mjs +0 -307
  242. package/dist/_chunks/_deps/httpxy.mjs +0 -580
  243. package/dist/_chunks/_deps/inherits.mjs +0 -57
  244. package/dist/_chunks/_deps/is-core-module.mjs +0 -596
  245. package/dist/_chunks/_deps/is-module.mjs +0 -25
  246. package/dist/_chunks/_deps/is-reference.mjs +0 -31
  247. package/dist/_chunks/_deps/klona.mjs +0 -137
  248. package/dist/_chunks/_deps/knitwork.mjs +0 -172
  249. package/dist/_chunks/_deps/local-pkg.mjs +0 -163
  250. package/dist/_chunks/_deps/mime-db.mjs +0 -11685
  251. package/dist/_chunks/_deps/mime-types.mjs +0 -287
  252. package/dist/_chunks/_deps/mime.mjs +0 -1172
  253. package/dist/_chunks/_deps/mlly.mjs +0 -2413
  254. package/dist/_chunks/_deps/ms.mjs +0 -172
  255. package/dist/_chunks/_deps/node-fetch-native.mjs +0 -3
  256. package/dist/_chunks/_deps/nypm.mjs +0 -219
  257. package/dist/_chunks/_deps/on-finished.mjs +0 -246
  258. package/dist/_chunks/_deps/parseurl.mjs +0 -168
  259. package/dist/_chunks/_deps/path-parse.mjs +0 -85
  260. package/dist/_chunks/_deps/pathe.mjs +0 -251
  261. package/dist/_chunks/_deps/perfect-debounce.mjs +0 -88
  262. package/dist/_chunks/_deps/picomatch.mjs +0 -2144
  263. package/dist/_chunks/_deps/pkg-types.mjs +0 -247
  264. package/dist/_chunks/_deps/pretty-bytes.mjs +0 -180
  265. package/dist/_chunks/_deps/quansync.mjs +0 -99
  266. package/dist/_chunks/_deps/range-parser.mjs +0 -171
  267. package/dist/_chunks/_deps/rc9.mjs +0 -219
  268. package/dist/_chunks/_deps/readdirp.mjs +0 -245
  269. package/dist/_chunks/_deps/resolve.mjs +0 -1260
  270. package/dist/_chunks/_deps/send.mjs +0 -1022
  271. package/dist/_chunks/_deps/serve-static.mjs +0 -228
  272. package/dist/_chunks/_deps/setprototypeof.mjs +0 -26
  273. package/dist/_chunks/_deps/statuses.mjs +0 -457
  274. package/dist/_chunks/_deps/std-env.mjs +0 -3
  275. package/dist/_chunks/_deps/strip-literal.mjs +0 -67
  276. package/dist/_chunks/_deps/supports-color.mjs +0 -44
  277. package/dist/_chunks/_deps/tinyexec.mjs +0 -552
  278. package/dist/_chunks/_deps/toidentifier.mjs +0 -41
  279. package/dist/_chunks/_deps/ultrahtml.mjs +0 -3
  280. package/dist/_chunks/_deps/unimport.mjs +0 -2267
  281. package/dist/_chunks/_deps/unplugin-utils.mjs +0 -65
  282. package/dist/_chunks/_deps/unplugin.mjs +0 -1294
  283. package/dist/_chunks/_deps/untyped.mjs +0 -375
  284. package/dist/_chunks/_deps/unwasm.mjs +0 -6959
  285. package/dist/_chunks/_deps/webpack-virtual-modules.mjs +0 -360
  286. package/dist/_chunks/_presets/_all.mjs +0 -59
  287. package/dist/_chunks/_presets/_nitro.mjs +0 -74
  288. package/dist/_chunks/_presets/_resolve.mjs +0 -64
  289. package/dist/_chunks/_presets/_static.mjs +0 -69
  290. package/dist/_chunks/_presets/_types.mjs +0 -3
  291. package/dist/_chunks/_presets/_utils.mjs +0 -31
  292. package/dist/_chunks/_presets/alwaysdata.mjs +0 -17
  293. package/dist/_chunks/_presets/aws-amplify.mjs +0 -111
  294. package/dist/_chunks/_presets/aws-lambda.mjs +0 -23
  295. package/dist/_chunks/_presets/azure.mjs +0 -162
  296. package/dist/_chunks/_presets/bun.mjs +0 -19
  297. package/dist/_chunks/_presets/cleavr.mjs +0 -15
  298. package/dist/_chunks/_presets/cloudflare.mjs +0 -608
  299. package/dist/_chunks/_presets/deno.mjs +0 -196
  300. package/dist/_chunks/_presets/digitalocean.mjs +0 -14
  301. package/dist/_chunks/_presets/firebase.mjs +0 -47
  302. package/dist/_chunks/_presets/flightcontrol.mjs +0 -14
  303. package/dist/_chunks/_presets/genezio.mjs +0 -13
  304. package/dist/_chunks/_presets/heroku.mjs +0 -14
  305. package/dist/_chunks/_presets/iis.mjs +0 -194
  306. package/dist/_chunks/_presets/index.mjs +0 -62
  307. package/dist/_chunks/_presets/koyeb.mjs +0 -14
  308. package/dist/_chunks/_presets/netlify.mjs +0 -241
  309. package/dist/_chunks/_presets/node.mjs +0 -54
  310. package/dist/_chunks/_presets/platform.mjs +0 -14
  311. package/dist/_chunks/_presets/render.mjs +0 -14
  312. package/dist/_chunks/_presets/standard.mjs +0 -23
  313. package/dist/_chunks/_presets/stormkit.mjs +0 -18
  314. package/dist/_chunks/_presets/vercel.mjs +0 -375
  315. package/dist/_chunks/_presets/winterjs.mjs +0 -22
  316. package/dist/_chunks/_presets/zeabur.mjs +0 -69
  317. package/dist/_chunks/_presets/zerops.mjs +0 -27
  318. package/dist/_chunks/app.mjs +0 -600
  319. package/dist/_chunks/builder.mjs +0 -648
  320. package/dist/_chunks/server.mjs +0 -256
  321. package/dist/_cli/build.mjs +0 -49
  322. package/dist/_cli/common.mjs +0 -13
  323. package/dist/_cli/dev.mjs +0 -121
  324. package/dist/_cli/index.mjs +0 -16
  325. package/dist/_cli/list.mjs +0 -33
  326. package/dist/_cli/prepare.mjs +0 -23
  327. package/dist/_cli/run.mjs +0 -59
  328. package/dist/presets/cloudflare/runtime/shims/workers.dev.d.mts +0 -21
  329. package/dist/runtime/internal/empty.d.mts +0 -0
  330. package/dist/runtime/internal/vite/dev-entry.d.mts +0 -1
  331. package/dist/runtime/internal/vite/dev-worker.d.mts +0 -1
  332. package/dist/runtime/internal/vite/prod-setup.d.mts +0 -4
  333. package/dist/runtime/internal/vite/ssr-renderer.d.mts +0 -4
  334. /package/lib/{indexd.mts → index.d.mts} +0 -0
@@ -1,2267 +0,0 @@
1
- import { readFileSync, existsSync, promises, accessSync, constants } from 'node:fs';
2
- import { readFile } from 'node:fs/promises';
3
- import process$1 from 'node:process';
4
- import { fileURLToPath } from 'node:url';
5
- import { camelCase, kebabCase } from 'scule';
6
- import os from 'node:os';
7
- import { basename } from 'node:path';
8
- import { M as MagicString } from './magic-string.mjs';
9
- import { c as createUnplugin } from './unplugin.mjs';
10
- import { c as createFilter } from './unplugin-utils.mjs';
11
- import { f as findStaticImports, p as parseStaticImport, d as detectSyntax, b as findExports, c as findTypeExports, e as resolve$1, g as resolveModuleExportNames } from './mlly.mjs';
12
- import { p as pm } from './picomatch.mjs';
13
- import { g as glob } from './tinyglobby.mjs';
14
- import { b as resolvePackageJSON, r as readPackageJSON } from './pkg-types.mjs';
15
- import { r as resolveModule } from './local-pkg.mjs';
16
- import { i as isAbsolute, a as relative, r as resolve, p as parse, d as dirname, n as normalize, j as join, b as basename$1 } from './pathe.mjs';
17
- import { p as parse$1 } from './acorn.mjs';
18
- import { a as walk } from './estree-walker.mjs';
19
- import { s as stripLiteral } from './strip-literal.mjs';
20
-
21
- const excludeRE = [
22
- // imported/exported from other module
23
- /\b(import|export)\b([\w$*{},\s]+?)\bfrom\s*["']/g,
24
- // defined as function
25
- /\bfunction\s*([\w$]+)\s*\(/g,
26
- // defined as class
27
- /\bclass\s*([\w$]+)\s*\{/g,
28
- // defined as local variable
29
- // eslint-disable-next-line regexp/no-super-linear-backtracking
30
- /\b(?:const|let|var)\s+?(\[.*?\]|\{.*?\}|.+?)\s*?[=;\n]/gs
31
- ];
32
- const importAsRE = /^.*\sas\s+/;
33
- const separatorRE = /[,[\]{}\n]|\b(?:import|export)\b/g;
34
- const matchRE = /(^|\.\.\.|(?:\bcase|\?)\s+|[^\w$/)]|\bextends\s+)([\w$]+)\s*(?=[.()[\]}:;?+\-*&|`<>,\n]|\b(?:instanceof|in)\b|$|(?<=extends\s+\w+)\s+\{)/g;
35
- const regexRE = /\/\S*?(?<!\\)(?<!\[[^\]]*)\/[gimsuy]*/g;
36
- function stripCommentsAndStrings(code, options) {
37
- return stripLiteral(code, options).replace(regexRE, 'new RegExp("")');
38
- }
39
-
40
- function defineUnimportPreset(preset) {
41
- return preset;
42
- }
43
- const identifierRE = /^[A-Z_$][\w$]*$/i;
44
- const safePropertyName = /^[a-z$_][\w$]*$/i;
45
- function stringifyWith(withValues) {
46
- let withDefs = "";
47
- for (let entries = Object.entries(withValues), l = entries.length, i = 0; i < l; i++) {
48
- const [prop, value] = entries[i];
49
- withDefs += safePropertyName.test(prop) ? prop : JSON.stringify(prop);
50
- withDefs += `: ${JSON.stringify(String(value))}`;
51
- if (i + 1 !== l)
52
- withDefs += ", ";
53
- }
54
- return `{ ${withDefs} }`;
55
- }
56
- function stringifyImports(imports, isCJS = false) {
57
- const map = toImportModuleMap(imports);
58
- return Object.entries(map).flatMap(([name, importSet]) => {
59
- const entries = [];
60
- const imports2 = Array.from(importSet).filter((i) => {
61
- if (!i.name || i.as === "") {
62
- let importStr;
63
- if (isCJS) {
64
- importStr = `require('${name}');`;
65
- } else {
66
- importStr = `import '${name}'`;
67
- if (i.with)
68
- importStr += ` with ${stringifyWith(i.with)}`;
69
- importStr += ";";
70
- }
71
- entries.push(importStr);
72
- return false;
73
- } else if (i.name === "default" || i.name === "=") {
74
- let importStr;
75
- if (isCJS) {
76
- importStr = i.name === "=" ? `const ${i.as} = require('${name}');` : `const { default: ${i.as} } = require('${name}');`;
77
- } else {
78
- importStr = `import ${i.as} from '${name}'`;
79
- if (i.with)
80
- importStr += ` with ${stringifyWith(i.with)}`;
81
- importStr += ";";
82
- }
83
- entries.push(importStr);
84
- return false;
85
- } else if (i.name === "*") {
86
- let importStr;
87
- if (isCJS) {
88
- importStr = `const ${i.as} = require('${name}');`;
89
- } else {
90
- importStr = `import * as ${i.as} from '${name}'`;
91
- if (i.with)
92
- importStr += ` with ${stringifyWith(i.with)}`;
93
- importStr += ";";
94
- }
95
- entries.push(importStr);
96
- return false;
97
- } else if (!isCJS && i.with) {
98
- entries.push(`import { ${stringifyImportAlias(i)} } from '${name}' with ${stringifyWith(i.with)};`);
99
- return false;
100
- }
101
- return true;
102
- });
103
- if (imports2.length) {
104
- const importsAs = imports2.map((i) => stringifyImportAlias(i, isCJS));
105
- entries.push(
106
- isCJS ? `const { ${importsAs.join(", ")} } = require('${name}');` : `import { ${importsAs.join(", ")} } from '${name}';`
107
- );
108
- }
109
- return entries;
110
- }).join("\n");
111
- }
112
- function dedupeImports(imports, warn) {
113
- const map = /* @__PURE__ */ new Map();
114
- const indexToRemove = /* @__PURE__ */ new Set();
115
- imports.filter((i) => !i.disabled).forEach((i, idx) => {
116
- if (i.declarationType === "enum" || i.declarationType === "class")
117
- return;
118
- const name = i.as ?? i.name;
119
- if (!map.has(name)) {
120
- map.set(name, idx);
121
- return;
122
- }
123
- const other = imports[map.get(name)];
124
- if (other.from === i.from) {
125
- indexToRemove.add(idx);
126
- return;
127
- }
128
- const diff = (other.priority || 1) - (i.priority || 1);
129
- if (diff === 0)
130
- warn(`Duplicated imports "${name}", the one from "${other.from}" has been ignored and "${i.from}" is used`);
131
- if (diff <= 0) {
132
- indexToRemove.add(map.get(name));
133
- map.set(name, idx);
134
- } else {
135
- indexToRemove.add(idx);
136
- }
137
- });
138
- return imports.filter((_, idx) => !indexToRemove.has(idx));
139
- }
140
- function toExports(imports, fileDir, includeType = false) {
141
- const map = toImportModuleMap(imports, includeType);
142
- return Object.entries(map).flatMap(([name, imports2]) => {
143
- if (isFilePath(name))
144
- name = name.replace(/\.[a-z]+$/i, "");
145
- if (fileDir && isAbsolute(name)) {
146
- name = relative(fileDir, name);
147
- if (!name.match(/^[./]/))
148
- name = `./${name}`;
149
- }
150
- const entries = [];
151
- const filtered = Array.from(imports2).filter((i) => {
152
- if (i.name === "*") {
153
- entries.push(`export * as ${i.as} from '${name}';`);
154
- return false;
155
- }
156
- return true;
157
- });
158
- if (filtered.length)
159
- entries.push(`export { ${filtered.map((i) => stringifyImportAlias(i, false)).join(", ")} } from '${name}';`);
160
- return entries;
161
- }).join("\n");
162
- }
163
- function stripFileExtension(path) {
164
- return path.replace(/\.[a-z]+$/i, "");
165
- }
166
- function toTypeDeclarationItems(imports, options) {
167
- return imports.map((i) => {
168
- const from = options?.resolvePath?.(i) || stripFileExtension(i.typeFrom || i.from);
169
- let typeDef = "";
170
- if (i.with)
171
- typeDef += `import('${from}', { with: ${stringifyWith(i.with)} })`;
172
- else
173
- typeDef += `import('${from}')`;
174
- if (i.name !== "*" && i.name !== "=")
175
- typeDef += identifierRE.test(i.name) ? `.${i.name}` : `['${i.name}']`;
176
- return `const ${i.as}: typeof ${typeDef}`;
177
- }).sort();
178
- }
179
- function toTypeDeclarationFile(imports, options) {
180
- const items = toTypeDeclarationItems(imports, options);
181
- const {
182
- exportHelper = true
183
- } = options || {};
184
- let declaration = "";
185
- if (exportHelper)
186
- declaration += "export {}\n";
187
- declaration += `declare global {
188
- ${items.map((i) => ` ${i}`).join("\n")}
189
- }`;
190
- return declaration;
191
- }
192
- function makeTypeModulesMap(imports, resolvePath) {
193
- const modulesMap = /* @__PURE__ */ new Map();
194
- const resolveImportFrom = typeof resolvePath === "function" ? (i) => {
195
- return resolvePath(i) || stripFileExtension(i.typeFrom || i.from);
196
- } : (i) => stripFileExtension(i.typeFrom || i.from);
197
- for (const import_ of imports) {
198
- const from = resolveImportFrom(import_);
199
- let module = modulesMap.get(from);
200
- if (!module) {
201
- module = { typeImports: /* @__PURE__ */ new Set(), starTypeImport: void 0 };
202
- modulesMap.set(from, module);
203
- }
204
- if (import_.name === "*") {
205
- if (import_.as)
206
- module.starTypeImport = import_;
207
- } else {
208
- module.typeImports.add(import_);
209
- }
210
- }
211
- return modulesMap;
212
- }
213
- function toTypeReExports(imports, options) {
214
- const importsMap = makeTypeModulesMap(imports, options?.resolvePath);
215
- const code = Array.from(importsMap).flatMap(([from, module]) => {
216
- from = from.replace(/\.d\.([cm]?)ts$/i, ".$1js");
217
- const { starTypeImport, typeImports } = module;
218
- const strings = [];
219
- if (typeImports.size) {
220
- const typeImportNames = Array.from(typeImports).map(({ name, as }) => {
221
- if (as && as !== name)
222
- return `${name} as ${as}`;
223
- return name;
224
- });
225
- strings.push(
226
- "// @ts-ignore",
227
- `export type { ${typeImportNames.join(", ")} } from '${from}'`
228
- );
229
- }
230
- if (starTypeImport) {
231
- strings.push(
232
- "// @ts-ignore",
233
- `export type * as ${starTypeImport.as} from '${from}'`
234
- );
235
- }
236
- if (strings.length) {
237
- strings.push(
238
- // This is a workaround for a TypeScript issue where type-only re-exports are not properly initialized.
239
- `import('${from}')`
240
- );
241
- }
242
- return strings;
243
- });
244
- return `// for type re-export
245
- declare global {
246
- ${code.map((i) => ` ${i}`).join("\n")}
247
- }`;
248
- }
249
- function stringifyImportAlias(item, isCJS = false) {
250
- return item.as === void 0 || item.name === item.as ? item.name : isCJS ? `${item.name}: ${item.as}` : `${item.name} as ${item.as}`;
251
- }
252
- function toImportModuleMap(imports, includeType = false) {
253
- const map = {};
254
- for (const _import of imports) {
255
- if (_import.type && !includeType)
256
- continue;
257
- if (!map[_import.from])
258
- map[_import.from] = /* @__PURE__ */ new Set();
259
- map[_import.from].add(_import);
260
- }
261
- return map;
262
- }
263
- function getMagicString(code) {
264
- if (typeof code === "string")
265
- return new MagicString(code);
266
- return code;
267
- }
268
- function addImportToCode(code, imports, isCJS = false, mergeExisting = false, injectAtLast = false, firstOccurrence = Number.POSITIVE_INFINITY, onResolved, onStringified) {
269
- let newImports = [];
270
- const s = getMagicString(code);
271
- let _staticImports;
272
- const strippedCode = stripCommentsAndStrings(s.original);
273
- function findStaticImportsLazy() {
274
- if (!_staticImports) {
275
- _staticImports = findStaticImports(s.original).filter((i) => Boolean(strippedCode.slice(i.start, i.end).trim())).map((i) => parseStaticImport(i));
276
- }
277
- return _staticImports;
278
- }
279
- function hasShebang() {
280
- const shebangRegex = /^#!.+/;
281
- return shebangRegex.test(s.original);
282
- }
283
- if (mergeExisting && !isCJS) {
284
- const existingImports = findStaticImportsLazy();
285
- const map = /* @__PURE__ */ new Map();
286
- imports.forEach((i) => {
287
- const target = existingImports.find((e) => e.specifier === i.from && e.imports.startsWith("{"));
288
- if (!target)
289
- return newImports.push(i);
290
- if (!map.has(target))
291
- map.set(target, []);
292
- map.get(target).push(i);
293
- });
294
- for (const [target, items] of map.entries()) {
295
- const strings = items.map((i) => `${stringifyImportAlias(i)}, `);
296
- const importLength = target.code.match(/^\s*import\s*\{/)?.[0]?.length;
297
- if (importLength)
298
- s.appendLeft(target.start + importLength, ` ${strings.join("").trim()}`);
299
- }
300
- } else {
301
- newImports = imports;
302
- }
303
- newImports = onResolved?.(newImports) ?? newImports;
304
- let newEntries = stringifyImports(newImports, isCJS);
305
- newEntries = onStringified?.(newEntries, newImports) ?? newEntries;
306
- if (newEntries) {
307
- const insertionIndex = injectAtLast ? findStaticImportsLazy().reverse().find((i) => i.end <= firstOccurrence)?.end ?? 0 : 0;
308
- if (insertionIndex > 0)
309
- s.appendRight(insertionIndex, `
310
- ${newEntries}
311
- `);
312
- else if (hasShebang())
313
- s.appendLeft(s.original.indexOf("\n") + 1, `
314
- ${newEntries}
315
- `);
316
- else
317
- s.prepend(`${newEntries}
318
- `);
319
- }
320
- return {
321
- s,
322
- get code() {
323
- return s.toString();
324
- }
325
- };
326
- }
327
- function normalizeImports(imports) {
328
- for (const _import of imports)
329
- _import.as = _import.as ?? _import.name;
330
- return imports;
331
- }
332
- function isFilePath(path) {
333
- return path.startsWith(".") || isAbsolute(path) || path.includes("://");
334
- }
335
-
336
- const contextRE$1 = /\b_ctx\.([$\w]+)\b/g;
337
- const UNREF_KEY = "__unimport_unref_";
338
- const VUE_TEMPLATE_NAME = "unimport:vue-template";
339
- function vueTemplateAddon() {
340
- const self = {
341
- name: VUE_TEMPLATE_NAME,
342
- async transform(s, id) {
343
- if (!s.original.includes("_ctx.") || s.original.includes(UNREF_KEY))
344
- return s;
345
- const matches = Array.from(s.original.matchAll(contextRE$1));
346
- const imports = await this.getImports();
347
- let targets = [];
348
- for (const match of matches) {
349
- const name = match[1];
350
- const item = imports.find((i) => i.as === name);
351
- if (!item)
352
- continue;
353
- const start = match.index;
354
- const end = start + match[0].length;
355
- const tempName = `__unimport_${name}`;
356
- s.overwrite(start, end, `(${JSON.stringify(name)} in _ctx ? _ctx.${name} : ${UNREF_KEY}(${tempName}))`);
357
- if (!targets.find((i) => i.as === tempName)) {
358
- targets.push({
359
- ...item,
360
- as: tempName
361
- });
362
- }
363
- }
364
- if (targets.length) {
365
- targets.push({
366
- name: "unref",
367
- from: "vue",
368
- as: UNREF_KEY
369
- });
370
- for (const addon of this.addons) {
371
- if (addon === self)
372
- continue;
373
- targets = await addon.injectImportsResolved?.call(this, targets, s, id) ?? targets;
374
- }
375
- let injection = stringifyImports(targets);
376
- for (const addon of this.addons) {
377
- if (addon === self)
378
- continue;
379
- injection = await addon.injectImportsStringified?.call(this, injection, targets, s, id) ?? injection;
380
- }
381
- s.prepend(injection);
382
- }
383
- return s;
384
- },
385
- async declaration(dts, options) {
386
- const imports = await this.getImports();
387
- const items = imports.map((i) => {
388
- if (i.type || i.dtsDisabled)
389
- return "";
390
- const from = options?.resolvePath?.(i) || i.from;
391
- return `readonly ${i.as}: UnwrapRef<typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}>`;
392
- }).filter(Boolean).sort();
393
- const extendItems = items.map((i) => ` ${i}`).join("\n");
394
- return `${dts}
395
- // for vue template auto import
396
- import { UnwrapRef } from 'vue'
397
- declare module 'vue' {
398
- interface ComponentCustomProperties {
399
- ${extendItems}
400
- }
401
- }`;
402
- }
403
- };
404
- return self;
405
- }
406
-
407
- const contextRE = /resolveDirective as _resolveDirective/;
408
- const contextText = `${contextRE.source}, `;
409
- const directiveRE = /(?:var|const) (\w+) = _resolveDirective\("([\w.-]+)"\);?\s*/g;
410
- const VUE_DIRECTIVES_NAME = "unimport:vue-directives";
411
- function vueDirectivesAddon(options = {}) {
412
- function isDirective(importEntry) {
413
- let isDirective2 = importEntry.meta?.vueDirective === true;
414
- if (isDirective2) {
415
- return true;
416
- }
417
- isDirective2 = options.isDirective?.(normalizePath(process$1.cwd(), importEntry.from), importEntry) ?? false;
418
- if (isDirective2) {
419
- importEntry.meta ??= {};
420
- importEntry.meta.vueDirective = true;
421
- }
422
- return isDirective2;
423
- }
424
- const self = {
425
- name: VUE_DIRECTIVES_NAME,
426
- async transform(s, id) {
427
- if (!s.original.match(contextRE))
428
- return s;
429
- const matches = Array.from(s.original.matchAll(directiveRE)).sort((a, b) => b.index - a.index);
430
- if (!matches.length)
431
- return s;
432
- let targets = [];
433
- for await (const [
434
- begin,
435
- end,
436
- importEntry
437
- ] of findDirectives(
438
- isDirective,
439
- matches,
440
- this.getImports()
441
- )) {
442
- s.overwrite(begin, end, "");
443
- targets.push(importEntry);
444
- }
445
- if (!targets.length)
446
- return s;
447
- if (!s.toString().match(directiveRE))
448
- s.replace(contextText, "");
449
- for (const addon of this.addons) {
450
- if (addon === self)
451
- continue;
452
- targets = await addon.injectImportsResolved?.call(this, targets, s, id) ?? targets;
453
- }
454
- let injection = stringifyImports(targets);
455
- for (const addon of this.addons) {
456
- if (addon === self)
457
- continue;
458
- injection = await addon.injectImportsStringified?.call(this, injection, targets, s, id) ?? injection;
459
- }
460
- s.prepend(injection);
461
- return s;
462
- },
463
- async declaration(dts, options2) {
464
- const directivesMap = await this.getImports().then((imports) => {
465
- return imports.filter(isDirective).reduce((acc, i) => {
466
- if (i.type || i.dtsDisabled)
467
- return acc;
468
- let name;
469
- if (i.name === "default" && (i.as === "default" || !i.as)) {
470
- const file = basename(i.from);
471
- const idx = file.indexOf(".");
472
- name = idx > -1 ? file.slice(0, idx) : file;
473
- } else {
474
- name = i.as ?? i.name;
475
- }
476
- name = name[0] === "v" ? camelCase(name) : camelCase(`v-${name}`);
477
- if (!acc.has(name)) {
478
- acc.set(name, i);
479
- }
480
- return acc;
481
- }, /* @__PURE__ */ new Map());
482
- });
483
- if (!directivesMap.size)
484
- return dts;
485
- const directives = Array.from(directivesMap.entries()).map(([name, i]) => ` ${name}: typeof import('${options2?.resolvePath?.(i) || i.from}')['${i.name}']`).sort().join("\n");
486
- return `${dts}
487
- // for vue directives auto import
488
- declare module 'vue' {
489
- interface GlobalDirectives {
490
- ${directives}
491
- }
492
- }`;
493
- }
494
- };
495
- return self;
496
- }
497
- function resolvePath(cwd, path) {
498
- return path[0] === "." ? resolve(cwd, path) : path;
499
- }
500
- function normalizePath(cwd, path) {
501
- return resolvePath(cwd, path).replace(/\\/g, "/");
502
- }
503
- async function* findDirectives(isDirective, regexArray, importsPromise) {
504
- const imports = (await importsPromise).filter(isDirective);
505
- if (!imports.length)
506
- return;
507
- const symbols = regexArray.reduce((acc, regex) => {
508
- const [all, symbol, resolveDirectiveName] = regex;
509
- if (acc.has(symbol))
510
- return acc;
511
- acc.set(symbol, [
512
- regex.index,
513
- regex.index + all.length,
514
- kebabCase(resolveDirectiveName)
515
- ]);
516
- return acc;
517
- }, /* @__PURE__ */ new Map());
518
- for (const [symbol, data] of symbols.entries()) {
519
- yield* findDirective(imports, symbol, data);
520
- }
521
- }
522
- function* findDirective(imports, symbol, [begin, end, importName]) {
523
- let resolvedName;
524
- for (const i of imports) {
525
- if (i.name === "default" && (i.as === "default" || !i.as)) {
526
- const file = basename(i.from);
527
- const idx = file.indexOf(".");
528
- resolvedName = kebabCase(idx > -1 ? file.slice(0, idx) : file);
529
- } else {
530
- resolvedName = kebabCase(i.as ?? i.name);
531
- }
532
- if (resolvedName === importName) {
533
- yield [
534
- begin,
535
- end,
536
- { ...i, name: i.name, as: symbol }
537
- ];
538
- return;
539
- }
540
- if (resolvedName[0] === "v") {
541
- resolvedName = resolvedName.slice(resolvedName[1] === "-" ? 2 : 1);
542
- }
543
- if (resolvedName === importName) {
544
- yield [
545
- begin,
546
- end,
547
- { ...i, name: i.name, as: symbol }
548
- ];
549
- return;
550
- }
551
- }
552
- }
553
-
554
- const version = "5.5.0";
555
-
556
- function configureAddons(opts) {
557
- const addons = [];
558
- if (Array.isArray(opts.addons)) {
559
- addons.push(...opts.addons);
560
- } else {
561
- const addonsMap = /* @__PURE__ */ new Map();
562
- if (opts.addons?.addons?.length) {
563
- let i = 0;
564
- for (const addon of opts.addons.addons) {
565
- addonsMap.set(addon.name || `external:custom-${i++}`, addon);
566
- }
567
- }
568
- if (opts.addons?.vueTemplate) {
569
- if (!addonsMap.has(VUE_TEMPLATE_NAME)) {
570
- addonsMap.set(VUE_TEMPLATE_NAME, vueTemplateAddon());
571
- }
572
- }
573
- if (opts.addons?.vueDirectives) {
574
- if (!addonsMap.has(VUE_DIRECTIVES_NAME)) {
575
- addonsMap.set(VUE_DIRECTIVES_NAME, vueDirectivesAddon(
576
- typeof opts.addons.vueDirectives === "object" ? opts.addons.vueDirectives : void 0
577
- ));
578
- }
579
- }
580
- addons.push(...addonsMap.values());
581
- }
582
- return addons;
583
- }
584
-
585
- async function detectImportsRegex(code, ctx, options) {
586
- const s = getMagicString(code);
587
- const original = s.original;
588
- const strippedCode = stripCommentsAndStrings(
589
- original,
590
- // Do not strip comments if they are virtual import names
591
- options?.transformVirtualImports !== false && ctx.options.virtualImports?.length ? {
592
- filter: (i) => !ctx.options.virtualImports.includes(i),
593
- fillChar: "-"
594
- } : void 0
595
- );
596
- const syntax = detectSyntax(strippedCode);
597
- const isCJSContext = syntax.hasCJS && !syntax.hasESM;
598
- let matchedImports = [];
599
- const occurrenceMap = /* @__PURE__ */ new Map();
600
- const map = await ctx.getImportMap();
601
- if (options?.autoImport !== false) {
602
- Array.from(strippedCode.matchAll(matchRE)).forEach((i) => {
603
- if (i[1] === ".")
604
- return null;
605
- const end = strippedCode[i.index + i[0].length];
606
- const before = strippedCode[i.index - 1];
607
- if (end === ":" && !["?", "case"].includes(i[1].trim()) && before !== ":")
608
- return null;
609
- const name = i[2];
610
- const occurrence = i.index + i[1].length;
611
- if (occurrenceMap.get(name) || Number.POSITIVE_INFINITY > occurrence)
612
- occurrenceMap.set(name, occurrence);
613
- });
614
- for (const regex of excludeRE) {
615
- for (const match of strippedCode.matchAll(regex)) {
616
- const segments = [...match[1]?.split(separatorRE) || [], ...match[2]?.split(separatorRE) || []];
617
- for (const segment of segments) {
618
- const identifier = segment.replace(importAsRE, "").trim();
619
- occurrenceMap.delete(identifier);
620
- }
621
- }
622
- }
623
- const identifiers = new Set(occurrenceMap.keys());
624
- matchedImports = Array.from(identifiers).map((name) => {
625
- const item = map.get(name);
626
- if (item && !item.disabled)
627
- return item;
628
- occurrenceMap.delete(name);
629
- return null;
630
- }).filter(Boolean);
631
- for (const addon of ctx.addons)
632
- matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
633
- }
634
- if (options?.transformVirtualImports !== false && ctx.options.virtualImports?.length) {
635
- const virtualImports = parseVirtualImportsRegex(strippedCode, map, ctx.options.virtualImports);
636
- virtualImports.ranges.forEach(([start, end]) => {
637
- s.remove(start, end);
638
- });
639
- matchedImports.push(...virtualImports.imports);
640
- }
641
- const firstOccurrence = Math.min(...Array.from(occurrenceMap.entries()).map((i) => i[1]));
642
- return {
643
- s,
644
- strippedCode,
645
- isCJSContext,
646
- matchedImports,
647
- firstOccurrence
648
- };
649
- }
650
- function parseVirtualImportsRegex(strippedCode, importMap, virtualImports) {
651
- const imports = [];
652
- const ranges = [];
653
- if (virtualImports?.length) {
654
- findStaticImports(strippedCode).filter((i) => virtualImports.includes(i.specifier)).map((i) => parseStaticImport(i)).forEach((i) => {
655
- ranges.push([i.start, i.end]);
656
- Object.entries(i.namedImports || {}).forEach(([name, as]) => {
657
- const original = importMap.get(name);
658
- if (!original)
659
- throw new Error(`[unimport] failed to find "${name}" imported from "${i.specifier}"`);
660
- imports.push({
661
- from: original.from,
662
- name: original.name,
663
- as
664
- });
665
- });
666
- });
667
- }
668
- return {
669
- imports,
670
- ranges
671
- };
672
- }
673
-
674
- async function detectImports(code, ctx, options) {
675
- if (options?.parser === "acorn")
676
- return Promise.resolve().then(function () { return detectAcorn; }).then((r) => r.detectImportsAcorn(code, ctx, options));
677
- return detectImportsRegex(code, ctx, options);
678
- }
679
-
680
- const FileExtensionLookup = [
681
- "mts",
682
- "cts",
683
- "ts",
684
- "tsx",
685
- "mjs",
686
- "cjs",
687
- "js",
688
- "jsx"
689
- ];
690
- const FileLookupPatterns = `*.{${FileExtensionLookup.join(",")}}`;
691
- function resolveGlobsExclude(glob2, cwd) {
692
- return `${glob2.startsWith("!") ? "!" : ""}${resolve(cwd, glob2.replace(/^!/, ""))}`;
693
- }
694
- function joinGlobFilePattern(glob2, filePattern) {
695
- return join(basename$1(glob2) === "*" ? dirname(glob2) : glob2, filePattern);
696
- }
697
- function normalizeScanDirs(dirs, options) {
698
- const topLevelTypes = options?.types ?? true;
699
- const cwd = options?.cwd ?? process$1.cwd();
700
- const filePatterns = options?.filePatterns || [FileLookupPatterns];
701
- return dirs.map((dir) => {
702
- const isString = typeof dir === "string";
703
- const glob2 = resolveGlobsExclude(isString ? dir : dir.glob, cwd);
704
- const types = isString ? topLevelTypes : dir.types ?? topLevelTypes;
705
- if (glob2.match(/\.\w+$/))
706
- return { glob: glob2, types };
707
- const withFilePatterns = filePatterns.map((filePattern) => ({ glob: joinGlobFilePattern(glob2, filePattern), types }));
708
- return [{ glob: glob2, types }, ...withFilePatterns];
709
- }).flat();
710
- }
711
- async function scanFilesFromDir(dir, options) {
712
- const dirGlobs = (Array.isArray(dir) ? dir : [dir]).map((i) => i.glob);
713
- const files = (await glob(
714
- dirGlobs,
715
- {
716
- absolute: true,
717
- cwd: options?.cwd || process$1.cwd(),
718
- onlyFiles: true,
719
- followSymbolicLinks: true,
720
- expandDirectories: false
721
- }
722
- )).map((i) => normalize(i));
723
- const fileFilter = options?.fileFilter || (() => true);
724
- const indexOfDirs = (file) => dirGlobs.findIndex((glob2) => pm.isMatch(file, glob2));
725
- const fileSortByDirs = files.reduce((acc, file) => {
726
- const index = indexOfDirs(file);
727
- if (acc[index])
728
- acc[index].push(normalize(file));
729
- else
730
- acc[index] = [normalize(file)];
731
- return acc;
732
- }, []).map((files2) => files2.sort()).flat();
733
- return fileSortByDirs.filter(fileFilter);
734
- }
735
- async function scanDirExports(dirs, options) {
736
- const normalizedDirs = normalizeScanDirs(dirs, options);
737
- const files = await scanFilesFromDir(normalizedDirs, options);
738
- const includeTypesDirs = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types);
739
- const isIncludeTypes = (file) => includeTypesDirs.some((dir) => pm.isMatch(file, dir.glob));
740
- const imports = (await Promise.all(files.map((file) => scanExports(file, isIncludeTypes(file))))).flat();
741
- const deduped = dedupeDtsExports(imports);
742
- return deduped;
743
- }
744
- function dedupeDtsExports(exports) {
745
- return exports.filter((i) => {
746
- if (!i.type)
747
- return true;
748
- if (i.declarationType === "enum" || i.declarationType === "class")
749
- return true;
750
- return !exports.find((e) => e.as === i.as && e.name === i.name && !e.type);
751
- });
752
- }
753
- async function scanExports(filepath, includeTypes, seen = /* @__PURE__ */ new Set()) {
754
- if (seen.has(filepath)) {
755
- console.warn(`[unimport] "${filepath}" is already scanned, skipping`);
756
- return [];
757
- }
758
- seen.add(filepath);
759
- const imports = [];
760
- const code = await readFile(filepath, "utf-8");
761
- const exports = findExports(code);
762
- const defaultExport = exports.find((i) => i.type === "default");
763
- if (defaultExport) {
764
- let name = parse(filepath).name;
765
- if (name === "index")
766
- name = parse(filepath.split("/").slice(0, -1).join("/")).name;
767
- const as = /[-_.]/.test(name) ? camelCase(name) : name;
768
- imports.push({ name: "default", as, from: filepath });
769
- }
770
- async function toImport(exports2, additional) {
771
- for (const exp of exports2) {
772
- if (exp.type === "named") {
773
- for (const name of exp.names)
774
- imports.push({ name, as: name, from: filepath, ...additional });
775
- } else if (exp.type === "declaration") {
776
- if (exp.name) {
777
- imports.push({ name: exp.name, as: exp.name, from: filepath, ...additional });
778
- if (exp.declarationType === "enum" || exp.declarationType === "class") {
779
- imports.push({ name: exp.name, as: exp.name, from: filepath, type: true, declarationType: exp.declarationType, ...additional });
780
- }
781
- }
782
- } else if (exp.type === "star" && exp.specifier) {
783
- if (exp.name) {
784
- imports.push({ name: exp.name, as: exp.name, from: filepath, ...additional });
785
- } else {
786
- const subfile = exp.specifier;
787
- let subfilepath = resolve(dirname(filepath), subfile);
788
- let subfilepathResolved = false;
789
- for (const ext of FileExtensionLookup) {
790
- if (existsSync(`${subfilepath}.${ext}`)) {
791
- subfilepath = `${subfilepath}.${ext}`;
792
- break;
793
- } else if (existsSync(`${subfilepath}/index.${ext}`)) {
794
- subfilepath = `${subfilepath}/index.${ext}`;
795
- break;
796
- }
797
- }
798
- if (existsSync(subfilepath)) {
799
- subfilepathResolved = true;
800
- } else {
801
- try {
802
- subfilepath = await resolve$1(exp.specifier);
803
- subfilepath = normalize(fileURLToPath(subfilepath));
804
- if (existsSync(subfilepath)) {
805
- subfilepathResolved = true;
806
- }
807
- } catch {
808
- }
809
- }
810
- if (!subfilepathResolved) {
811
- console.warn(`[unimport] failed to resolve "${subfilepath}", skip scanning`);
812
- continue;
813
- }
814
- const nested = await scanExports(subfilepath, includeTypes, seen);
815
- imports.push(...additional ? nested.map((i) => ({ ...i, ...additional })) : nested);
816
- }
817
- }
818
- }
819
- }
820
- const isDts = filepath.match(/\.d\.[mc]?ts$/);
821
- if (isDts) {
822
- if (includeTypes) {
823
- await toImport(exports, { type: true });
824
- await toImport(findTypeExports(code), { type: true });
825
- }
826
- } else {
827
- await toImport(exports);
828
- if (includeTypes)
829
- await toImport(findTypeExports(code), { type: true });
830
- }
831
- return imports;
832
- }
833
-
834
- const CACHE_PATH = /* @__PURE__ */ join(os.tmpdir(), "unimport");
835
- let CACHE_WRITEABLE;
836
- async function resolvePackagePreset(preset) {
837
- const scanned = await extractExports(preset.package, preset.url, preset.cache);
838
- const filtered = scanned.filter((name) => {
839
- for (const item of preset.ignore || []) {
840
- if (typeof item === "string" && item === name)
841
- return false;
842
- if (item instanceof RegExp && item.test(name))
843
- return false;
844
- if (typeof item === "function" && item(name) === false)
845
- return false;
846
- }
847
- return true;
848
- });
849
- return filtered.map((name) => ({
850
- from: preset.package,
851
- name
852
- }));
853
- }
854
- async function extractExports(name, url, cache = true) {
855
- const packageJsonPath = await resolvePackageJSON(name, { url });
856
- const packageJson = await readPackageJSON(packageJsonPath);
857
- const version = packageJson.version;
858
- const cachePath = join(CACHE_PATH, `${name}@${version}`, "exports.json");
859
- if (cache && CACHE_WRITEABLE === void 0) {
860
- try {
861
- CACHE_WRITEABLE = isWritable(CACHE_PATH);
862
- } catch {
863
- CACHE_WRITEABLE = false;
864
- }
865
- }
866
- const useCache = cache && version && CACHE_WRITEABLE;
867
- if (useCache && existsSync(cachePath))
868
- return JSON.parse(await promises.readFile(cachePath, "utf-8"));
869
- const scanned = await resolveModuleExportNames(name, { url });
870
- if (useCache) {
871
- await promises.mkdir(dirname(cachePath), { recursive: true });
872
- await promises.writeFile(cachePath, JSON.stringify(scanned), "utf-8");
873
- }
874
- return scanned;
875
- }
876
- function isWritable(filename) {
877
- try {
878
- accessSync(filename, constants.W_OK);
879
- return true;
880
- } catch {
881
- return false;
882
- }
883
- }
884
-
885
- const dateFns = defineUnimportPreset({
886
- from: "date-fns",
887
- imports: [
888
- "add",
889
- "addBusinessDays",
890
- "addDays",
891
- "addHours",
892
- "addISOWeekYears",
893
- "addMilliseconds",
894
- "addMinutes",
895
- "addMonths",
896
- "addQuarters",
897
- "addSeconds",
898
- "addWeeks",
899
- "addYears",
900
- "areIntervalsOverlapping",
901
- "clamp",
902
- "closestIndexTo",
903
- "closestTo",
904
- "compareAsc",
905
- "compareDesc",
906
- "constants",
907
- "daysToWeeks",
908
- "differenceInBusinessDays",
909
- "differenceInCalendarDays",
910
- "differenceInCalendarISOWeekYears",
911
- "differenceInCalendarISOWeeks",
912
- "differenceInCalendarMonths",
913
- "differenceInCalendarQuarters",
914
- "differenceInCalendarWeeks",
915
- "differenceInCalendarYears",
916
- "differenceInDays",
917
- "differenceInHours",
918
- "differenceInISOWeekYears",
919
- "differenceInMilliseconds",
920
- "differenceInMinutes",
921
- "differenceInMonths",
922
- "differenceInQuarters",
923
- "differenceInSeconds",
924
- "differenceInWeeks",
925
- "differenceInYears",
926
- "eachDayOfInterval",
927
- "eachHourOfInterval",
928
- "eachMinuteOfInterval",
929
- "eachMonthOfInterval",
930
- "eachQuarterOfInterval",
931
- "eachWeekOfInterval",
932
- "eachWeekendOfInterval",
933
- "eachWeekendOfMonth",
934
- "eachWeekendOfYear",
935
- "eachYearOfInterval",
936
- "endOfDay",
937
- "endOfDecade",
938
- "endOfHour",
939
- "endOfISOWeek",
940
- "endOfISOWeekYear",
941
- "endOfMinute",
942
- "endOfMonth",
943
- "endOfQuarter",
944
- "endOfSecond",
945
- "endOfToday",
946
- "endOfTomorrow",
947
- "endOfWeek",
948
- "endOfYear",
949
- "endOfYesterday",
950
- "format",
951
- "formatDistance",
952
- "formatDistanceStrict",
953
- "formatDistanceToNow",
954
- "formatDistanceToNowStrict",
955
- "formatDuration",
956
- "formatISO",
957
- "formatISO9075",
958
- "formatISODuration",
959
- "formatRFC3339",
960
- "formatRFC7231",
961
- "formatRelative",
962
- "fromUnixTime",
963
- "getDate",
964
- "getDay",
965
- "getDayOfYear",
966
- "getDaysInMonth",
967
- "getDaysInYear",
968
- "getDecade",
969
- "getDefaultOptions",
970
- "getHours",
971
- "getISODay",
972
- "getISOWeek",
973
- "getISOWeekYear",
974
- "getISOWeeksInYear",
975
- "getMilliseconds",
976
- "getMinutes",
977
- "getMonth",
978
- "getOverlappingDaysInIntervals",
979
- "getQuarter",
980
- "getSeconds",
981
- "getTime",
982
- "getUnixTime",
983
- "getWeek",
984
- "getWeekOfMonth",
985
- "getWeekYear",
986
- "getWeeksInMonth",
987
- "getYear",
988
- "hoursToMilliseconds",
989
- "hoursToMinutes",
990
- "hoursToSeconds",
991
- "intervalToDuration",
992
- "intlFormat",
993
- "intlFormatDistance",
994
- "isAfter",
995
- "isBefore",
996
- "isDate",
997
- "isEqual",
998
- "isExists",
999
- "isFirstDayOfMonth",
1000
- "isFriday",
1001
- "isFuture",
1002
- "isLastDayOfMonth",
1003
- "isLeapYear",
1004
- "isMatch",
1005
- "isMonday",
1006
- "isPast",
1007
- "isSameDay",
1008
- "isSameHour",
1009
- "isSameISOWeek",
1010
- "isSameISOWeekYear",
1011
- "isSameMinute",
1012
- "isSameMonth",
1013
- "isSameQuarter",
1014
- "isSameSecond",
1015
- "isSameWeek",
1016
- "isSameYear",
1017
- "isSaturday",
1018
- "isSunday",
1019
- "isThisHour",
1020
- "isThisISOWeek",
1021
- "isThisMinute",
1022
- "isThisMonth",
1023
- "isThisQuarter",
1024
- "isThisSecond",
1025
- "isThisWeek",
1026
- "isThisYear",
1027
- "isThursday",
1028
- "isToday",
1029
- "isTomorrow",
1030
- "isTuesday",
1031
- "isValid",
1032
- "isWednesday",
1033
- "isWeekend",
1034
- "isWithinInterval",
1035
- "isYesterday",
1036
- "lastDayOfDecade",
1037
- "lastDayOfISOWeek",
1038
- "lastDayOfISOWeekYear",
1039
- "lastDayOfMonth",
1040
- "lastDayOfQuarter",
1041
- "lastDayOfWeek",
1042
- "lastDayOfYear",
1043
- "lightFormat",
1044
- "max",
1045
- "milliseconds",
1046
- "millisecondsToHours",
1047
- "millisecondsToMinutes",
1048
- "millisecondsToSeconds",
1049
- "min",
1050
- "minutesToHours",
1051
- "minutesToMilliseconds",
1052
- "minutesToSeconds",
1053
- "monthsToQuarters",
1054
- "monthsToYears",
1055
- "nextDay",
1056
- "nextFriday",
1057
- "nextMonday",
1058
- "nextSaturday",
1059
- "nextSunday",
1060
- "nextThursday",
1061
- "nextTuesday",
1062
- "nextWednesday",
1063
- "parse",
1064
- "parseISO",
1065
- "parseJSON",
1066
- "previousDay",
1067
- "previousFriday",
1068
- "previousMonday",
1069
- "previousSaturday",
1070
- "previousSunday",
1071
- "previousThursday",
1072
- "previousTuesday",
1073
- "previousWednesday",
1074
- "quartersToMonths",
1075
- "quartersToYears",
1076
- "roundToNearestMinutes",
1077
- "secondsToHours",
1078
- "secondsToMilliseconds",
1079
- "secondsToMinutes",
1080
- "set",
1081
- "setDate",
1082
- "setDay",
1083
- "setDayOfYear",
1084
- "setDefaultOptions",
1085
- "setHours",
1086
- "setISODay",
1087
- "setISOWeek",
1088
- "setISOWeekYear",
1089
- "setMilliseconds",
1090
- "setMinutes",
1091
- "setMonth",
1092
- "setQuarter",
1093
- "setSeconds",
1094
- "setWeek",
1095
- "setWeekYear",
1096
- "setYear",
1097
- "startOfDay",
1098
- "startOfDecade",
1099
- "startOfHour",
1100
- "startOfISOWeek",
1101
- "startOfISOWeekYear",
1102
- "startOfMinute",
1103
- "startOfMonth",
1104
- "startOfQuarter",
1105
- "startOfSecond",
1106
- "startOfToday",
1107
- "startOfTomorrow",
1108
- "startOfWeek",
1109
- "startOfWeekYear",
1110
- "startOfYear",
1111
- "startOfYesterday",
1112
- "sub",
1113
- "subBusinessDays",
1114
- "subDays",
1115
- "subHours",
1116
- "subISOWeekYears",
1117
- "subMilliseconds",
1118
- "subMinutes",
1119
- "subMonths",
1120
- "subQuarters",
1121
- "subSeconds",
1122
- "subWeeks",
1123
- "subYears",
1124
- "toDate",
1125
- "weeksToDays",
1126
- "yearsToMonths",
1127
- "yearsToQuarters"
1128
- ]
1129
- });
1130
-
1131
- const pinia = defineUnimportPreset({
1132
- from: "pinia",
1133
- imports: [
1134
- // https://pinia.esm.dev/api/modules/pinia.html#functions
1135
- "acceptHMRUpdate",
1136
- "createPinia",
1137
- "defineStore",
1138
- "getActivePinia",
1139
- "mapActions",
1140
- "mapGetters",
1141
- "mapState",
1142
- "mapStores",
1143
- "mapWritableState",
1144
- "setActivePinia",
1145
- "setMapStoreSuffix",
1146
- "storeToRefs"
1147
- ]
1148
- });
1149
-
1150
- const preact = defineUnimportPreset({
1151
- from: "preact",
1152
- imports: [
1153
- "useState",
1154
- "useCallback",
1155
- "useMemo",
1156
- "useEffect",
1157
- "useRef",
1158
- "useContext",
1159
- "useReducer"
1160
- ]
1161
- });
1162
-
1163
- const quasar = defineUnimportPreset({
1164
- from: "quasar",
1165
- imports: [
1166
- // https://quasar.dev/vue-composables
1167
- "useQuasar",
1168
- "useDialogPluginComponent",
1169
- "useFormChild",
1170
- "useMeta"
1171
- ]
1172
- });
1173
-
1174
- const react = defineUnimportPreset({
1175
- from: "react",
1176
- imports: [
1177
- "useState",
1178
- "useCallback",
1179
- "useMemo",
1180
- "useEffect",
1181
- "useRef",
1182
- "useContext",
1183
- "useReducer"
1184
- ]
1185
- });
1186
-
1187
- const ReactRouterHooks = [
1188
- "useOutletContext",
1189
- "useHref",
1190
- "useInRouterContext",
1191
- "useLocation",
1192
- "useNavigationType",
1193
- "useNavigate",
1194
- "useOutlet",
1195
- "useParams",
1196
- "useResolvedPath",
1197
- "useRoutes"
1198
- ];
1199
- const reactRouter = defineUnimportPreset({
1200
- from: "react-router",
1201
- imports: [
1202
- ...ReactRouterHooks
1203
- ]
1204
- });
1205
-
1206
- const reactRouterDom = defineUnimportPreset({
1207
- from: "react-router-dom",
1208
- imports: [
1209
- ...ReactRouterHooks,
1210
- // react-router-dom only hooks
1211
- "useLinkClickHandler",
1212
- "useSearchParams",
1213
- // react-router-dom Component
1214
- // call once in general
1215
- // 'BrowserRouter',
1216
- // 'HashRouter',
1217
- // 'MemoryRouter',
1218
- "Link",
1219
- "NavLink",
1220
- "Navigate",
1221
- "Outlet",
1222
- "Route",
1223
- "Routes"
1224
- ]
1225
- });
1226
-
1227
- const rxjs = defineUnimportPreset({
1228
- from: "rxjs",
1229
- imports: [
1230
- "of",
1231
- "from",
1232
- "map",
1233
- "tap",
1234
- "filter",
1235
- "forkJoin",
1236
- "throwError",
1237
- "catchError",
1238
- "Observable",
1239
- "mergeMap",
1240
- "switchMap",
1241
- "merge",
1242
- "zip",
1243
- "take",
1244
- "takeUntil",
1245
- "first",
1246
- "lastValueFrom",
1247
- "skip",
1248
- "skipUntil",
1249
- "distinct",
1250
- "distinctUntilChanged",
1251
- "throttle",
1252
- "throttleTime",
1253
- "retry",
1254
- "retryWhen",
1255
- "timeout",
1256
- "delay",
1257
- "debounce",
1258
- "debounceTime",
1259
- "find",
1260
- "every"
1261
- ]
1262
- });
1263
-
1264
- const solidCore = defineUnimportPreset({
1265
- from: "solid-js",
1266
- imports: [
1267
- "createSignal",
1268
- "createEffect",
1269
- "createMemo",
1270
- "createResource",
1271
- "onMount",
1272
- "onCleanup",
1273
- "onError",
1274
- "untrack",
1275
- "batch",
1276
- "on",
1277
- "createRoot",
1278
- "mergeProps",
1279
- "splitProps",
1280
- "useTransition",
1281
- "observable",
1282
- "mapArray",
1283
- "indexArray",
1284
- "createContext",
1285
- "useContext",
1286
- "children",
1287
- "lazy",
1288
- "createDeferred",
1289
- "createRenderEffect",
1290
- "createSelector",
1291
- "For",
1292
- "Show",
1293
- "Switch",
1294
- "Match",
1295
- "Index",
1296
- "ErrorBoundary",
1297
- "Suspense",
1298
- "SuspenseList"
1299
- ]
1300
- });
1301
- const solidStore = defineUnimportPreset({
1302
- from: "solid-js/store",
1303
- imports: [
1304
- "createStore",
1305
- "produce",
1306
- "reconcile",
1307
- "createMutable"
1308
- ]
1309
- });
1310
- const solidWeb = defineUnimportPreset({
1311
- from: "solid-js/web",
1312
- imports: [
1313
- "Dynamic",
1314
- "hydrate",
1315
- "render",
1316
- "renderToString",
1317
- "renderToStringAsync",
1318
- "renderToStream",
1319
- "isServer",
1320
- "Portal"
1321
- ]
1322
- });
1323
- const solid = defineUnimportPreset({
1324
- from: "solid-js",
1325
- imports: [
1326
- solidCore,
1327
- solidStore,
1328
- solidWeb
1329
- ]
1330
- });
1331
-
1332
- const solidAppRouter = defineUnimportPreset({
1333
- from: "solid-app-router",
1334
- imports: [
1335
- "Link",
1336
- "NavLink",
1337
- "Navigate",
1338
- "Outlet",
1339
- "Route",
1340
- "Router",
1341
- "Routes",
1342
- "_mergeSearchString",
1343
- "createIntegration",
1344
- "hashIntegration",
1345
- "normalizeIntegration",
1346
- "pathIntegration",
1347
- "staticIntegration",
1348
- "useHref",
1349
- "useIsRouting",
1350
- "useLocation",
1351
- "useMatch",
1352
- "useNavigate",
1353
- "useParams",
1354
- "useResolvedPath",
1355
- "useRouteData",
1356
- "useRoutes",
1357
- "useSearchParams"
1358
- ]
1359
- });
1360
-
1361
- const svelteAnimate = defineUnimportPreset({
1362
- from: "svelte/animate",
1363
- imports: [
1364
- "flip"
1365
- ]
1366
- });
1367
- const svelteEasing = defineUnimportPreset({
1368
- from: "svelte/easing",
1369
- imports: [
1370
- "back",
1371
- "bounce",
1372
- "circ",
1373
- "cubic",
1374
- "elastic",
1375
- "expo",
1376
- "quad",
1377
- "quart",
1378
- "quint",
1379
- "sine"
1380
- ].reduce((acc, e) => {
1381
- acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
1382
- return acc;
1383
- }, ["linear"])
1384
- });
1385
- const svelteStore = defineUnimportPreset({
1386
- from: "svelte/store",
1387
- imports: [
1388
- "writable",
1389
- "readable",
1390
- "derived",
1391
- "get"
1392
- ]
1393
- });
1394
- const svelteMotion = defineUnimportPreset({
1395
- from: "svelte/motion",
1396
- imports: [
1397
- "tweened",
1398
- "spring"
1399
- ]
1400
- });
1401
- const svelteTransition = defineUnimportPreset({
1402
- from: "svelte/transition",
1403
- imports: [
1404
- "fade",
1405
- "blur",
1406
- "fly",
1407
- "slide",
1408
- "scale",
1409
- "draw",
1410
- "crossfade"
1411
- ]
1412
- });
1413
- const svelte = defineUnimportPreset({
1414
- from: "svelte",
1415
- imports: [
1416
- // lifecycle
1417
- "onMount",
1418
- "beforeUpdate",
1419
- "afterUpdate",
1420
- "onDestroy",
1421
- // tick
1422
- "tick",
1423
- // context
1424
- "setContext",
1425
- "getContext",
1426
- "hasContext",
1427
- "getAllContexts",
1428
- // event dispatcher
1429
- "createEventDispatcher"
1430
- ]
1431
- });
1432
-
1433
- const uniApp = defineUnimportPreset({
1434
- from: "@dcloudio/uni-app",
1435
- imports: [
1436
- "onAddToFavorites",
1437
- "onBackPress",
1438
- "onError",
1439
- "onHide",
1440
- "onLaunch",
1441
- "onLoad",
1442
- "onNavigationBarButtonTap",
1443
- "onNavigationBarSearchInputChanged",
1444
- "onNavigationBarSearchInputClicked",
1445
- "onNavigationBarSearchInputConfirmed",
1446
- "onNavigationBarSearchInputFocusChanged",
1447
- "onPageNotFound",
1448
- "onPageScroll",
1449
- "onPullDownRefresh",
1450
- "onReachBottom",
1451
- "onReady",
1452
- "onResize",
1453
- "onShareAppMessage",
1454
- "onShareTimeline",
1455
- "onShow",
1456
- "onTabItemTap",
1457
- "onThemeChange",
1458
- "onUnhandledRejection",
1459
- "onUnload"
1460
- ]
1461
- });
1462
-
1463
- const veeValidate = defineUnimportPreset({
1464
- from: "vee-validate",
1465
- imports: [
1466
- // https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
1467
- // https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
1468
- "validate",
1469
- "defineRule",
1470
- "configure",
1471
- "useField",
1472
- "useForm",
1473
- "useFieldArray",
1474
- "useResetForm",
1475
- "useIsFieldDirty",
1476
- "useIsFieldTouched",
1477
- "useIsFieldValid",
1478
- "useIsSubmitting",
1479
- "useValidateField",
1480
- "useIsFormDirty",
1481
- "useIsFormTouched",
1482
- "useIsFormValid",
1483
- "useValidateForm",
1484
- "useSubmitCount",
1485
- "useFieldValue",
1486
- "useFormValues",
1487
- "useFormErrors",
1488
- "useFieldError",
1489
- "useSubmitForm",
1490
- "FormContextKey",
1491
- "FieldContextKey"
1492
- ]
1493
- });
1494
-
1495
- const vitepress = defineUnimportPreset({
1496
- from: "vitepress",
1497
- imports: [
1498
- // helper methods
1499
- "useData",
1500
- "useRoute",
1501
- "useRouter",
1502
- "withBase"
1503
- ]
1504
- });
1505
-
1506
- const vitest = defineUnimportPreset({
1507
- from: "vitest",
1508
- imports: [
1509
- // suite
1510
- "suite",
1511
- "test",
1512
- "describe",
1513
- "it",
1514
- // chai
1515
- "chai",
1516
- "expect",
1517
- "assert",
1518
- // utils
1519
- "vitest",
1520
- "vi",
1521
- // hooks
1522
- "beforeAll",
1523
- "afterAll",
1524
- "beforeEach",
1525
- "afterEach"
1526
- ]
1527
- });
1528
-
1529
- const CommonCompositionAPI = [
1530
- // lifecycle
1531
- "onActivated",
1532
- "onBeforeMount",
1533
- "onBeforeUnmount",
1534
- "onBeforeUpdate",
1535
- "onErrorCaptured",
1536
- "onDeactivated",
1537
- "onMounted",
1538
- "onServerPrefetch",
1539
- "onUnmounted",
1540
- "onUpdated",
1541
- // setup helpers
1542
- "useAttrs",
1543
- "useSlots",
1544
- // reactivity,
1545
- "computed",
1546
- "customRef",
1547
- "isReadonly",
1548
- "isRef",
1549
- "isShallow",
1550
- "isProxy",
1551
- "isReactive",
1552
- "markRaw",
1553
- "reactive",
1554
- "readonly",
1555
- "ref",
1556
- "shallowReactive",
1557
- "shallowReadonly",
1558
- "shallowRef",
1559
- "triggerRef",
1560
- "toRaw",
1561
- "toRef",
1562
- "toRefs",
1563
- "toValue",
1564
- "unref",
1565
- "watch",
1566
- "watchEffect",
1567
- "watchPostEffect",
1568
- "watchSyncEffect",
1569
- // component
1570
- "defineComponent",
1571
- "defineAsyncComponent",
1572
- "getCurrentInstance",
1573
- "h",
1574
- "inject",
1575
- "nextTick",
1576
- "provide",
1577
- "useCssModule",
1578
- "createApp",
1579
- // effect scope
1580
- "effectScope",
1581
- "EffectScope",
1582
- "getCurrentScope",
1583
- "onScopeDispose",
1584
- // types
1585
- ...[
1586
- "Component",
1587
- "Slot",
1588
- "Slots",
1589
- "ComponentPublicInstance",
1590
- "ComputedRef",
1591
- "DirectiveBinding",
1592
- "ExtractDefaultPropTypes",
1593
- "ExtractPropTypes",
1594
- "ExtractPublicPropTypes",
1595
- "InjectionKey",
1596
- "PropType",
1597
- "Ref",
1598
- "ShallowRef",
1599
- "MaybeRef",
1600
- "MaybeRefOrGetter",
1601
- "VNode",
1602
- "WritableComputedRef"
1603
- ].map((name) => ({ name, type: true }))
1604
- ];
1605
- const vue = defineUnimportPreset({
1606
- from: "vue",
1607
- imports: [
1608
- ...CommonCompositionAPI,
1609
- // vue3 only
1610
- "onRenderTracked",
1611
- "onRenderTriggered",
1612
- "resolveComponent",
1613
- "useCssVars",
1614
- // vue3.4+
1615
- "useModel",
1616
- // vue3.5+
1617
- "getCurrentWatcher",
1618
- "onWatcherCleanup",
1619
- "useId",
1620
- "useTemplateRef"
1621
- ]
1622
- });
1623
-
1624
- const vueCompositionApi = defineUnimportPreset({
1625
- from: "@vue/composition-api",
1626
- imports: CommonCompositionAPI
1627
- });
1628
-
1629
- const vueDemi = defineUnimportPreset({
1630
- from: "vue-demi",
1631
- imports: CommonCompositionAPI
1632
- });
1633
-
1634
- const vueI18n = defineUnimportPreset({
1635
- from: "vue-i18n",
1636
- imports: [
1637
- "useI18n"
1638
- ]
1639
- });
1640
-
1641
- const vueMacros = defineUnimportPreset({
1642
- from: "vue/macros",
1643
- imports: [
1644
- // https://vuejs.org/guide/extras/reactivity-transform.html#refs-vs-reactive-variables
1645
- "$",
1646
- "$$",
1647
- "$ref",
1648
- "$shallowRef",
1649
- "$toRef",
1650
- "$customRef",
1651
- "$computed"
1652
- ]
1653
- });
1654
-
1655
- const vueRouter = defineUnimportPreset({
1656
- from: "vue-router",
1657
- imports: [
1658
- "useRouter",
1659
- "useRoute",
1660
- "useLink",
1661
- "onBeforeRouteLeave",
1662
- "onBeforeRouteUpdate"
1663
- ]
1664
- });
1665
-
1666
- const vueRouterComposables = defineUnimportPreset({
1667
- from: "vue-router/composables",
1668
- imports: [
1669
- "useRouter",
1670
- "useRoute",
1671
- "useLink",
1672
- "onBeforeRouteLeave",
1673
- "onBeforeRouteUpdate"
1674
- ]
1675
- });
1676
-
1677
- let _cache;
1678
- const vueuseCore = () => {
1679
- const excluded = ["toRefs", "utils"];
1680
- if (!_cache) {
1681
- try {
1682
- const corePath = resolveModule("@vueuse/core") || process$1.cwd();
1683
- const path = resolveModule("@vueuse/core/indexes.json") || resolveModule("@vueuse/metadata/index.json") || resolveModule("@vueuse/metadata/index.json", { paths: [corePath] });
1684
- const indexesJson = JSON.parse(readFileSync(path, "utf-8"));
1685
- _cache = defineUnimportPreset({
1686
- from: "@vueuse/core",
1687
- imports: indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).map((i) => i.name).filter((i) => i && i.length >= 4 && !excluded.includes(i))
1688
- });
1689
- } catch (error) {
1690
- console.error(error);
1691
- throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
1692
- }
1693
- }
1694
- return _cache;
1695
- };
1696
-
1697
- const vueuseHead = defineUnimportPreset({
1698
- from: "@vueuse/head",
1699
- imports: [
1700
- "useHead"
1701
- ]
1702
- });
1703
-
1704
- const vuex = defineUnimportPreset({
1705
- from: "vuex",
1706
- imports: [
1707
- // https://next.vuex.vuejs.org/api/#createstore
1708
- "createStore",
1709
- // https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
1710
- "createLogger",
1711
- // https://next.vuex.vuejs.org/api/#component-binding-helpers
1712
- "mapState",
1713
- "mapGetters",
1714
- "mapActions",
1715
- "mapMutations",
1716
- "createNamespacedHelpers",
1717
- // https://next.vuex.vuejs.org/api/#composable-functions
1718
- "useStore"
1719
- ]
1720
- });
1721
-
1722
- const builtinPresets = {
1723
- "@vue/composition-api": vueCompositionApi,
1724
- "@vueuse/core": vueuseCore,
1725
- "@vueuse/head": vueuseHead,
1726
- "pinia": pinia,
1727
- "preact": preact,
1728
- "quasar": quasar,
1729
- "react": react,
1730
- "react-router": reactRouter,
1731
- "react-router-dom": reactRouterDom,
1732
- "svelte": svelte,
1733
- "svelte/animate": svelteAnimate,
1734
- "svelte/easing": svelteEasing,
1735
- "svelte/motion": svelteMotion,
1736
- "svelte/store": svelteStore,
1737
- "svelte/transition": svelteTransition,
1738
- "vee-validate": veeValidate,
1739
- "vitepress": vitepress,
1740
- "vue-demi": vueDemi,
1741
- "vue-i18n": vueI18n,
1742
- "vue-router": vueRouter,
1743
- "vue-router-composables": vueRouterComposables,
1744
- "vue": vue,
1745
- "vue/macros": vueMacros,
1746
- "vuex": vuex,
1747
- "vitest": vitest,
1748
- "uni-app": uniApp,
1749
- "solid-js": solid,
1750
- "solid-app-router": solidAppRouter,
1751
- "rxjs": rxjs,
1752
- "date-fns": dateFns
1753
- };
1754
-
1755
- const commonProps = [
1756
- "from",
1757
- "priority",
1758
- "disabled",
1759
- "dtsDisabled",
1760
- "declarationType",
1761
- "meta",
1762
- "type",
1763
- "typeFrom"
1764
- ];
1765
- async function resolvePreset(preset) {
1766
- const imports = [];
1767
- if ("package" in preset)
1768
- return await resolvePackagePreset(preset);
1769
- const common = {};
1770
- commonProps.forEach((i) => {
1771
- if (i in preset) {
1772
- common[i] = preset[i];
1773
- }
1774
- });
1775
- for (const _import of preset.imports) {
1776
- if (typeof _import === "string")
1777
- imports.push({ ...common, name: _import, as: _import });
1778
- else if (Array.isArray(_import))
1779
- imports.push({ ...common, name: _import[0], as: _import[1] || _import[0], from: _import[2] || preset.from });
1780
- else if (_import.imports)
1781
- imports.push(...await resolvePreset(_import));
1782
- else
1783
- imports.push({ ...common, ..._import });
1784
- }
1785
- return imports;
1786
- }
1787
- async function resolveBuiltinPresets(presets) {
1788
- const resolved = await Promise.all(presets.map(async (p) => {
1789
- let preset = typeof p === "string" ? builtinPresets[p] : p;
1790
- if (typeof preset === "function")
1791
- preset = preset();
1792
- return await resolvePreset(preset);
1793
- }));
1794
- return resolved.flat();
1795
- }
1796
-
1797
- function createUnimport(opts) {
1798
- const ctx = createInternalContext(opts);
1799
- async function generateTypeDeclarations(options) {
1800
- const opts2 = {
1801
- resolvePath: (i) => stripFileExtension(i.typeFrom || i.from),
1802
- ...options
1803
- };
1804
- const {
1805
- typeReExports = true
1806
- } = opts2;
1807
- const imports = await ctx.getImports();
1808
- let dts = toTypeDeclarationFile(imports.filter((i) => !i.type && !i.dtsDisabled), opts2);
1809
- const typeOnly = imports.filter((i) => i.type);
1810
- if (typeReExports && typeOnly.length)
1811
- dts += `
1812
- ${toTypeReExports(typeOnly, opts2)}`;
1813
- for (const addon of ctx.addons)
1814
- dts = await addon.declaration?.call(ctx, dts, opts2) ?? dts;
1815
- return dts;
1816
- }
1817
- async function scanImportsFromFile(filepath, includeTypes = true) {
1818
- const additions = await scanExports(filepath, includeTypes);
1819
- await ctx.modifyDynamicImports((imports) => imports.filter((i) => i.from !== filepath).concat(additions));
1820
- return additions;
1821
- }
1822
- async function scanImportsFromDir(dirs = ctx.options.dirs || [], options = ctx.options.dirsScanOptions) {
1823
- const imports = await scanDirExports(dirs, options);
1824
- const files = new Set(imports.map((f) => f.from));
1825
- await ctx.modifyDynamicImports((i) => i.filter((i2) => !files.has(i2.from)).concat(imports));
1826
- return imports;
1827
- }
1828
- async function injectImportsWithContext(code, id, options) {
1829
- const result = await injectImports(code, id, ctx, {
1830
- ...opts,
1831
- ...options
1832
- });
1833
- const metadata = ctx.getMetadata();
1834
- if (metadata) {
1835
- result.imports.forEach((i) => {
1836
- metadata.injectionUsage[i.name] = metadata.injectionUsage[i.name] || { import: i, count: 0, moduleIds: [] };
1837
- metadata.injectionUsage[i.name].count++;
1838
- if (id && !metadata.injectionUsage[i.name].moduleIds.includes(id))
1839
- metadata.injectionUsage[i.name].moduleIds.push(id);
1840
- });
1841
- }
1842
- return result;
1843
- }
1844
- async function init() {
1845
- if (ctx.options.dirs?.length)
1846
- await scanImportsFromDir();
1847
- }
1848
- return {
1849
- version,
1850
- init,
1851
- clearDynamicImports: () => ctx.clearDynamicImports(),
1852
- modifyDynamicImports: (fn) => ctx.modifyDynamicImports(fn),
1853
- scanImportsFromDir,
1854
- scanImportsFromFile,
1855
- getImports: () => ctx.getImports(),
1856
- getImportMap: () => ctx.getImportMap(),
1857
- detectImports: (code) => detectImports(code, ctx),
1858
- injectImports: injectImportsWithContext,
1859
- generateTypeDeclarations: (options) => generateTypeDeclarations(options),
1860
- getMetadata: () => ctx.getMetadata(),
1861
- getInternalContext: () => ctx,
1862
- // Deprecated
1863
- toExports: async (filepath, includeTypes = false) => toExports(await ctx.getImports(), filepath, includeTypes)
1864
- };
1865
- }
1866
- function createInternalContext(opts) {
1867
- let _combinedImports;
1868
- const _map = /* @__PURE__ */ new Map();
1869
- const addons = configureAddons(opts);
1870
- opts.addons = addons;
1871
- opts.commentsDisable = opts.commentsDisable ?? ["@unimport-disable", "@imports-disable"];
1872
- opts.commentsDebug = opts.commentsDebug ?? ["@unimport-debug", "@imports-debug"];
1873
- let metadata;
1874
- if (opts.collectMeta) {
1875
- metadata = {
1876
- injectionUsage: {}
1877
- };
1878
- }
1879
- let resolvePromise;
1880
- const ctx = {
1881
- version,
1882
- options: opts,
1883
- addons,
1884
- staticImports: [...opts.imports || []].filter(Boolean),
1885
- dynamicImports: [],
1886
- modifyDynamicImports,
1887
- clearDynamicImports,
1888
- async getImports() {
1889
- await resolvePromise;
1890
- return updateImports();
1891
- },
1892
- async replaceImports(imports) {
1893
- ctx.staticImports = [...imports || []].filter(Boolean);
1894
- ctx.invalidate();
1895
- await resolvePromise;
1896
- return updateImports();
1897
- },
1898
- async getImportMap() {
1899
- await ctx.getImports();
1900
- return _map;
1901
- },
1902
- getMetadata() {
1903
- return metadata;
1904
- },
1905
- invalidate() {
1906
- _combinedImports = void 0;
1907
- },
1908
- resolveId: (id, parentId) => opts.resolveId?.(id, parentId)
1909
- };
1910
- resolvePromise = resolveBuiltinPresets(opts.presets || []).then((r) => {
1911
- ctx.staticImports.unshift(...r);
1912
- _combinedImports = void 0;
1913
- updateImports();
1914
- });
1915
- function updateImports() {
1916
- if (!_combinedImports) {
1917
- let imports = normalizeImports(dedupeImports([...ctx.staticImports, ...ctx.dynamicImports], opts.warn || console.warn));
1918
- for (const addon of ctx.addons) {
1919
- if (addon.extendImports)
1920
- imports = addon.extendImports.call(ctx, imports) ?? imports;
1921
- }
1922
- imports = imports.filter((i) => !i.disabled);
1923
- _map.clear();
1924
- for (const _import of imports) {
1925
- if (!_import.type)
1926
- _map.set(_import.as ?? _import.name, _import);
1927
- }
1928
- _combinedImports = imports;
1929
- }
1930
- return _combinedImports;
1931
- }
1932
- async function modifyDynamicImports(fn) {
1933
- const result = await fn(ctx.dynamicImports);
1934
- if (Array.isArray(result))
1935
- ctx.dynamicImports = result;
1936
- ctx.invalidate();
1937
- }
1938
- function clearDynamicImports() {
1939
- ctx.dynamicImports.length = 0;
1940
- ctx.invalidate();
1941
- }
1942
- return ctx;
1943
- }
1944
- async function injectImports(code, id, ctx, options) {
1945
- const s = getMagicString(code);
1946
- if (ctx.options.commentsDisable?.some((c) => s.original.includes(c))) {
1947
- return {
1948
- s,
1949
- get code() {
1950
- return s.toString();
1951
- },
1952
- imports: []
1953
- };
1954
- }
1955
- for (const addon of ctx.addons)
1956
- await addon.transform?.call(ctx, s, id);
1957
- const { isCJSContext, matchedImports, firstOccurrence } = await detectImports(s, ctx, options);
1958
- const imports = await resolveImports(ctx, matchedImports, id);
1959
- if (ctx.options.commentsDebug?.some((c) => s.original.includes(c))) {
1960
- const log = ctx.options.debugLog || console.log;
1961
- log(`[unimport] ${imports.length} imports detected in "${id}"${imports.length ? `: ${imports.map((i) => i.name).join(", ")}` : ""}`);
1962
- }
1963
- return {
1964
- ...addImportToCode(
1965
- s,
1966
- imports,
1967
- isCJSContext,
1968
- options?.mergeExisting,
1969
- options?.injectAtEnd,
1970
- firstOccurrence,
1971
- (imports2) => {
1972
- for (const addon of ctx.addons)
1973
- imports2 = addon.injectImportsResolved?.call(ctx, imports2, s, id) ?? imports2;
1974
- return imports2;
1975
- },
1976
- (str, imports2) => {
1977
- for (const addon of ctx.addons)
1978
- str = addon.injectImportsStringified?.call(ctx, str, imports2, s, id) ?? str;
1979
- return str;
1980
- }
1981
- ),
1982
- imports
1983
- };
1984
- }
1985
- async function resolveImports(ctx, imports, id) {
1986
- const resolveCache = /* @__PURE__ */ new Map();
1987
- const _imports = await Promise.all(imports.map(async (i) => {
1988
- if (!resolveCache.has(i.from))
1989
- resolveCache.set(i.from, await ctx.resolveId(i.from, id) || i.from);
1990
- const from = resolveCache.get(i.from);
1991
- if (i.from === id || !from || from === "." || from === id)
1992
- return;
1993
- return {
1994
- ...i,
1995
- from
1996
- };
1997
- }));
1998
- return _imports.filter(Boolean);
1999
- }
2000
-
2001
- const defaultIncludes = [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/];
2002
- const defaultExcludes = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/];
2003
- function toArray(x) {
2004
- return x == null ? [] : Array.isArray(x) ? x : [x];
2005
- }
2006
- const unplugin = createUnplugin((options = {}) => {
2007
- const ctx = createUnimport(options);
2008
- const filter = createFilter(
2009
- toArray(options.include || []).length ? options.include : defaultIncludes,
2010
- options.exclude || defaultExcludes
2011
- );
2012
- const dts = options.dts === true ? "unimport.d.ts" : options.dts;
2013
- const {
2014
- autoImport = true
2015
- } = options;
2016
- return {
2017
- name: "unimport",
2018
- enforce: "post",
2019
- transformInclude(id) {
2020
- return filter(id);
2021
- },
2022
- async transform(code, id) {
2023
- const s = new MagicString(code);
2024
- await ctx.injectImports(s, id, {
2025
- autoImport
2026
- });
2027
- if (!s.hasChanged())
2028
- return;
2029
- return {
2030
- code: s.toString(),
2031
- map: s.generateMap()
2032
- };
2033
- },
2034
- async buildStart() {
2035
- await ctx.init();
2036
- if (dts)
2037
- return promises.writeFile(dts, await ctx.generateTypeDeclarations(), "utf-8");
2038
- }
2039
- };
2040
- });
2041
-
2042
- async function detectImportsAcorn(code, ctx, options) {
2043
- const s = getMagicString(code);
2044
- const map = await ctx.getImportMap();
2045
- let matchedImports = [];
2046
- const enableAutoImport = options?.autoImport !== false;
2047
- const enableTransformVirtualImports = options?.transformVirtualImports !== false && ctx.options.virtualImports?.length;
2048
- if (enableAutoImport || enableTransformVirtualImports) {
2049
- const ast = parse$1(s.original, {
2050
- sourceType: "module",
2051
- ecmaVersion: "latest",
2052
- locations: true
2053
- });
2054
- const virtualImports = createVirtualImportsAcronWalker(map, ctx.options.virtualImports);
2055
- const scopes = traveseScopes(
2056
- ast,
2057
- enableTransformVirtualImports ? virtualImports.walk : {}
2058
- );
2059
- if (enableAutoImport) {
2060
- const identifiers = scopes.unmatched;
2061
- matchedImports.push(
2062
- ...Array.from(identifiers).map((name) => {
2063
- const item = map.get(name);
2064
- if (item && !item.disabled)
2065
- return item;
2066
- return null;
2067
- }).filter(Boolean)
2068
- );
2069
- for (const addon of ctx.addons)
2070
- matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
2071
- }
2072
- virtualImports.ranges.forEach(([start, end]) => {
2073
- s.remove(start, end);
2074
- });
2075
- matchedImports.push(...virtualImports.imports);
2076
- }
2077
- return {
2078
- s,
2079
- strippedCode: code.toString(),
2080
- matchedImports,
2081
- isCJSContext: false,
2082
- firstOccurrence: 0
2083
- // TODO:
2084
- };
2085
- }
2086
- function traveseScopes(ast, additionalWalk) {
2087
- const scopes = [];
2088
- let scopeCurrent = void 0;
2089
- const scopesStack = [];
2090
- function pushScope(node) {
2091
- scopeCurrent = {
2092
- node,
2093
- parent: scopeCurrent,
2094
- declarations: /* @__PURE__ */ new Set(),
2095
- references: /* @__PURE__ */ new Set()
2096
- };
2097
- scopes.push(scopeCurrent);
2098
- scopesStack.push(scopeCurrent);
2099
- }
2100
- function popScope(node) {
2101
- const scope = scopesStack.pop();
2102
- if (scope?.node !== node)
2103
- throw new Error("Scope mismatch");
2104
- scopeCurrent = scopesStack[scopesStack.length - 1];
2105
- }
2106
- pushScope(void 0);
2107
- walk(ast, {
2108
- enter(node, parent, prop, index) {
2109
- additionalWalk?.enter?.call(this, node, parent, prop, index);
2110
- switch (node.type) {
2111
- // ====== Declaration ======
2112
- case "ImportSpecifier":
2113
- case "ImportDefaultSpecifier":
2114
- case "ImportNamespaceSpecifier":
2115
- scopeCurrent.declarations.add(node.local.name);
2116
- return;
2117
- case "FunctionDeclaration":
2118
- case "ClassDeclaration":
2119
- if (node.id)
2120
- scopeCurrent.declarations.add(node.id.name);
2121
- return;
2122
- case "VariableDeclarator":
2123
- if (node.id.type === "Identifier") {
2124
- scopeCurrent.declarations.add(node.id.name);
2125
- } else {
2126
- walk(node.id, {
2127
- enter(node2) {
2128
- if (node2.type === "ObjectPattern") {
2129
- node2.properties.forEach((i) => {
2130
- if (i.type === "Property" && i.value.type === "Identifier")
2131
- scopeCurrent.declarations.add(i.value.name);
2132
- else if (i.type === "RestElement" && i.argument.type === "Identifier")
2133
- scopeCurrent.declarations.add(i.argument.name);
2134
- });
2135
- } else if (node2.type === "ArrayPattern") {
2136
- node2.elements.forEach((i) => {
2137
- if (i?.type === "Identifier")
2138
- scopeCurrent.declarations.add(i.name);
2139
- if (i?.type === "RestElement" && i.argument.type === "Identifier")
2140
- scopeCurrent.declarations.add(i.argument.name);
2141
- });
2142
- }
2143
- }
2144
- });
2145
- }
2146
- return;
2147
- // ====== Scope ======
2148
- case "BlockStatement":
2149
- pushScope(node);
2150
- return;
2151
- // ====== Reference ======
2152
- case "Identifier":
2153
- switch (parent?.type) {
2154
- case "CallExpression":
2155
- if (parent.callee === node || parent.arguments.includes(node))
2156
- scopeCurrent.references.add(node.name);
2157
- return;
2158
- case "MemberExpression":
2159
- if (parent.object === node)
2160
- scopeCurrent.references.add(node.name);
2161
- return;
2162
- case "VariableDeclarator":
2163
- if (parent.init === node)
2164
- scopeCurrent.references.add(node.name);
2165
- return;
2166
- case "SpreadElement":
2167
- if (parent.argument === node)
2168
- scopeCurrent.references.add(node.name);
2169
- return;
2170
- case "ClassDeclaration":
2171
- if (parent.superClass === node)
2172
- scopeCurrent.references.add(node.name);
2173
- return;
2174
- case "Property":
2175
- if (parent.value === node)
2176
- scopeCurrent.references.add(node.name);
2177
- return;
2178
- case "TemplateLiteral":
2179
- if (parent.expressions.includes(node))
2180
- scopeCurrent.references.add(node.name);
2181
- return;
2182
- case "AssignmentExpression":
2183
- if (parent.right === node)
2184
- scopeCurrent.references.add(node.name);
2185
- return;
2186
- case "IfStatement":
2187
- case "WhileStatement":
2188
- case "DoWhileStatement":
2189
- if (parent.test === node)
2190
- scopeCurrent.references.add(node.name);
2191
- return;
2192
- case "SwitchStatement":
2193
- if (parent.discriminant === node)
2194
- scopeCurrent.references.add(node.name);
2195
- return;
2196
- }
2197
- if (parent?.type.includes("Expression"))
2198
- scopeCurrent.references.add(node.name);
2199
- }
2200
- },
2201
- leave(node, parent, prop, index) {
2202
- additionalWalk?.leave?.call(this, node, parent, prop, index);
2203
- switch (node.type) {
2204
- case "BlockStatement":
2205
- popScope(node);
2206
- }
2207
- }
2208
- });
2209
- const unmatched = /* @__PURE__ */ new Set();
2210
- for (const scope of scopes) {
2211
- for (const name of scope.references) {
2212
- let defined = false;
2213
- let parent = scope;
2214
- while (parent) {
2215
- if (parent.declarations.has(name)) {
2216
- defined = true;
2217
- break;
2218
- }
2219
- parent = parent?.parent;
2220
- }
2221
- if (!defined)
2222
- unmatched.add(name);
2223
- }
2224
- }
2225
- return {
2226
- unmatched,
2227
- scopes
2228
- };
2229
- }
2230
- function createVirtualImportsAcronWalker(importMap, virtualImports = []) {
2231
- const imports = [];
2232
- const ranges = [];
2233
- return {
2234
- imports,
2235
- ranges,
2236
- walk: {
2237
- enter(node) {
2238
- if (node.type === "ImportDeclaration") {
2239
- if (virtualImports.includes(node.source.value)) {
2240
- ranges.push([node.start, node.end]);
2241
- node.specifiers.forEach((i) => {
2242
- if (i.type === "ImportSpecifier" && i.imported.type === "Identifier") {
2243
- const original = importMap.get(i.imported.name);
2244
- if (!original)
2245
- throw new Error(`[unimport] failed to find "${i.imported.name}" imported from "${node.source.value}"`);
2246
- imports.push({
2247
- from: original.from,
2248
- name: original.name,
2249
- as: i.local.name
2250
- });
2251
- }
2252
- });
2253
- }
2254
- }
2255
- }
2256
- }
2257
- };
2258
- }
2259
-
2260
- const detectAcorn = {
2261
- __proto__: null,
2262
- createVirtualImportsAcronWalker: createVirtualImportsAcronWalker,
2263
- detectImportsAcorn: detectImportsAcorn,
2264
- traveseScopes: traveseScopes
2265
- };
2266
-
2267
- export { createUnimport as c, toExports as t, unplugin as u };