nitro-nightly 3.0.1-20260106-122901-e9c3a660 → 3.0.1-20260106-182834-5019d347

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 (72) hide show
  1. package/dist/_build/rolldown.mjs +11 -11
  2. package/dist/_build/rollup.mjs +19 -11
  3. package/dist/_build/shared.mjs +3 -2
  4. package/dist/_build/shared2.mjs +1 -1
  5. package/dist/_build/shared3.mjs +2 -2
  6. package/dist/_build/vite.build.mjs +8 -9
  7. package/dist/_dev.mjs +4 -3
  8. package/dist/_libs/@hiogawa/vite-plugin-fullstack.mjs +6 -1561
  9. package/dist/_libs/@jridgewell/gen-mapping.mjs +2 -304
  10. package/dist/_libs/@jridgewell/remapping.mjs +2 -1
  11. package/dist/_libs/@jridgewell/resolve-uri.mjs +166 -0
  12. package/dist/_libs/@jridgewell/sourcemap-codec.mjs +167 -0
  13. package/dist/_libs/@jridgewell/trace-mapping.mjs +141 -0
  14. package/dist/_libs/@rolldown/pluginutils.mjs +31 -0
  15. package/dist/_libs/@rollup/plugin-commonjs.mjs +33 -2636
  16. package/dist/_libs/@rollup/plugin-inject.mjs +3 -2
  17. package/dist/_libs/@rollup/plugin-json.mjs +1 -1
  18. package/dist/_libs/@rollup/plugin-node-resolve.mjs +8 -1112
  19. package/dist/_libs/@rollup/plugin-replace.mjs +2 -2
  20. package/dist/_libs/@rollup/pluginutils.mjs +241 -0
  21. package/dist/_libs/c12.mjs +63 -2513
  22. package/dist/_libs/chokidar.mjs +2 -235
  23. package/dist/_libs/commondir.mjs +22 -0
  24. package/dist/_libs/confbox.mjs +1511 -911
  25. package/dist/_libs/deepmerge.mjs +86 -0
  26. package/dist/_libs/dotenv.mjs +345 -0
  27. package/dist/_libs/estree-walker.mjs +144 -1
  28. package/dist/_libs/exsolve.mjs +1007 -0
  29. package/dist/_libs/fdir.mjs +514 -0
  30. package/dist/_libs/function-bind.mjs +63 -0
  31. package/dist/_libs/giget.mjs +1380 -2238
  32. package/dist/_libs/hasown.mjs +14 -0
  33. package/dist/_libs/is-core-module.mjs +220 -0
  34. package/dist/_libs/is-module.mjs +13 -0
  35. package/dist/_libs/is-reference.mjs +33 -0
  36. package/dist/_libs/js-tokens.mjs +382 -0
  37. package/dist/_libs/local-pkg.mjs +7 -1561
  38. package/dist/_libs/magic-string.mjs +939 -0
  39. package/dist/_libs/mlly.mjs +1415 -0
  40. package/dist/_libs/node-fetch-native.mjs +7 -0
  41. package/dist/_libs/nypm.mjs +239 -0
  42. package/dist/_libs/path-parse.mjs +47 -0
  43. package/dist/_libs/pathe.mjs +163 -2
  44. package/dist/_libs/perfect-debounce.mjs +89 -0
  45. package/dist/_libs/picomatch.mjs +1673 -0
  46. package/dist/_libs/pkg-types.mjs +197 -0
  47. package/dist/_libs/quansync.mjs +90 -0
  48. package/dist/_libs/rc9.mjs +136 -0
  49. package/dist/_libs/readdirp.mjs +237 -0
  50. package/dist/_libs/resolve.mjs +689 -0
  51. package/dist/_libs/strip-literal.mjs +51 -0
  52. package/dist/_libs/tinyexec.mjs +627 -0
  53. package/dist/_libs/tinyglobby.mjs +2 -1
  54. package/dist/_libs/tsconfck.mjs +1 -1
  55. package/dist/_libs/unimport.mjs +93 -1617
  56. package/dist/_libs/unplugin-utils.mjs +61 -0
  57. package/dist/_libs/unplugin.mjs +1225 -0
  58. package/dist/_libs/unwasm.mjs +3 -2
  59. package/dist/_libs/webpack-virtual-modules.mjs +272 -0
  60. package/dist/_nitro.mjs +9 -7
  61. package/dist/_nitro2.mjs +6 -7
  62. package/dist/_presets.mjs +9 -7
  63. package/dist/builder.mjs +5 -5
  64. package/dist/cli/_chunks/build.mjs +1 -1
  65. package/dist/cli/_chunks/dev.mjs +1 -1
  66. package/dist/cli/_chunks/list.mjs +1 -1
  67. package/dist/cli/_chunks/prepare.mjs +1 -1
  68. package/dist/cli/_chunks/run.mjs +1 -1
  69. package/dist/vite.mjs +1825 -22
  70. package/package.json +2 -2
  71. package/dist/_build/shared4.mjs +0 -1112
  72. package/dist/_build/vite.plugin.mjs +0 -712
@@ -0,0 +1,1225 @@
1
+ import { i as __toESM } from "../_rolldown.mjs";
2
+ import { t as require_picomatch } from "./picomatch.mjs";
3
+ import { t as Parser } from "./acorn.mjs";
4
+ import { t as remapping } from "./@jridgewell/remapping.mjs";
5
+ import { t as require_lib } from "./webpack-virtual-modules.mjs";
6
+ import { createRequire } from "node:module";
7
+ import fs from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import path, { basename, dirname, extname, isAbsolute, normalize, resolve } from "node:path";
10
+ import process$1 from "node:process";
11
+ import { Buffer } from "node:buffer";
12
+ import * as querystring from "node:querystring";
13
+
14
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/context-Csj9j3eN.js
15
+ var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
16
+ function toArray(array) {
17
+ array = array || [];
18
+ if (Array.isArray(array)) return array;
19
+ return [array];
20
+ }
21
+ const BACKSLASH_REGEX = /\\/g;
22
+ function normalize$1(path$1) {
23
+ return path$1.replace(BACKSLASH_REGEX, "/");
24
+ }
25
+ const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i;
26
+ function isAbsolute$1(path$1) {
27
+ return ABSOLUTE_PATH_REGEX.test(path$1);
28
+ }
29
+ function getMatcherString(glob, cwd$1) {
30
+ if (glob.startsWith("**") || isAbsolute$1(glob)) return normalize$1(glob);
31
+ return normalize$1(resolve(cwd$1, glob));
32
+ }
33
+ function patternToIdFilter(pattern) {
34
+ if (pattern instanceof RegExp) return (id) => {
35
+ const normalizedId = normalize$1(id);
36
+ const result = pattern.test(normalizedId);
37
+ pattern.lastIndex = 0;
38
+ return result;
39
+ };
40
+ const matcher = (0, import_picomatch.default)(getMatcherString(pattern, process.cwd()), { dot: true });
41
+ return (id) => {
42
+ return matcher(normalize$1(id));
43
+ };
44
+ }
45
+ function patternToCodeFilter(pattern) {
46
+ if (pattern instanceof RegExp) return (code) => {
47
+ const result = pattern.test(code);
48
+ pattern.lastIndex = 0;
49
+ return result;
50
+ };
51
+ return (code) => code.includes(pattern);
52
+ }
53
+ function createFilter(exclude, include) {
54
+ if (!exclude && !include) return;
55
+ return (input) => {
56
+ if (exclude?.some((filter) => filter(input))) return false;
57
+ if (include?.some((filter) => filter(input))) return true;
58
+ return !(include && include.length > 0);
59
+ };
60
+ }
61
+ function normalizeFilter(filter) {
62
+ if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
63
+ if (Array.isArray(filter)) return { include: filter };
64
+ return {
65
+ exclude: filter.exclude ? toArray(filter.exclude) : void 0,
66
+ include: filter.include ? toArray(filter.include) : void 0
67
+ };
68
+ }
69
+ function createIdFilter(filter) {
70
+ if (!filter) return;
71
+ const { exclude, include } = normalizeFilter(filter);
72
+ const excludeFilter = exclude?.map(patternToIdFilter);
73
+ const includeFilter = include?.map(patternToIdFilter);
74
+ return createFilter(excludeFilter, includeFilter);
75
+ }
76
+ function createCodeFilter(filter) {
77
+ if (!filter) return;
78
+ const { exclude, include } = normalizeFilter(filter);
79
+ const excludeFilter = exclude?.map(patternToCodeFilter);
80
+ const includeFilter = include?.map(patternToCodeFilter);
81
+ return createFilter(excludeFilter, includeFilter);
82
+ }
83
+ function createFilterForId(filter) {
84
+ const filterFunction = createIdFilter(filter);
85
+ return filterFunction ? (id) => !!filterFunction(id) : void 0;
86
+ }
87
+ function createFilterForTransform(idFilter, codeFilter) {
88
+ if (!idFilter && !codeFilter) return;
89
+ const idFilterFunction = createIdFilter(idFilter);
90
+ const codeFilterFunction = createCodeFilter(codeFilter);
91
+ return (id, code) => {
92
+ let fallback = true;
93
+ if (idFilterFunction) fallback &&= idFilterFunction(id);
94
+ if (!fallback) return false;
95
+ if (codeFilterFunction) fallback &&= codeFilterFunction(code);
96
+ return fallback;
97
+ };
98
+ }
99
+ function normalizeObjectHook(name, hook) {
100
+ let handler;
101
+ let filter;
102
+ if (typeof hook === "function") handler = hook;
103
+ else {
104
+ handler = hook.handler;
105
+ const hookFilter = hook.filter;
106
+ if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id);
107
+ else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code);
108
+ }
109
+ return {
110
+ handler,
111
+ filter: filter || (() => true)
112
+ };
113
+ }
114
+ function parse(code, opts = {}) {
115
+ return Parser.parse(code, {
116
+ sourceType: "module",
117
+ ecmaVersion: "latest",
118
+ locations: true,
119
+ ...opts
120
+ });
121
+ }
122
+
123
+ //#endregion
124
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/webpack-like-DFGTNSuV.js
125
+ function transformUse(data, plugin, transformLoader) {
126
+ if (data.resource == null) return [];
127
+ const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
128
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return [];
129
+ const { filter } = normalizeObjectHook("load", plugin.transform);
130
+ if (!filter(id)) return [];
131
+ return [{
132
+ loader: transformLoader,
133
+ options: { plugin },
134
+ ident: plugin.name
135
+ }];
136
+ }
137
+ /**
138
+ * Normalizes a given path when it's absolute. Normalizing means returning a new path by converting
139
+ * the input path to the native os format. This is useful in cases where we want to normalize
140
+ * the `id` argument of a hook. Any absolute ids should be in the default format
141
+ * of the operating system. Any relative imports or node_module imports should remain
142
+ * untouched.
143
+ *
144
+ * @param path - Path to normalize.
145
+ * @returns a new normalized path.
146
+ */
147
+ function normalizeAbsolutePath(path$1) {
148
+ if (isAbsolute(path$1)) return normalize(path$1);
149
+ else return path$1;
150
+ }
151
+
152
+ //#endregion
153
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/context-DkYlx1xL.js
154
+ function createBuildContext$1(compiler, compilation, loaderContext, inputSourceMap) {
155
+ return {
156
+ getNativeBuildContext() {
157
+ return {
158
+ framework: "rspack",
159
+ compiler,
160
+ compilation,
161
+ loaderContext,
162
+ inputSourceMap
163
+ };
164
+ },
165
+ addWatchFile(file) {
166
+ const cwd$1 = process.cwd();
167
+ compilation.fileDependencies.add(resolve(cwd$1, file));
168
+ },
169
+ getWatchFiles() {
170
+ return Array.from(compilation.fileDependencies);
171
+ },
172
+ parse,
173
+ emitFile(emittedFile) {
174
+ const outFileName = emittedFile.fileName || emittedFile.name;
175
+ if (emittedFile.source && outFileName) {
176
+ const { sources } = compilation.compiler.webpack;
177
+ compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)));
178
+ }
179
+ }
180
+ };
181
+ }
182
+ function normalizeMessage$1(error) {
183
+ const err = new Error(typeof error === "string" ? error : error.message);
184
+ if (typeof error === "object") {
185
+ err.stack = error.stack;
186
+ err.cause = error.meta;
187
+ }
188
+ return err;
189
+ }
190
+
191
+ //#endregion
192
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/utils-BosfZ0pB.js
193
+ function encodeVirtualModuleId(id, plugin) {
194
+ return resolve(plugin.__virtualModulePrefix, encodeURIComponent(id));
195
+ }
196
+ function decodeVirtualModuleId(encoded, _plugin) {
197
+ return decodeURIComponent(basename(encoded));
198
+ }
199
+ function isVirtualModuleId(encoded, plugin) {
200
+ return dirname(encoded) === plugin.__virtualModulePrefix;
201
+ }
202
+ var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin$1 {
203
+ name = "FakeVirtualModulesPlugin";
204
+ static counters = /* @__PURE__ */ new Map();
205
+ static initCleanup = false;
206
+ constructor(plugin) {
207
+ this.plugin = plugin;
208
+ if (!FakeVirtualModulesPlugin$1.initCleanup) {
209
+ FakeVirtualModulesPlugin$1.initCleanup = true;
210
+ process.once("exit", () => {
211
+ FakeVirtualModulesPlugin$1.counters.forEach((_, dir) => {
212
+ fs.rmSync(dir, {
213
+ recursive: true,
214
+ force: true
215
+ });
216
+ });
217
+ });
218
+ }
219
+ }
220
+ apply(compiler) {
221
+ const dir = this.plugin.__virtualModulePrefix;
222
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
223
+ const counter = FakeVirtualModulesPlugin$1.counters.get(dir) ?? 0;
224
+ FakeVirtualModulesPlugin$1.counters.set(dir, counter + 1);
225
+ compiler.hooks.shutdown.tap(this.name, () => {
226
+ const counter$1 = (FakeVirtualModulesPlugin$1.counters.get(dir) ?? 1) - 1;
227
+ if (counter$1 === 0) {
228
+ FakeVirtualModulesPlugin$1.counters.delete(dir);
229
+ fs.rmSync(dir, {
230
+ recursive: true,
231
+ force: true
232
+ });
233
+ } else FakeVirtualModulesPlugin$1.counters.set(dir, counter$1);
234
+ });
235
+ }
236
+ async writeModule(file) {
237
+ return fs.promises.writeFile(file, "");
238
+ }
239
+ };
240
+
241
+ //#endregion
242
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/context-OCFO8EW1.js
243
+ function contextOptionsFromCompilation(compilation) {
244
+ return {
245
+ addWatchFile(file) {
246
+ (compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
247
+ },
248
+ getWatchFiles() {
249
+ return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
250
+ }
251
+ };
252
+ }
253
+ const require = createRequire(import.meta.url);
254
+ function getSource(fileSource) {
255
+ return new (require("webpack")).sources.RawSource(typeof fileSource === "string" ? fileSource : Buffer.from(fileSource.buffer));
256
+ }
257
+ function createBuildContext(options, compiler, compilation, loaderContext, inputSourceMap) {
258
+ return {
259
+ parse,
260
+ addWatchFile(id) {
261
+ options.addWatchFile(resolve(process$1.cwd(), id));
262
+ },
263
+ emitFile(emittedFile) {
264
+ const outFileName = emittedFile.fileName || emittedFile.name;
265
+ if (emittedFile.source && outFileName) {
266
+ if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
267
+ compilation.emitAsset(outFileName, getSource(emittedFile.source));
268
+ }
269
+ },
270
+ getWatchFiles() {
271
+ return options.getWatchFiles();
272
+ },
273
+ getNativeBuildContext() {
274
+ return {
275
+ framework: "webpack",
276
+ compiler,
277
+ compilation,
278
+ loaderContext,
279
+ inputSourceMap
280
+ };
281
+ }
282
+ };
283
+ }
284
+ function normalizeMessage(error) {
285
+ const err = new Error(typeof error === "string" ? error : error.message);
286
+ if (typeof error === "object") {
287
+ err.stack = error.stack;
288
+ err.cause = error.meta;
289
+ }
290
+ return err;
291
+ }
292
+
293
+ //#endregion
294
+ //#region node_modules/.pnpm/unplugin@2.3.11/node_modules/unplugin/dist/index.js
295
+ var import_lib = /* @__PURE__ */ __toESM(require_lib(), 1);
296
+ const ExtToLoader = {
297
+ ".js": "js",
298
+ ".mjs": "js",
299
+ ".cjs": "js",
300
+ ".jsx": "jsx",
301
+ ".ts": "ts",
302
+ ".cts": "ts",
303
+ ".mts": "ts",
304
+ ".tsx": "tsx",
305
+ ".css": "css",
306
+ ".less": "css",
307
+ ".stylus": "css",
308
+ ".scss": "css",
309
+ ".sass": "css",
310
+ ".json": "json",
311
+ ".txt": "text"
312
+ };
313
+ function guessLoader(code, id) {
314
+ return ExtToLoader[path.extname(id).toLowerCase()] || "js";
315
+ }
316
+ function unwrapLoader(loader, code, id) {
317
+ if (typeof loader === "function") return loader(code, id);
318
+ return loader;
319
+ }
320
+ function fixSourceMap(map) {
321
+ if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", {
322
+ enumerable: false,
323
+ value: function toString() {
324
+ return JSON.stringify(this);
325
+ }
326
+ });
327
+ if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", {
328
+ enumerable: false,
329
+ value: function toUrl() {
330
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString("base64")}`;
331
+ }
332
+ });
333
+ return map;
334
+ }
335
+ const nullSourceMap = {
336
+ names: [],
337
+ sources: [],
338
+ mappings: "",
339
+ version: 3
340
+ };
341
+ function combineSourcemaps(filename, sourcemapList) {
342
+ sourcemapList = sourcemapList.filter((m) => m.sources);
343
+ if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
344
+ let map;
345
+ let mapIndex = 1;
346
+ if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map = remapping(sourcemapList, () => null, true);
347
+ else map = remapping(sourcemapList[0], (sourcefile) => {
348
+ if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
349
+ else return { ...nullSourceMap };
350
+ }, true);
351
+ if (!map.file) delete map.file;
352
+ return map;
353
+ }
354
+ function createBuildContext$2(build) {
355
+ const watchFiles = [];
356
+ const { initialOptions } = build;
357
+ return {
358
+ parse,
359
+ addWatchFile() {
360
+ throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
361
+ },
362
+ emitFile(emittedFile) {
363
+ const outFileName = emittedFile.fileName || emittedFile.name;
364
+ if (initialOptions.outdir && emittedFile.source && outFileName) {
365
+ const outPath = path.resolve(initialOptions.outdir, outFileName);
366
+ const outDir = path.dirname(outPath);
367
+ if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
368
+ fs.writeFileSync(outPath, emittedFile.source);
369
+ }
370
+ },
371
+ getWatchFiles() {
372
+ return watchFiles;
373
+ },
374
+ getNativeBuildContext() {
375
+ return {
376
+ framework: "esbuild",
377
+ build
378
+ };
379
+ }
380
+ };
381
+ }
382
+ function createPluginContext(context) {
383
+ const errors = [];
384
+ const warnings = [];
385
+ const pluginContext = {
386
+ error(message) {
387
+ errors.push(normalizeMessage$2(message));
388
+ },
389
+ warn(message) {
390
+ warnings.push(normalizeMessage$2(message));
391
+ }
392
+ };
393
+ return {
394
+ errors,
395
+ warnings,
396
+ mixedContext: {
397
+ ...context,
398
+ ...pluginContext,
399
+ addWatchFile(id) {
400
+ context.getWatchFiles().push(id);
401
+ }
402
+ }
403
+ };
404
+ }
405
+ function normalizeMessage$2(message) {
406
+ if (typeof message === "string") message = { message };
407
+ return {
408
+ id: message.id,
409
+ pluginName: message.plugin,
410
+ text: message.message,
411
+ location: message.loc ? {
412
+ file: message.loc.file,
413
+ line: message.loc.line,
414
+ column: message.loc.column
415
+ } : null,
416
+ detail: message.meta,
417
+ notes: []
418
+ };
419
+ }
420
+ function processCodeWithSourceMap(map, code) {
421
+ if (map) {
422
+ if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code];
423
+ map = fixSourceMap(map);
424
+ code += `\n//# sourceMappingURL=${map.toUrl()}`;
425
+ }
426
+ return code;
427
+ }
428
+ function getEsbuildPlugin(factory) {
429
+ return (userOptions) => {
430
+ const meta = { framework: "esbuild" };
431
+ const plugins = toArray(factory(userOptions, meta));
432
+ const setupPlugins = async (build) => {
433
+ const setup = buildSetup();
434
+ const loaders = [];
435
+ for (const plugin of plugins) {
436
+ const loader = {};
437
+ await setup(plugin)({
438
+ ...build,
439
+ onLoad(_options, callback) {
440
+ loader.options = _options;
441
+ loader.onLoadCb = callback;
442
+ },
443
+ onTransform(_options, callback) {
444
+ loader.options ||= _options;
445
+ loader.onTransformCb = callback;
446
+ }
447
+ }, build);
448
+ if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader);
449
+ }
450
+ if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
451
+ function checkFilter(options) {
452
+ return loaders.length === 1 || !options?.filter || options.filter.test(args.path);
453
+ }
454
+ let result;
455
+ for (const { options, onLoadCb } of loaders) {
456
+ if (!checkFilter(options)) continue;
457
+ if (onLoadCb) result = await onLoadCb(args);
458
+ if (result?.contents) break;
459
+ }
460
+ let fsContentsCache;
461
+ for (const { options, onTransformCb } of loaders) {
462
+ if (!checkFilter(options)) continue;
463
+ if (onTransformCb) {
464
+ const _result = await onTransformCb({
465
+ ...result,
466
+ ...args,
467
+ async getContents() {
468
+ if (result?.contents) return result.contents;
469
+ if (fsContentsCache) return fsContentsCache;
470
+ return fsContentsCache = await fs.promises.readFile(args.path, "utf8");
471
+ }
472
+ });
473
+ if (_result?.contents) result = _result;
474
+ }
475
+ }
476
+ if (result?.contents) return result;
477
+ });
478
+ };
479
+ return {
480
+ name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
481
+ setup: setupPlugins
482
+ };
483
+ };
484
+ }
485
+ function buildSetup() {
486
+ return (plugin) => {
487
+ return (build, rawBuild) => {
488
+ const context = createBuildContext$2(rawBuild);
489
+ const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build;
490
+ const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
491
+ const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
492
+ const loader = plugin.esbuild?.loader ?? guessLoader;
493
+ plugin.esbuild?.config?.call(context, initialOptions);
494
+ if (plugin.buildStart) onStart(() => plugin.buildStart.call(context));
495
+ if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => {
496
+ if (plugin.buildEnd) await plugin.buildEnd.call(context);
497
+ if (plugin.writeBundle) await plugin.writeBundle();
498
+ });
499
+ if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => {
500
+ const id = args.path;
501
+ if (initialOptions.external?.includes(id)) return;
502
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
503
+ if (!filter(id)) return;
504
+ const { errors, warnings, mixedContext } = createPluginContext(context);
505
+ const isEntry = args.kind === "entry-point";
506
+ const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry });
507
+ if (typeof result === "string") return {
508
+ path: result,
509
+ namespace: plugin.name,
510
+ errors,
511
+ warnings,
512
+ watchFiles: mixedContext.getWatchFiles()
513
+ };
514
+ else if (typeof result === "object" && result !== null) return {
515
+ path: result.id,
516
+ external: result.external,
517
+ namespace: plugin.name,
518
+ errors,
519
+ warnings,
520
+ watchFiles: mixedContext.getWatchFiles()
521
+ };
522
+ });
523
+ if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => {
524
+ const { handler, filter } = normalizeObjectHook("load", plugin.load);
525
+ const id = args.path + (args.suffix || "");
526
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return;
527
+ if (!filter(id)) return;
528
+ const { errors, warnings, mixedContext } = createPluginContext(context);
529
+ let code;
530
+ let map;
531
+ const result = await handler.call(mixedContext, id);
532
+ if (typeof result === "string") code = result;
533
+ else if (typeof result === "object" && result !== null) {
534
+ code = result.code;
535
+ map = result.map;
536
+ }
537
+ if (code === void 0) return null;
538
+ if (map) code = processCodeWithSourceMap(map, code);
539
+ const resolveDir = path.dirname(args.path);
540
+ return {
541
+ contents: code,
542
+ errors,
543
+ warnings,
544
+ watchFiles: mixedContext.getWatchFiles(),
545
+ loader: unwrapLoader(loader, code, args.path),
546
+ resolveDir
547
+ };
548
+ });
549
+ if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => {
550
+ const { handler, filter } = normalizeObjectHook("transform", plugin.transform);
551
+ const id = args.path + (args.suffix || "");
552
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return;
553
+ let code = await args.getContents();
554
+ if (!filter(id, code)) return;
555
+ const { mixedContext, errors, warnings } = createPluginContext(context);
556
+ const resolveDir = path.dirname(args.path);
557
+ let map;
558
+ const result = await handler.call(mixedContext, code, id);
559
+ if (typeof result === "string") code = result;
560
+ else if (typeof result === "object" && result !== null) {
561
+ code = result.code;
562
+ if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]);
563
+ else if (typeof result.map === "string") map = JSON.parse(result.map);
564
+ else map = result.map;
565
+ }
566
+ if (code) {
567
+ if (map) code = processCodeWithSourceMap(map, code);
568
+ return {
569
+ contents: code,
570
+ errors,
571
+ warnings,
572
+ watchFiles: mixedContext.getWatchFiles(),
573
+ loader: unwrapLoader(loader, code, args.path),
574
+ resolveDir
575
+ };
576
+ }
577
+ });
578
+ if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild);
579
+ };
580
+ };
581
+ }
582
+ function createFarmContext(context, currentResolveId) {
583
+ return {
584
+ parse,
585
+ addWatchFile(id) {
586
+ context.addWatchFile(id, currentResolveId || id);
587
+ },
588
+ emitFile(emittedFile) {
589
+ const outFileName = emittedFile.fileName || emittedFile.name;
590
+ if (emittedFile.source && outFileName) context.emitFile({
591
+ resolvedPath: outFileName,
592
+ name: outFileName,
593
+ content: [...Buffer.from(emittedFile.source)],
594
+ resourceType: extname(outFileName)
595
+ });
596
+ },
597
+ getWatchFiles() {
598
+ return context.getWatchFiles();
599
+ },
600
+ getNativeBuildContext() {
601
+ return {
602
+ framework: "farm",
603
+ context
604
+ };
605
+ }
606
+ };
607
+ }
608
+ function unpluginContext(context) {
609
+ return {
610
+ error: (error) => context.error(typeof error === "string" ? new Error(error) : error),
611
+ warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
612
+ };
613
+ }
614
+ function convertEnforceToPriority(value) {
615
+ const defaultPriority = 100;
616
+ const enforceToPriority = {
617
+ pre: 102,
618
+ post: 98
619
+ };
620
+ return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
621
+ }
622
+ function convertWatchEventChange(value) {
623
+ return {
624
+ Added: "create",
625
+ Updated: "update",
626
+ Removed: "delete"
627
+ }[value];
628
+ }
629
+ function isString(variable) {
630
+ return typeof variable === "string";
631
+ }
632
+ function isObject(variable) {
633
+ return typeof variable === "object" && variable !== null;
634
+ }
635
+ function customParseQueryString(url) {
636
+ if (!url) return [];
637
+ const queryString = url.split("?")[1];
638
+ const parsedParams = querystring.parse(queryString);
639
+ const paramsArray = [];
640
+ for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]);
641
+ return paramsArray;
642
+ }
643
+ function encodeStr(str) {
644
+ const len = str.length;
645
+ if (len === 0) return str;
646
+ const firstNullIndex = str.indexOf("\0");
647
+ if (firstNullIndex === -1) return str;
648
+ const result = Array.from({ length: len + countNulls(str, firstNullIndex) });
649
+ let pos = 0;
650
+ for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i];
651
+ for (let i = firstNullIndex; i < len; i++) {
652
+ const char = str[i];
653
+ if (char === "\0") {
654
+ result[pos++] = "\\";
655
+ result[pos++] = "0";
656
+ } else result[pos++] = char;
657
+ }
658
+ return path.posix.normalize(result.join(""));
659
+ }
660
+ function decodeStr(str) {
661
+ const len = str.length;
662
+ if (len === 0) return str;
663
+ const firstIndex = str.indexOf("\\0");
664
+ if (firstIndex === -1) return str;
665
+ const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) });
666
+ let pos = 0;
667
+ for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1];
668
+ let i = firstIndex;
669
+ while (i < len) if (str[i] === "\\" && str[i + 1] === "0") {
670
+ result[pos++] = "\0";
671
+ i += 2;
672
+ } else result[pos++] = str[i++];
673
+ return path.posix.normalize(result.join(""));
674
+ }
675
+ function getContentValue(content) {
676
+ if (content === null || content === void 0) throw new Error("Content cannot be null or undefined");
677
+ return encodeStr(typeof content === "string" ? content : content.code || "");
678
+ }
679
+ function countNulls(str, startIndex) {
680
+ let count = 0;
681
+ const len = str.length;
682
+ for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++;
683
+ return count;
684
+ }
685
+ function countBackslashZeros(str, startIndex) {
686
+ let count = 0;
687
+ const len = str.length;
688
+ for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") {
689
+ count++;
690
+ i++;
691
+ }
692
+ return count;
693
+ }
694
+ function removeQuery(pathe) {
695
+ const queryIndex = pathe.indexOf("?");
696
+ if (queryIndex !== -1) return path.posix.normalize(pathe.slice(0, queryIndex));
697
+ return path.posix.normalize(pathe);
698
+ }
699
+ function isStartsWithSlash(str) {
700
+ return str?.startsWith("/");
701
+ }
702
+ function appendQuery(id, query) {
703
+ if (!query.length) return id;
704
+ return `${id}?${stringifyQuery(query)}`;
705
+ }
706
+ function stringifyQuery(query) {
707
+ if (!query.length) return "";
708
+ let queryStr = "";
709
+ for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`;
710
+ return `${queryStr.slice(0, -1)}`;
711
+ }
712
+ const CSS_LANGS_RES = [
713
+ [/\.(less)(?:$|\?)/, "less"],
714
+ [/\.(scss|sass)(?:$|\?)/, "sass"],
715
+ [/\.(styl|stylus)(?:$|\?)/, "stylus"],
716
+ [/\.(css)(?:$|\?)/, "css"]
717
+ ];
718
+ const JS_LANGS_RES = [
719
+ [/\.(js|mjs|cjs)(?:$|\?)/, "js"],
720
+ [/\.(jsx)(?:$|\?)/, "jsx"],
721
+ [/\.(ts|cts|mts)(?:$|\?)/, "ts"],
722
+ [/\.(tsx)(?:$|\?)/, "tsx"]
723
+ ];
724
+ function getCssModuleType(id) {
725
+ for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang;
726
+ return null;
727
+ }
728
+ function getJsModuleType(id) {
729
+ for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang;
730
+ return null;
731
+ }
732
+ function formatLoadModuleType(id) {
733
+ const cssModuleType = getCssModuleType(id);
734
+ if (cssModuleType) return cssModuleType;
735
+ const jsModuleType = getJsModuleType(id);
736
+ if (jsModuleType) return jsModuleType;
737
+ return "js";
738
+ }
739
+ function formatTransformModuleType(id) {
740
+ return formatLoadModuleType(id);
741
+ }
742
+ function getFarmPlugin(factory) {
743
+ return ((userOptions) => {
744
+ const plugins = toArray(factory(userOptions, { framework: "farm" })).map((rawPlugin) => {
745
+ const plugin = toFarmPlugin(rawPlugin, userOptions);
746
+ if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm);
747
+ return plugin;
748
+ });
749
+ return plugins.length === 1 ? plugins[0] : plugins;
750
+ });
751
+ }
752
+ function toFarmPlugin(plugin, options) {
753
+ const farmPlugin = {
754
+ name: plugin.name,
755
+ priority: convertEnforceToPriority(plugin.enforce)
756
+ };
757
+ if (plugin.farm) Object.keys(plugin.farm).forEach((key) => {
758
+ const value = plugin.farm[key];
759
+ if (value) Reflect.set(farmPlugin, key, value);
760
+ });
761
+ if (plugin.buildStart) {
762
+ const _buildStart = plugin.buildStart;
763
+ farmPlugin.buildStart = { async executor(_, context) {
764
+ await _buildStart.call(createFarmContext(context));
765
+ } };
766
+ }
767
+ if (plugin.resolveId) {
768
+ const _resolveId = plugin.resolveId;
769
+ let filters = [];
770
+ if (options) filters = options?.filters ?? [];
771
+ farmPlugin.resolve = {
772
+ filters: {
773
+ sources: filters.length ? filters : [".*"],
774
+ importers: [".*"]
775
+ },
776
+ async executor(params, context) {
777
+ const resolvedIdPath = path.resolve(params.importer ?? "");
778
+ const id = decodeStr(params.source);
779
+ const { handler, filter } = normalizeObjectHook("resolveId", _resolveId);
780
+ if (!filter(id)) return null;
781
+ let isEntry = false;
782
+ if (isObject(params.kind) && "entry" in params.kind) isEntry = params.kind.entry === "index";
783
+ const farmContext = createFarmContext(context, resolvedIdPath);
784
+ const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry });
785
+ if (isString(resolveIdResult)) return {
786
+ resolvedPath: removeQuery(encodeStr(resolveIdResult)),
787
+ query: customParseQueryString(resolveIdResult),
788
+ sideEffects: true,
789
+ external: false,
790
+ meta: {}
791
+ };
792
+ if (isObject(resolveIdResult)) return {
793
+ resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)),
794
+ query: customParseQueryString(resolveIdResult?.id),
795
+ sideEffects: false,
796
+ external: Boolean(resolveIdResult?.external),
797
+ meta: {}
798
+ };
799
+ if (!isStartsWithSlash(params.source)) return null;
800
+ }
801
+ };
802
+ }
803
+ if (plugin.load) {
804
+ const _load = plugin.load;
805
+ farmPlugin.load = {
806
+ filters: { resolvedPaths: [".*"] },
807
+ async executor(params, context) {
808
+ const id = appendQuery(decodeStr(params.resolvedPath), params.query);
809
+ const loader = formatTransformModuleType(id);
810
+ if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null;
811
+ const { handler, filter } = normalizeObjectHook("load", _load);
812
+ if (!filter(id)) return null;
813
+ const farmContext = createFarmContext(context, id);
814
+ return {
815
+ content: getContentValue(await handler.call(Object.assign(unpluginContext(context), farmContext), id)),
816
+ moduleType: loader
817
+ };
818
+ }
819
+ };
820
+ }
821
+ if (plugin.transform) {
822
+ const _transform = plugin.transform;
823
+ farmPlugin.transform = {
824
+ filters: {
825
+ resolvedPaths: [".*"],
826
+ moduleTypes: [".*"]
827
+ },
828
+ async executor(params, context) {
829
+ const id = appendQuery(decodeStr(params.resolvedPath), params.query);
830
+ const loader = formatTransformModuleType(id);
831
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return null;
832
+ const { handler, filter } = normalizeObjectHook("transform", _transform);
833
+ if (!filter(id, params.content)) return null;
834
+ const farmContext = createFarmContext(context, id);
835
+ const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id);
836
+ if (resource && typeof resource !== "string") return {
837
+ content: getContentValue(resource),
838
+ moduleType: loader,
839
+ sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0
840
+ };
841
+ }
842
+ };
843
+ }
844
+ if (plugin.watchChange) {
845
+ const _watchChange = plugin.watchChange;
846
+ farmPlugin.updateModules = { async executor(param, context) {
847
+ const updatePathContent = param.paths[0];
848
+ const ModifiedPath = updatePathContent[0];
849
+ const eventChange = convertWatchEventChange(updatePathContent[1]);
850
+ await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange });
851
+ } };
852
+ }
853
+ if (plugin.buildEnd) {
854
+ const _buildEnd = plugin.buildEnd;
855
+ farmPlugin.buildEnd = { async executor(_, context) {
856
+ await _buildEnd.call(createFarmContext(context));
857
+ } };
858
+ }
859
+ if (plugin.writeBundle) {
860
+ const _writeBundle = plugin.writeBundle;
861
+ farmPlugin.finish = { async executor() {
862
+ await _writeBundle();
863
+ } };
864
+ }
865
+ return farmPlugin;
866
+ }
867
+ function getRollupPlugin(factory) {
868
+ return ((userOptions) => {
869
+ const plugins = toArray(factory(userOptions, { framework: "rollup" })).map((plugin) => toRollupPlugin(plugin, "rollup"));
870
+ return plugins.length === 1 ? plugins[0] : plugins;
871
+ });
872
+ }
873
+ function toRollupPlugin(plugin, key) {
874
+ const nativeFilter = key === "rolldown";
875
+ if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) {
876
+ const resolveIdHook = plugin.resolveId;
877
+ const { handler, filter } = normalizeObjectHook("load", resolveIdHook);
878
+ replaceHookHandler("resolveId", resolveIdHook, function(...args) {
879
+ const [id] = args;
880
+ if (!supportNativeFilter(this, key) && !filter(id)) return;
881
+ return handler.apply(this, args);
882
+ });
883
+ }
884
+ if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) {
885
+ const loadHook = plugin.load;
886
+ const { handler, filter } = normalizeObjectHook("load", loadHook);
887
+ replaceHookHandler("load", loadHook, function(...args) {
888
+ const [id] = args;
889
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return;
890
+ if (!supportNativeFilter(this, key) && !filter(id)) return;
891
+ return handler.apply(this, args);
892
+ });
893
+ }
894
+ if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) {
895
+ const transformHook = plugin.transform;
896
+ const { handler, filter } = normalizeObjectHook("transform", transformHook);
897
+ replaceHookHandler("transform", transformHook, function(...args) {
898
+ const [code, id] = args;
899
+ if (plugin.transformInclude && !plugin.transformInclude(id)) return;
900
+ if (!supportNativeFilter(this, key) && !filter(id, code)) return;
901
+ return handler.apply(this, args);
902
+ });
903
+ }
904
+ if (plugin[key]) Object.assign(plugin, plugin[key]);
905
+ return plugin;
906
+ function replaceHookHandler(name, hook, handler) {
907
+ if (typeof hook === "function") plugin[name] = handler;
908
+ else hook.handler = handler;
909
+ }
910
+ }
911
+ function supportNativeFilter(context, framework) {
912
+ if (framework === "unloader") return false;
913
+ if (framework === "vite") return !!context?.meta?.viteVersion;
914
+ if (framework === "rolldown") return true;
915
+ const rollupVersion = context?.meta?.rollupVersion;
916
+ if (!rollupVersion) return false;
917
+ const [major, minor] = rollupVersion.split(".");
918
+ return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40;
919
+ }
920
+ function getRolldownPlugin(factory) {
921
+ return ((userOptions) => {
922
+ const plugins = toArray(factory(userOptions, { framework: "rolldown" })).map((rawPlugin) => {
923
+ return toRollupPlugin(rawPlugin, "rolldown");
924
+ });
925
+ return plugins.length === 1 ? plugins[0] : plugins;
926
+ });
927
+ }
928
+ const getFilename = () => fileURLToPath(import.meta.url);
929
+ const getDirname = () => path.dirname(getFilename());
930
+ const __dirname = /* @__PURE__ */ getDirname();
931
+ const TRANSFORM_LOADER$1 = resolve(__dirname, "rspack/loaders/transform");
932
+ const LOAD_LOADER$1 = resolve(__dirname, "rspack/loaders/load");
933
+ function getRspackPlugin(factory) {
934
+ return (userOptions) => {
935
+ return { apply(compiler) {
936
+ const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), "node_modules/.virtual", compiler.rspack.experiments.VirtualModulesPlugin ? "" : process.pid.toString());
937
+ const meta = {
938
+ framework: "rspack",
939
+ rspack: { compiler }
940
+ };
941
+ const rawPlugins = toArray(factory(userOptions, meta));
942
+ for (const rawPlugin of rawPlugins) {
943
+ const plugin = Object.assign(rawPlugin, {
944
+ __unpluginMeta: meta,
945
+ __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
946
+ });
947
+ const externalModules = /* @__PURE__ */ new Set();
948
+ if (plugin.resolveId) {
949
+ const createPlugin = (plugin$1) => {
950
+ if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin();
951
+ return new FakeVirtualModulesPlugin(plugin$1);
952
+ };
953
+ const vfs = createPlugin(plugin);
954
+ vfs.apply(compiler);
955
+ const vfsModules = /* @__PURE__ */ new Map();
956
+ plugin.__vfsModules = vfsModules;
957
+ plugin.__vfs = vfs;
958
+ compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
959
+ normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
960
+ const id = normalizeAbsolutePath(resolveData.request);
961
+ const requestContext = resolveData.contextInfo;
962
+ let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
963
+ const isEntry = requestContext.issuer === "";
964
+ if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
965
+ const context = createBuildContext$1(compiler, compilation);
966
+ let error;
967
+ const pluginContext = {
968
+ error(msg) {
969
+ if (error == null) error = normalizeMessage$1(msg);
970
+ else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
971
+ },
972
+ warn(msg) {
973
+ console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
974
+ }
975
+ };
976
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
977
+ if (!filter(id)) return;
978
+ const resolveIdResult = await handler.call({
979
+ ...context,
980
+ ...pluginContext
981
+ }, id, importer, { isEntry });
982
+ if (error != null) throw error;
983
+ if (resolveIdResult == null) return;
984
+ let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
985
+ if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved);
986
+ let isVirtual = true;
987
+ try {
988
+ (compiler.inputFileSystem?.statSync ?? fs.statSync)(resolved);
989
+ isVirtual = false;
990
+ } catch {
991
+ isVirtual = !isVirtualModuleId(resolved, plugin);
992
+ }
993
+ if (isVirtual) {
994
+ const encodedVirtualPath = encodeVirtualModuleId(resolved, plugin);
995
+ if (!vfsModules.has(resolved)) {
996
+ const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, ""));
997
+ vfsModules.set(resolved, fsPromise);
998
+ await fsPromise;
999
+ } else await vfsModules.get(resolved);
1000
+ resolved = encodedVirtualPath;
1001
+ }
1002
+ resolveData.request = resolved;
1003
+ });
1004
+ });
1005
+ }
1006
+ if (plugin.load) compiler.options.module.rules.unshift({
1007
+ enforce: plugin.enforce,
1008
+ include(id) {
1009
+ if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin);
1010
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
1011
+ const { filter } = normalizeObjectHook("load", plugin.load);
1012
+ if (!filter(id)) return false;
1013
+ return !externalModules.has(id);
1014
+ },
1015
+ use: [{
1016
+ loader: LOAD_LOADER$1,
1017
+ options: { plugin }
1018
+ }],
1019
+ type: "javascript/auto"
1020
+ });
1021
+ if (plugin.transform) compiler.options.module.rules.unshift({
1022
+ enforce: plugin.enforce,
1023
+ use(data) {
1024
+ return transformUse(data, plugin, TRANSFORM_LOADER$1);
1025
+ }
1026
+ });
1027
+ if (plugin.rspack) plugin.rspack(compiler);
1028
+ if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
1029
+ const context = createBuildContext$1(compiler, compilation);
1030
+ if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
1031
+ const promises$1 = [];
1032
+ if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises$1.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
1033
+ if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises$1.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
1034
+ await Promise.all(promises$1);
1035
+ }
1036
+ if (plugin.buildStart) return await plugin.buildStart.call(context);
1037
+ });
1038
+ if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
1039
+ await plugin.buildEnd.call(createBuildContext$1(compiler, compilation));
1040
+ });
1041
+ if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
1042
+ await plugin.writeBundle();
1043
+ });
1044
+ }
1045
+ } };
1046
+ };
1047
+ }
1048
+ function getUnloaderPlugin(factory) {
1049
+ return ((userOptions) => {
1050
+ const plugins = toArray(factory(userOptions, { framework: "unloader" })).map((rawPlugin) => {
1051
+ return toRollupPlugin(rawPlugin, "unloader");
1052
+ });
1053
+ return plugins.length === 1 ? plugins[0] : plugins;
1054
+ });
1055
+ }
1056
+ function getVitePlugin(factory) {
1057
+ return ((userOptions) => {
1058
+ const plugins = toArray(factory(userOptions, { framework: "vite" })).map((rawPlugin) => {
1059
+ return toRollupPlugin(rawPlugin, "vite");
1060
+ });
1061
+ return plugins.length === 1 ? plugins[0] : plugins;
1062
+ });
1063
+ }
1064
+ const TRANSFORM_LOADER = resolve(__dirname, "webpack/loaders/transform");
1065
+ const LOAD_LOADER = resolve(__dirname, "webpack/loaders/load");
1066
+ function getWebpackPlugin(factory) {
1067
+ return (userOptions) => {
1068
+ return { apply(compiler) {
1069
+ const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process$1.cwd(), "_virtual_");
1070
+ const meta = {
1071
+ framework: "webpack",
1072
+ webpack: { compiler }
1073
+ };
1074
+ const rawPlugins = toArray(factory(userOptions, meta));
1075
+ for (const rawPlugin of rawPlugins) {
1076
+ const plugin = Object.assign(rawPlugin, {
1077
+ __unpluginMeta: meta,
1078
+ __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
1079
+ });
1080
+ const externalModules = /* @__PURE__ */ new Set();
1081
+ if (plugin.resolveId) {
1082
+ let vfs = compiler.options.plugins.find((i) => i instanceof import_lib.default);
1083
+ if (!vfs) {
1084
+ vfs = new import_lib.default();
1085
+ compiler.options.plugins.push(vfs);
1086
+ }
1087
+ const vfsModules = /* @__PURE__ */ new Set();
1088
+ plugin.__vfsModules = vfsModules;
1089
+ plugin.__vfs = vfs;
1090
+ const resolverPlugin = { apply(resolver) {
1091
+ const target = resolver.ensureHook("resolve");
1092
+ resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
1093
+ if (!request.request) return callback();
1094
+ if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback();
1095
+ const id = normalizeAbsolutePath(request.request);
1096
+ const requestContext = request.context;
1097
+ let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
1098
+ const isEntry = requestContext.issuer === "";
1099
+ if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
1100
+ const fileDependencies = /* @__PURE__ */ new Set();
1101
+ const context = createBuildContext({
1102
+ addWatchFile(file) {
1103
+ fileDependencies.add(file);
1104
+ resolveContext.fileDependencies?.add(file);
1105
+ },
1106
+ getWatchFiles() {
1107
+ return Array.from(fileDependencies);
1108
+ }
1109
+ }, compiler);
1110
+ let error;
1111
+ const pluginContext = {
1112
+ error(msg) {
1113
+ if (error == null) error = normalizeMessage(msg);
1114
+ else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
1115
+ },
1116
+ warn(msg) {
1117
+ console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
1118
+ }
1119
+ };
1120
+ const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId);
1121
+ if (!filter(id)) return callback();
1122
+ const resolveIdResult = await handler.call({
1123
+ ...context,
1124
+ ...pluginContext
1125
+ }, id, importer, { isEntry });
1126
+ if (error != null) return callback(error);
1127
+ if (resolveIdResult == null) return callback();
1128
+ let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
1129
+ if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved);
1130
+ if (!fs.existsSync(resolved)) {
1131
+ resolved = normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved));
1132
+ if (!vfsModules.has(resolved)) {
1133
+ plugin.__vfs.writeModule(resolved, "");
1134
+ vfsModules.add(resolved);
1135
+ }
1136
+ }
1137
+ const newRequest = {
1138
+ ...request,
1139
+ request: resolved
1140
+ };
1141
+ resolver.doResolve(target, newRequest, null, resolveContext, callback);
1142
+ });
1143
+ } };
1144
+ compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
1145
+ compiler.options.resolve.plugins.push(resolverPlugin);
1146
+ }
1147
+ if (plugin.load) compiler.options.module.rules.unshift({
1148
+ include(id) {
1149
+ return shouldLoad(id, plugin, externalModules);
1150
+ },
1151
+ enforce: plugin.enforce,
1152
+ use: [{
1153
+ loader: LOAD_LOADER,
1154
+ options: { plugin }
1155
+ }],
1156
+ type: "javascript/auto"
1157
+ });
1158
+ if (plugin.transform) compiler.options.module.rules.unshift({
1159
+ enforce: plugin.enforce,
1160
+ use(data) {
1161
+ return transformUse(data, plugin, TRANSFORM_LOADER);
1162
+ }
1163
+ });
1164
+ if (plugin.webpack) plugin.webpack(compiler);
1165
+ if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
1166
+ const context = createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation);
1167
+ if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
1168
+ const promises$1 = [];
1169
+ if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises$1.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
1170
+ if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises$1.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
1171
+ await Promise.all(promises$1);
1172
+ }
1173
+ if (plugin.buildStart) return await plugin.buildStart.call(context);
1174
+ });
1175
+ if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
1176
+ await plugin.buildEnd.call(createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation));
1177
+ });
1178
+ if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
1179
+ await plugin.writeBundle();
1180
+ });
1181
+ }
1182
+ } };
1183
+ };
1184
+ }
1185
+ function shouldLoad(id, plugin, externalModules) {
1186
+ if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
1187
+ if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
1188
+ const { filter } = normalizeObjectHook("load", plugin.load);
1189
+ if (!filter(id)) return false;
1190
+ return !externalModules.has(id);
1191
+ }
1192
+ function createUnplugin(factory) {
1193
+ return {
1194
+ get esbuild() {
1195
+ return getEsbuildPlugin(factory);
1196
+ },
1197
+ get rollup() {
1198
+ return getRollupPlugin(factory);
1199
+ },
1200
+ get vite() {
1201
+ return getVitePlugin(factory);
1202
+ },
1203
+ get rolldown() {
1204
+ return getRolldownPlugin(factory);
1205
+ },
1206
+ get webpack() {
1207
+ return getWebpackPlugin(factory);
1208
+ },
1209
+ get rspack() {
1210
+ return getRspackPlugin(factory);
1211
+ },
1212
+ get farm() {
1213
+ return getFarmPlugin(factory);
1214
+ },
1215
+ get unloader() {
1216
+ return getUnloaderPlugin(factory);
1217
+ },
1218
+ get raw() {
1219
+ return factory;
1220
+ }
1221
+ };
1222
+ }
1223
+
1224
+ //#endregion
1225
+ export { createUnplugin as t };