@voidzero-dev/vite-plus-core 0.0.0-0bfcc90f.20260209-0731

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 (114) hide show
  1. package/LICENSE +41 -0
  2. package/dist/pluginutils/filter/composable-filters.d.ts +90 -0
  3. package/dist/pluginutils/filter/composable-filters.js +256 -0
  4. package/dist/pluginutils/filter/filter-vite-plugins.d.ts +28 -0
  5. package/dist/pluginutils/filter/filter-vite-plugins.js +75 -0
  6. package/dist/pluginutils/filter/index.d.ts +3 -0
  7. package/dist/pluginutils/filter/index.js +3 -0
  8. package/dist/pluginutils/filter/simple-filters.d.ts +71 -0
  9. package/dist/pluginutils/filter/simple-filters.js +70 -0
  10. package/dist/pluginutils/index.d.ts +1 -0
  11. package/dist/pluginutils/index.js +1 -0
  12. package/dist/pluginutils/utils.d.ts +2 -0
  13. package/dist/pluginutils/utils.js +17 -0
  14. package/dist/rolldown/cli-setup.d.mts +1 -0
  15. package/dist/rolldown/cli-setup.mjs +17 -0
  16. package/dist/rolldown/cli.d.mts +1 -0
  17. package/dist/rolldown/cli.mjs +608 -0
  18. package/dist/rolldown/config.d.mts +7 -0
  19. package/dist/rolldown/config.mjs +10 -0
  20. package/dist/rolldown/experimental-index.d.mts +194 -0
  21. package/dist/rolldown/experimental-index.mjs +291 -0
  22. package/dist/rolldown/experimental-runtime-types.d.ts +98 -0
  23. package/dist/rolldown/filter-index.d.mts +197 -0
  24. package/dist/rolldown/filter-index.mjs +369 -0
  25. package/dist/rolldown/get-log-filter.d.mts +7 -0
  26. package/dist/rolldown/get-log-filter.mjs +47 -0
  27. package/dist/rolldown/index.d.mts +4 -0
  28. package/dist/rolldown/index.mjs +57 -0
  29. package/dist/rolldown/parallel-plugin-worker.d.mts +1 -0
  30. package/dist/rolldown/parallel-plugin-worker.mjs +32 -0
  31. package/dist/rolldown/parallel-plugin.d.mts +14 -0
  32. package/dist/rolldown/parallel-plugin.mjs +7 -0
  33. package/dist/rolldown/parse-ast-index.d.mts +8 -0
  34. package/dist/rolldown/parse-ast-index.mjs +47 -0
  35. package/dist/rolldown/plugins-index.d.mts +30 -0
  36. package/dist/rolldown/plugins-index.mjs +40 -0
  37. package/dist/rolldown/shared/binding-D-XMzSaG.d.mts +1665 -0
  38. package/dist/rolldown/shared/binding-DuOSzYPt.mjs +587 -0
  39. package/dist/rolldown/shared/bindingify-input-options-Bu6nUTgS.mjs +2257 -0
  40. package/dist/rolldown/shared/constructors-DZVRHTli.mjs +61 -0
  41. package/dist/rolldown/shared/constructors-KD7LvxpN.d.mts +28 -0
  42. package/dist/rolldown/shared/define-config-BVG4QvnP.mjs +7 -0
  43. package/dist/rolldown/shared/define-config-U4pj0ZDn.d.mts +3616 -0
  44. package/dist/rolldown/shared/load-config-O1K_tT_z.mjs +114 -0
  45. package/dist/rolldown/shared/logging-CE90D8JR.d.mts +50 -0
  46. package/dist/rolldown/shared/logs-NH298mHo.mjs +183 -0
  47. package/dist/rolldown/shared/misc-CCZIsXVO.mjs +22 -0
  48. package/dist/rolldown/shared/normalize-string-or-regex-DeZqg15i.mjs +61 -0
  49. package/dist/rolldown/shared/parse-DLraxqjd.mjs +56 -0
  50. package/dist/rolldown/shared/prompt-DeISmFRp.mjs +847 -0
  51. package/dist/rolldown/shared/rolldown-O0UKbTKf.mjs +42 -0
  52. package/dist/rolldown/shared/rolldown-build-BIs7C4B_.mjs +3354 -0
  53. package/dist/rolldown/shared/watch-DQXGaDjx.mjs +379 -0
  54. package/dist/tsdown/build-l5WhXg4M-BBPqZr0m.js +4933 -0
  55. package/dist/tsdown/chunk-CdeBBKNj.js +44 -0
  56. package/dist/tsdown/debug-Cb_Nqpo4-BueIRvg1.js +18 -0
  57. package/dist/tsdown/detect-CCATtVj7-B86m8IqW.js +165 -0
  58. package/dist/tsdown/dist-BUOkzr_P.js +201 -0
  59. package/dist/tsdown/dist-BVMGwPdF.js +32363 -0
  60. package/dist/tsdown/dist-dc0X0G6b.js +742 -0
  61. package/dist/tsdown/filename-7rlgePeo.js +31 -0
  62. package/dist/tsdown/index-node-BjDys8jy--sqPE5mM.js +251 -0
  63. package/dist/tsdown/index-types.d.ts +2163 -0
  64. package/dist/tsdown/index.js +14 -0
  65. package/dist/tsdown/main-d9yZSQqW.js +926 -0
  66. package/dist/tsdown/node-Cb5OsnKg.js +271 -0
  67. package/dist/tsdown/npm_cjs_chunk_chunk.cjs +11 -0
  68. package/dist/tsdown/npm_cjs_chunk_range.cjs +484 -0
  69. package/dist/tsdown/npm_cjs_chunk_semver.cjs +362 -0
  70. package/dist/tsdown/npm_entry_picomatch.cjs +1676 -0
  71. package/dist/tsdown/npm_entry_semver_functions_coerce.cjs +52 -0
  72. package/dist/tsdown/npm_entry_semver_functions_satisfies.cjs +23 -0
  73. package/dist/tsdown/npm_entry_semver_ranges_min-version.cjs +48 -0
  74. package/dist/tsdown/npm_entry_tree-kill.cjs +103 -0
  75. package/dist/tsdown/resolver-j7HY1N36-CIu_7LX6.js +20 -0
  76. package/dist/tsdown/run.js +537 -0
  77. package/dist/tsdown/tsc-context-BNYuT3cE.js +25 -0
  78. package/dist/tsdown/tsc-reo6aLWc.js +423 -0
  79. package/dist/vite/client/client.mjs +1140 -0
  80. package/dist/vite/client/env.mjs +19 -0
  81. package/dist/vite/client.d.ts +279 -0
  82. package/dist/vite/misc/false.d.ts +2 -0
  83. package/dist/vite/misc/false.js +1 -0
  84. package/dist/vite/misc/true.d.ts +2 -0
  85. package/dist/vite/misc/true.js +1 -0
  86. package/dist/vite/node/chunks/build2.js +5538 -0
  87. package/dist/vite/node/chunks/chunk.js +45 -0
  88. package/dist/vite/node/chunks/dist.js +6758 -0
  89. package/dist/vite/node/chunks/dist2.js +6651 -0
  90. package/dist/vite/node/chunks/fetchableEnvironments.js +41395 -0
  91. package/dist/vite/node/chunks/lib.js +377 -0
  92. package/dist/vite/node/chunks/logger.js +332 -0
  93. package/dist/vite/node/chunks/moduleRunnerTransport.d.ts +96 -0
  94. package/dist/vite/node/chunks/postcss-import.js +479 -0
  95. package/dist/vite/node/cli.js +699 -0
  96. package/dist/vite/node/index.d.ts +3807 -0
  97. package/dist/vite/node/index.js +15 -0
  98. package/dist/vite/node/internal.d.ts +2 -0
  99. package/dist/vite/node/internal.js +3 -0
  100. package/dist/vite/node/module-runner.d.ts +311 -0
  101. package/dist/vite/node/module-runner.js +1159 -0
  102. package/dist/vite/types/customEvent.d.ts +52 -0
  103. package/dist/vite/types/hmrPayload.d.ts +80 -0
  104. package/dist/vite/types/hot.d.ts +39 -0
  105. package/dist/vite/types/import-meta.d.ts +5 -0
  106. package/dist/vite/types/importGlob.d.ts +89 -0
  107. package/dist/vite/types/importMeta.d.ts +30 -0
  108. package/dist/vite/types/internal/cssPreprocessorOptions.d.ts +44 -0
  109. package/dist/vite/types/internal/esbuildOptions.d.ts +28 -0
  110. package/dist/vite/types/internal/lightningcssOptions.d.ts +18 -0
  111. package/dist/vite/types/internal/rollupTypeCompat.d.ts +24 -0
  112. package/dist/vite/types/internal/terserOptions.d.ts +11 -0
  113. package/dist/vite/types/metadata.d.ts +47 -0
  114. package/package.json +204 -0
@@ -0,0 +1,4933 @@
1
+ import { n as __exportAll, r as __toESM, t as __commonJSMin } from "./chunk-CdeBBKNj.js";
2
+ import { C as green, S as dim, T as yellow, _ as resolveRegex, a as __exportAll$1, b as blue, c as getNameLabel, d as matchPattern, f as noop, g as resolveComma, h as promiseWithResolvers, i as LogLevels, l as globalLogger, m as prettyFormat, n as q, o as createLogger, p as pkgExists, r as version, s as generateColor, u as importWithError, v as slash, w as underline, x as bold, y as toArray } from "./main-d9yZSQqW.js";
3
+ import { t as createDebug } from "./node-Cb5OsnKg.js";
4
+ import { i as RE_JS, n as RE_DTS, o as RE_NODE_MODULES$1, t as RE_CSS } from "./filename-7rlgePeo.js";
5
+ import module$1, { builtinModules, createRequire, isBuiltin } from "node:module";
6
+ import process$1, { env } from "node:process";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import readline from "node:readline";
9
+ import { formatWithOptions, inspect, promisify } from "node:util";
10
+ import { VERSION, build, watch } from "@voidzero-dev/vite-plus-core/rolldown";
11
+ import { createRequire as createRequire$1 } from "module";
12
+ import path, { dirname, isAbsolute, join, parse, resolve } from "node:path";
13
+ import { access, chmod, cp, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
14
+ import * as nativeFs$1 from "fs";
15
+ import nativeFs from "fs";
16
+ import path$1, { basename, dirname as dirname$1, normalize as normalize$1, posix, relative, resolve as resolve$1, sep } from "path";
17
+ import { fileURLToPath as fileURLToPath$1 } from "url";
18
+ import fs$1, { existsSync, readFileSync, writeFileSync } from "node:fs";
19
+ import { and, id, importerId, include } from "@voidzero-dev/vite-plus-core/rolldown/filter";
20
+ import { Buffer } from "node:buffer";
21
+ import { brotliCompress, gzip } from "node:zlib";
22
+ import { tmpdir } from "node:os";
23
+ import { importGlobPlugin } from "@voidzero-dev/vite-plus-core/rolldown/experimental";
24
+
25
+ //#region ../../node_modules/.pnpm/tsdown@0.20.2_@arethetypeswrong+core@0.18.2_@typescript+native-preview@7.0.0-dev.202601_11c6934cad7d4cedf7999249d5905a1c/node_modules/tsdown/dist/format-BD2e_4xO.mjs
26
+ function fsExists(path) {
27
+ return access(path).then(() => true, () => false);
28
+ }
29
+ function fsStat(path) {
30
+ return stat(path).catch(() => null);
31
+ }
32
+ function fsRemove(path) {
33
+ return rm(path, {
34
+ force: true,
35
+ recursive: true
36
+ }).catch(() => {});
37
+ }
38
+ function fsCopy(from, to) {
39
+ return cp(from, to, {
40
+ recursive: true,
41
+ force: true
42
+ });
43
+ }
44
+ function lowestCommonAncestor(...filepaths) {
45
+ if (filepaths.length === 0) return "";
46
+ if (filepaths.length === 1) return path.dirname(filepaths[0]);
47
+ filepaths = filepaths.map(path.normalize);
48
+ const [first, ...rest] = filepaths;
49
+ let ancestor = first.split(path.sep);
50
+ for (const filepath of rest) {
51
+ const directories = filepath.split(path.sep, ancestor.length);
52
+ let index = 0;
53
+ for (const directory of directories) if (directory === ancestor[index]) index += 1;
54
+ else {
55
+ ancestor = ancestor.slice(0, index);
56
+ break;
57
+ }
58
+ ancestor = ancestor.slice(0, index);
59
+ }
60
+ return ancestor.length <= 1 && ancestor[0] === "" ? path.sep + ancestor[0] : ancestor.join(path.sep);
61
+ }
62
+ function stripExtname(filePath) {
63
+ const ext = path.extname(filePath);
64
+ if (!ext.length) return filePath;
65
+ return filePath.slice(0, -ext.length);
66
+ }
67
+ function formatBytes(bytes) {
68
+ if (bytes === Infinity) return void 0;
69
+ return `${(bytes / 1e3).toFixed(2)} kB`;
70
+ }
71
+ function detectIndentation(jsonText) {
72
+ const lines = jsonText.split(/\r?\n/);
73
+ for (const line of lines) {
74
+ const match = line.match(/^(\s+)\S/);
75
+ if (!match) continue;
76
+ if (match[1].includes(" ")) return " ";
77
+ return match[1].length;
78
+ }
79
+ return 2;
80
+ }
81
+
82
+ //#endregion
83
+ //#region ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
84
+ function isPlainObject(value) {
85
+ if (value === null || typeof value !== "object") return false;
86
+ const prototype = Object.getPrototypeOf(value);
87
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
88
+ if (Symbol.iterator in value) return false;
89
+ if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
90
+ return true;
91
+ }
92
+ function _defu(baseObject, defaults, namespace = ".", merger) {
93
+ if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
94
+ const object = Object.assign({}, defaults);
95
+ for (const key in baseObject) {
96
+ if (key === "__proto__" || key === "constructor") continue;
97
+ const value = baseObject[key];
98
+ if (value === null || value === void 0) continue;
99
+ if (merger && merger(object, key, value, namespace)) continue;
100
+ if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
101
+ else if (isPlainObject(value) && isPlainObject(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
102
+ else object[key] = value;
103
+ }
104
+ return object;
105
+ }
106
+ function createDefu(merger) {
107
+ return (...arguments_) => arguments_.reduce((p, c) => _defu(p, c, "", merger), {});
108
+ }
109
+ const defu$1 = createDefu();
110
+ const defuFn = createDefu((object, key, currentValue) => {
111
+ if (object[key] !== void 0 && typeof currentValue === "function") {
112
+ object[key] = currentValue(object[key]);
113
+ return true;
114
+ }
115
+ });
116
+ const defuArrayFn = createDefu((object, key, currentValue) => {
117
+ if (Array.isArray(object[key]) && typeof currentValue === "function") {
118
+ object[key] = currentValue(object[key]);
119
+ return true;
120
+ }
121
+ });
122
+
123
+ //#endregion
124
+ //#region ../../node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.3/node_modules/fdir/dist/index.mjs
125
+ var __require$1 = /* @__PURE__ */ createRequire$1(import.meta.url);
126
+ function cleanPath(path) {
127
+ let normalized = normalize$1(path);
128
+ if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
129
+ return normalized;
130
+ }
131
+ const SLASHES_REGEX = /[\\/]/g;
132
+ function convertSlashes(path, separator) {
133
+ return path.replace(SLASHES_REGEX, separator);
134
+ }
135
+ const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
136
+ function isRootDirectory(path) {
137
+ return path === "/" || WINDOWS_ROOT_DIR_REGEX.test(path);
138
+ }
139
+ function normalizePath(path, options) {
140
+ const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
141
+ const pathNeedsCleaning = process.platform === "win32" && path.includes("/") || path.startsWith(".");
142
+ if (resolvePaths) path = resolve$1(path);
143
+ if (normalizePath$1 || pathNeedsCleaning) path = cleanPath(path);
144
+ if (path === ".") return "";
145
+ return convertSlashes(path[path.length - 1] !== pathSeparator ? path + pathSeparator : path, pathSeparator);
146
+ }
147
+ function joinPathWithBasePath(filename, directoryPath) {
148
+ return directoryPath + filename;
149
+ }
150
+ function joinPathWithRelativePath(root, options) {
151
+ return function(filename, directoryPath) {
152
+ if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename;
153
+ else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
154
+ };
155
+ }
156
+ function joinPath(filename) {
157
+ return filename;
158
+ }
159
+ function joinDirectoryPath(filename, directoryPath, separator) {
160
+ return directoryPath + filename + separator;
161
+ }
162
+ function build$7(root, options) {
163
+ const { relativePaths, includeBasePath } = options;
164
+ return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
165
+ }
166
+ function pushDirectoryWithRelativePath(root) {
167
+ return function(directoryPath, paths) {
168
+ paths.push(directoryPath.substring(root.length) || ".");
169
+ };
170
+ }
171
+ function pushDirectoryFilterWithRelativePath(root) {
172
+ return function(directoryPath, paths, filters) {
173
+ const relativePath = directoryPath.substring(root.length) || ".";
174
+ if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
175
+ };
176
+ }
177
+ const pushDirectory = (directoryPath, paths) => {
178
+ paths.push(directoryPath || ".");
179
+ };
180
+ const pushDirectoryFilter = (directoryPath, paths, filters) => {
181
+ const path = directoryPath || ".";
182
+ if (filters.every((filter) => filter(path, true))) paths.push(path);
183
+ };
184
+ const empty$2 = () => {};
185
+ function build$6(root, options) {
186
+ const { includeDirs, filters, relativePaths } = options;
187
+ if (!includeDirs) return empty$2;
188
+ if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
189
+ return filters && filters.length ? pushDirectoryFilter : pushDirectory;
190
+ }
191
+ const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
192
+ if (filters.every((filter) => filter(filename, false))) counts.files++;
193
+ };
194
+ const pushFileFilter = (filename, paths, _counts, filters) => {
195
+ if (filters.every((filter) => filter(filename, false))) paths.push(filename);
196
+ };
197
+ const pushFileCount = (_filename, _paths, counts, _filters) => {
198
+ counts.files++;
199
+ };
200
+ const pushFile = (filename, paths) => {
201
+ paths.push(filename);
202
+ };
203
+ const empty$1 = () => {};
204
+ function build$5(options) {
205
+ const { excludeFiles, filters, onlyCounts } = options;
206
+ if (excludeFiles) return empty$1;
207
+ if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
208
+ else if (onlyCounts) return pushFileCount;
209
+ else return pushFile;
210
+ }
211
+ const getArray = (paths) => {
212
+ return paths;
213
+ };
214
+ const getArrayGroup = () => {
215
+ return [""].slice(0, 0);
216
+ };
217
+ function build$4(options) {
218
+ return options.group ? getArrayGroup : getArray;
219
+ }
220
+ const groupFiles = (groups, directory, files) => {
221
+ groups.push({
222
+ directory,
223
+ files,
224
+ dir: directory
225
+ });
226
+ };
227
+ const empty = () => {};
228
+ function build$3(options) {
229
+ return options.group ? groupFiles : empty;
230
+ }
231
+ const resolveSymlinksAsync = function(path, state, callback$1) {
232
+ const { queue, fs, options: { suppressErrors } } = state;
233
+ queue.enqueue();
234
+ fs.realpath(path, (error, resolvedPath) => {
235
+ if (error) return queue.dequeue(suppressErrors ? null : error, state);
236
+ fs.stat(resolvedPath, (error$1, stat) => {
237
+ if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
238
+ if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return queue.dequeue(null, state);
239
+ callback$1(stat, resolvedPath);
240
+ queue.dequeue(null, state);
241
+ });
242
+ });
243
+ };
244
+ const resolveSymlinks = function(path, state, callback$1) {
245
+ const { queue, fs, options: { suppressErrors } } = state;
246
+ queue.enqueue();
247
+ try {
248
+ const resolvedPath = fs.realpathSync(path);
249
+ const stat = fs.statSync(resolvedPath);
250
+ if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return;
251
+ callback$1(stat, resolvedPath);
252
+ } catch (e) {
253
+ if (!suppressErrors) throw e;
254
+ }
255
+ };
256
+ function build$2(options, isSynchronous) {
257
+ if (!options.resolveSymlinks || options.excludeSymlinks) return null;
258
+ return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
259
+ }
260
+ function isRecursive(path, resolved, state) {
261
+ if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
262
+ let parent = dirname$1(path);
263
+ let depth = 1;
264
+ while (parent !== state.root && depth < 2) {
265
+ const resolvedPath = state.symlinks.get(parent);
266
+ if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth++;
267
+ else parent = dirname$1(parent);
268
+ }
269
+ state.symlinks.set(path, resolved);
270
+ return depth > 1;
271
+ }
272
+ function isRecursiveUsingRealPaths(resolved, state) {
273
+ return state.visited.includes(resolved + state.options.pathSeparator);
274
+ }
275
+ const onlyCountsSync = (state) => {
276
+ return state.counts;
277
+ };
278
+ const groupsSync = (state) => {
279
+ return state.groups;
280
+ };
281
+ const defaultSync = (state) => {
282
+ return state.paths;
283
+ };
284
+ const limitFilesSync = (state) => {
285
+ return state.paths.slice(0, state.options.maxFiles);
286
+ };
287
+ const onlyCountsAsync = (state, error, callback$1) => {
288
+ report(error, callback$1, state.counts, state.options.suppressErrors);
289
+ return null;
290
+ };
291
+ const defaultAsync = (state, error, callback$1) => {
292
+ report(error, callback$1, state.paths, state.options.suppressErrors);
293
+ return null;
294
+ };
295
+ const limitFilesAsync = (state, error, callback$1) => {
296
+ report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
297
+ return null;
298
+ };
299
+ const groupsAsync = (state, error, callback$1) => {
300
+ report(error, callback$1, state.groups, state.options.suppressErrors);
301
+ return null;
302
+ };
303
+ function report(error, callback$1, output, suppressErrors) {
304
+ if (error && !suppressErrors) callback$1(error, output);
305
+ else callback$1(null, output);
306
+ }
307
+ function build$1$1(options, isSynchronous) {
308
+ const { onlyCounts, group, maxFiles } = options;
309
+ if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
310
+ else if (group) return isSynchronous ? groupsSync : groupsAsync;
311
+ else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
312
+ else return isSynchronous ? defaultSync : defaultAsync;
313
+ }
314
+ const readdirOpts = { withFileTypes: true };
315
+ const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
316
+ state.queue.enqueue();
317
+ if (currentDepth < 0) return state.queue.dequeue(null, state);
318
+ const { fs } = state;
319
+ state.visited.push(crawlPath);
320
+ state.counts.directories++;
321
+ fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
322
+ callback$1(entries, directoryPath, currentDepth);
323
+ state.queue.dequeue(state.options.suppressErrors ? null : error, state);
324
+ });
325
+ };
326
+ const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
327
+ const { fs } = state;
328
+ if (currentDepth < 0) return;
329
+ state.visited.push(crawlPath);
330
+ state.counts.directories++;
331
+ let entries = [];
332
+ try {
333
+ entries = fs.readdirSync(crawlPath || ".", readdirOpts);
334
+ } catch (e) {
335
+ if (!state.options.suppressErrors) throw e;
336
+ }
337
+ callback$1(entries, directoryPath, currentDepth);
338
+ };
339
+ function build$8(isSynchronous) {
340
+ return isSynchronous ? walkSync : walkAsync;
341
+ }
342
+ /**
343
+ * This is a custom stateless queue to track concurrent async fs calls.
344
+ * It increments a counter whenever a call is queued and decrements it
345
+ * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
346
+ */
347
+ var Queue = class {
348
+ count = 0;
349
+ constructor(onQueueEmpty) {
350
+ this.onQueueEmpty = onQueueEmpty;
351
+ }
352
+ enqueue() {
353
+ this.count++;
354
+ return this.count;
355
+ }
356
+ dequeue(error, output) {
357
+ if (this.onQueueEmpty && (--this.count <= 0 || error)) {
358
+ this.onQueueEmpty(error, output);
359
+ if (error) {
360
+ output.controller.abort();
361
+ this.onQueueEmpty = void 0;
362
+ }
363
+ }
364
+ }
365
+ };
366
+ var Counter = class {
367
+ _files = 0;
368
+ _directories = 0;
369
+ set files(num) {
370
+ this._files = num;
371
+ }
372
+ get files() {
373
+ return this._files;
374
+ }
375
+ set directories(num) {
376
+ this._directories = num;
377
+ }
378
+ get directories() {
379
+ return this._directories;
380
+ }
381
+ /**
382
+ * @deprecated use `directories` instead
383
+ */
384
+ /* c8 ignore next 3 */
385
+ get dirs() {
386
+ return this._directories;
387
+ }
388
+ };
389
+ /**
390
+ * AbortController is not supported on Node 14 so we use this until we can drop
391
+ * support for Node 14.
392
+ */
393
+ var Aborter = class {
394
+ aborted = false;
395
+ abort() {
396
+ this.aborted = true;
397
+ }
398
+ };
399
+ var Walker = class {
400
+ root;
401
+ isSynchronous;
402
+ state;
403
+ joinPath;
404
+ pushDirectory;
405
+ pushFile;
406
+ getArray;
407
+ groupFiles;
408
+ resolveSymlink;
409
+ walkDirectory;
410
+ callbackInvoker;
411
+ constructor(root, options, callback$1) {
412
+ this.isSynchronous = !callback$1;
413
+ this.callbackInvoker = build$1$1(options, this.isSynchronous);
414
+ this.root = normalizePath(root, options);
415
+ this.state = {
416
+ root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
417
+ paths: [""].slice(0, 0),
418
+ groups: [],
419
+ counts: new Counter(),
420
+ options,
421
+ queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
422
+ symlinks: /* @__PURE__ */ new Map(),
423
+ visited: [""].slice(0, 0),
424
+ controller: new Aborter(),
425
+ fs: options.fs || nativeFs$1
426
+ };
427
+ this.joinPath = build$7(this.root, options);
428
+ this.pushDirectory = build$6(this.root, options);
429
+ this.pushFile = build$5(options);
430
+ this.getArray = build$4(options);
431
+ this.groupFiles = build$3(options);
432
+ this.resolveSymlink = build$2(options, this.isSynchronous);
433
+ this.walkDirectory = build$8(this.isSynchronous);
434
+ }
435
+ start() {
436
+ this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
437
+ this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
438
+ return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
439
+ }
440
+ walk = (entries, directoryPath, depth) => {
441
+ const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
442
+ if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
443
+ const files = this.getArray(this.state.paths);
444
+ for (let i = 0; i < entries.length; ++i) {
445
+ const entry = entries[i];
446
+ if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
447
+ const filename = this.joinPath(entry.name, directoryPath);
448
+ this.pushFile(filename, files, this.state.counts, filters);
449
+ } else if (entry.isDirectory()) {
450
+ let path = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
451
+ if (exclude && exclude(entry.name, path)) continue;
452
+ this.pushDirectory(path, paths, filters);
453
+ this.walkDirectory(this.state, path, path, depth - 1, this.walk);
454
+ } else if (this.resolveSymlink && entry.isSymbolicLink()) {
455
+ let path = joinPathWithBasePath(entry.name, directoryPath);
456
+ this.resolveSymlink(path, this.state, (stat, resolvedPath) => {
457
+ if (stat.isDirectory()) {
458
+ resolvedPath = normalizePath(resolvedPath, this.state.options);
459
+ if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path + pathSeparator)) return;
460
+ this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk);
461
+ } else {
462
+ resolvedPath = useRealPaths ? resolvedPath : path;
463
+ const filename = basename(resolvedPath);
464
+ const directoryPath$1 = normalizePath(dirname$1(resolvedPath), this.state.options);
465
+ resolvedPath = this.joinPath(filename, directoryPath$1);
466
+ this.pushFile(resolvedPath, files, this.state.counts, filters);
467
+ }
468
+ });
469
+ }
470
+ }
471
+ this.groupFiles(this.state.groups, directoryPath, files);
472
+ };
473
+ };
474
+ function promise(root, options) {
475
+ return new Promise((resolve$1, reject) => {
476
+ callback(root, options, (err, output) => {
477
+ if (err) return reject(err);
478
+ resolve$1(output);
479
+ });
480
+ });
481
+ }
482
+ function callback(root, options, callback$1) {
483
+ new Walker(root, options, callback$1).start();
484
+ }
485
+ function sync(root, options) {
486
+ return new Walker(root, options).start();
487
+ }
488
+ var APIBuilder = class {
489
+ constructor(root, options) {
490
+ this.root = root;
491
+ this.options = options;
492
+ }
493
+ withPromise() {
494
+ return promise(this.root, this.options);
495
+ }
496
+ withCallback(cb) {
497
+ callback(this.root, this.options, cb);
498
+ }
499
+ sync() {
500
+ return sync(this.root, this.options);
501
+ }
502
+ };
503
+ let pm = null;
504
+ /* c8 ignore next 6 */
505
+ try {
506
+ __require$1.resolve("picomatch");
507
+ pm = __require$1("./npm_entry_picomatch.cjs");
508
+ } catch {}
509
+ var Builder = class {
510
+ globCache = {};
511
+ options = {
512
+ maxDepth: Infinity,
513
+ suppressErrors: true,
514
+ pathSeparator: sep,
515
+ filters: []
516
+ };
517
+ globFunction;
518
+ constructor(options) {
519
+ this.options = {
520
+ ...this.options,
521
+ ...options
522
+ };
523
+ this.globFunction = this.options.globFunction;
524
+ }
525
+ group() {
526
+ this.options.group = true;
527
+ return this;
528
+ }
529
+ withPathSeparator(separator) {
530
+ this.options.pathSeparator = separator;
531
+ return this;
532
+ }
533
+ withBasePath() {
534
+ this.options.includeBasePath = true;
535
+ return this;
536
+ }
537
+ withRelativePaths() {
538
+ this.options.relativePaths = true;
539
+ return this;
540
+ }
541
+ withDirs() {
542
+ this.options.includeDirs = true;
543
+ return this;
544
+ }
545
+ withMaxDepth(depth) {
546
+ this.options.maxDepth = depth;
547
+ return this;
548
+ }
549
+ withMaxFiles(limit) {
550
+ this.options.maxFiles = limit;
551
+ return this;
552
+ }
553
+ withFullPaths() {
554
+ this.options.resolvePaths = true;
555
+ this.options.includeBasePath = true;
556
+ return this;
557
+ }
558
+ withErrors() {
559
+ this.options.suppressErrors = false;
560
+ return this;
561
+ }
562
+ withSymlinks({ resolvePaths = true } = {}) {
563
+ this.options.resolveSymlinks = true;
564
+ this.options.useRealPaths = resolvePaths;
565
+ return this.withFullPaths();
566
+ }
567
+ withAbortSignal(signal) {
568
+ this.options.signal = signal;
569
+ return this;
570
+ }
571
+ normalize() {
572
+ this.options.normalizePath = true;
573
+ return this;
574
+ }
575
+ filter(predicate) {
576
+ this.options.filters.push(predicate);
577
+ return this;
578
+ }
579
+ onlyDirs() {
580
+ this.options.excludeFiles = true;
581
+ this.options.includeDirs = true;
582
+ return this;
583
+ }
584
+ exclude(predicate) {
585
+ this.options.exclude = predicate;
586
+ return this;
587
+ }
588
+ onlyCounts() {
589
+ this.options.onlyCounts = true;
590
+ return this;
591
+ }
592
+ crawl(root) {
593
+ return new APIBuilder(root || ".", this.options);
594
+ }
595
+ withGlobFunction(fn) {
596
+ this.globFunction = fn;
597
+ return this;
598
+ }
599
+ /**
600
+ * @deprecated Pass options using the constructor instead:
601
+ * ```ts
602
+ * new fdir(options).crawl("/path/to/root");
603
+ * ```
604
+ * This method will be removed in v7.0
605
+ */
606
+ /* c8 ignore next 4 */
607
+ crawlWithOptions(root, options) {
608
+ this.options = {
609
+ ...this.options,
610
+ ...options
611
+ };
612
+ return new APIBuilder(root || ".", this.options);
613
+ }
614
+ glob(...patterns) {
615
+ if (this.globFunction) return this.globWithOptions(patterns);
616
+ return this.globWithOptions(patterns, ...[{ dot: true }]);
617
+ }
618
+ globWithOptions(patterns, ...options) {
619
+ const globFn = this.globFunction || pm;
620
+ /* c8 ignore next 5 */
621
+ if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
622
+ var isMatch = this.globCache[patterns.join("\0")];
623
+ if (!isMatch) {
624
+ isMatch = globFn(patterns, ...options);
625
+ this.globCache[patterns.join("\0")] = isMatch;
626
+ }
627
+ this.options.filters.push((path) => isMatch(path));
628
+ return this;
629
+ }
630
+ };
631
+
632
+ //#endregion
633
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js
634
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
635
+ const WIN_SLASH = "\\\\/";
636
+ const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
637
+ /**
638
+ * Posix glob regex
639
+ */
640
+ const DOT_LITERAL = "\\.";
641
+ const PLUS_LITERAL = "\\+";
642
+ const QMARK_LITERAL = "\\?";
643
+ const SLASH_LITERAL = "\\/";
644
+ const ONE_CHAR = "(?=.)";
645
+ const QMARK = "[^/]";
646
+ const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
647
+ const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
648
+ const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
649
+ const POSIX_CHARS = {
650
+ DOT_LITERAL,
651
+ PLUS_LITERAL,
652
+ QMARK_LITERAL,
653
+ SLASH_LITERAL,
654
+ ONE_CHAR,
655
+ QMARK,
656
+ END_ANCHOR,
657
+ DOTS_SLASH,
658
+ NO_DOT: `(?!${DOT_LITERAL})`,
659
+ NO_DOTS: `(?!${START_ANCHOR}${DOTS_SLASH})`,
660
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`,
661
+ NO_DOTS_SLASH: `(?!${DOTS_SLASH})`,
662
+ QMARK_NO_DOT: `[^.${SLASH_LITERAL}]`,
663
+ STAR: `${QMARK}*?`,
664
+ START_ANCHOR,
665
+ SEP: "/"
666
+ };
667
+ /**
668
+ * Windows glob regex
669
+ */
670
+ const WINDOWS_CHARS = {
671
+ ...POSIX_CHARS,
672
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
673
+ QMARK: WIN_NO_SLASH,
674
+ STAR: `${WIN_NO_SLASH}*?`,
675
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
676
+ NO_DOT: `(?!${DOT_LITERAL})`,
677
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
678
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
679
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
680
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
681
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
682
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
683
+ SEP: "\\"
684
+ };
685
+ /**
686
+ * POSIX Bracket Regex
687
+ */
688
+ const POSIX_REGEX_SOURCE = {
689
+ alnum: "a-zA-Z0-9",
690
+ alpha: "a-zA-Z",
691
+ ascii: "\\x00-\\x7F",
692
+ blank: " \\t",
693
+ cntrl: "\\x00-\\x1F\\x7F",
694
+ digit: "0-9",
695
+ graph: "\\x21-\\x7E",
696
+ lower: "a-z",
697
+ print: "\\x20-\\x7E ",
698
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
699
+ space: " \\t\\r\\n\\v\\f",
700
+ upper: "A-Z",
701
+ word: "A-Za-z0-9_",
702
+ xdigit: "A-Fa-f0-9"
703
+ };
704
+ module.exports = {
705
+ MAX_LENGTH: 1024 * 64,
706
+ POSIX_REGEX_SOURCE,
707
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
708
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
709
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
710
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
711
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
712
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
713
+ REPLACEMENTS: {
714
+ __proto__: null,
715
+ "***": "*",
716
+ "**/**": "**",
717
+ "**/**/**": "**"
718
+ },
719
+ CHAR_0: 48,
720
+ CHAR_9: 57,
721
+ CHAR_UPPERCASE_A: 65,
722
+ CHAR_LOWERCASE_A: 97,
723
+ CHAR_UPPERCASE_Z: 90,
724
+ CHAR_LOWERCASE_Z: 122,
725
+ CHAR_LEFT_PARENTHESES: 40,
726
+ CHAR_RIGHT_PARENTHESES: 41,
727
+ CHAR_ASTERISK: 42,
728
+ CHAR_AMPERSAND: 38,
729
+ CHAR_AT: 64,
730
+ CHAR_BACKWARD_SLASH: 92,
731
+ CHAR_CARRIAGE_RETURN: 13,
732
+ CHAR_CIRCUMFLEX_ACCENT: 94,
733
+ CHAR_COLON: 58,
734
+ CHAR_COMMA: 44,
735
+ CHAR_DOT: 46,
736
+ CHAR_DOUBLE_QUOTE: 34,
737
+ CHAR_EQUAL: 61,
738
+ CHAR_EXCLAMATION_MARK: 33,
739
+ CHAR_FORM_FEED: 12,
740
+ CHAR_FORWARD_SLASH: 47,
741
+ CHAR_GRAVE_ACCENT: 96,
742
+ CHAR_HASH: 35,
743
+ CHAR_HYPHEN_MINUS: 45,
744
+ CHAR_LEFT_ANGLE_BRACKET: 60,
745
+ CHAR_LEFT_CURLY_BRACE: 123,
746
+ CHAR_LEFT_SQUARE_BRACKET: 91,
747
+ CHAR_LINE_FEED: 10,
748
+ CHAR_NO_BREAK_SPACE: 160,
749
+ CHAR_PERCENT: 37,
750
+ CHAR_PLUS: 43,
751
+ CHAR_QUESTION_MARK: 63,
752
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
753
+ CHAR_RIGHT_CURLY_BRACE: 125,
754
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
755
+ CHAR_SEMICOLON: 59,
756
+ CHAR_SINGLE_QUOTE: 39,
757
+ CHAR_SPACE: 32,
758
+ CHAR_TAB: 9,
759
+ CHAR_UNDERSCORE: 95,
760
+ CHAR_VERTICAL_LINE: 124,
761
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
762
+ extglobChars(chars) {
763
+ return {
764
+ "!": {
765
+ type: "negate",
766
+ open: "(?:(?!(?:",
767
+ close: `))${chars.STAR})`
768
+ },
769
+ "?": {
770
+ type: "qmark",
771
+ open: "(?:",
772
+ close: ")?"
773
+ },
774
+ "+": {
775
+ type: "plus",
776
+ open: "(?:",
777
+ close: ")+"
778
+ },
779
+ "*": {
780
+ type: "star",
781
+ open: "(?:",
782
+ close: ")*"
783
+ },
784
+ "@": {
785
+ type: "at",
786
+ open: "(?:",
787
+ close: ")"
788
+ }
789
+ };
790
+ },
791
+ globChars(win32) {
792
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
793
+ }
794
+ };
795
+ }));
796
+
797
+ //#endregion
798
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js
799
+ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
800
+ const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
801
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
802
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
803
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
804
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
805
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
806
+ exports.isWindows = () => {
807
+ if (typeof navigator !== "undefined" && navigator.platform) {
808
+ const platform = navigator.platform.toLowerCase();
809
+ return platform === "win32" || platform === "windows";
810
+ }
811
+ if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
812
+ return false;
813
+ };
814
+ exports.removeBackslashes = (str) => {
815
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
816
+ return match === "\\" ? "" : match;
817
+ });
818
+ };
819
+ exports.escapeLast = (input, char, lastIdx) => {
820
+ const idx = input.lastIndexOf(char, lastIdx);
821
+ if (idx === -1) return input;
822
+ if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
823
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
824
+ };
825
+ exports.removePrefix = (input, state = {}) => {
826
+ let output = input;
827
+ if (output.startsWith("./")) {
828
+ output = output.slice(2);
829
+ state.prefix = "./";
830
+ }
831
+ return output;
832
+ };
833
+ exports.wrapOutput = (input, state = {}, options = {}) => {
834
+ let output = `${options.contains ? "" : "^"}(?:${input})${options.contains ? "" : "$"}`;
835
+ if (state.negated === true) output = `(?:^(?!${output}).*$)`;
836
+ return output;
837
+ };
838
+ exports.basename = (path, { windows } = {}) => {
839
+ const segs = path.split(windows ? /[\\/]/ : "/");
840
+ const last = segs[segs.length - 1];
841
+ if (last === "") return segs[segs.length - 2];
842
+ return last;
843
+ };
844
+ }));
845
+
846
+ //#endregion
847
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js
848
+ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
849
+ const utils = require_utils();
850
+ const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
851
+ const isPathSeparator = (code) => {
852
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
853
+ };
854
+ const depth = (token) => {
855
+ if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
856
+ };
857
+ /**
858
+ * Quickly scans a glob pattern and returns an object with a handful of
859
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
860
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
861
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
862
+ *
863
+ * ```js
864
+ * const pm = require('picomatch');
865
+ * console.log(pm.scan('foo/bar/*.js'));
866
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
867
+ * ```
868
+ * @param {String} `str`
869
+ * @param {Object} `options`
870
+ * @return {Object} Returns an object with tokens and regex source string.
871
+ * @api public
872
+ */
873
+ const scan = (input, options) => {
874
+ const opts = options || {};
875
+ const length = input.length - 1;
876
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
877
+ const slashes = [];
878
+ const tokens = [];
879
+ const parts = [];
880
+ let str = input;
881
+ let index = -1;
882
+ let start = 0;
883
+ let lastIndex = 0;
884
+ let isBrace = false;
885
+ let isBracket = false;
886
+ let isGlob = false;
887
+ let isExtglob = false;
888
+ let isGlobstar = false;
889
+ let braceEscaped = false;
890
+ let backslashes = false;
891
+ let negated = false;
892
+ let negatedExtglob = false;
893
+ let finished = false;
894
+ let braces = 0;
895
+ let prev;
896
+ let code;
897
+ let token = {
898
+ value: "",
899
+ depth: 0,
900
+ isGlob: false
901
+ };
902
+ const eos = () => index >= length;
903
+ const peek = () => str.charCodeAt(index + 1);
904
+ const advance = () => {
905
+ prev = code;
906
+ return str.charCodeAt(++index);
907
+ };
908
+ while (index < length) {
909
+ code = advance();
910
+ let next;
911
+ if (code === CHAR_BACKWARD_SLASH) {
912
+ backslashes = token.backslashes = true;
913
+ code = advance();
914
+ if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
915
+ continue;
916
+ }
917
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
918
+ braces++;
919
+ while (eos() !== true && (code = advance())) {
920
+ if (code === CHAR_BACKWARD_SLASH) {
921
+ backslashes = token.backslashes = true;
922
+ advance();
923
+ continue;
924
+ }
925
+ if (code === CHAR_LEFT_CURLY_BRACE) {
926
+ braces++;
927
+ continue;
928
+ }
929
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
930
+ isBrace = token.isBrace = true;
931
+ isGlob = token.isGlob = true;
932
+ finished = true;
933
+ if (scanToEnd === true) continue;
934
+ break;
935
+ }
936
+ if (braceEscaped !== true && code === CHAR_COMMA) {
937
+ isBrace = token.isBrace = true;
938
+ isGlob = token.isGlob = true;
939
+ finished = true;
940
+ if (scanToEnd === true) continue;
941
+ break;
942
+ }
943
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
944
+ braces--;
945
+ if (braces === 0) {
946
+ braceEscaped = false;
947
+ isBrace = token.isBrace = true;
948
+ finished = true;
949
+ break;
950
+ }
951
+ }
952
+ }
953
+ if (scanToEnd === true) continue;
954
+ break;
955
+ }
956
+ if (code === CHAR_FORWARD_SLASH) {
957
+ slashes.push(index);
958
+ tokens.push(token);
959
+ token = {
960
+ value: "",
961
+ depth: 0,
962
+ isGlob: false
963
+ };
964
+ if (finished === true) continue;
965
+ if (prev === CHAR_DOT && index === start + 1) {
966
+ start += 2;
967
+ continue;
968
+ }
969
+ lastIndex = index + 1;
970
+ continue;
971
+ }
972
+ if (opts.noext !== true) {
973
+ if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) {
974
+ isGlob = token.isGlob = true;
975
+ isExtglob = token.isExtglob = true;
976
+ finished = true;
977
+ if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
978
+ if (scanToEnd === true) {
979
+ while (eos() !== true && (code = advance())) {
980
+ if (code === CHAR_BACKWARD_SLASH) {
981
+ backslashes = token.backslashes = true;
982
+ code = advance();
983
+ continue;
984
+ }
985
+ if (code === CHAR_RIGHT_PARENTHESES) {
986
+ isGlob = token.isGlob = true;
987
+ finished = true;
988
+ break;
989
+ }
990
+ }
991
+ continue;
992
+ }
993
+ break;
994
+ }
995
+ }
996
+ if (code === CHAR_ASTERISK) {
997
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
998
+ isGlob = token.isGlob = true;
999
+ finished = true;
1000
+ if (scanToEnd === true) continue;
1001
+ break;
1002
+ }
1003
+ if (code === CHAR_QUESTION_MARK) {
1004
+ isGlob = token.isGlob = true;
1005
+ finished = true;
1006
+ if (scanToEnd === true) continue;
1007
+ break;
1008
+ }
1009
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
1010
+ while (eos() !== true && (next = advance())) {
1011
+ if (next === CHAR_BACKWARD_SLASH) {
1012
+ backslashes = token.backslashes = true;
1013
+ advance();
1014
+ continue;
1015
+ }
1016
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1017
+ isBracket = token.isBracket = true;
1018
+ isGlob = token.isGlob = true;
1019
+ finished = true;
1020
+ break;
1021
+ }
1022
+ }
1023
+ if (scanToEnd === true) continue;
1024
+ break;
1025
+ }
1026
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
1027
+ negated = token.negated = true;
1028
+ start++;
1029
+ continue;
1030
+ }
1031
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
1032
+ isGlob = token.isGlob = true;
1033
+ if (scanToEnd === true) {
1034
+ while (eos() !== true && (code = advance())) {
1035
+ if (code === CHAR_LEFT_PARENTHESES) {
1036
+ backslashes = token.backslashes = true;
1037
+ code = advance();
1038
+ continue;
1039
+ }
1040
+ if (code === CHAR_RIGHT_PARENTHESES) {
1041
+ finished = true;
1042
+ break;
1043
+ }
1044
+ }
1045
+ continue;
1046
+ }
1047
+ break;
1048
+ }
1049
+ if (isGlob === true) {
1050
+ finished = true;
1051
+ if (scanToEnd === true) continue;
1052
+ break;
1053
+ }
1054
+ }
1055
+ if (opts.noext === true) {
1056
+ isExtglob = false;
1057
+ isGlob = false;
1058
+ }
1059
+ let base = str;
1060
+ let prefix = "";
1061
+ let glob = "";
1062
+ if (start > 0) {
1063
+ prefix = str.slice(0, start);
1064
+ str = str.slice(start);
1065
+ lastIndex -= start;
1066
+ }
1067
+ if (base && isGlob === true && lastIndex > 0) {
1068
+ base = str.slice(0, lastIndex);
1069
+ glob = str.slice(lastIndex);
1070
+ } else if (isGlob === true) {
1071
+ base = "";
1072
+ glob = str;
1073
+ } else base = str;
1074
+ if (base && base !== "" && base !== "/" && base !== str) {
1075
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
1076
+ }
1077
+ if (opts.unescape === true) {
1078
+ if (glob) glob = utils.removeBackslashes(glob);
1079
+ if (base && backslashes === true) base = utils.removeBackslashes(base);
1080
+ }
1081
+ const state = {
1082
+ prefix,
1083
+ input,
1084
+ start,
1085
+ base,
1086
+ glob,
1087
+ isBrace,
1088
+ isBracket,
1089
+ isGlob,
1090
+ isExtglob,
1091
+ isGlobstar,
1092
+ negated,
1093
+ negatedExtglob
1094
+ };
1095
+ if (opts.tokens === true) {
1096
+ state.maxDepth = 0;
1097
+ if (!isPathSeparator(code)) tokens.push(token);
1098
+ state.tokens = tokens;
1099
+ }
1100
+ if (opts.parts === true || opts.tokens === true) {
1101
+ let prevIndex;
1102
+ for (let idx = 0; idx < slashes.length; idx++) {
1103
+ const n = prevIndex ? prevIndex + 1 : start;
1104
+ const i = slashes[idx];
1105
+ const value = input.slice(n, i);
1106
+ if (opts.tokens) {
1107
+ if (idx === 0 && start !== 0) {
1108
+ tokens[idx].isPrefix = true;
1109
+ tokens[idx].value = prefix;
1110
+ } else tokens[idx].value = value;
1111
+ depth(tokens[idx]);
1112
+ state.maxDepth += tokens[idx].depth;
1113
+ }
1114
+ if (idx !== 0 || value !== "") parts.push(value);
1115
+ prevIndex = i;
1116
+ }
1117
+ if (prevIndex && prevIndex + 1 < input.length) {
1118
+ const value = input.slice(prevIndex + 1);
1119
+ parts.push(value);
1120
+ if (opts.tokens) {
1121
+ tokens[tokens.length - 1].value = value;
1122
+ depth(tokens[tokens.length - 1]);
1123
+ state.maxDepth += tokens[tokens.length - 1].depth;
1124
+ }
1125
+ }
1126
+ state.slashes = slashes;
1127
+ state.parts = parts;
1128
+ }
1129
+ return state;
1130
+ };
1131
+ module.exports = scan;
1132
+ }));
1133
+
1134
+ //#endregion
1135
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js
1136
+ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1137
+ const constants = require_constants();
1138
+ const utils = require_utils();
1139
+ /**
1140
+ * Constants
1141
+ */
1142
+ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants;
1143
+ /**
1144
+ * Helpers
1145
+ */
1146
+ const expandRange = (args, options) => {
1147
+ if (typeof options.expandRange === "function") return options.expandRange(...args, options);
1148
+ args.sort();
1149
+ const value = `[${args.join("-")}]`;
1150
+ try {
1151
+ new RegExp(value);
1152
+ } catch (ex) {
1153
+ return args.map((v) => utils.escapeRegex(v)).join("..");
1154
+ }
1155
+ return value;
1156
+ };
1157
+ /**
1158
+ * Create the message for a syntax error
1159
+ */
1160
+ const syntaxError = (type, char) => {
1161
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
1162
+ };
1163
+ /**
1164
+ * Parse the given input string.
1165
+ * @param {String} input
1166
+ * @param {Object} options
1167
+ * @return {Object}
1168
+ */
1169
+ const parse = (input, options) => {
1170
+ if (typeof input !== "string") throw new TypeError("Expected a string");
1171
+ input = REPLACEMENTS[input] || input;
1172
+ const opts = { ...options };
1173
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1174
+ let len = input.length;
1175
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1176
+ const bos = {
1177
+ type: "bos",
1178
+ value: "",
1179
+ output: opts.prepend || ""
1180
+ };
1181
+ const tokens = [bos];
1182
+ const capture = opts.capture ? "" : "?:";
1183
+ const PLATFORM_CHARS = constants.globChars(opts.windows);
1184
+ const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
1185
+ const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS;
1186
+ const globstar = (opts) => {
1187
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
1188
+ };
1189
+ const nodot = opts.dot ? "" : NO_DOT;
1190
+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
1191
+ let star = opts.bash === true ? globstar(opts) : STAR;
1192
+ if (opts.capture) star = `(${star})`;
1193
+ if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
1194
+ const state = {
1195
+ input,
1196
+ index: -1,
1197
+ start: 0,
1198
+ dot: opts.dot === true,
1199
+ consumed: "",
1200
+ output: "",
1201
+ prefix: "",
1202
+ backtrack: false,
1203
+ negated: false,
1204
+ brackets: 0,
1205
+ braces: 0,
1206
+ parens: 0,
1207
+ quotes: 0,
1208
+ globstar: false,
1209
+ tokens
1210
+ };
1211
+ input = utils.removePrefix(input, state);
1212
+ len = input.length;
1213
+ const extglobs = [];
1214
+ const braces = [];
1215
+ const stack = [];
1216
+ let prev = bos;
1217
+ let value;
1218
+ /**
1219
+ * Tokenizing helpers
1220
+ */
1221
+ const eos = () => state.index === len - 1;
1222
+ const peek = state.peek = (n = 1) => input[state.index + n];
1223
+ const advance = state.advance = () => input[++state.index] || "";
1224
+ const remaining = () => input.slice(state.index + 1);
1225
+ const consume = (value = "", num = 0) => {
1226
+ state.consumed += value;
1227
+ state.index += num;
1228
+ };
1229
+ const append = (token) => {
1230
+ state.output += token.output != null ? token.output : token.value;
1231
+ consume(token.value);
1232
+ };
1233
+ const negate = () => {
1234
+ let count = 1;
1235
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
1236
+ advance();
1237
+ state.start++;
1238
+ count++;
1239
+ }
1240
+ if (count % 2 === 0) return false;
1241
+ state.negated = true;
1242
+ state.start++;
1243
+ return true;
1244
+ };
1245
+ const increment = (type) => {
1246
+ state[type]++;
1247
+ stack.push(type);
1248
+ };
1249
+ const decrement = (type) => {
1250
+ state[type]--;
1251
+ stack.pop();
1252
+ };
1253
+ /**
1254
+ * Push tokens onto the tokens array. This helper speeds up
1255
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
1256
+ * and 2) helping us avoid creating extra tokens when consecutive
1257
+ * characters are plain text. This improves performance and simplifies
1258
+ * lookbehinds.
1259
+ */
1260
+ const push = (tok) => {
1261
+ if (prev.type === "globstar") {
1262
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
1263
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
1264
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
1265
+ state.output = state.output.slice(0, -prev.output.length);
1266
+ prev.type = "star";
1267
+ prev.value = "*";
1268
+ prev.output = star;
1269
+ state.output += prev.output;
1270
+ }
1271
+ }
1272
+ if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
1273
+ if (tok.value || tok.output) append(tok);
1274
+ if (prev && prev.type === "text" && tok.type === "text") {
1275
+ prev.output = (prev.output || prev.value) + tok.value;
1276
+ prev.value += tok.value;
1277
+ return;
1278
+ }
1279
+ tok.prev = prev;
1280
+ tokens.push(tok);
1281
+ prev = tok;
1282
+ };
1283
+ const extglobOpen = (type, value) => {
1284
+ const token = {
1285
+ ...EXTGLOB_CHARS[value],
1286
+ conditions: 1,
1287
+ inner: ""
1288
+ };
1289
+ token.prev = prev;
1290
+ token.parens = state.parens;
1291
+ token.output = state.output;
1292
+ const output = (opts.capture ? "(" : "") + token.open;
1293
+ increment("parens");
1294
+ push({
1295
+ type,
1296
+ value,
1297
+ output: state.output ? "" : ONE_CHAR
1298
+ });
1299
+ push({
1300
+ type: "paren",
1301
+ extglob: true,
1302
+ value: advance(),
1303
+ output
1304
+ });
1305
+ extglobs.push(token);
1306
+ };
1307
+ const extglobClose = (token) => {
1308
+ let output = token.close + (opts.capture ? ")" : "");
1309
+ let rest;
1310
+ if (token.type === "negate") {
1311
+ let extglobStar = star;
1312
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
1313
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
1314
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse(rest, {
1315
+ ...options,
1316
+ fastpaths: false
1317
+ }).output})${extglobStar})`;
1318
+ if (token.prev.type === "bos") state.negatedExtglob = true;
1319
+ }
1320
+ push({
1321
+ type: "paren",
1322
+ extglob: true,
1323
+ value,
1324
+ output
1325
+ });
1326
+ decrement("parens");
1327
+ };
1328
+ /**
1329
+ * Fast paths
1330
+ */
1331
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
1332
+ let backslashes = false;
1333
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
1334
+ if (first === "\\") {
1335
+ backslashes = true;
1336
+ return m;
1337
+ }
1338
+ if (first === "?") {
1339
+ if (esc) return esc + first + (rest ? QMARK.repeat(rest.length) : "");
1340
+ if (index === 0) return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
1341
+ return QMARK.repeat(chars.length);
1342
+ }
1343
+ if (first === ".") return DOT_LITERAL.repeat(chars.length);
1344
+ if (first === "*") {
1345
+ if (esc) return esc + first + (rest ? star : "");
1346
+ return star;
1347
+ }
1348
+ return esc ? m : `\\${m}`;
1349
+ });
1350
+ if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
1351
+ else output = output.replace(/\\+/g, (m) => {
1352
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
1353
+ });
1354
+ if (output === input && opts.contains === true) {
1355
+ state.output = input;
1356
+ return state;
1357
+ }
1358
+ state.output = utils.wrapOutput(output, state, options);
1359
+ return state;
1360
+ }
1361
+ /**
1362
+ * Tokenize input until we reach end-of-string
1363
+ */
1364
+ while (!eos()) {
1365
+ value = advance();
1366
+ if (value === "\0") continue;
1367
+ /**
1368
+ * Escaped characters
1369
+ */
1370
+ if (value === "\\") {
1371
+ const next = peek();
1372
+ if (next === "/" && opts.bash !== true) continue;
1373
+ if (next === "." || next === ";") continue;
1374
+ if (!next) {
1375
+ value += "\\";
1376
+ push({
1377
+ type: "text",
1378
+ value
1379
+ });
1380
+ continue;
1381
+ }
1382
+ const match = /^\\+/.exec(remaining());
1383
+ let slashes = 0;
1384
+ if (match && match[0].length > 2) {
1385
+ slashes = match[0].length;
1386
+ state.index += slashes;
1387
+ if (slashes % 2 !== 0) value += "\\";
1388
+ }
1389
+ if (opts.unescape === true) value = advance();
1390
+ else value += advance();
1391
+ if (state.brackets === 0) {
1392
+ push({
1393
+ type: "text",
1394
+ value
1395
+ });
1396
+ continue;
1397
+ }
1398
+ }
1399
+ /**
1400
+ * If we're inside a regex character class, continue
1401
+ * until we reach the closing bracket.
1402
+ */
1403
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
1404
+ if (opts.posix !== false && value === ":") {
1405
+ const inner = prev.value.slice(1);
1406
+ if (inner.includes("[")) {
1407
+ prev.posix = true;
1408
+ if (inner.includes(":")) {
1409
+ const idx = prev.value.lastIndexOf("[");
1410
+ const pre = prev.value.slice(0, idx);
1411
+ const posix = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)];
1412
+ if (posix) {
1413
+ prev.value = pre + posix;
1414
+ state.backtrack = true;
1415
+ advance();
1416
+ if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR;
1417
+ continue;
1418
+ }
1419
+ }
1420
+ }
1421
+ }
1422
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
1423
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
1424
+ if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
1425
+ prev.value += value;
1426
+ append({ value });
1427
+ continue;
1428
+ }
1429
+ /**
1430
+ * If we're inside a quoted string, continue
1431
+ * until we reach the closing double quote.
1432
+ */
1433
+ if (state.quotes === 1 && value !== "\"") {
1434
+ value = utils.escapeRegex(value);
1435
+ prev.value += value;
1436
+ append({ value });
1437
+ continue;
1438
+ }
1439
+ /**
1440
+ * Double quotes
1441
+ */
1442
+ if (value === "\"") {
1443
+ state.quotes = state.quotes === 1 ? 0 : 1;
1444
+ if (opts.keepQuotes === true) push({
1445
+ type: "text",
1446
+ value
1447
+ });
1448
+ continue;
1449
+ }
1450
+ /**
1451
+ * Parentheses
1452
+ */
1453
+ if (value === "(") {
1454
+ increment("parens");
1455
+ push({
1456
+ type: "paren",
1457
+ value
1458
+ });
1459
+ continue;
1460
+ }
1461
+ if (value === ")") {
1462
+ if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
1463
+ const extglob = extglobs[extglobs.length - 1];
1464
+ if (extglob && state.parens === extglob.parens + 1) {
1465
+ extglobClose(extglobs.pop());
1466
+ continue;
1467
+ }
1468
+ push({
1469
+ type: "paren",
1470
+ value,
1471
+ output: state.parens ? ")" : "\\)"
1472
+ });
1473
+ decrement("parens");
1474
+ continue;
1475
+ }
1476
+ /**
1477
+ * Square brackets
1478
+ */
1479
+ if (value === "[") {
1480
+ if (opts.nobracket === true || !remaining().includes("]")) {
1481
+ if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1482
+ value = `\\${value}`;
1483
+ } else increment("brackets");
1484
+ push({
1485
+ type: "bracket",
1486
+ value
1487
+ });
1488
+ continue;
1489
+ }
1490
+ if (value === "]") {
1491
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
1492
+ push({
1493
+ type: "text",
1494
+ value,
1495
+ output: `\\${value}`
1496
+ });
1497
+ continue;
1498
+ }
1499
+ if (state.brackets === 0) {
1500
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
1501
+ push({
1502
+ type: "text",
1503
+ value,
1504
+ output: `\\${value}`
1505
+ });
1506
+ continue;
1507
+ }
1508
+ decrement("brackets");
1509
+ const prevValue = prev.value.slice(1);
1510
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
1511
+ prev.value += value;
1512
+ append({ value });
1513
+ if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) continue;
1514
+ const escaped = utils.escapeRegex(prev.value);
1515
+ state.output = state.output.slice(0, -prev.value.length);
1516
+ if (opts.literalBrackets === true) {
1517
+ state.output += escaped;
1518
+ prev.value = escaped;
1519
+ continue;
1520
+ }
1521
+ prev.value = `(${capture}${escaped}|${prev.value})`;
1522
+ state.output += prev.value;
1523
+ continue;
1524
+ }
1525
+ /**
1526
+ * Braces
1527
+ */
1528
+ if (value === "{" && opts.nobrace !== true) {
1529
+ increment("braces");
1530
+ const open = {
1531
+ type: "brace",
1532
+ value,
1533
+ output: "(",
1534
+ outputIndex: state.output.length,
1535
+ tokensIndex: state.tokens.length
1536
+ };
1537
+ braces.push(open);
1538
+ push(open);
1539
+ continue;
1540
+ }
1541
+ if (value === "}") {
1542
+ const brace = braces[braces.length - 1];
1543
+ if (opts.nobrace === true || !brace) {
1544
+ push({
1545
+ type: "text",
1546
+ value,
1547
+ output: value
1548
+ });
1549
+ continue;
1550
+ }
1551
+ let output = ")";
1552
+ if (brace.dots === true) {
1553
+ const arr = tokens.slice();
1554
+ const range = [];
1555
+ for (let i = arr.length - 1; i >= 0; i--) {
1556
+ tokens.pop();
1557
+ if (arr[i].type === "brace") break;
1558
+ if (arr[i].type !== "dots") range.unshift(arr[i].value);
1559
+ }
1560
+ output = expandRange(range, opts);
1561
+ state.backtrack = true;
1562
+ }
1563
+ if (brace.comma !== true && brace.dots !== true) {
1564
+ const out = state.output.slice(0, brace.outputIndex);
1565
+ const toks = state.tokens.slice(brace.tokensIndex);
1566
+ brace.value = brace.output = "\\{";
1567
+ value = output = "\\}";
1568
+ state.output = out;
1569
+ for (const t of toks) state.output += t.output || t.value;
1570
+ }
1571
+ push({
1572
+ type: "brace",
1573
+ value,
1574
+ output
1575
+ });
1576
+ decrement("braces");
1577
+ braces.pop();
1578
+ continue;
1579
+ }
1580
+ /**
1581
+ * Pipes
1582
+ */
1583
+ if (value === "|") {
1584
+ if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
1585
+ push({
1586
+ type: "text",
1587
+ value
1588
+ });
1589
+ continue;
1590
+ }
1591
+ /**
1592
+ * Commas
1593
+ */
1594
+ if (value === ",") {
1595
+ let output = value;
1596
+ const brace = braces[braces.length - 1];
1597
+ if (brace && stack[stack.length - 1] === "braces") {
1598
+ brace.comma = true;
1599
+ output = "|";
1600
+ }
1601
+ push({
1602
+ type: "comma",
1603
+ value,
1604
+ output
1605
+ });
1606
+ continue;
1607
+ }
1608
+ /**
1609
+ * Slashes
1610
+ */
1611
+ if (value === "/") {
1612
+ if (prev.type === "dot" && state.index === state.start + 1) {
1613
+ state.start = state.index + 1;
1614
+ state.consumed = "";
1615
+ state.output = "";
1616
+ tokens.pop();
1617
+ prev = bos;
1618
+ continue;
1619
+ }
1620
+ push({
1621
+ type: "slash",
1622
+ value,
1623
+ output: SLASH_LITERAL
1624
+ });
1625
+ continue;
1626
+ }
1627
+ /**
1628
+ * Dots
1629
+ */
1630
+ if (value === ".") {
1631
+ if (state.braces > 0 && prev.type === "dot") {
1632
+ if (prev.value === ".") prev.output = DOT_LITERAL;
1633
+ const brace = braces[braces.length - 1];
1634
+ prev.type = "dots";
1635
+ prev.output += value;
1636
+ prev.value += value;
1637
+ brace.dots = true;
1638
+ continue;
1639
+ }
1640
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1641
+ push({
1642
+ type: "text",
1643
+ value,
1644
+ output: DOT_LITERAL
1645
+ });
1646
+ continue;
1647
+ }
1648
+ push({
1649
+ type: "dot",
1650
+ value,
1651
+ output: DOT_LITERAL
1652
+ });
1653
+ continue;
1654
+ }
1655
+ /**
1656
+ * Question marks
1657
+ */
1658
+ if (value === "?") {
1659
+ if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1660
+ extglobOpen("qmark", value);
1661
+ continue;
1662
+ }
1663
+ if (prev && prev.type === "paren") {
1664
+ const next = peek();
1665
+ let output = value;
1666
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
1667
+ push({
1668
+ type: "text",
1669
+ value,
1670
+ output
1671
+ });
1672
+ continue;
1673
+ }
1674
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1675
+ push({
1676
+ type: "qmark",
1677
+ value,
1678
+ output: QMARK_NO_DOT
1679
+ });
1680
+ continue;
1681
+ }
1682
+ push({
1683
+ type: "qmark",
1684
+ value,
1685
+ output: QMARK
1686
+ });
1687
+ continue;
1688
+ }
1689
+ /**
1690
+ * Exclamation
1691
+ */
1692
+ if (value === "!") {
1693
+ if (opts.noextglob !== true && peek() === "(") {
1694
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1695
+ extglobOpen("negate", value);
1696
+ continue;
1697
+ }
1698
+ }
1699
+ if (opts.nonegate !== true && state.index === 0) {
1700
+ negate();
1701
+ continue;
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Plus
1706
+ */
1707
+ if (value === "+") {
1708
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1709
+ extglobOpen("plus", value);
1710
+ continue;
1711
+ }
1712
+ if (prev && prev.value === "(" || opts.regex === false) {
1713
+ push({
1714
+ type: "plus",
1715
+ value,
1716
+ output: PLUS_LITERAL
1717
+ });
1718
+ continue;
1719
+ }
1720
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1721
+ push({
1722
+ type: "plus",
1723
+ value
1724
+ });
1725
+ continue;
1726
+ }
1727
+ push({
1728
+ type: "plus",
1729
+ value: PLUS_LITERAL
1730
+ });
1731
+ continue;
1732
+ }
1733
+ /**
1734
+ * Plain text
1735
+ */
1736
+ if (value === "@") {
1737
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1738
+ push({
1739
+ type: "at",
1740
+ extglob: true,
1741
+ value,
1742
+ output: ""
1743
+ });
1744
+ continue;
1745
+ }
1746
+ push({
1747
+ type: "text",
1748
+ value
1749
+ });
1750
+ continue;
1751
+ }
1752
+ /**
1753
+ * Plain text
1754
+ */
1755
+ if (value !== "*") {
1756
+ if (value === "$" || value === "^") value = `\\${value}`;
1757
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1758
+ if (match) {
1759
+ value += match[0];
1760
+ state.index += match[0].length;
1761
+ }
1762
+ push({
1763
+ type: "text",
1764
+ value
1765
+ });
1766
+ continue;
1767
+ }
1768
+ /**
1769
+ * Stars
1770
+ */
1771
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
1772
+ prev.type = "star";
1773
+ prev.star = true;
1774
+ prev.value += value;
1775
+ prev.output = star;
1776
+ state.backtrack = true;
1777
+ state.globstar = true;
1778
+ consume(value);
1779
+ continue;
1780
+ }
1781
+ let rest = remaining();
1782
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1783
+ extglobOpen("star", value);
1784
+ continue;
1785
+ }
1786
+ if (prev.type === "star") {
1787
+ if (opts.noglobstar === true) {
1788
+ consume(value);
1789
+ continue;
1790
+ }
1791
+ const prior = prev.prev;
1792
+ const before = prior.prev;
1793
+ const isStart = prior.type === "slash" || prior.type === "bos";
1794
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
1795
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1796
+ push({
1797
+ type: "star",
1798
+ value,
1799
+ output: ""
1800
+ });
1801
+ continue;
1802
+ }
1803
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
1804
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1805
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1806
+ push({
1807
+ type: "star",
1808
+ value,
1809
+ output: ""
1810
+ });
1811
+ continue;
1812
+ }
1813
+ while (rest.slice(0, 3) === "/**") {
1814
+ const after = input[state.index + 4];
1815
+ if (after && after !== "/") break;
1816
+ rest = rest.slice(3);
1817
+ consume("/**", 3);
1818
+ }
1819
+ if (prior.type === "bos" && eos()) {
1820
+ prev.type = "globstar";
1821
+ prev.value += value;
1822
+ prev.output = globstar(opts);
1823
+ state.output = prev.output;
1824
+ state.globstar = true;
1825
+ consume(value);
1826
+ continue;
1827
+ }
1828
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1829
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1830
+ prior.output = `(?:${prior.output}`;
1831
+ prev.type = "globstar";
1832
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
1833
+ prev.value += value;
1834
+ state.globstar = true;
1835
+ state.output += prior.output + prev.output;
1836
+ consume(value);
1837
+ continue;
1838
+ }
1839
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1840
+ const end = rest[1] !== void 0 ? "|$" : "";
1841
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1842
+ prior.output = `(?:${prior.output}`;
1843
+ prev.type = "globstar";
1844
+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
1845
+ prev.value += value;
1846
+ state.output += prior.output + prev.output;
1847
+ state.globstar = true;
1848
+ consume(value + advance());
1849
+ push({
1850
+ type: "slash",
1851
+ value: "/",
1852
+ output: ""
1853
+ });
1854
+ continue;
1855
+ }
1856
+ if (prior.type === "bos" && rest[0] === "/") {
1857
+ prev.type = "globstar";
1858
+ prev.value += value;
1859
+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
1860
+ state.output = prev.output;
1861
+ state.globstar = true;
1862
+ consume(value + advance());
1863
+ push({
1864
+ type: "slash",
1865
+ value: "/",
1866
+ output: ""
1867
+ });
1868
+ continue;
1869
+ }
1870
+ state.output = state.output.slice(0, -prev.output.length);
1871
+ prev.type = "globstar";
1872
+ prev.output = globstar(opts);
1873
+ prev.value += value;
1874
+ state.output += prev.output;
1875
+ state.globstar = true;
1876
+ consume(value);
1877
+ continue;
1878
+ }
1879
+ const token = {
1880
+ type: "star",
1881
+ value,
1882
+ output: star
1883
+ };
1884
+ if (opts.bash === true) {
1885
+ token.output = ".*?";
1886
+ if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
1887
+ push(token);
1888
+ continue;
1889
+ }
1890
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1891
+ token.output = value;
1892
+ push(token);
1893
+ continue;
1894
+ }
1895
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1896
+ if (prev.type === "dot") {
1897
+ state.output += NO_DOT_SLASH;
1898
+ prev.output += NO_DOT_SLASH;
1899
+ } else if (opts.dot === true) {
1900
+ state.output += NO_DOTS_SLASH;
1901
+ prev.output += NO_DOTS_SLASH;
1902
+ } else {
1903
+ state.output += nodot;
1904
+ prev.output += nodot;
1905
+ }
1906
+ if (peek() !== "*") {
1907
+ state.output += ONE_CHAR;
1908
+ prev.output += ONE_CHAR;
1909
+ }
1910
+ }
1911
+ push(token);
1912
+ }
1913
+ while (state.brackets > 0) {
1914
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1915
+ state.output = utils.escapeLast(state.output, "[");
1916
+ decrement("brackets");
1917
+ }
1918
+ while (state.parens > 0) {
1919
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
1920
+ state.output = utils.escapeLast(state.output, "(");
1921
+ decrement("parens");
1922
+ }
1923
+ while (state.braces > 0) {
1924
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
1925
+ state.output = utils.escapeLast(state.output, "{");
1926
+ decrement("braces");
1927
+ }
1928
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
1929
+ type: "maybe_slash",
1930
+ value: "",
1931
+ output: `${SLASH_LITERAL}?`
1932
+ });
1933
+ if (state.backtrack === true) {
1934
+ state.output = "";
1935
+ for (const token of state.tokens) {
1936
+ state.output += token.output != null ? token.output : token.value;
1937
+ if (token.suffix) state.output += token.suffix;
1938
+ }
1939
+ }
1940
+ return state;
1941
+ };
1942
+ /**
1943
+ * Fast paths for creating regular expressions for common glob patterns.
1944
+ * This can significantly speed up processing and has very little downside
1945
+ * impact when none of the fast paths match.
1946
+ */
1947
+ parse.fastpaths = (input, options) => {
1948
+ const opts = { ...options };
1949
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1950
+ const len = input.length;
1951
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1952
+ input = REPLACEMENTS[input] || input;
1953
+ const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(opts.windows);
1954
+ const nodot = opts.dot ? NO_DOTS : NO_DOT;
1955
+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
1956
+ const capture = opts.capture ? "" : "?:";
1957
+ const state = {
1958
+ negated: false,
1959
+ prefix: ""
1960
+ };
1961
+ let star = opts.bash === true ? ".*?" : STAR;
1962
+ if (opts.capture) star = `(${star})`;
1963
+ const globstar = (opts) => {
1964
+ if (opts.noglobstar === true) return star;
1965
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
1966
+ };
1967
+ const create = (str) => {
1968
+ switch (str) {
1969
+ case "*": return `${nodot}${ONE_CHAR}${star}`;
1970
+ case ".*": return `${DOT_LITERAL}${ONE_CHAR}${star}`;
1971
+ case "*.*": return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1972
+ case "*/*": return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
1973
+ case "**": return nodot + globstar(opts);
1974
+ case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
1975
+ case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1976
+ case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
1977
+ default: {
1978
+ const match = /^(.*?)\.(\w+)$/.exec(str);
1979
+ if (!match) return;
1980
+ const source = create(match[1]);
1981
+ if (!source) return;
1982
+ return source + DOT_LITERAL + match[2];
1983
+ }
1984
+ }
1985
+ };
1986
+ let source = create(utils.removePrefix(input, state));
1987
+ if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL}?`;
1988
+ return source;
1989
+ };
1990
+ module.exports = parse;
1991
+ }));
1992
+
1993
+ //#endregion
1994
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js
1995
+ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1996
+ const scan = require_scan();
1997
+ const parse = require_parse();
1998
+ const utils = require_utils();
1999
+ const constants = require_constants();
2000
+ const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
2001
+ /**
2002
+ * Creates a matcher function from one or more glob patterns. The
2003
+ * returned function takes a string to match as its first argument,
2004
+ * and returns true if the string is a match. The returned matcher
2005
+ * function also takes a boolean as the second argument that, when true,
2006
+ * returns an object with additional information.
2007
+ *
2008
+ * ```js
2009
+ * const picomatch = require('picomatch');
2010
+ * // picomatch(glob[, options]);
2011
+ *
2012
+ * const isMatch = picomatch('*.!(*a)');
2013
+ * console.log(isMatch('a.a')); //=> false
2014
+ * console.log(isMatch('a.b')); //=> true
2015
+ * ```
2016
+ * @name picomatch
2017
+ * @param {String|Array} `globs` One or more glob patterns.
2018
+ * @param {Object=} `options`
2019
+ * @return {Function=} Returns a matcher function.
2020
+ * @api public
2021
+ */
2022
+ const picomatch = (glob, options, returnState = false) => {
2023
+ if (Array.isArray(glob)) {
2024
+ const fns = glob.map((input) => picomatch(input, options, returnState));
2025
+ const arrayMatcher = (str) => {
2026
+ for (const isMatch of fns) {
2027
+ const state = isMatch(str);
2028
+ if (state) return state;
2029
+ }
2030
+ return false;
2031
+ };
2032
+ return arrayMatcher;
2033
+ }
2034
+ const isState = isObject(glob) && glob.tokens && glob.input;
2035
+ if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
2036
+ const opts = options || {};
2037
+ const posix = opts.windows;
2038
+ const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
2039
+ const state = regex.state;
2040
+ delete regex.state;
2041
+ let isIgnored = () => false;
2042
+ if (opts.ignore) {
2043
+ const ignoreOpts = {
2044
+ ...options,
2045
+ ignore: null,
2046
+ onMatch: null,
2047
+ onResult: null
2048
+ };
2049
+ isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
2050
+ }
2051
+ const matcher = (input, returnObject = false) => {
2052
+ const { isMatch, match, output } = picomatch.test(input, regex, options, {
2053
+ glob,
2054
+ posix
2055
+ });
2056
+ const result = {
2057
+ glob,
2058
+ state,
2059
+ regex,
2060
+ posix,
2061
+ input,
2062
+ output,
2063
+ match,
2064
+ isMatch
2065
+ };
2066
+ if (typeof opts.onResult === "function") opts.onResult(result);
2067
+ if (isMatch === false) {
2068
+ result.isMatch = false;
2069
+ return returnObject ? result : false;
2070
+ }
2071
+ if (isIgnored(input)) {
2072
+ if (typeof opts.onIgnore === "function") opts.onIgnore(result);
2073
+ result.isMatch = false;
2074
+ return returnObject ? result : false;
2075
+ }
2076
+ if (typeof opts.onMatch === "function") opts.onMatch(result);
2077
+ return returnObject ? result : true;
2078
+ };
2079
+ if (returnState) matcher.state = state;
2080
+ return matcher;
2081
+ };
2082
+ /**
2083
+ * Test `input` with the given `regex`. This is used by the main
2084
+ * `picomatch()` function to test the input string.
2085
+ *
2086
+ * ```js
2087
+ * const picomatch = require('picomatch');
2088
+ * // picomatch.test(input, regex[, options]);
2089
+ *
2090
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
2091
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
2092
+ * ```
2093
+ * @param {String} `input` String to test.
2094
+ * @param {RegExp} `regex`
2095
+ * @return {Object} Returns an object with matching info.
2096
+ * @api public
2097
+ */
2098
+ picomatch.test = (input, regex, options, { glob, posix } = {}) => {
2099
+ if (typeof input !== "string") throw new TypeError("Expected input to be a string");
2100
+ if (input === "") return {
2101
+ isMatch: false,
2102
+ output: ""
2103
+ };
2104
+ const opts = options || {};
2105
+ const format = opts.format || (posix ? utils.toPosixSlashes : null);
2106
+ let match = input === glob;
2107
+ let output = match && format ? format(input) : input;
2108
+ if (match === false) {
2109
+ output = format ? format(input) : input;
2110
+ match = output === glob;
2111
+ }
2112
+ if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch.matchBase(input, regex, options, posix);
2113
+ else match = regex.exec(output);
2114
+ return {
2115
+ isMatch: Boolean(match),
2116
+ match,
2117
+ output
2118
+ };
2119
+ };
2120
+ /**
2121
+ * Match the basename of a filepath.
2122
+ *
2123
+ * ```js
2124
+ * const picomatch = require('picomatch');
2125
+ * // picomatch.matchBase(input, glob[, options]);
2126
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
2127
+ * ```
2128
+ * @param {String} `input` String to test.
2129
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
2130
+ * @return {Boolean}
2131
+ * @api public
2132
+ */
2133
+ picomatch.matchBase = (input, glob, options) => {
2134
+ return (glob instanceof RegExp ? glob : picomatch.makeRe(glob, options)).test(utils.basename(input));
2135
+ };
2136
+ /**
2137
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
2138
+ *
2139
+ * ```js
2140
+ * const picomatch = require('picomatch');
2141
+ * // picomatch.isMatch(string, patterns[, options]);
2142
+ *
2143
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
2144
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
2145
+ * ```
2146
+ * @param {String|Array} str The string to test.
2147
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
2148
+ * @param {Object} [options] See available [options](#options).
2149
+ * @return {Boolean} Returns true if any patterns match `str`
2150
+ * @api public
2151
+ */
2152
+ picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
2153
+ /**
2154
+ * Parse a glob pattern to create the source string for a regular
2155
+ * expression.
2156
+ *
2157
+ * ```js
2158
+ * const picomatch = require('picomatch');
2159
+ * const result = picomatch.parse(pattern[, options]);
2160
+ * ```
2161
+ * @param {String} `pattern`
2162
+ * @param {Object} `options`
2163
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
2164
+ * @api public
2165
+ */
2166
+ picomatch.parse = (pattern, options) => {
2167
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options));
2168
+ return parse(pattern, {
2169
+ ...options,
2170
+ fastpaths: false
2171
+ });
2172
+ };
2173
+ /**
2174
+ * Scan a glob pattern to separate the pattern into segments.
2175
+ *
2176
+ * ```js
2177
+ * const picomatch = require('picomatch');
2178
+ * // picomatch.scan(input[, options]);
2179
+ *
2180
+ * const result = picomatch.scan('!./foo/*.js');
2181
+ * console.log(result);
2182
+ * { prefix: '!./',
2183
+ * input: '!./foo/*.js',
2184
+ * start: 3,
2185
+ * base: 'foo',
2186
+ * glob: '*.js',
2187
+ * isBrace: false,
2188
+ * isBracket: false,
2189
+ * isGlob: true,
2190
+ * isExtglob: false,
2191
+ * isGlobstar: false,
2192
+ * negated: true }
2193
+ * ```
2194
+ * @param {String} `input` Glob pattern to scan.
2195
+ * @param {Object} `options`
2196
+ * @return {Object} Returns an object with
2197
+ * @api public
2198
+ */
2199
+ picomatch.scan = (input, options) => scan(input, options);
2200
+ /**
2201
+ * Compile a regular expression from the `state` object returned by the
2202
+ * [parse()](#parse) method.
2203
+ *
2204
+ * @param {Object} `state`
2205
+ * @param {Object} `options`
2206
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
2207
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
2208
+ * @return {RegExp}
2209
+ * @api public
2210
+ */
2211
+ picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
2212
+ if (returnOutput === true) return state.output;
2213
+ const opts = options || {};
2214
+ const prepend = opts.contains ? "" : "^";
2215
+ const append = opts.contains ? "" : "$";
2216
+ let source = `${prepend}(?:${state.output})${append}`;
2217
+ if (state && state.negated === true) source = `^(?!${source}).*$`;
2218
+ const regex = picomatch.toRegex(source, options);
2219
+ if (returnState === true) regex.state = state;
2220
+ return regex;
2221
+ };
2222
+ /**
2223
+ * Create a regular expression from a parsed glob pattern.
2224
+ *
2225
+ * ```js
2226
+ * const picomatch = require('picomatch');
2227
+ * const state = picomatch.parse('*.js');
2228
+ * // picomatch.compileRe(state[, options]);
2229
+ *
2230
+ * console.log(picomatch.compileRe(state));
2231
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
2232
+ * ```
2233
+ * @param {String} `state` The object returned from the `.parse` method.
2234
+ * @param {Object} `options`
2235
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
2236
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
2237
+ * @return {RegExp} Returns a regex created from the given pattern.
2238
+ * @api public
2239
+ */
2240
+ picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
2241
+ if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
2242
+ let parsed = {
2243
+ negated: false,
2244
+ fastpaths: true
2245
+ };
2246
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
2247
+ if (!parsed.output) parsed = parse(input, options);
2248
+ return picomatch.compileRe(parsed, options, returnOutput, returnState);
2249
+ };
2250
+ /**
2251
+ * Create a regular expression from the given regex source string.
2252
+ *
2253
+ * ```js
2254
+ * const picomatch = require('picomatch');
2255
+ * // picomatch.toRegex(source[, options]);
2256
+ *
2257
+ * const { output } = picomatch.parse('*.js');
2258
+ * console.log(picomatch.toRegex(output));
2259
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
2260
+ * ```
2261
+ * @param {String} `source` Regular expression source string.
2262
+ * @param {Object} `options`
2263
+ * @return {RegExp}
2264
+ * @api public
2265
+ */
2266
+ picomatch.toRegex = (source, options) => {
2267
+ try {
2268
+ const opts = options || {};
2269
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
2270
+ } catch (err) {
2271
+ if (options && options.debug === true) throw err;
2272
+ return /$^/;
2273
+ }
2274
+ };
2275
+ /**
2276
+ * Picomatch constants.
2277
+ * @return {Object}
2278
+ */
2279
+ picomatch.constants = constants;
2280
+ /**
2281
+ * Expose "picomatch"
2282
+ */
2283
+ module.exports = picomatch;
2284
+ }));
2285
+
2286
+ //#endregion
2287
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js
2288
+ var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2289
+ const pico = require_picomatch$1();
2290
+ const utils = require_utils();
2291
+ function picomatch(glob, options, returnState = false) {
2292
+ if (options && (options.windows === null || options.windows === void 0)) options = {
2293
+ ...options,
2294
+ windows: utils.isWindows()
2295
+ };
2296
+ return pico(glob, options, returnState);
2297
+ }
2298
+ Object.assign(picomatch, pico);
2299
+ module.exports = picomatch;
2300
+ }));
2301
+
2302
+ //#endregion
2303
+ //#region ../../node_modules/.pnpm/tinyglobby@0.2.15/node_modules/tinyglobby/dist/index.mjs
2304
+ var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
2305
+ const isReadonlyArray = Array.isArray;
2306
+ const isWin = process.platform === "win32";
2307
+ const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
2308
+ function getPartialMatcher(patterns, options = {}) {
2309
+ const patternsCount = patterns.length;
2310
+ const patternsParts = Array(patternsCount);
2311
+ const matchers = Array(patternsCount);
2312
+ const globstarEnabled = !options.noglobstar;
2313
+ for (let i = 0; i < patternsCount; i++) {
2314
+ const parts = splitPattern(patterns[i]);
2315
+ patternsParts[i] = parts;
2316
+ const partsCount = parts.length;
2317
+ const partMatchers = Array(partsCount);
2318
+ for (let j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
2319
+ matchers[i] = partMatchers;
2320
+ }
2321
+ return (input) => {
2322
+ const inputParts = input.split("/");
2323
+ if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
2324
+ for (let i = 0; i < patterns.length; i++) {
2325
+ const patternParts = patternsParts[i];
2326
+ const matcher = matchers[i];
2327
+ const inputPatternCount = inputParts.length;
2328
+ const minParts = Math.min(inputPatternCount, patternParts.length);
2329
+ let j = 0;
2330
+ while (j < minParts) {
2331
+ const part = patternParts[j];
2332
+ if (part.includes("/")) return true;
2333
+ if (!matcher[j](inputParts[j])) break;
2334
+ if (globstarEnabled && part === "**") return true;
2335
+ j++;
2336
+ }
2337
+ if (j === inputPatternCount) return true;
2338
+ }
2339
+ return false;
2340
+ };
2341
+ }
2342
+ /* node:coverage ignore next 2 */
2343
+ const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
2344
+ const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
2345
+ function buildFormat(cwd, root, absolute) {
2346
+ if (cwd === root || root.startsWith(`${cwd}/`)) {
2347
+ if (absolute) {
2348
+ const start = isRoot(cwd) ? cwd.length : cwd.length + 1;
2349
+ return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
2350
+ }
2351
+ const prefix = root.slice(cwd.length + 1);
2352
+ if (prefix) return (p, isDir) => {
2353
+ if (p === ".") return prefix;
2354
+ const result = `${prefix}/${p}`;
2355
+ return isDir ? result.slice(0, -1) : result;
2356
+ };
2357
+ return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
2358
+ }
2359
+ if (absolute) return (p) => posix.relative(cwd, p) || ".";
2360
+ return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
2361
+ }
2362
+ function buildRelative(cwd, root) {
2363
+ if (root.startsWith(`${cwd}/`)) {
2364
+ const prefix = root.slice(cwd.length + 1);
2365
+ return (p) => `${prefix}/${p}`;
2366
+ }
2367
+ return (p) => {
2368
+ const result = posix.relative(cwd, `${root}/${p}`);
2369
+ if (p.endsWith("/") && result !== "") return `${result}/`;
2370
+ return result || ".";
2371
+ };
2372
+ }
2373
+ const splitPatternOptions = { parts: true };
2374
+ function splitPattern(path$1) {
2375
+ var _result$parts;
2376
+ const result = import_picomatch.default.scan(path$1, splitPatternOptions);
2377
+ return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1];
2378
+ }
2379
+ const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
2380
+ const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
2381
+ const escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
2382
+ const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
2383
+ /**
2384
+ * Escapes a path's special characters depending on the platform.
2385
+ * @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
2386
+ */
2387
+ /* node:coverage ignore next */
2388
+ const escapePath = isWin ? escapeWin32Path : escapePosixPath;
2389
+ /**
2390
+ * Checks if a pattern has dynamic parts.
2391
+ *
2392
+ * Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
2393
+ *
2394
+ * - Doesn't necessarily return `false` on patterns that include `\`.
2395
+ * - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
2396
+ * - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
2397
+ * - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
2398
+ *
2399
+ * @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
2400
+ */
2401
+ function isDynamicPattern(pattern, options) {
2402
+ if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
2403
+ const scan = import_picomatch.default.scan(pattern);
2404
+ return scan.isGlob || scan.negated;
2405
+ }
2406
+ function log(...tasks) {
2407
+ console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
2408
+ }
2409
+ const PARENT_DIRECTORY = /^(\/?\.\.)+/;
2410
+ const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
2411
+ const BACKSLASHES = /\\/g;
2412
+ function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
2413
+ let result = pattern;
2414
+ if (pattern.endsWith("/")) result = pattern.slice(0, -1);
2415
+ if (!result.endsWith("*") && expandDirectories) result += "/**";
2416
+ const escapedCwd = escapePath(cwd);
2417
+ if (path$1.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
2418
+ else result = posix.normalize(result);
2419
+ const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
2420
+ const parts = splitPattern(result);
2421
+ if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
2422
+ const n = (parentDirectoryMatch[0].length + 1) / 3;
2423
+ let i = 0;
2424
+ const cwdParts = escapedCwd.split("/");
2425
+ while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
2426
+ result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
2427
+ i++;
2428
+ }
2429
+ const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
2430
+ if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
2431
+ props.root = potentialRoot;
2432
+ props.depthOffset = -n + i;
2433
+ }
2434
+ }
2435
+ if (!isIgnore && props.depthOffset >= 0) {
2436
+ var _props$commonPath;
2437
+ (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
2438
+ const newCommonPath = [];
2439
+ const length = Math.min(props.commonPath.length, parts.length);
2440
+ for (let i = 0; i < length; i++) {
2441
+ const part = parts[i];
2442
+ if (part === "**" && !parts[i + 1]) {
2443
+ newCommonPath.pop();
2444
+ break;
2445
+ }
2446
+ if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
2447
+ newCommonPath.push(part);
2448
+ }
2449
+ props.depthOffset = newCommonPath.length;
2450
+ props.commonPath = newCommonPath;
2451
+ props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
2452
+ }
2453
+ return result;
2454
+ }
2455
+ function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) {
2456
+ if (typeof patterns === "string") patterns = [patterns];
2457
+ if (typeof ignore === "string") ignore = [ignore];
2458
+ const matchPatterns = [];
2459
+ const ignorePatterns = [];
2460
+ for (const pattern of ignore) {
2461
+ if (!pattern) continue;
2462
+ if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
2463
+ }
2464
+ for (const pattern of patterns) {
2465
+ if (!pattern) continue;
2466
+ if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
2467
+ else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
2468
+ }
2469
+ return {
2470
+ match: matchPatterns,
2471
+ ignore: ignorePatterns
2472
+ };
2473
+ }
2474
+ function formatPaths(paths, relative) {
2475
+ for (let i = paths.length - 1; i >= 0; i--) {
2476
+ const path$1 = paths[i];
2477
+ paths[i] = relative(path$1);
2478
+ }
2479
+ return paths;
2480
+ }
2481
+ function normalizeCwd(cwd) {
2482
+ if (!cwd) return process.cwd().replace(BACKSLASHES, "/");
2483
+ if (cwd instanceof URL) return fileURLToPath$1(cwd).replace(BACKSLASHES, "/");
2484
+ return path$1.resolve(cwd).replace(BACKSLASHES, "/");
2485
+ }
2486
+ function getCrawler(patterns, inputOptions = {}) {
2487
+ const options = process.env.TINYGLOBBY_DEBUG ? {
2488
+ ...inputOptions,
2489
+ debug: true
2490
+ } : inputOptions;
2491
+ const cwd = normalizeCwd(options.cwd);
2492
+ if (options.debug) log("globbing with:", {
2493
+ patterns,
2494
+ options,
2495
+ cwd
2496
+ });
2497
+ if (Array.isArray(patterns) && patterns.length === 0) return [{
2498
+ sync: () => [],
2499
+ withPromise: async () => []
2500
+ }, false];
2501
+ const props = {
2502
+ root: cwd,
2503
+ commonPath: null,
2504
+ depthOffset: 0
2505
+ };
2506
+ const processed = processPatterns({
2507
+ ...options,
2508
+ patterns
2509
+ }, cwd, props);
2510
+ if (options.debug) log("internal processing patterns:", processed);
2511
+ const matchOptions = {
2512
+ dot: options.dot,
2513
+ nobrace: options.braceExpansion === false,
2514
+ nocase: options.caseSensitiveMatch === false,
2515
+ noextglob: options.extglob === false,
2516
+ noglobstar: options.globstar === false,
2517
+ posix: true
2518
+ };
2519
+ const matcher = (0, import_picomatch.default)(processed.match, {
2520
+ ...matchOptions,
2521
+ ignore: processed.ignore
2522
+ });
2523
+ const ignore = (0, import_picomatch.default)(processed.ignore, matchOptions);
2524
+ const partialMatcher = getPartialMatcher(processed.match, matchOptions);
2525
+ const format = buildFormat(cwd, props.root, options.absolute);
2526
+ const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true);
2527
+ const fdirOptions = {
2528
+ filters: [options.debug ? (p, isDirectory) => {
2529
+ const path$1 = format(p, isDirectory);
2530
+ const matches = matcher(path$1);
2531
+ if (matches) log(`matched ${path$1}`);
2532
+ return matches;
2533
+ } : (p, isDirectory) => matcher(format(p, isDirectory))],
2534
+ exclude: options.debug ? (_, p) => {
2535
+ const relativePath = formatExclude(p, true);
2536
+ const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
2537
+ if (skipped) log(`skipped ${p}`);
2538
+ else log(`crawling ${p}`);
2539
+ return skipped;
2540
+ } : (_, p) => {
2541
+ const relativePath = formatExclude(p, true);
2542
+ return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
2543
+ },
2544
+ fs: options.fs ? {
2545
+ readdir: options.fs.readdir || nativeFs.readdir,
2546
+ readdirSync: options.fs.readdirSync || nativeFs.readdirSync,
2547
+ realpath: options.fs.realpath || nativeFs.realpath,
2548
+ realpathSync: options.fs.realpathSync || nativeFs.realpathSync,
2549
+ stat: options.fs.stat || nativeFs.stat,
2550
+ statSync: options.fs.statSync || nativeFs.statSync
2551
+ } : void 0,
2552
+ pathSeparator: "/",
2553
+ relativePaths: true,
2554
+ resolveSymlinks: true,
2555
+ signal: options.signal
2556
+ };
2557
+ if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
2558
+ if (options.absolute) {
2559
+ fdirOptions.relativePaths = false;
2560
+ fdirOptions.resolvePaths = true;
2561
+ fdirOptions.includeBasePath = true;
2562
+ }
2563
+ if (options.followSymbolicLinks === false) {
2564
+ fdirOptions.resolveSymlinks = false;
2565
+ fdirOptions.excludeSymlinks = true;
2566
+ }
2567
+ if (options.onlyDirectories) {
2568
+ fdirOptions.excludeFiles = true;
2569
+ fdirOptions.includeDirs = true;
2570
+ } else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
2571
+ props.root = props.root.replace(BACKSLASHES, "");
2572
+ const root = props.root;
2573
+ if (options.debug) log("internal properties:", props);
2574
+ const relative = cwd !== root && !options.absolute && buildRelative(cwd, props.root);
2575
+ return [new Builder(fdirOptions).crawl(root), relative];
2576
+ }
2577
+ async function glob(patternsOrOptions, options) {
2578
+ if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
2579
+ const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
2580
+ const opts = isModern ? options : patternsOrOptions;
2581
+ const [crawler, relative] = getCrawler(isModern ? patternsOrOptions : patternsOrOptions.patterns, opts);
2582
+ if (!relative) return crawler.withPromise();
2583
+ return formatPaths(await crawler.withPromise(), relative);
2584
+ }
2585
+
2586
+ //#endregion
2587
+ //#region ../../node_modules/.pnpm/empathic@2.0.0/node_modules/empathic/resolve.mjs
2588
+ /**
2589
+ * Resolve an absolute path from {@link root}, but only
2590
+ * if {@link input} isn't already absolute.
2591
+ *
2592
+ * @param input The path to resolve.
2593
+ * @param root The base path; default = process.cwd()
2594
+ * @returns The resolved absolute path.
2595
+ */
2596
+ function absolute(input, root) {
2597
+ return isAbsolute(input) ? input : resolve(root || ".", input);
2598
+ }
2599
+
2600
+ //#endregion
2601
+ //#region ../../node_modules/.pnpm/empathic@2.0.0/node_modules/empathic/walk.mjs
2602
+ /**
2603
+ * Get all parent directories of {@link base}.
2604
+ * Stops after {@link Options['last']} is processed.
2605
+ *
2606
+ * @returns An array of absolute paths of all parent directories.
2607
+ */
2608
+ function up$2(base, options) {
2609
+ let { last, cwd } = options || {};
2610
+ let tmp = absolute(base, cwd);
2611
+ let root = absolute(last || "/", cwd);
2612
+ let prev, arr = [];
2613
+ while (prev !== root) {
2614
+ arr.push(tmp);
2615
+ tmp = dirname(prev = tmp);
2616
+ if (tmp === prev) break;
2617
+ }
2618
+ return arr;
2619
+ }
2620
+
2621
+ //#endregion
2622
+ //#region ../../node_modules/.pnpm/empathic@2.0.0/node_modules/empathic/find.mjs
2623
+ /**
2624
+ * Find an item by name, walking parent directories until found.
2625
+ *
2626
+ * @param name The item name to find.
2627
+ * @returns The absolute path to the item, if found.
2628
+ */
2629
+ function up$1(name, options) {
2630
+ let dir, tmp;
2631
+ let start = options && options.cwd || "";
2632
+ for (dir of up$2(start, options)) {
2633
+ tmp = join(dir, name);
2634
+ if (existsSync(tmp)) return tmp;
2635
+ }
2636
+ }
2637
+
2638
+ //#endregion
2639
+ //#region ../../node_modules/.pnpm/empathic@2.0.0/node_modules/empathic/package.mjs
2640
+ /**
2641
+ * Find the closest "package.json" file while walking parent directories.
2642
+ * @returns The absolute path to a "package.json", if found.
2643
+ */
2644
+ function up(options) {
2645
+ return up$1("package.json", options);
2646
+ }
2647
+
2648
+ //#endregion
2649
+ //#region ../../node_modules/.pnpm/import-without-cache@0.2.5/node_modules/import-without-cache/dist/index.mjs
2650
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
2651
+ const namespace = "no-cache://";
2652
+ const namespaceLength = 11;
2653
+ const isSupported = !!module$1.registerHooks;
2654
+ const RE_NODE_MODULES = /[/\\]node_modules[/\\]/;
2655
+ let deregister;
2656
+ function init({ skipNodeModules } = {}) {
2657
+ if (process$1.versions.bun) throw new Error("init is unnecessary in Bun, use clearRequireCache() instead.");
2658
+ if (!isSupported) throw new Error("import-without-cache requires Node.js v22.15.0 or higher.");
2659
+ if (deregister) return deregister;
2660
+ const hooks = module$1.registerHooks({
2661
+ resolve(specifier, context, nextResolve) {
2662
+ let noCache = context.importAttributes?.cache === "no";
2663
+ if (specifier.startsWith(namespace)) {
2664
+ specifier = specifier.slice(namespaceLength);
2665
+ noCache = true;
2666
+ }
2667
+ const resolved = nextResolve(specifier, context);
2668
+ if (skipNodeModules && RE_NODE_MODULES.test(resolved.url)) return resolved;
2669
+ if (!resolved.url.startsWith("file://")) return resolved;
2670
+ const parentUUID = getParentUUID(context.parentURL);
2671
+ if (!noCache && !parentUUID) return resolved;
2672
+ resolved.url = appendUUID(resolved.url, parentUUID || crypto.randomUUID());
2673
+ return resolved;
2674
+ },
2675
+ load(url, context, nextLoad) {
2676
+ cleanupImportAttributes(context);
2677
+ return nextLoad(url, context);
2678
+ }
2679
+ });
2680
+ return deregister = () => {
2681
+ hooks.deregister();
2682
+ deregister = void 0;
2683
+ };
2684
+ }
2685
+ function clearRequireCache() {
2686
+ for (const key of Object.keys(__require.cache)) delete __require.cache[key];
2687
+ }
2688
+ function getParentUUID(parentURL) {
2689
+ if (!parentURL) return;
2690
+ return new URL(parentURL).searchParams.get("no-cache") ?? void 0;
2691
+ }
2692
+ function appendUUID(url, uuid) {
2693
+ const parsed = new URL(url);
2694
+ parsed.searchParams.set("no-cache", uuid);
2695
+ return parsed.toString();
2696
+ }
2697
+ function cleanupImportAttributes(context) {
2698
+ if (!context.importAttributes?.cache) return;
2699
+ const attrs = Object.assign(Object.create(null), context.importAttributes);
2700
+ delete attrs.cache;
2701
+ context.importAttributes = attrs;
2702
+ Object.freeze(context.importAttributes);
2703
+ }
2704
+
2705
+ //#endregion
2706
+ //#region ../../node_modules/.pnpm/quansync@1.0.0/node_modules/quansync/dist/src-C2Pm6gXo.js
2707
+ const GET_IS_ASYNC = Symbol.for("quansync.getIsAsync");
2708
+ var QuansyncError = class extends Error {
2709
+ constructor(message = "Unexpected promise in sync context") {
2710
+ super(message);
2711
+ this.name = "QuansyncError";
2712
+ }
2713
+ };
2714
+ function isThenable(value) {
2715
+ return value && typeof value === "object" && typeof value.then === "function";
2716
+ }
2717
+ function isQuansyncGenerator(value) {
2718
+ return value && typeof value === "object" && typeof value[Symbol.iterator] === "function" && "__quansync" in value;
2719
+ }
2720
+ function fromObject(options) {
2721
+ const generator = function* (...args) {
2722
+ if (yield GET_IS_ASYNC) return yield options.async.apply(this, args);
2723
+ return options.sync.apply(this, args);
2724
+ };
2725
+ function fn(...args) {
2726
+ const iter = generator.apply(this, args);
2727
+ iter.then = (...thenArgs) => options.async.apply(this, args).then(...thenArgs);
2728
+ iter.__quansync = true;
2729
+ return iter;
2730
+ }
2731
+ fn.sync = options.sync;
2732
+ fn.async = options.async;
2733
+ return fn;
2734
+ }
2735
+ function fromPromise(promise) {
2736
+ return fromObject({
2737
+ async: () => Promise.resolve(promise),
2738
+ sync: () => {
2739
+ if (isThenable(promise)) throw new QuansyncError();
2740
+ return promise;
2741
+ }
2742
+ });
2743
+ }
2744
+ function unwrapYield(value, isAsync) {
2745
+ if (value === GET_IS_ASYNC) return isAsync;
2746
+ if (isQuansyncGenerator(value)) return isAsync ? iterateAsync(value) : iterateSync(value);
2747
+ if (!isAsync && isThenable(value)) throw new QuansyncError();
2748
+ return value;
2749
+ }
2750
+ const DEFAULT_ON_YIELD = (value) => value;
2751
+ function iterateSync(generator, onYield = DEFAULT_ON_YIELD) {
2752
+ let current = generator.next();
2753
+ while (!current.done) try {
2754
+ current = generator.next(unwrapYield(onYield(current.value, false)));
2755
+ } catch (err) {
2756
+ current = generator.throw(err);
2757
+ }
2758
+ return unwrapYield(current.value);
2759
+ }
2760
+ async function iterateAsync(generator, onYield = DEFAULT_ON_YIELD) {
2761
+ let current = generator.next();
2762
+ while (!current.done) try {
2763
+ current = generator.next(await unwrapYield(onYield(current.value, true), true));
2764
+ } catch (err) {
2765
+ current = generator.throw(err);
2766
+ }
2767
+ return current.value;
2768
+ }
2769
+ function fromGeneratorFn(generatorFn, options) {
2770
+ return fromObject({
2771
+ name: generatorFn.name,
2772
+ async(...args) {
2773
+ return iterateAsync(generatorFn.apply(this, args), options?.onYield);
2774
+ },
2775
+ sync(...args) {
2776
+ return iterateSync(generatorFn.apply(this, args), options?.onYield);
2777
+ }
2778
+ });
2779
+ }
2780
+ function quansync$1(input, options) {
2781
+ if (isThenable(input)) return fromPromise(input);
2782
+ if (typeof input === "function") return fromGeneratorFn(input, options);
2783
+ else return fromObject(input);
2784
+ }
2785
+ /**
2786
+ * @returns `true` if the current context is async, `false` otherwise.
2787
+ */
2788
+ const getIsAsync = quansync$1({
2789
+ async: () => Promise.resolve(true),
2790
+ sync: () => false
2791
+ });
2792
+
2793
+ //#endregion
2794
+ //#region ../../node_modules/.pnpm/quansync@1.0.0/node_modules/quansync/dist/macro.js
2795
+ /**
2796
+ * This function is equivalent to `quansync` from main entry
2797
+ * but accepts a fake argument type of async functions.
2798
+ *
2799
+ * This requires to be used with the macro transformer `unplugin-quansync`.
2800
+ * Do NOT use it directly.
2801
+ *
2802
+ * @internal
2803
+ */
2804
+ const quansync = quansync$1;
2805
+
2806
+ //#endregion
2807
+ //#region ../../node_modules/.pnpm/@quansync+fs@1.0.0/node_modules/@quansync/fs/dist/index.mjs
2808
+ /**
2809
+ * @link https://nodejs.org/api/fs.html#fspromisesreadfilepath-options
2810
+ */
2811
+ const readFile$1 = quansync$1({
2812
+ sync: fs$1.readFileSync,
2813
+ async: fs$1.promises.readFile
2814
+ });
2815
+ /**
2816
+ * @link https://nodejs.org/api/fs.html#fspromiseswritefilefile-data-options
2817
+ */
2818
+ const writeFile$1 = quansync$1({
2819
+ sync: fs$1.writeFileSync,
2820
+ async: fs$1.promises.writeFile
2821
+ });
2822
+ /**
2823
+ * @link https://nodejs.org/api/fs.html#fspromisesunlinkpath
2824
+ */
2825
+ const unlink = quansync$1({
2826
+ sync: fs$1.unlinkSync,
2827
+ async: fs$1.promises.unlink
2828
+ });
2829
+ /**
2830
+ * @link https://nodejs.org/api/fs.html#fspromisesaccesspath-mode
2831
+ */
2832
+ const access$1 = quansync$1({
2833
+ sync: fs$1.accessSync,
2834
+ async: fs$1.promises.access
2835
+ });
2836
+ /**
2837
+ * @link https://nodejs.org/api/fs.html#fspromisesstatpath-options
2838
+ */
2839
+ const stat$1 = quansync$1({
2840
+ sync: fs$1.statSync,
2841
+ async: fs$1.promises.stat
2842
+ });
2843
+ const lstat = quansync$1({
2844
+ sync: fs$1.lstatSync,
2845
+ async: fs$1.promises.lstat
2846
+ });
2847
+ /**
2848
+ * @link https://nodejs.org/api/fs.html#fspromisescpsrc-dest-options
2849
+ */
2850
+ const cp$1 = quansync$1({
2851
+ sync: fs$1.copyFileSync,
2852
+ async: fs$1.promises.copyFile
2853
+ });
2854
+ /**
2855
+ * @link https://nodejs.org/api/fs.html#fspromisesrmpath-options
2856
+ */
2857
+ const rm$1 = quansync$1({
2858
+ sync: fs$1.rmSync,
2859
+ async: fs$1.promises.rm
2860
+ });
2861
+ /**
2862
+ * @link https://nodejs.org/api/fs.html#fspromisesmkdirpath-options
2863
+ */
2864
+ const mkdir = quansync$1({
2865
+ sync: fs$1.mkdirSync,
2866
+ async: fs$1.promises.mkdir
2867
+ });
2868
+ /**
2869
+ * @link https://nodejs.org/api/fs.html#fspromisesrenameoldpath-newpath
2870
+ */
2871
+ const rename = quansync$1({
2872
+ sync: fs$1.renameSync,
2873
+ async: fs$1.promises.rename
2874
+ });
2875
+ /**
2876
+ * @link https://nodejs.org/api/fs.html#fspromisesreaddirpath-options
2877
+ */
2878
+ const readdir = quansync$1({
2879
+ sync: fs$1.readdirSync,
2880
+ async: fs$1.promises.readdir
2881
+ });
2882
+ /**
2883
+ * @link https://nodejs.org/api/fs.html#fspromisesrealpathpath-options
2884
+ */
2885
+ const realpath = quansync$1({
2886
+ sync: fs$1.realpathSync,
2887
+ async: fs$1.promises.realpath
2888
+ });
2889
+ /**
2890
+ * @link https://nodejs.org/api/fs.html#fspromisesreadlinkpath-options
2891
+ */
2892
+ const readlink = quansync$1({
2893
+ sync: fs$1.readlinkSync,
2894
+ async: fs$1.promises.readlink
2895
+ });
2896
+ /**
2897
+ * @link https://nodejs.org/api/fs.html#fspromisessymlinktarget-path-type
2898
+ */
2899
+ const symlink = quansync$1({
2900
+ sync: fs$1.symlinkSync,
2901
+ async: fs$1.promises.symlink
2902
+ });
2903
+ /**
2904
+ * @link https://nodejs.org/api/fs.html#fspromiseschownpath-uid-gid
2905
+ */
2906
+ const chown = quansync$1({
2907
+ sync: fs$1.chownSync,
2908
+ async: fs$1.promises.chown
2909
+ });
2910
+ /**
2911
+ * @link https://nodejs.org/api/fs.html#fspromiseslchownpath-uid-gid
2912
+ */
2913
+ const lchown = quansync$1({
2914
+ sync: fs$1.lchownSync,
2915
+ async: fs$1.promises.lchown
2916
+ });
2917
+ /**
2918
+ * @link https://nodejs.org/api/fs.html#fspromiseschmodpath-mode
2919
+ */
2920
+ const chmod$1 = quansync$1({
2921
+ sync: fs$1.chmodSync,
2922
+ async: fs$1.promises.chmod
2923
+ });
2924
+ /**
2925
+ * @link https://nodejs.org/api/fs.html#fspromisesutimespath-atime-mtime
2926
+ */
2927
+ const utimes = quansync$1({
2928
+ sync: fs$1.utimesSync,
2929
+ async: fs$1.promises.utimes
2930
+ });
2931
+ /**
2932
+ * @link https://nodejs.org/api/fs.html#fspromiseslutimespath-atime-mtime
2933
+ */
2934
+ const lutimes = quansync$1({
2935
+ sync: fs$1.lutimesSync,
2936
+ async: fs$1.promises.lutimes
2937
+ });
2938
+ /**
2939
+ * @link https://nodejs.org/api/fs.html#fspromisesmkdtempprefix-options
2940
+ */
2941
+ const mkdtemp$1 = quansync$1({
2942
+ sync: fs$1.mkdtempSync,
2943
+ async: fs$1.promises.mkdtemp
2944
+ });
2945
+
2946
+ //#endregion
2947
+ //#region ../../node_modules/.pnpm/unconfig-core@7.4.2/node_modules/unconfig-core/dist/index.mjs
2948
+ const isFile = quansync(function* (path, allowSymlinks) {
2949
+ try {
2950
+ return (yield (allowSymlinks ? stat$1 : lstat)(path)).isFile();
2951
+ } catch {
2952
+ return false;
2953
+ }
2954
+ });
2955
+ const findUp = quansync(function* (paths, options = {}) {
2956
+ const { cwd = process$1.cwd(), stopAt = parse(cwd).root, multiple = false, allowSymlinks = true } = options;
2957
+ let current = cwd;
2958
+ const files = [];
2959
+ while (current && current !== stopAt) {
2960
+ for (const path of paths) {
2961
+ const filepath = resolve(current, path);
2962
+ if (yield isFile(filepath, allowSymlinks)) {
2963
+ files.push(filepath);
2964
+ if (!multiple) return files;
2965
+ }
2966
+ }
2967
+ const parent = dirname(current);
2968
+ if (parent === current) break;
2969
+ current = parent;
2970
+ }
2971
+ return files;
2972
+ });
2973
+ const loadConfigFile$1 = quansync(function* (filepath, source) {
2974
+ try {
2975
+ const config = yield source.parser(filepath);
2976
+ if (!config) return;
2977
+ return {
2978
+ config,
2979
+ source: filepath
2980
+ };
2981
+ } catch (e) {
2982
+ if (source.skipOnError) return;
2983
+ throw e;
2984
+ }
2985
+ });
2986
+ function createConfigCoreLoader(options) {
2987
+ const { cwd = process$1.cwd(), multiple, sources } = options;
2988
+ const results = [];
2989
+ let matchedFiles;
2990
+ const findConfigs = quansync(function* () {
2991
+ if (matchedFiles == null) matchedFiles = [];
2992
+ matchedFiles.length = 0;
2993
+ for (const source of sources) {
2994
+ const { extensions } = source;
2995
+ const files = yield findUp(source.files.flatMap((file) => !extensions?.length ? [file] : extensions.map((ext) => ext ? `${file}.${ext}` : file)), {
2996
+ cwd,
2997
+ stopAt: options.stopAt,
2998
+ multiple
2999
+ });
3000
+ matchedFiles.push([source, files]);
3001
+ }
3002
+ return matchedFiles.flatMap((i) => i[1]);
3003
+ });
3004
+ return {
3005
+ load: quansync(function* (force = false) {
3006
+ if (matchedFiles == null || force) yield findConfigs();
3007
+ for (const [source, files] of matchedFiles) {
3008
+ if (!files.length) continue;
3009
+ if (!multiple) {
3010
+ const result = yield loadConfigFile$1(files[0], source);
3011
+ if (result) return [result];
3012
+ } else for (const file of files) {
3013
+ const result = yield loadConfigFile$1(file, source);
3014
+ if (result) results.push(result);
3015
+ }
3016
+ }
3017
+ return results;
3018
+ }),
3019
+ findConfigs
3020
+ };
3021
+ }
3022
+
3023
+ //#endregion
3024
+ //#region ../../node_modules/.pnpm/tsdown@0.20.2_@arethetypeswrong+core@0.18.2_@typescript+native-preview@7.0.0-dev.202601_11c6934cad7d4cedf7999249d5905a1c/node_modules/tsdown/dist/options-DfwuH01N.mjs
3025
+ const __cjs_require$1 = createRequire(import.meta.url);
3026
+ const picomatch = __cjs_require$1("./npm_entry_picomatch.cjs");
3027
+ const minVersion = __cjs_require$1("./npm_entry_semver_ranges_min-version.cjs");
3028
+ const check = (key) => key in env && env[key] !== "0" && env[key] !== "false";
3029
+ const isInCi = check("CI") || check("CONTINUOUS_INTEGRATION");
3030
+ const debug$3$2 = createDebug("tsdown:clean");
3031
+ const RE_LAST_SLASH = /[/\\]$/;
3032
+ async function cleanOutDir(configs) {
3033
+ const removes = /* @__PURE__ */ new Set();
3034
+ for (const config of configs) {
3035
+ if (config.devtools && (config.devtools.clean ?? true)) config.clean.push("node_modules/.rolldown");
3036
+ if (!config.clean.length) continue;
3037
+ const files = await glob(config.clean, {
3038
+ cwd: config.cwd,
3039
+ absolute: true,
3040
+ onlyFiles: false,
3041
+ dot: true
3042
+ });
3043
+ const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, "");
3044
+ for (const file of files) if (file.replace(RE_LAST_SLASH, "") !== normalizedOutDir) removes.add(file);
3045
+ }
3046
+ if (!removes.size) return;
3047
+ globalLogger.info(`Cleaning ${removes.size} files`);
3048
+ await Promise.all([...removes].map(async (file) => {
3049
+ debug$3$2("Removing", file);
3050
+ await fsRemove(file);
3051
+ }));
3052
+ debug$3$2("Removed %d files", removes.size);
3053
+ }
3054
+ function resolveClean(clean, outDir, cwd) {
3055
+ if (clean === true) clean = [slash(outDir)];
3056
+ else if (!clean) clean = [];
3057
+ if (clean.some((item) => path.resolve(item) === cwd)) throw new Error("Cannot clean the current working directory. Please specify a different path to clean option.");
3058
+ return clean;
3059
+ }
3060
+ async function cleanChunks(outDir, chunks) {
3061
+ await Promise.all(chunks.map(async (chunk) => {
3062
+ const filePath = path.resolve(outDir, chunk.fileName);
3063
+ debug$3$2("Removing chunk file", filePath);
3064
+ await fsRemove(filePath);
3065
+ }));
3066
+ }
3067
+ const defaultCssBundleName = "style.css";
3068
+ function resolveCssOptions(options = {}) {
3069
+ return {
3070
+ splitting: options.splitting ?? true,
3071
+ fileName: options.fileName ?? defaultCssBundleName
3072
+ };
3073
+ }
3074
+ async function resolveEntry(logger, entry, cwd, color, nameLabel) {
3075
+ if (!entry || Object.keys(entry).length === 0) {
3076
+ const defaultEntry = path.resolve(cwd, "src/index.ts");
3077
+ if (await fsExists(defaultEntry)) entry = { index: defaultEntry };
3078
+ else throw new Error(`${nameLabel} No input files, try "tsdown <your-file>" or create src/index.ts`);
3079
+ }
3080
+ const entryMap = await toObjectEntry(entry, cwd);
3081
+ const entries = Object.values(entryMap);
3082
+ if (entries.length === 0) throw new Error(`${nameLabel} Cannot find entry: ${JSON.stringify(entry)}`);
3083
+ logger.info(nameLabel, `entry: ${color(entries.map((entry) => path.relative(cwd, entry)).join(", "))}`);
3084
+ return entryMap;
3085
+ }
3086
+ function toObjectEntry(entry, cwd) {
3087
+ if (typeof entry === "string") entry = [entry];
3088
+ if (!Array.isArray(entry)) return resolveObjectEntry(entry, cwd);
3089
+ return resolveArrayEntry(entry, cwd);
3090
+ }
3091
+ async function resolveObjectEntry(entries, cwd) {
3092
+ return Object.fromEntries((await Promise.all(Object.entries(entries).map(async ([key, value]) => {
3093
+ if (!key.includes("*")) {
3094
+ if (Array.isArray(value)) throw new TypeError(`Object entry "${key}" cannot have an array value when the key is not a glob pattern.`);
3095
+ return [[key, value]];
3096
+ }
3097
+ const patterns = toArray(value);
3098
+ const files = await glob(patterns, {
3099
+ cwd,
3100
+ expandDirectories: false
3101
+ });
3102
+ if (!files.length) throw new Error(`Cannot find files for entry key "${key}" with patterns: ${JSON.stringify(patterns)}`);
3103
+ let valueGlobBase;
3104
+ for (const pattern of patterns) {
3105
+ if (pattern.startsWith("!")) continue;
3106
+ const base = picomatch.scan(pattern).base;
3107
+ if (valueGlobBase === void 0) valueGlobBase = base;
3108
+ else if (valueGlobBase !== base) throw new Error(`When using object entry with glob pattern key "${key}", all value glob patterns must have the same base directory.`);
3109
+ }
3110
+ if (valueGlobBase === void 0) throw new Error(`Cannot determine base directory for value glob patterns of key "${key}".`);
3111
+ return files.map((file) => [slash(key.replaceAll("*", stripExtname(path.relative(valueGlobBase, file)))), path.resolve(cwd, file)]);
3112
+ }))).flat());
3113
+ }
3114
+ async function resolveArrayEntry(entries, cwd) {
3115
+ const stringEntries = [];
3116
+ const objectEntries = [];
3117
+ for (const e of entries) if (typeof e === "string") stringEntries.push(e);
3118
+ else objectEntries.push(e);
3119
+ const isGlob = stringEntries.some((e) => isDynamicPattern(e));
3120
+ let resolvedEntries;
3121
+ if (isGlob) resolvedEntries = (await glob(stringEntries, {
3122
+ cwd,
3123
+ expandDirectories: false,
3124
+ absolute: true
3125
+ })).map((file) => path.resolve(file));
3126
+ else resolvedEntries = stringEntries;
3127
+ const base = lowestCommonAncestor(...resolvedEntries);
3128
+ const arrayEntryMap = Object.fromEntries(resolvedEntries.map((file) => {
3129
+ return [slash(stripExtname(path.relative(base, file))), file];
3130
+ }));
3131
+ return Object.assign({}, arrayEntryMap, ...await Promise.all(objectEntries.map((entry) => resolveObjectEntry(entry, cwd))));
3132
+ }
3133
+ async function writeExports(options, chunks) {
3134
+ const { pkg } = options;
3135
+ const { publishExports, ...generated } = await generateExports(pkg, chunks, options);
3136
+ const updatedPkg = {
3137
+ ...pkg,
3138
+ ...generated,
3139
+ packageJsonPath: void 0
3140
+ };
3141
+ if (publishExports) {
3142
+ updatedPkg.publishConfig ||= {};
3143
+ updatedPkg.publishConfig.exports = publishExports;
3144
+ }
3145
+ const original = readFileSync(pkg.packageJsonPath, "utf8");
3146
+ let contents = JSON.stringify(updatedPkg, null, detectIndentation(original));
3147
+ if (original.endsWith("\n")) contents += "\n";
3148
+ if (contents !== original) writeFileSync(pkg.packageJsonPath, contents, "utf8");
3149
+ }
3150
+ function shouldExclude(fileName, exclude) {
3151
+ if (!exclude?.length) return false;
3152
+ return matchPattern(fileName, exclude);
3153
+ }
3154
+ async function generateExports(pkg, chunks, options) {
3155
+ let { exports: { devExports, all, packageJson = true, exclude, customExports, legacy }, css, logger } = options;
3156
+ const pkgRoot = path.dirname(pkg.packageJsonPath);
3157
+ let main, module, cjsTypes, esmTypes;
3158
+ const exportsMap = /* @__PURE__ */ new Map();
3159
+ const formats = Object.keys(chunks);
3160
+ if (!formats.includes("cjs") && !formats.includes("es")) logger.warn(`No CJS or ESM formats found in chunks for package ${pkg.name}`);
3161
+ const isPureESM = formats.length === 1 && formats[0] === "es";
3162
+ legacy ??= !isPureESM;
3163
+ for (const [format, chunksByFormat] of Object.entries(chunks)) {
3164
+ if (format !== "es" && format !== "cjs") continue;
3165
+ const filteredChunks = chunksByFormat.filter((chunk) => {
3166
+ if (chunk.type !== "chunk" || !chunk.isEntry) return false;
3167
+ const [name] = getExportName(chunk);
3168
+ return !shouldExclude(name, exclude);
3169
+ });
3170
+ const onlyOneEntry = filteredChunks.filter((chunk) => !RE_DTS.test(chunk.fileName)).length === 1;
3171
+ for (const chunk of filteredChunks) {
3172
+ let [name, normalizedName, isDts] = getExportName(chunk);
3173
+ const isIndex = onlyOneEntry || name === "index";
3174
+ const distFile = join$1(pkgRoot, chunk.outDir, normalizedName);
3175
+ if (isIndex) {
3176
+ name = ".";
3177
+ if (format === "cjs") if (isDts) cjsTypes = distFile;
3178
+ else main = distFile;
3179
+ else if (format === "es") if (isDts) esmTypes = distFile;
3180
+ else module = distFile;
3181
+ } else if (name.endsWith("/index")) name = `./${name.slice(0, -6)}`;
3182
+ else name = `./${name}`;
3183
+ let subExport = exportsMap.get(name);
3184
+ if (!subExport) {
3185
+ subExport = {};
3186
+ exportsMap.set(name, subExport);
3187
+ }
3188
+ if (!isDts) {
3189
+ subExport[format] = distFile;
3190
+ if (chunk.facadeModuleId && !subExport.src) subExport.src = `./${slash(path.relative(pkgRoot, chunk.facadeModuleId))}`;
3191
+ }
3192
+ }
3193
+ }
3194
+ const sortedExportsMap = Array.from(exportsMap.entries()).toSorted(([a], [b]) => {
3195
+ if (a === "index") return -1;
3196
+ return a.localeCompare(b);
3197
+ });
3198
+ let exports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(devExports, subExport)]));
3199
+ exportMeta(exports, all, packageJson);
3200
+ exportCss(exports, chunks, css, pkgRoot);
3201
+ if (customExports) exports = await customExports(exports, {
3202
+ pkg,
3203
+ chunks,
3204
+ isPublish: false
3205
+ });
3206
+ let publishExports;
3207
+ if (devExports) {
3208
+ publishExports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(false, subExport)]));
3209
+ exportMeta(publishExports, all, packageJson);
3210
+ exportCss(publishExports, chunks, css, pkgRoot);
3211
+ if (customExports) publishExports = await customExports(publishExports, {
3212
+ pkg,
3213
+ chunks,
3214
+ isPublish: true
3215
+ });
3216
+ }
3217
+ return {
3218
+ main: legacy ? main || module || pkg.main : void 0,
3219
+ module: legacy ? module || pkg.module : void 0,
3220
+ types: legacy ? cjsTypes || esmTypes || pkg.types : pkg.types,
3221
+ exports,
3222
+ publishExports
3223
+ };
3224
+ }
3225
+ function genSubExport(devExports, { src, es, cjs }) {
3226
+ if (devExports === true) return src;
3227
+ let value;
3228
+ const dualFormat = es && cjs;
3229
+ if (!dualFormat && !devExports) value = cjs || es;
3230
+ else {
3231
+ value = {};
3232
+ if (typeof devExports === "string") value[devExports] = src;
3233
+ if (es) value[dualFormat ? "import" : "default"] = es;
3234
+ if (cjs) value[dualFormat ? "require" : "default"] = cjs;
3235
+ }
3236
+ return value;
3237
+ }
3238
+ function exportMeta(exports, all, packageJson) {
3239
+ if (all) exports["./*"] = "./*";
3240
+ else if (packageJson) exports["./package.json"] = "./package.json";
3241
+ }
3242
+ function exportCss(exports, chunks, { splitting }, pkgRoot) {
3243
+ if (splitting) return;
3244
+ for (const chunksByFormat of Object.values(chunks)) for (const chunk of chunksByFormat) if (chunk.type === "asset" && RE_CSS.test(chunk.fileName)) {
3245
+ const filename = slash(chunk.fileName);
3246
+ exports[`./${filename}`] = join$1(pkgRoot, chunk.outDir, filename);
3247
+ return;
3248
+ }
3249
+ }
3250
+ function hasExportsTypes(pkg) {
3251
+ const exports = pkg?.exports;
3252
+ if (!exports) return false;
3253
+ if (typeof exports === "object" && exports !== null && !Array.isArray(exports)) {
3254
+ if ("types" in exports) return true;
3255
+ if ("." in exports) {
3256
+ const mainExport = exports["."];
3257
+ if (typeof mainExport === "object" && mainExport !== null && "types" in mainExport) return true;
3258
+ }
3259
+ }
3260
+ return false;
3261
+ }
3262
+ function getExportName(chunk) {
3263
+ const normalizedName = slash(chunk.fileName);
3264
+ let name = stripExtname(normalizedName);
3265
+ const isDts = name.endsWith(".d");
3266
+ if (isDts) name = name.slice(0, -2);
3267
+ return [
3268
+ name,
3269
+ normalizedName,
3270
+ isDts
3271
+ ];
3272
+ }
3273
+ function join$1(pkgRoot, outDir, fileName) {
3274
+ const outDirRelative = slash(path.relative(pkgRoot, outDir));
3275
+ return `${outDirRelative ? `./${outDirRelative}` : "."}/${fileName}`;
3276
+ }
3277
+ function resolveTarget(logger, target, color, pkg, nameLabel) {
3278
+ if (target === false) return;
3279
+ if (target == null) {
3280
+ const pkgTarget = resolvePackageTarget(pkg);
3281
+ if (pkgTarget) target = pkgTarget;
3282
+ else return;
3283
+ }
3284
+ if (typeof target === "number") throw new TypeError(`Invalid target: ${target}`);
3285
+ const targets = resolveComma(toArray(target));
3286
+ if (targets.length) logger.info(nameLabel, `target${targets.length > 1 ? "s" : ""}: ${color(targets.join(", "))}`);
3287
+ return targets;
3288
+ }
3289
+ function resolvePackageTarget(pkg) {
3290
+ const nodeVersion = pkg?.engines?.node;
3291
+ if (!nodeVersion) return;
3292
+ const nodeMinVersion = minVersion(nodeVersion);
3293
+ if (!nodeMinVersion) return;
3294
+ if (nodeMinVersion.version === "0.0.0") return;
3295
+ return `node${nodeMinVersion.version}`;
3296
+ }
3297
+ function findTsconfig(cwd, name = "tsconfig.json") {
3298
+ return up$1(name, { cwd }) || false;
3299
+ }
3300
+ async function resolveTsconfig(logger, tsconfig, cwd, color, nameLabel) {
3301
+ const original = tsconfig;
3302
+ if (tsconfig !== false) {
3303
+ if (tsconfig === true || tsconfig == null) {
3304
+ tsconfig = findTsconfig(cwd);
3305
+ if (original && !tsconfig) logger.warn(`No tsconfig found in ${blue(cwd)}`);
3306
+ } else {
3307
+ const tsconfigPath = path.resolve(cwd, tsconfig);
3308
+ const stat = await fsStat(tsconfigPath);
3309
+ if (stat?.isFile()) tsconfig = tsconfigPath;
3310
+ else if (stat?.isDirectory()) {
3311
+ tsconfig = findTsconfig(tsconfigPath);
3312
+ if (!tsconfig) logger.warn(`No tsconfig found in ${blue(tsconfigPath)}`);
3313
+ } else {
3314
+ tsconfig = findTsconfig(cwd, tsconfig);
3315
+ if (!tsconfig) logger.warn(`tsconfig ${blue(original)} doesn't exist`);
3316
+ }
3317
+ }
3318
+ if (tsconfig) logger.info(nameLabel, `tsconfig: ${color(path.relative(cwd, tsconfig))}`);
3319
+ }
3320
+ return tsconfig;
3321
+ }
3322
+ const debug$2$2 = createDebug("tsdown:package");
3323
+ async function readPackageJson(dir) {
3324
+ const packageJsonPath = up({ cwd: dir });
3325
+ if (!packageJsonPath) return;
3326
+ debug$2$2("Reading package.json:", packageJsonPath);
3327
+ const contents = await readFile(packageJsonPath, "utf8");
3328
+ return {
3329
+ ...JSON.parse(contents),
3330
+ packageJsonPath
3331
+ };
3332
+ }
3333
+ function getPackageType(pkg) {
3334
+ if (pkg?.type) {
3335
+ if (!["module", "commonjs"].includes(pkg.type)) throw new Error(`Invalid package.json type: ${pkg.type}`);
3336
+ return pkg.type;
3337
+ }
3338
+ }
3339
+ function normalizeFormat(format) {
3340
+ switch (format) {
3341
+ case "es":
3342
+ case "esm":
3343
+ case "module": return "es";
3344
+ case "cjs":
3345
+ case "commonjs": return "cjs";
3346
+ default: return format;
3347
+ }
3348
+ }
3349
+ const debug$1$6 = createDebug("tsdown:config:file");
3350
+ async function loadViteConfig(prefix, cwd, configLoader) {
3351
+ const loader = resolveConfigLoader(configLoader);
3352
+ debug$1$6("Loading Vite config via loader: ", loader);
3353
+ const parser = createParser(loader);
3354
+ const [result] = await createConfigCoreLoader({
3355
+ sources: [{
3356
+ files: [`${prefix}.config`],
3357
+ extensions: [
3358
+ "js",
3359
+ "mjs",
3360
+ "ts",
3361
+ "cjs",
3362
+ "mts",
3363
+ "cts"
3364
+ ],
3365
+ parser
3366
+ }],
3367
+ cwd
3368
+ }).load(true);
3369
+ if (!result) return;
3370
+ const { config, source } = result;
3371
+ globalLogger.info(`Using Vite config: ${underline(source)}`);
3372
+ const resolved = await config;
3373
+ if (typeof resolved === "function") return resolved({
3374
+ command: "build",
3375
+ mode: "production"
3376
+ });
3377
+ return resolved;
3378
+ }
3379
+ const configPrefix = "tsdown.config";
3380
+ async function loadConfigFile(inlineConfig, workspace) {
3381
+ let cwd = inlineConfig.cwd || process$1.cwd();
3382
+ let overrideConfig = false;
3383
+ let { config: filePath } = inlineConfig;
3384
+ if (filePath === false) return { configs: [{}] };
3385
+ if (typeof filePath === "string") {
3386
+ const stats = await fsStat(filePath);
3387
+ if (stats) {
3388
+ const resolved = path.resolve(filePath);
3389
+ if (stats.isFile()) {
3390
+ overrideConfig = true;
3391
+ filePath = resolved;
3392
+ cwd = path.dirname(filePath);
3393
+ } else if (stats.isDirectory()) cwd = resolved;
3394
+ }
3395
+ }
3396
+ const loader = resolveConfigLoader(inlineConfig.configLoader);
3397
+ debug$1$6("Using config loader:", loader);
3398
+ const parser = createParser(loader);
3399
+ const [result] = await createConfigCoreLoader({
3400
+ sources: overrideConfig ? [{
3401
+ files: [filePath],
3402
+ extensions: [],
3403
+ parser
3404
+ }] : [{
3405
+ files: [configPrefix],
3406
+ extensions: [
3407
+ "ts",
3408
+ "mts",
3409
+ "cts",
3410
+ "js",
3411
+ "mjs",
3412
+ "cjs",
3413
+ "json"
3414
+ ],
3415
+ parser
3416
+ }, {
3417
+ files: ["package.json"],
3418
+ parser
3419
+ }],
3420
+ cwd,
3421
+ stopAt: workspace && path.dirname(workspace)
3422
+ }).load(true);
3423
+ let exported = [];
3424
+ let file;
3425
+ if (result) {
3426
+ ({config: exported, source: file} = result);
3427
+ globalLogger.info(`config file: ${underline(file)}`, loader === "native" ? "" : `(${loader})`);
3428
+ exported = await exported;
3429
+ if (typeof exported === "function") exported = await exported(inlineConfig, { ci: isInCi });
3430
+ }
3431
+ exported = toArray(exported);
3432
+ if (exported.length === 0) exported.push({});
3433
+ if (exported.some((config) => typeof config === "function")) throw new Error("Function should not be nested within multiple tsdown configurations. It must be at the top level.\nExample: export default defineConfig(() => [...])");
3434
+ return {
3435
+ configs: exported.map((config) => ({
3436
+ ...config,
3437
+ cwd: config.cwd ? path.resolve(cwd, config.cwd) : cwd
3438
+ })),
3439
+ file
3440
+ };
3441
+ }
3442
+ const isBun = !!process$1.versions.bun;
3443
+ const nativeTS = process$1.features.typescript || process$1.versions.deno;
3444
+ const autoLoader = isBun || nativeTS && isSupported ? "native" : "unrun";
3445
+ function resolveConfigLoader(configLoader = "auto") {
3446
+ if (configLoader === "auto") return autoLoader;
3447
+ else return configLoader === "native" ? "native" : "unrun";
3448
+ }
3449
+ function createParser(loader) {
3450
+ return async (filepath) => {
3451
+ const basename = path.basename(filepath);
3452
+ const isPkgJson = basename === "package.json";
3453
+ if (basename === configPrefix || isPkgJson || basename.endsWith(".json")) {
3454
+ const contents = await readFile(filepath, "utf8");
3455
+ const parsed = JSON.parse(contents);
3456
+ if (isPkgJson) return parsed?.tsdown;
3457
+ return parsed;
3458
+ }
3459
+ if (loader === "native") return nativeImport(filepath);
3460
+ return unrunImport(filepath);
3461
+ };
3462
+ }
3463
+ async function nativeImport(id) {
3464
+ const url = pathToFileURL(id);
3465
+ const importAttributes = Object.create(null);
3466
+ if (isSupported) {
3467
+ importAttributes.cache = "no";
3468
+ init({ skipNodeModules: true });
3469
+ } else if (!isBun) url.searchParams.set("no-cache", crypto.randomUUID());
3470
+ const mod = await import(url.href, { with: importAttributes }).catch((error) => {
3471
+ if (error?.message?.includes?.("Cannot find module")) throw new Error(`Failed to load the config file. Try setting the --config-loader CLI flag to \`unrun\`.\n\n${error.message}`, { cause: error });
3472
+ else throw error;
3473
+ });
3474
+ return mod.default || mod;
3475
+ }
3476
+ async function unrunImport(id) {
3477
+ const { unrun } = await import("./dist-dc0X0G6b.js");
3478
+ const { module } = await unrun({ path: pathToFileURL(id).href });
3479
+ return module;
3480
+ }
3481
+ const debug$7 = createDebug("tsdown:config:options");
3482
+ const parseEnv = process$1.getBuiltinModule("node:util").parseEnv;
3483
+ /**
3484
+ * Resolve user config into resolved configs
3485
+ *
3486
+ * **Internal API, not for public use**
3487
+ * @private
3488
+ */
3489
+ async function resolveUserConfig(userConfig, inlineConfig) {
3490
+ let { entry, format = ["es"], plugins = [], clean = true, logLevel = "info", failOnWarn = "ci-only", customLogger, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch = false, ignoreWatch, shims = false, skipNodeModulesBundle = false, publint = false, attw = false, fromVite, alias, tsconfig, report = true, target, env = {}, envFile, envPrefix = "TSDOWN_", copy, publicDir, hash = true, cwd = process$1.cwd(), name, workspace, external, noExternal, exports = false, bundle, unbundle = typeof bundle === "boolean" ? !bundle : false, removeNodeProtocol, nodeProtocol, cjsDefault = true, globImport = true, inlineOnly, css, fixedExtension = platform === "node", devtools = false, write = true } = userConfig;
3491
+ const pkg = await readPackageJson(cwd);
3492
+ if (workspace) name ||= pkg?.name;
3493
+ const color = generateColor(name);
3494
+ const nameLabel = getNameLabel(color, name);
3495
+ if (!filterConfig(inlineConfig.filter, cwd, name)) {
3496
+ debug$7("[filter] skipping config %s", cwd);
3497
+ return [];
3498
+ }
3499
+ const logger = createLogger(logLevel, {
3500
+ customLogger,
3501
+ failOnWarn: resolveFeatureOption(failOnWarn, true)
3502
+ });
3503
+ if (typeof bundle === "boolean") logger.warn("`bundle` option is deprecated. Use `unbundle` instead.");
3504
+ if (removeNodeProtocol) {
3505
+ if (nodeProtocol) throw new TypeError("`removeNodeProtocol` is deprecated. Please only use `nodeProtocol` instead.");
3506
+ logger.warn("`removeNodeProtocol` is deprecated. Use `nodeProtocol: \"strip\"` instead.");
3507
+ }
3508
+ nodeProtocol = nodeProtocol ?? (removeNodeProtocol ? "strip" : false);
3509
+ outDir = path.resolve(cwd, outDir);
3510
+ clean = resolveClean(clean, outDir, cwd);
3511
+ const resolvedEntry = await resolveEntry(logger, entry, cwd, color, nameLabel);
3512
+ if (dts == null) dts = !!(pkg?.types || pkg?.typings || hasExportsTypes(pkg));
3513
+ target = resolveTarget(logger, target, color, pkg, nameLabel);
3514
+ tsconfig = await resolveTsconfig(logger, tsconfig, cwd, color, nameLabel);
3515
+ if (typeof external === "string") external = resolveRegex(external);
3516
+ if (typeof noExternal === "string") noExternal = resolveRegex(noExternal);
3517
+ publint = resolveFeatureOption(publint, {});
3518
+ attw = resolveFeatureOption(attw, {});
3519
+ exports = resolveFeatureOption(exports, {});
3520
+ unused = resolveFeatureOption(unused, {});
3521
+ report = resolveFeatureOption(report, {});
3522
+ dts = resolveFeatureOption(dts, {});
3523
+ if (!pkg) {
3524
+ if (exports) throw new Error("`package.json` not found, cannot write exports");
3525
+ if (publint) logger.warn(nameLabel, "publint is enabled but package.json is not found");
3526
+ if (attw) logger.warn(nameLabel, "attw is enabled but package.json is not found");
3527
+ }
3528
+ if (publicDir) if (copy) throw new TypeError("`publicDir` is deprecated. Cannot be used with `copy`");
3529
+ else logger.warn(`${blue`publicDir`} is deprecated. Use ${blue`copy`} instead.`);
3530
+ envPrefix = toArray(envPrefix);
3531
+ if (envPrefix.includes("")) logger.warn("`envPrefix` includes an empty string; filtering is disabled. All environment variables from the env file and process.env will be injected into the build. Ensure this is intended to avoid accidental leakage of sensitive information.");
3532
+ const envFromProcess = filterEnv(process$1.env, envPrefix);
3533
+ if (envFile) {
3534
+ if (!parseEnv) throw new Error(`Your runtime does not support 'util.parseEnv()'. Please upgrade to Node.js v20.12.0 or later.`);
3535
+ const resolvedPath = path.resolve(cwd, envFile);
3536
+ logger.info(nameLabel, `env file: ${color(resolvedPath)}`);
3537
+ env = {
3538
+ ...filterEnv(parseEnv(await readFile(resolvedPath, "utf8")), envPrefix),
3539
+ ...envFromProcess,
3540
+ ...env
3541
+ };
3542
+ } else env = {
3543
+ ...envFromProcess,
3544
+ ...env
3545
+ };
3546
+ debug$7(`Environment variables: %O`, env);
3547
+ if (fromVite) {
3548
+ const viteUserConfig = await loadViteConfig(fromVite === true ? "vite" : fromVite, cwd, inlineConfig.configLoader);
3549
+ if (viteUserConfig) {
3550
+ const viteAlias = viteUserConfig.resolve?.alias;
3551
+ if (Array.isArray(viteAlias)) throw new TypeError("Unsupported resolve.alias in Vite config. Use object instead of array");
3552
+ if (viteAlias) alias = {
3553
+ ...alias,
3554
+ ...viteAlias
3555
+ };
3556
+ if (viteUserConfig.plugins) plugins = [viteUserConfig.plugins, plugins];
3557
+ }
3558
+ }
3559
+ ignoreWatch = toArray(ignoreWatch).map((ignore) => {
3560
+ ignore = resolveRegex(ignore);
3561
+ if (typeof ignore === "string") return path.resolve(cwd, ignore);
3562
+ return ignore;
3563
+ });
3564
+ if (noExternal != null && typeof noExternal !== "function") {
3565
+ const noExternalPatterns = toArray(noExternal);
3566
+ noExternal = (id) => matchPattern(id, noExternalPatterns);
3567
+ }
3568
+ if (skipNodeModulesBundle && noExternal != null) throw new TypeError("`skipNodeModulesBundle` and `noExternal` are mutually exclusive options and cannot be used together.");
3569
+ if (inlineOnly != null && inlineOnly !== false) inlineOnly = toArray(inlineOnly);
3570
+ devtools = resolveFeatureOption(devtools, {});
3571
+ if (devtools) if (watch) {
3572
+ if (devtools.ui) logger.warn("Devtools UI is not supported in watch mode, disabling it.");
3573
+ devtools.ui = false;
3574
+ } else devtools.ui ??= !!pkgExists("@vitejs/devtools/cli");
3575
+ const config = {
3576
+ ...userConfig,
3577
+ alias,
3578
+ attw,
3579
+ cjsDefault,
3580
+ clean,
3581
+ copy: publicDir || copy,
3582
+ css: resolveCssOptions(css),
3583
+ cwd,
3584
+ devtools,
3585
+ dts,
3586
+ entry: resolvedEntry,
3587
+ env,
3588
+ exports,
3589
+ external,
3590
+ fixedExtension,
3591
+ globImport,
3592
+ hash,
3593
+ ignoreWatch,
3594
+ inlineOnly,
3595
+ logger,
3596
+ name,
3597
+ nameLabel,
3598
+ nodeProtocol,
3599
+ noExternal,
3600
+ outDir,
3601
+ pkg,
3602
+ platform,
3603
+ plugins,
3604
+ publint,
3605
+ report,
3606
+ shims,
3607
+ skipNodeModulesBundle,
3608
+ sourcemap,
3609
+ target,
3610
+ treeshake,
3611
+ tsconfig,
3612
+ unbundle,
3613
+ unused,
3614
+ watch,
3615
+ write
3616
+ };
3617
+ const objectFormat = typeof format === "object" && !Array.isArray(format);
3618
+ return (objectFormat ? Object.keys(format) : resolveComma(toArray(format, "es"))).map((fmt, idx) => {
3619
+ const once = idx === 0;
3620
+ const overrides = objectFormat ? format[fmt] : void 0;
3621
+ return {
3622
+ ...config,
3623
+ copy: once ? config.copy : void 0,
3624
+ onSuccess: once ? config.onSuccess : void 0,
3625
+ format: normalizeFormat(fmt),
3626
+ ...overrides
3627
+ };
3628
+ });
3629
+ }
3630
+ /** filter env variables by prefixes */
3631
+ function filterEnv(envDict, envPrefixes) {
3632
+ const env = {};
3633
+ for (const [key, value] of Object.entries(envDict)) if (value != null && envPrefixes.some((prefix) => key.startsWith(prefix))) env[key] = value;
3634
+ return env;
3635
+ }
3636
+ const defu = createDefu((obj, key, value) => {
3637
+ if (Array.isArray(obj[key]) && Array.isArray(value)) {
3638
+ obj[key] = value;
3639
+ return true;
3640
+ }
3641
+ });
3642
+ function mergeConfig(defaults, overrides) {
3643
+ return defu(overrides, defaults);
3644
+ }
3645
+ async function mergeUserOptions(defaults, user, args) {
3646
+ const userOutputOptions = typeof user === "function" ? await user(defaults, ...args) : user;
3647
+ if (!userOutputOptions) return defaults;
3648
+ return defu(userOutputOptions, defaults);
3649
+ }
3650
+ function resolveFeatureOption(value, defaults) {
3651
+ if (typeof value === "object" && value !== null) return resolveCIOption(value.enabled ?? true) ? value : false;
3652
+ return resolveCIOption(value) ? defaults : false;
3653
+ }
3654
+ function resolveCIOption(value) {
3655
+ if (value === "ci-only") return isInCi ? true : false;
3656
+ if (value === "local-only") return isInCi ? false : true;
3657
+ return value;
3658
+ }
3659
+ function filterConfig(filter, configCwd, name) {
3660
+ if (!filter) return true;
3661
+ let cwd = path.relative(process$1.cwd(), configCwd);
3662
+ if (cwd === "") cwd = ".";
3663
+ if (filter instanceof RegExp) return name && filter.test(name) || filter.test(cwd);
3664
+ return toArray(filter).some((value) => name && name === value || cwd === value);
3665
+ }
3666
+
3667
+ //#endregion
3668
+ //#region ../../node_modules/.pnpm/tsdown@0.20.2_@arethetypeswrong+core@0.18.2_@typescript+native-preview@7.0.0-dev.202601_11c6934cad7d4cedf7999249d5905a1c/node_modules/tsdown/dist/watch-y9OGYH2L.mjs
3669
+ const shimFile = path.resolve(import.meta.dirname, "..", "esm-shims.js");
3670
+ function getShimsInject(format, platform) {
3671
+ if (format === "es" && platform === "node") return {
3672
+ __dirname: [shimFile, "__dirname"],
3673
+ __filename: [shimFile, "__filename"]
3674
+ };
3675
+ }
3676
+ const debug$1$1 = createDebug("tsdown:dep");
3677
+ function DepPlugin({ pkg, noExternal, inlineOnly, skipNodeModulesBundle, logger, nameLabel }) {
3678
+ const deps = pkg && Array.from(getProductionDeps(pkg));
3679
+ return {
3680
+ name: "tsdown:external",
3681
+ resolveId: {
3682
+ filter: [include(and(id(/^[^.]/), importerId(/./)))],
3683
+ async handler(id, importer, extraOptions) {
3684
+ if (extraOptions.isEntry) return;
3685
+ const shouldExternal = await externalStrategy(this, id, importer, extraOptions);
3686
+ const nodeBuiltinModule = isBuiltin(id);
3687
+ debug$1$1("shouldExternal: %o = %o", id, shouldExternal);
3688
+ if (shouldExternal === true || shouldExternal === "absolute") return {
3689
+ id,
3690
+ external: shouldExternal,
3691
+ moduleSideEffects: nodeBuiltinModule ? false : void 0
3692
+ };
3693
+ }
3694
+ },
3695
+ generateBundle: inlineOnly === false ? void 0 : {
3696
+ order: "post",
3697
+ handler(options, bundle) {
3698
+ const deps = /* @__PURE__ */ new Set();
3699
+ const importers = /* @__PURE__ */ new Map();
3700
+ for (const chunk of Object.values(bundle)) {
3701
+ if (chunk.type === "asset") continue;
3702
+ for (const id of chunk.moduleIds) {
3703
+ if (!RE_NODE_MODULES$1.test(id)) continue;
3704
+ const parts = slash(id).split("/node_modules/").at(-1)?.split("/");
3705
+ if (!parts) continue;
3706
+ let dep;
3707
+ if (parts[0][0] === "@") dep = `${parts[0]}/${parts[1]}`;
3708
+ else dep = parts[0];
3709
+ deps.add(dep);
3710
+ const module = this.getModuleInfo(id);
3711
+ if (module) importers.set(dep, new Set([...module.importers, ...importers.get(dep) || []]));
3712
+ }
3713
+ }
3714
+ debug$1$1("found deps in bundle: %o", deps);
3715
+ if (inlineOnly) {
3716
+ const errors = Array.from(deps).filter((dep) => !matchPattern(dep, inlineOnly)).map((dep) => `${yellow(dep)} is located in ${blue`node_modules`} but is not included in ${blue`inlineOnly`} option.\nTo fix this, either add it to ${blue`inlineOnly`}, declare it as a production or peer dependency in your package.json, or externalize it manually.\nImported by\n${[...importers.get(dep) || []].map((s) => `- ${underline(s)}`).join("\n")}`);
3717
+ if (errors.length) this.error(errors.join("\n\n"));
3718
+ const unusedPatterns = inlineOnly.filter((pattern) => !Array.from(deps).some((dep) => matchPattern(dep, [pattern])));
3719
+ if (unusedPatterns.length) logger.info(nameLabel, `The following entries in ${blue`inlineOnly`} are not used in the bundle:\n${unusedPatterns.map((pattern) => `- ${yellow(pattern)}`).join("\n")}\nConsider removing them to keep your configuration clean.`);
3720
+ } else if (deps.size) logger.warn(nameLabel, `Consider adding ${blue`inlineOnly`} option to avoid unintended bundling of dependencies, or set ${blue`inlineOnly: false`} to disable this warning.\nDetected dependencies in bundle:\n${Array.from(deps).map((dep) => `- ${yellow(dep)}`).join("\n")}`);
3721
+ }
3722
+ }
3723
+ };
3724
+ /**
3725
+ * - `true`: always external
3726
+ * - `false`: skip, let other plugins handle it
3727
+ * - `'absolute'`: external as absolute path
3728
+ * - `'no-external'`: skip, but mark as non-external for inlineOnly check
3729
+ */
3730
+ async function externalStrategy(context, id, importer, extraOptions) {
3731
+ if (id === shimFile) return false;
3732
+ if (noExternal?.(id, importer)) return "no-external";
3733
+ if (skipNodeModulesBundle) {
3734
+ const resolved = await context.resolve(id, importer, extraOptions);
3735
+ if (resolved && (resolved.external || RE_NODE_MODULES$1.test(resolved.id))) return true;
3736
+ }
3737
+ if (deps) {
3738
+ if (deps.includes(id) || deps.some((dep) => id.startsWith(`${dep}/`))) return true;
3739
+ if (importer && RE_DTS.test(importer) && !id.startsWith("@types/")) {
3740
+ const typesName = `@types/${id.replace(/^@/, "").replaceAll("/", "__")}`;
3741
+ if (deps.includes(typesName)) return true;
3742
+ }
3743
+ }
3744
+ return false;
3745
+ }
3746
+ }
3747
+ function getProductionDeps(pkg) {
3748
+ return new Set([...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})]);
3749
+ }
3750
+ /**
3751
+ * The `node:` protocol was added in Node.js v14.18.0.
3752
+ * @see https://nodejs.org/api/esm.html#node-imports
3753
+ */
3754
+ function NodeProtocolPlugin(nodeProtocolOption) {
3755
+ const modulesWithoutProtocol = builtinModules.filter((mod) => !mod.startsWith("node:"));
3756
+ return {
3757
+ name: `tsdown:node-protocol`,
3758
+ resolveId: {
3759
+ order: "pre",
3760
+ filter: { id: nodeProtocolOption === "strip" ? new RegExp(`^node:(${modulesWithoutProtocol.join("|")})$`) : new RegExp(`^(${modulesWithoutProtocol.join("|")})$`) },
3761
+ handler: nodeProtocolOption === "strip" ? (id) => {
3762
+ return {
3763
+ id: id.slice(5),
3764
+ external: true,
3765
+ moduleSideEffects: false
3766
+ };
3767
+ } : (id) => {
3768
+ return {
3769
+ id: `node:${id}`,
3770
+ external: true,
3771
+ moduleSideEffects: false
3772
+ };
3773
+ }
3774
+ }
3775
+ };
3776
+ }
3777
+ const debug$5 = createDebug("tsdown:report");
3778
+ const brotliCompressAsync = promisify(brotliCompress);
3779
+ const gzipAsync = promisify(gzip);
3780
+ const defaultOptions = {
3781
+ gzip: true,
3782
+ brotli: false,
3783
+ maxCompressSize: 1e6
3784
+ };
3785
+ function ReportPlugin(userOptions, logger, cwd, cjsDts, nameLabel, isDualFormat) {
3786
+ const options = {
3787
+ ...defaultOptions,
3788
+ ...userOptions
3789
+ };
3790
+ return {
3791
+ name: "tsdown:report",
3792
+ async writeBundle(outputOptions, bundle) {
3793
+ const outDir = path.relative(cwd, outputOptions.file ? path.resolve(cwd, outputOptions.file, "..") : path.resolve(cwd, outputOptions.dir));
3794
+ const sizes = [];
3795
+ for (const chunk of Object.values(bundle)) {
3796
+ const size = await calcSize(options, chunk);
3797
+ sizes.push(size);
3798
+ }
3799
+ const filenameLength = Math.max(...sizes.map((size) => size.filename.length));
3800
+ const rawTextLength = Math.max(...sizes.map((size) => size.rawText.length));
3801
+ const gzipTextLength = Math.max(...sizes.map((size) => size.gzipText == null ? 0 : size.gzipText.length));
3802
+ const brotliTextLength = Math.max(...sizes.map((size) => size.brotliText == null ? 0 : size.brotliText.length));
3803
+ let totalRaw = 0;
3804
+ for (const size of sizes) {
3805
+ size.rawText = size.rawText.padStart(rawTextLength);
3806
+ size.gzipText = size.gzipText?.padStart(gzipTextLength);
3807
+ size.brotliText = size.brotliText?.padStart(brotliTextLength);
3808
+ totalRaw += size.raw;
3809
+ }
3810
+ sizes.sort((a, b) => {
3811
+ if (a.dts !== b.dts) return a.dts ? 1 : -1;
3812
+ if (a.isEntry !== b.isEntry) return a.isEntry ? -1 : 1;
3813
+ return b.raw - a.raw;
3814
+ });
3815
+ const formatLabel = isDualFormat && prettyFormat(cjsDts ? "cjs" : outputOptions.format);
3816
+ for (const size of sizes) {
3817
+ const filenameColor = size.dts ? green : noop;
3818
+ const filename = path.normalize(size.filename);
3819
+ logger.info(nameLabel, formatLabel, dim(outDir + path.sep) + filenameColor((size.isEntry ? bold : noop)(filename)), ` `.repeat(filenameLength - size.filename.length), dim(size.rawText), options.gzip && size.gzipText && dim`│ gzip: ${size.gzipText}`, options.brotli && size.brotliText && dim`│ brotli: ${size.brotliText}`);
3820
+ }
3821
+ const totalSizeText = formatBytes(totalRaw);
3822
+ logger.info(nameLabel, formatLabel, `${sizes.length} files, total: ${totalSizeText}`);
3823
+ }
3824
+ };
3825
+ }
3826
+ async function calcSize(options, chunk) {
3827
+ debug$5(`Calculating size for`, chunk.fileName);
3828
+ const content = chunk.type === "chunk" ? chunk.code : chunk.source;
3829
+ const raw = Buffer.byteLength(content, "utf8");
3830
+ debug$5("[size]", chunk.fileName, raw);
3831
+ let gzip = Infinity;
3832
+ let brotli = Infinity;
3833
+ if (raw > options.maxCompressSize) debug$5(chunk.fileName, "file size exceeds limit, skip gzip/brotli");
3834
+ else {
3835
+ if (options.gzip) {
3836
+ gzip = (await gzipAsync(content)).length;
3837
+ debug$5("[gzip]", chunk.fileName, gzip);
3838
+ }
3839
+ if (options.brotli) {
3840
+ brotli = (await brotliCompressAsync(content)).length;
3841
+ debug$5("[brotli]", chunk.fileName, brotli);
3842
+ }
3843
+ }
3844
+ return {
3845
+ filename: chunk.fileName,
3846
+ dts: RE_DTS.test(chunk.fileName),
3847
+ isEntry: chunk.type === "chunk" && chunk.isEntry,
3848
+ raw,
3849
+ rawText: formatBytes(raw),
3850
+ gzip,
3851
+ gzipText: formatBytes(gzip),
3852
+ brotli,
3853
+ brotliText: formatBytes(brotli)
3854
+ };
3855
+ }
3856
+ const RE_SHEBANG = /^#!.*/;
3857
+ function ShebangPlugin(logger, cwd, nameLabel, isDualFormat) {
3858
+ return {
3859
+ name: "tsdown:shebang",
3860
+ async writeBundle(options, bundle) {
3861
+ for (const chunk of Object.values(bundle)) {
3862
+ if (chunk.type !== "chunk" || !chunk.isEntry) continue;
3863
+ if (!RE_SHEBANG.test(chunk.code)) continue;
3864
+ const filepath = path.resolve(cwd, options.file || path.join(options.dir, chunk.fileName));
3865
+ if (await fsExists(filepath)) {
3866
+ logger.info(nameLabel, isDualFormat && prettyFormat(options.format), `Granting execute permission to ${underline(path.relative(cwd, filepath))}`);
3867
+ await chmod(filepath, 493);
3868
+ }
3869
+ }
3870
+ }
3871
+ };
3872
+ }
3873
+ function addOutDirToChunks(chunks, outDir) {
3874
+ return chunks.map((chunk) => {
3875
+ chunk.outDir = outDir;
3876
+ return chunk;
3877
+ });
3878
+ }
3879
+ const endsWithConfig = /[\\/](?:tsdown\.config.*|package\.json|tsconfig\.json)$/;
3880
+ function WatchPlugin(configFiles, { config, chunks }) {
3881
+ return {
3882
+ name: "tsdown:watch",
3883
+ options: config.ignoreWatch.length ? (inputOptions) => {
3884
+ inputOptions.watch ||= {};
3885
+ inputOptions.watch.exclude = toArray(inputOptions.watch.exclude);
3886
+ inputOptions.watch.exclude.push(...config.ignoreWatch);
3887
+ } : void 0,
3888
+ buildStart() {
3889
+ config.tsconfig && this.addWatchFile(config.tsconfig);
3890
+ for (const file of configFiles) this.addWatchFile(file);
3891
+ if (typeof config.watch !== "boolean") for (const file of resolveComma(toArray(config.watch))) this.addWatchFile(file);
3892
+ if (config.pkg) this.addWatchFile(config.pkg.packageJsonPath);
3893
+ },
3894
+ generateBundle: {
3895
+ order: "post",
3896
+ handler(outputOptions, bundle) {
3897
+ chunks.push(...addOutDirToChunks(Object.values(bundle), config.outDir));
3898
+ }
3899
+ }
3900
+ };
3901
+ }
3902
+
3903
+ //#endregion
3904
+ //#region ../../node_modules/.pnpm/hookable@6.0.1/node_modules/hookable/dist/index.mjs
3905
+ function flatHooks(configHooks, hooks = {}, parentName) {
3906
+ for (const key in configHooks) {
3907
+ const subHook = configHooks[key];
3908
+ const name = parentName ? `${parentName}:${key}` : key;
3909
+ if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks, name);
3910
+ else if (typeof subHook === "function") hooks[name] = subHook;
3911
+ }
3912
+ return hooks;
3913
+ }
3914
+ const createTask = /* @__PURE__ */ (() => {
3915
+ if (console.createTask) return console.createTask;
3916
+ const defaultTask = { run: (fn) => fn() };
3917
+ return () => defaultTask;
3918
+ })();
3919
+ function callHooks(hooks, args, startIndex, task) {
3920
+ for (let i = startIndex; i < hooks.length; i += 1) try {
3921
+ const result = task ? task.run(() => hooks[i](...args)) : hooks[i](...args);
3922
+ if (result instanceof Promise) return result.then(() => callHooks(hooks, args, i + 1, task));
3923
+ } catch (error) {
3924
+ return Promise.reject(error);
3925
+ }
3926
+ }
3927
+ function serialTaskCaller(hooks, args, name) {
3928
+ if (hooks.length > 0) return callHooks(hooks, args, 0, createTask(name));
3929
+ }
3930
+ function parallelTaskCaller(hooks, args, name) {
3931
+ if (hooks.length > 0) {
3932
+ const task = createTask(name);
3933
+ return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
3934
+ }
3935
+ }
3936
+ function callEachWith(callbacks, arg0) {
3937
+ for (const callback of [...callbacks]) callback(arg0);
3938
+ }
3939
+ var Hookable = class {
3940
+ _hooks;
3941
+ _before;
3942
+ _after;
3943
+ _deprecatedHooks;
3944
+ _deprecatedMessages;
3945
+ constructor() {
3946
+ this._hooks = {};
3947
+ this._before = void 0;
3948
+ this._after = void 0;
3949
+ this._deprecatedMessages = void 0;
3950
+ this._deprecatedHooks = {};
3951
+ this.hook = this.hook.bind(this);
3952
+ this.callHook = this.callHook.bind(this);
3953
+ this.callHookWith = this.callHookWith.bind(this);
3954
+ }
3955
+ hook(name, function_, options = {}) {
3956
+ if (!name || typeof function_ !== "function") return () => {};
3957
+ const originalName = name;
3958
+ let dep;
3959
+ while (this._deprecatedHooks[name]) {
3960
+ dep = this._deprecatedHooks[name];
3961
+ name = dep.to;
3962
+ }
3963
+ if (dep && !options.allowDeprecated) {
3964
+ let message = dep.message;
3965
+ if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
3966
+ if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
3967
+ if (!this._deprecatedMessages.has(message)) {
3968
+ console.warn(message);
3969
+ this._deprecatedMessages.add(message);
3970
+ }
3971
+ }
3972
+ if (!function_.name) try {
3973
+ Object.defineProperty(function_, "name", {
3974
+ get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
3975
+ configurable: true
3976
+ });
3977
+ } catch {}
3978
+ this._hooks[name] = this._hooks[name] || [];
3979
+ this._hooks[name].push(function_);
3980
+ return () => {
3981
+ if (function_) {
3982
+ this.removeHook(name, function_);
3983
+ function_ = void 0;
3984
+ }
3985
+ };
3986
+ }
3987
+ hookOnce(name, function_) {
3988
+ let _unreg;
3989
+ let _function = (...arguments_) => {
3990
+ if (typeof _unreg === "function") _unreg();
3991
+ _unreg = void 0;
3992
+ _function = void 0;
3993
+ return function_(...arguments_);
3994
+ };
3995
+ _unreg = this.hook(name, _function);
3996
+ return _unreg;
3997
+ }
3998
+ removeHook(name, function_) {
3999
+ const hooks = this._hooks[name];
4000
+ if (hooks) {
4001
+ const index = hooks.indexOf(function_);
4002
+ if (index !== -1) hooks.splice(index, 1);
4003
+ if (hooks.length === 0) this._hooks[name] = void 0;
4004
+ }
4005
+ }
4006
+ deprecateHook(name, deprecated) {
4007
+ this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
4008
+ const _hooks = this._hooks[name] || [];
4009
+ this._hooks[name] = void 0;
4010
+ for (const hook of _hooks) this.hook(name, hook);
4011
+ }
4012
+ deprecateHooks(deprecatedHooks) {
4013
+ for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
4014
+ }
4015
+ addHooks(configHooks) {
4016
+ const hooks = flatHooks(configHooks);
4017
+ const removeFns = Object.keys(hooks).map((key) => this.hook(key, hooks[key]));
4018
+ return () => {
4019
+ for (const unreg of removeFns) unreg();
4020
+ removeFns.length = 0;
4021
+ };
4022
+ }
4023
+ removeHooks(configHooks) {
4024
+ const hooks = flatHooks(configHooks);
4025
+ for (const key in hooks) this.removeHook(key, hooks[key]);
4026
+ }
4027
+ removeAllHooks() {
4028
+ this._hooks = {};
4029
+ }
4030
+ callHook(name, ...args) {
4031
+ return this.callHookWith(serialTaskCaller, name, args);
4032
+ }
4033
+ callHookParallel(name, ...args) {
4034
+ return this.callHookWith(parallelTaskCaller, name, args);
4035
+ }
4036
+ callHookWith(caller, name, args) {
4037
+ const event = this._before || this._after ? {
4038
+ name,
4039
+ args,
4040
+ context: {}
4041
+ } : void 0;
4042
+ if (this._before) callEachWith(this._before, event);
4043
+ const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], args, name);
4044
+ if (result instanceof Promise) return result.finally(() => {
4045
+ if (this._after && event) callEachWith(this._after, event);
4046
+ });
4047
+ if (this._after && event) callEachWith(this._after, event);
4048
+ return result;
4049
+ }
4050
+ beforeEach(function_) {
4051
+ this._before = this._before || [];
4052
+ this._before.push(function_);
4053
+ return () => {
4054
+ if (this._before !== void 0) {
4055
+ const index = this._before.indexOf(function_);
4056
+ if (index !== -1) this._before.splice(index, 1);
4057
+ }
4058
+ };
4059
+ }
4060
+ afterEach(function_) {
4061
+ this._after = this._after || [];
4062
+ this._after.push(function_);
4063
+ return () => {
4064
+ if (this._after !== void 0) {
4065
+ const index = this._after.indexOf(function_);
4066
+ if (index !== -1) this._after.splice(index, 1);
4067
+ }
4068
+ };
4069
+ }
4070
+ };
4071
+
4072
+ //#endregion
4073
+ //#region ../../node_modules/.pnpm/tsdown@0.20.2_@arethetypeswrong+core@0.18.2_@typescript+native-preview@7.0.0-dev.202601_11c6934cad7d4cedf7999249d5905a1c/node_modules/tsdown/dist/build-l5WhXg4M.mjs
4074
+ var build_l5WhXg4M_exports = /* @__PURE__ */ __exportAll({
4075
+ n: () => buildWithConfigs,
4076
+ r: () => build_exports,
4077
+ t: () => build$1
4078
+ });
4079
+ const __cjs_require = createRequire(import.meta.url);
4080
+ const coerce = __cjs_require("./npm_entry_semver_functions_coerce.cjs");
4081
+ const satisfies = __cjs_require("./npm_entry_semver_functions_satisfies.cjs");
4082
+ const treeKill = __cjs_require("./npm_entry_tree-kill.cjs");
4083
+ const debug$4 = createDebug("tsdown:config:workspace");
4084
+ const DEFAULT_EXCLUDE_WORKSPACE = [
4085
+ "**/node_modules/**",
4086
+ "**/dist/**",
4087
+ "**/test?(s)/**",
4088
+ "**/t?(e)mp/**"
4089
+ ];
4090
+ async function resolveWorkspace(config, inlineConfig) {
4091
+ const normalized = {
4092
+ ...config,
4093
+ ...inlineConfig
4094
+ };
4095
+ const rootCwd = normalized.cwd || process$1.cwd();
4096
+ let { workspace } = normalized;
4097
+ if (!workspace) return {
4098
+ configs: [normalized],
4099
+ files: []
4100
+ };
4101
+ if (workspace === true) workspace = {};
4102
+ else if (typeof workspace === "string" || Array.isArray(workspace)) workspace = { include: workspace };
4103
+ let { include: packages = "auto", exclude = DEFAULT_EXCLUDE_WORKSPACE, config: workspaceConfig } = workspace;
4104
+ if (packages === "auto") packages = (await glob("**/package.json", {
4105
+ ignore: exclude,
4106
+ cwd: rootCwd,
4107
+ expandDirectories: false
4108
+ })).filter((file) => file !== "package.json").map((file) => slash(path.resolve(rootCwd, file, "..")));
4109
+ else packages = (await glob(packages, {
4110
+ ignore: exclude,
4111
+ cwd: rootCwd,
4112
+ onlyDirectories: true,
4113
+ absolute: true,
4114
+ expandDirectories: false
4115
+ })).map((file) => slash(path.resolve(file)));
4116
+ if (packages.length === 0) throw new Error("No workspace packages found, please check your config");
4117
+ const files = [];
4118
+ return {
4119
+ configs: (await Promise.all(packages.map(async (cwd) => {
4120
+ debug$4("loading workspace config %s", cwd);
4121
+ const { configs, file } = await loadConfigFile({
4122
+ ...inlineConfig,
4123
+ config: workspaceConfig,
4124
+ cwd
4125
+ }, cwd);
4126
+ if (file) {
4127
+ debug$4("loaded workspace config file %s", file);
4128
+ files.push(file);
4129
+ } else debug$4("no workspace config file found in %s", cwd);
4130
+ return configs.map((config) => ({
4131
+ ...normalized,
4132
+ ...config
4133
+ }));
4134
+ }))).flat(),
4135
+ files
4136
+ };
4137
+ }
4138
+ const debug$3 = createDebug("tsdown:config");
4139
+ async function resolveConfig(inlineConfig) {
4140
+ debug$3("inline config %O", inlineConfig);
4141
+ if (inlineConfig.cwd) inlineConfig.cwd = path.resolve(inlineConfig.cwd);
4142
+ const { configs: rootConfigs, file } = await loadConfigFile(inlineConfig);
4143
+ const files = [];
4144
+ if (file) {
4145
+ files.push(file);
4146
+ debug$3("loaded root user config file %s", file);
4147
+ debug$3("root user configs %O", rootConfigs);
4148
+ } else debug$3("no root user config file found");
4149
+ const configs = (await Promise.all(rootConfigs.map(async (rootConfig) => {
4150
+ const { configs: workspaceConfigs, files: workspaceFiles } = await resolveWorkspace(rootConfig, inlineConfig);
4151
+ debug$3("workspace configs %O", workspaceConfigs);
4152
+ if (workspaceFiles) files.push(...workspaceFiles);
4153
+ return (await Promise.all(workspaceConfigs.filter((config) => !config.workspace || config.entry).map((config) => resolveUserConfig(config, inlineConfig)))).flat().filter((config) => !!config);
4154
+ }))).flat();
4155
+ debug$3("resolved configs %O", configs);
4156
+ if (configs.length === 0) throw new Error("No valid configuration found.");
4157
+ return {
4158
+ configs,
4159
+ files
4160
+ };
4161
+ }
4162
+ function warnLegacyCJS(config) {
4163
+ if (!config.target || !(config.checks?.legacyCjs ?? true) || !config.format.includes("cjs")) return;
4164
+ if (config.target.some((t) => {
4165
+ const version = coerce(t.split("node")[1]);
4166
+ return version && satisfies(version, "^20.19.0 || >=22.12.0");
4167
+ })) config.logger.warnOnce("We recommend using the ESM format instead of CommonJS.\nThe ESM format is compatible with modern platforms and runtimes, and most new libraries are now distributed only in ESM format.\nLearn more at https://nodejs.org/en/learn/modules/publishing-a-package#how-did-we-get-here");
4168
+ }
4169
+ async function copy(options) {
4170
+ if (!options.copy) return;
4171
+ const copy = typeof options.copy === "function" ? await options.copy(options) : options.copy;
4172
+ const resolved = (await Promise.all(toArray(copy).map(async (entry) => {
4173
+ if (typeof entry === "string") entry = { from: [entry] };
4174
+ let from = toArray(entry.from);
4175
+ if (from.some((f) => isDynamicPattern(f))) from = await glob(from, {
4176
+ cwd: options.cwd,
4177
+ onlyFiles: true,
4178
+ expandDirectories: false
4179
+ });
4180
+ return from.map((file) => resolveCopyEntry({
4181
+ ...entry,
4182
+ from: file
4183
+ }));
4184
+ }))).flat();
4185
+ if (!resolved.length) {
4186
+ options.logger.warn(options.nameLabel, `No files matched for copying.`);
4187
+ return;
4188
+ }
4189
+ await Promise.all(resolved.map(({ from, to, verbose }) => {
4190
+ if (verbose) options.logger.info(options.nameLabel, `Copying files from ${path.relative(options.cwd, from)} to ${path.relative(options.cwd, to)}`);
4191
+ return fsCopy(from, to);
4192
+ }));
4193
+ function resolveCopyEntry(entry) {
4194
+ const { flatten = true, rename } = entry;
4195
+ const from = path.resolve(options.cwd, entry.from);
4196
+ const to = entry.to ? path.resolve(options.cwd, entry.to) : options.outDir;
4197
+ const { base, dir } = path.parse(path.relative(options.cwd, from));
4198
+ const destFolder = flatten || !flatten && !dir ? to : dir.replace(dir.split(path.sep)[0], to);
4199
+ const dest = path.join(destFolder, rename ? renameTarget(base, rename, from) : base);
4200
+ return {
4201
+ ...entry,
4202
+ from,
4203
+ to: dest
4204
+ };
4205
+ }
4206
+ }
4207
+ function renameTarget(target, rename, src) {
4208
+ const parsedPath = path.parse(target);
4209
+ return typeof rename === "string" ? rename : rename(parsedPath.name, parsedPath.ext.replace(".", ""), src);
4210
+ }
4211
+ async function startDevtoolsUI(config) {
4212
+ const { start } = await importWithError("@vitejs/devtools/cli-commands");
4213
+ await start({
4214
+ host: "127.0.0.1",
4215
+ open: true,
4216
+ ...typeof config.ui === "object" ? config.ui : {}
4217
+ });
4218
+ }
4219
+ async function createHooks(options) {
4220
+ const hooks = new Hookable();
4221
+ if (typeof options.hooks === "object") hooks.addHooks(options.hooks);
4222
+ else if (typeof options.hooks === "function") await options.hooks(hooks);
4223
+ return {
4224
+ hooks,
4225
+ context: {
4226
+ options,
4227
+ hooks
4228
+ }
4229
+ };
4230
+ }
4231
+ function executeOnSuccess(config) {
4232
+ if (!config.onSuccess) return;
4233
+ const ab = new AbortController();
4234
+ if (typeof config.onSuccess === "string") {
4235
+ const p = q(config.onSuccess, [], { nodeOptions: {
4236
+ shell: true,
4237
+ stdio: "inherit"
4238
+ } });
4239
+ p.then(({ exitCode }) => {
4240
+ if (exitCode) process$1.exitCode = exitCode;
4241
+ });
4242
+ ab.signal.addEventListener("abort", () => {
4243
+ if (typeof p.pid === "number") treeKill(p.pid);
4244
+ });
4245
+ } else config.onSuccess(config, ab.signal);
4246
+ return ab;
4247
+ }
4248
+ const debug$2 = createDebug("tsdown:attw");
4249
+ const label$1 = dim`[attw]`;
4250
+ const problemFlags = {
4251
+ NoResolution: "no-resolution",
4252
+ UntypedResolution: "untyped-resolution",
4253
+ FalseCJS: "false-cjs",
4254
+ FalseESM: "false-esm",
4255
+ CJSResolvesToESM: "cjs-resolves-to-esm",
4256
+ FallbackCondition: "fallback-condition",
4257
+ CJSOnlyExportsDefault: "cjs-only-exports-default",
4258
+ NamedExports: "named-exports",
4259
+ FalseExportDefault: "false-export-default",
4260
+ MissingExportEquals: "missing-export-equals",
4261
+ UnexpectedModuleSyntax: "unexpected-module-syntax",
4262
+ InternalResolutionError: "internal-resolution-error"
4263
+ };
4264
+ /**
4265
+ * ATTW profiles.
4266
+ * Defines the resolution modes to ignore for each profile.
4267
+ *
4268
+ * @see https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/packages/cli/README.md#profiles
4269
+ */
4270
+ const profiles = {
4271
+ strict: [],
4272
+ node16: ["node10"],
4273
+ "esm-only": ["node10", "node16-cjs"]
4274
+ };
4275
+ async function attw(options, tarball) {
4276
+ if (!options.attw) return;
4277
+ if (!options.pkg) {
4278
+ options.logger.warn("attw is enabled but package.json is not found");
4279
+ return;
4280
+ }
4281
+ const { profile = "strict", level = "warn", ignoreRules = [], ...attwOptions } = options.attw;
4282
+ const invalidRules = ignoreRules.filter((rule) => !Object.values(problemFlags).includes(rule));
4283
+ if (invalidRules.length) options.logger.warn(`attw config option 'ignoreRules' contains invalid value '${invalidRules.join(", ")}'.`);
4284
+ const t = performance.now();
4285
+ debug$2("Running attw check");
4286
+ const attwCore = await importWithError("@arethetypeswrong/core", options.attw.resolvePaths);
4287
+ const pkg = attwCore.createPackageFromTarballData(tarball);
4288
+ const checkResult = await attwCore.checkPackage(pkg, attwOptions);
4289
+ let errorMessage;
4290
+ if (checkResult.types) {
4291
+ const problems = checkResult.problems.filter((problem) => {
4292
+ if (ignoreRules.includes(problemFlags[problem.kind])) return false;
4293
+ if ("resolutionKind" in problem) return !profiles[profile]?.includes(problem.resolutionKind);
4294
+ return true;
4295
+ });
4296
+ if (problems.length) errorMessage = `problems found:\n${problems.map((problem) => formatProblem(checkResult.packageName, problem)).join("\n")}`;
4297
+ } else errorMessage = `Package has no types`;
4298
+ if (errorMessage) options.logger[level](options.nameLabel, label$1, errorMessage);
4299
+ else options.logger.success(options.nameLabel, label$1, "No problems found", dim`(${Math.round(performance.now() - t)}ms)`);
4300
+ }
4301
+ /**
4302
+ * Format an ATTW problem for display
4303
+ */
4304
+ function formatProblem(packageName, problem) {
4305
+ const resolutionKind = "resolutionKind" in problem ? ` (${problem.resolutionKind})` : "";
4306
+ const entrypoint = "entrypoint" in problem ? ` at ${slash(path.join(packageName, problem.entrypoint))}` : "";
4307
+ switch (problem.kind) {
4308
+ case "NoResolution": return ` ❌ No resolution${resolutionKind}${entrypoint}`;
4309
+ case "UntypedResolution": return ` ⚠️ Untyped resolution${resolutionKind}${entrypoint}`;
4310
+ case "FalseESM": return ` 🔄 False ESM: Types indicate ESM (${problem.typesModuleKind}) but implementation is CJS (${problem.implementationModuleKind})\n Types: ${problem.typesFileName} | Implementation: ${problem.implementationFileName}`;
4311
+ case "FalseCJS": return ` 🔄 False CJS: Types indicate CJS (${problem.typesModuleKind}) but implementation is ESM (${problem.implementationModuleKind})\n Types: ${problem.typesFileName} | Implementation: ${problem.implementationFileName}`;
4312
+ case "CJSResolvesToESM": return ` ⚡ CJS resolves to ESM${resolutionKind}${entrypoint}`;
4313
+ case "NamedExports": {
4314
+ const missingExports = problem.missing?.length > 0 ? ` Missing: ${problem.missing.join(", ")}` : "";
4315
+ return ` 📤 Named exports problem${problem.isMissingAllNamed ? " (all named exports missing)" : ""}${missingExports}\n Types: ${problem.typesFileName} | Implementation: ${problem.implementationFileName}`;
4316
+ }
4317
+ case "FallbackCondition": return ` 🎯 Fallback condition used${resolutionKind}${entrypoint}`;
4318
+ case "FalseExportDefault": return ` 🎭 False export default\n Types: ${problem.typesFileName} | Implementation: ${problem.implementationFileName}`;
4319
+ case "MissingExportEquals": return ` 📝 Missing export equals\n Types: ${problem.typesFileName} | Implementation: ${problem.implementationFileName}`;
4320
+ case "InternalResolutionError": return ` 💥 Internal resolution error in ${problem.fileName} (${problem.resolutionOption})\n Module: ${problem.moduleSpecifier} | Mode: ${problem.resolutionMode}`;
4321
+ case "UnexpectedModuleSyntax": return ` 📋 Unexpected module syntax in ${problem.fileName}\n Expected: ${problem.moduleKind} | Found: ${problem.syntax === 99 ? "ESM" : "CJS"}`;
4322
+ case "CJSOnlyExportsDefault": return ` 🏷️ CJS only exports default in ${problem.fileName}`;
4323
+ default: return ` ❓ Unknown problem: ${JSON.stringify(problem)}`;
4324
+ }
4325
+ }
4326
+ const debug$1 = createDebug("tsdown:publint");
4327
+ const label = dim`[publint]`;
4328
+ async function publint(options, tarball) {
4329
+ if (!options.publint) return;
4330
+ if (!options.pkg) {
4331
+ options.logger.warn(options.nameLabel, "publint is enabled but package.json is not found");
4332
+ return;
4333
+ }
4334
+ const t = performance.now();
4335
+ debug$1("Running publint");
4336
+ const { publint } = await importWithError("publint", options.publint.resolvePaths);
4337
+ const { formatMessage } = await importWithError("publint/utils", options.publint.resolvePaths);
4338
+ const { messages } = await publint({
4339
+ ...options.publint,
4340
+ pack: { tarball: tarball.buffer }
4341
+ });
4342
+ debug$1("Found %d issues", messages.length);
4343
+ if (!messages.length) {
4344
+ options.logger.success(options.nameLabel, label, "No issues found", dim`(${Math.round(performance.now() - t)}ms)`);
4345
+ return;
4346
+ }
4347
+ for (const message of messages) {
4348
+ const formattedMessage = formatMessage(message, options.pkg);
4349
+ const logType = {
4350
+ error: "error",
4351
+ warning: "warn",
4352
+ suggestion: "info"
4353
+ }[message.type];
4354
+ options.logger[logType](options.nameLabel, label, formattedMessage);
4355
+ }
4356
+ }
4357
+ function initBundleByPkg(configs) {
4358
+ const map = {};
4359
+ for (const config of configs) {
4360
+ const pkgJson = config.pkg?.packageJsonPath;
4361
+ if (!pkgJson) continue;
4362
+ if (!map[pkgJson]) {
4363
+ const { promise, resolve } = promiseWithResolvers();
4364
+ map[pkgJson] = {
4365
+ promise,
4366
+ resolve,
4367
+ count: 0,
4368
+ formats: /* @__PURE__ */ new Set(),
4369
+ bundles: []
4370
+ };
4371
+ }
4372
+ map[pkgJson].count++;
4373
+ map[pkgJson].formats.add(config.format);
4374
+ }
4375
+ return map;
4376
+ }
4377
+ async function bundleDone(bundleByPkg, bundle) {
4378
+ const pkg = bundle.config.pkg;
4379
+ if (!pkg) return;
4380
+ const ctx = bundleByPkg[pkg.packageJsonPath];
4381
+ ctx.bundles.push(bundle);
4382
+ if (ctx.bundles.length < ctx.count) return ctx.promise;
4383
+ const configs = ctx.bundles.map(({ config }) => config);
4384
+ const exportsConfigs = dedupeConfigs(configs, "exports");
4385
+ if (exportsConfigs.length) {
4386
+ if (exportsConfigs.length > 1) throw new Error(`Conflicting exports options for package at ${pkg.packageJsonPath}. Please merge them:\n${exportsConfigs.map((config) => `- ${formatWithOptions({ colors: true }, config.exports)}`).join("\n")}`);
4387
+ const chunks = {};
4388
+ for (const bundle of ctx.bundles) {
4389
+ if (!bundle.config.exports) continue;
4390
+ chunks[bundle.config.format] ||= [];
4391
+ chunks[bundle.config.format].push(...bundle.chunks);
4392
+ }
4393
+ await writeExports(exportsConfigs[0], chunks);
4394
+ }
4395
+ const publintConfigs = dedupeConfigs(configs, "publint");
4396
+ const attwConfigs = dedupeConfigs(configs, "attw");
4397
+ if (publintConfigs.length > 1 || attwConfigs.length > 1) publintConfigs[1].logger.warn(`Multiple publint or attw configurations found for package at ${pkg.packageJsonPath}. Consider merging them for better consistency and performance.`);
4398
+ try {
4399
+ if (publintConfigs.length || attwConfigs.length) {
4400
+ const tarball = await packTarball(pkg.packageJsonPath);
4401
+ await Promise.all([...publintConfigs.map((config) => publint(config, tarball)), ...attwConfigs.map((config) => attw(config, tarball))]);
4402
+ }
4403
+ } catch (error) {
4404
+ configs[0].logger.error("Pack failed:", error);
4405
+ }
4406
+ ctx.resolve();
4407
+ }
4408
+ async function packTarball(packageJsonPath) {
4409
+ const pkgDir = path.dirname(packageJsonPath);
4410
+ const destination = await mkdtemp(path.join(tmpdir(), "tsdown-pack-"));
4411
+ const [{ detect }, { pack }] = await Promise.all([import("./detect-CCATtVj7-B86m8IqW.js"), import("./index-node-BjDys8jy--sqPE5mM.js")]);
4412
+ try {
4413
+ const detected = await detect({ cwd: pkgDir });
4414
+ if (detected?.name === "deno") throw new Error(`Cannot pack tarball for Deno projects at ${pkgDir}`);
4415
+ return readFile(await pack(pkgDir, {
4416
+ destination,
4417
+ packageManager: detected?.name
4418
+ }));
4419
+ } finally {
4420
+ await fsRemove(destination);
4421
+ }
4422
+ }
4423
+ function dedupeConfigs(configs, key) {
4424
+ const filtered = configs.filter((config) => config[key]);
4425
+ if (!filtered.length) return [];
4426
+ const seen = /* @__PURE__ */ new Set();
4427
+ const results = filtered.filter((config) => {
4428
+ if (!Object.keys(config[key]).length) return false;
4429
+ if (seen.has(config[key])) return false;
4430
+ seen.add(config[key]);
4431
+ return true;
4432
+ });
4433
+ if (results.length === 0) return [filtered[0]];
4434
+ return results;
4435
+ }
4436
+ /**
4437
+ * Converts esbuild target [^1] (which is also used by Rolldown [^2]) to Lightning CSS targets [^3].
4438
+ *
4439
+ * [^1]: https://esbuild.github.io/api/#target
4440
+ * [^2]: https://github.com/rolldown/rolldown/blob/v1.0.0-beta.8/packages/rolldown/src/binding.d.ts#L1429-L1431
4441
+ * [^3]: https://lightningcss.dev/transpilation.html
4442
+ */
4443
+ function esbuildTargetToLightningCSS(target) {
4444
+ let targets;
4445
+ const matches = [...target.join(" ").toLowerCase().matchAll(TARGET_REGEX)];
4446
+ for (const match of matches) {
4447
+ const browser = ESBUILD_LIGHTNINGCSS_MAPPING[match[1]];
4448
+ if (!browser) continue;
4449
+ const version = match[2];
4450
+ const versionInt = parseVersion(version);
4451
+ if (versionInt == null) continue;
4452
+ targets = targets || {};
4453
+ targets[browser] = versionInt;
4454
+ }
4455
+ return targets;
4456
+ }
4457
+ const TARGET_REGEX = /([a-z]+)(\d+(?:\.\d+)*)/g;
4458
+ const ESBUILD_LIGHTNINGCSS_MAPPING = {
4459
+ chrome: "chrome",
4460
+ edge: "edge",
4461
+ firefox: "firefox",
4462
+ ie: "ie",
4463
+ ios: "ios_saf",
4464
+ opera: "opera",
4465
+ safari: "safari"
4466
+ };
4467
+ function parseVersion(version) {
4468
+ const [major, minor = 0, patch = 0] = version.split("-")[0].split(".").map((v) => Number.parseInt(v, 10));
4469
+ if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch)) return null;
4470
+ return major << 16 | minor << 8 | patch;
4471
+ }
4472
+ async function LightningCSSPlugin(options) {
4473
+ const LightningCSS = await import("unplugin-lightningcss/rolldown").catch(() => void 0);
4474
+ if (!LightningCSS) return;
4475
+ const targets = options.target && esbuildTargetToLightningCSS(options.target);
4476
+ if (!targets) return;
4477
+ return LightningCSS.default({ options: { targets } });
4478
+ }
4479
+ /**
4480
+ * CSS Code Split Plugin
4481
+ *
4482
+ * When css.splitting is false, this plugin merges all CSS files into a single file.
4483
+ * When css.splitting is true (default), CSS code splitting is preserved.
4484
+ * Based on Vite's implementation.
4485
+ */
4486
+ function CssCodeSplitPlugin(config) {
4487
+ const { splitting, fileName } = config.css;
4488
+ if (splitting) return;
4489
+ return {
4490
+ name: "tsdown:css:splitting",
4491
+ generateBundle(_outputOptions, bundle) {
4492
+ const chunks = Object.values(bundle);
4493
+ const cssAssets = /* @__PURE__ */ new Map();
4494
+ for (const asset of chunks) if (asset.type === "asset" && typeof asset.source === "string" && RE_CSS.test(fileName)) cssAssets.set(asset.fileName, asset.source);
4495
+ if (!cssAssets.size) return;
4496
+ const chunkCSSMap = /* @__PURE__ */ new Map();
4497
+ for (const chunk of chunks) {
4498
+ if (chunk.type !== "chunk") continue;
4499
+ for (const moduleId of chunk.moduleIds) if (RE_CSS.test(moduleId)) {
4500
+ if (!chunkCSSMap.has(chunk.fileName)) chunkCSSMap.set(chunk.fileName, []);
4501
+ break;
4502
+ }
4503
+ }
4504
+ for (const cssFileName of cssAssets.keys()) {
4505
+ const cssBaseName = normalizeCssFileName(cssFileName);
4506
+ for (const chunkFileName of chunkCSSMap.keys()) if (normalizeChunkFileName(chunkFileName) === cssBaseName || chunkFileName.startsWith(`${cssBaseName}-`)) {
4507
+ chunkCSSMap.get(chunkFileName).push(cssFileName);
4508
+ break;
4509
+ }
4510
+ }
4511
+ let extractedCss = "";
4512
+ const collected = /* @__PURE__ */ new Set();
4513
+ const dynamicImports = /* @__PURE__ */ new Set();
4514
+ function collect(chunk) {
4515
+ if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
4516
+ collected.add(chunk);
4517
+ chunk.imports.forEach((importName) => {
4518
+ collect(bundle[importName]);
4519
+ });
4520
+ chunk.dynamicImports.forEach((importName) => {
4521
+ dynamicImports.add(importName);
4522
+ });
4523
+ const files = chunkCSSMap.get(chunk.fileName);
4524
+ if (files && files.length > 0) for (const filename of files) extractedCss += cssAssets.get(filename) ?? "";
4525
+ }
4526
+ for (const chunk of chunks) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
4527
+ for (const chunkName of dynamicImports) collect(bundle[chunkName]);
4528
+ if (extractedCss) {
4529
+ for (const fileName of cssAssets.keys()) delete bundle[fileName];
4530
+ this.emitFile({
4531
+ type: "asset",
4532
+ source: extractedCss,
4533
+ fileName,
4534
+ originalFileName: defaultCssBundleName
4535
+ });
4536
+ }
4537
+ }
4538
+ };
4539
+ }
4540
+ const RE_CSS_HASH = /-[\w-]+\.css$/;
4541
+ const RE_CHUNK_HASH = /-[\w-]+\.(m?js|cjs)$/;
4542
+ const RE_CHUNK_EXT = /\.(m?js|cjs)$/;
4543
+ /**
4544
+ * Normalize CSS file name by removing hash pattern and extension.
4545
+ * e.g., "async-DcjEOEdU.css" -> "async"
4546
+ */
4547
+ function normalizeCssFileName(cssFileName) {
4548
+ return cssFileName.replace(RE_CSS_HASH, "").replace(RE_CSS, "");
4549
+ }
4550
+ /**
4551
+ * Normalize chunk file name by removing hash pattern and extension.
4552
+ * e.g., "async-CvIfFAic.mjs" -> "async"
4553
+ */
4554
+ function normalizeChunkFileName(chunkFileName) {
4555
+ return chunkFileName.replace(RE_CHUNK_HASH, "").replace(RE_CHUNK_EXT, "");
4556
+ }
4557
+ function resolveJsOutputExtension(packageType, format, fixedExtension) {
4558
+ switch (format) {
4559
+ case "es": return !fixedExtension && packageType === "module" ? "js" : "mjs";
4560
+ case "cjs": return fixedExtension || packageType === "module" ? "cjs" : "js";
4561
+ default: return "js";
4562
+ }
4563
+ }
4564
+ function resolveChunkFilename({ outExtensions, fixedExtension, pkg, hash }, inputOptions, format) {
4565
+ const packageType = getPackageType(pkg);
4566
+ let jsExtension;
4567
+ let dtsExtension;
4568
+ if (outExtensions) {
4569
+ const { js, dts } = outExtensions({
4570
+ options: inputOptions,
4571
+ format,
4572
+ pkgType: packageType
4573
+ }) || {};
4574
+ jsExtension = js;
4575
+ dtsExtension = dts;
4576
+ }
4577
+ jsExtension ??= `.${resolveJsOutputExtension(packageType, format, fixedExtension)}`;
4578
+ const suffix = format === "iife" || format === "umd" ? `.${format}` : "";
4579
+ return [createChunkFilename(`[name]${suffix}`, jsExtension, dtsExtension), createChunkFilename(`[name]${suffix}${hash ? "-[hash]" : ""}`, jsExtension, dtsExtension)];
4580
+ }
4581
+ function createChunkFilename(basename, jsExtension, dtsExtension) {
4582
+ if (dtsExtension === void 0) return `${basename}${jsExtension}`;
4583
+ return (chunk) => {
4584
+ return `${basename}${chunk.name.endsWith(".d") ? dtsExtension : jsExtension}`;
4585
+ };
4586
+ }
4587
+ function resolveChunkAddon(chunkAddon, format) {
4588
+ if (!chunkAddon) return;
4589
+ return (chunk) => {
4590
+ if (typeof chunkAddon === "function") chunkAddon = chunkAddon({
4591
+ format,
4592
+ fileName: chunk.fileName
4593
+ });
4594
+ if (typeof chunkAddon === "string") return chunkAddon;
4595
+ switch (true) {
4596
+ case RE_JS.test(chunk.fileName): return chunkAddon?.js || "";
4597
+ case RE_CSS.test(chunk.fileName): return chunkAddon?.css || "";
4598
+ case RE_DTS.test(chunk.fileName): return chunkAddon?.dts || "";
4599
+ default: return "";
4600
+ }
4601
+ };
4602
+ }
4603
+ const debug = createDebug("tsdown:rolldown");
4604
+ async function getBuildOptions(config, format, configFiles, bundle, cjsDts = false, isDualFormat) {
4605
+ const inputOptions = await resolveInputOptions(config, format, configFiles, bundle, cjsDts, isDualFormat);
4606
+ const outputOptions = await resolveOutputOptions(inputOptions, config, format, cjsDts);
4607
+ const rolldownConfig = {
4608
+ ...inputOptions,
4609
+ output: outputOptions,
4610
+ write: config.write
4611
+ };
4612
+ debug("rolldown config with format \"%s\" %O", cjsDts ? "cjs dts" : format, rolldownConfig);
4613
+ return rolldownConfig;
4614
+ }
4615
+ async function resolveInputOptions(config, format, configFiles, bundle, cjsDts, isDualFormat) {
4616
+ const { alias, checks: { legacyCjs, ...checks } = {}, cjsDefault, cwd, devtools, dts, entry, env, external, globImport, loader, logger, nameLabel, nodeProtocol, platform, plugins: userPlugins, report, shims, target, treeshake, tsconfig, unused, watch } = config;
4617
+ const plugins = [];
4618
+ if (nodeProtocol) plugins.push(NodeProtocolPlugin(nodeProtocol));
4619
+ if (config.pkg || config.skipNodeModulesBundle) plugins.push(DepPlugin(config));
4620
+ if (dts) {
4621
+ const { dts: dtsPlugin } = await import("./dist-BVMGwPdF.js");
4622
+ const options = {
4623
+ tsconfig,
4624
+ ...dts
4625
+ };
4626
+ if (format === "es") plugins.push(dtsPlugin(options));
4627
+ else if (cjsDts) plugins.push(dtsPlugin({
4628
+ ...options,
4629
+ emitDtsOnly: true,
4630
+ cjsDefault
4631
+ }));
4632
+ }
4633
+ if (!cjsDts) {
4634
+ if (unused) {
4635
+ const { Unused } = await importWithError("unplugin-unused");
4636
+ plugins.push(Unused.rolldown({
4637
+ root: cwd,
4638
+ ...unused
4639
+ }));
4640
+ }
4641
+ if (target) plugins.push(await LightningCSSPlugin({ target }));
4642
+ const cssPlugin = CssCodeSplitPlugin(config);
4643
+ if (cssPlugin) plugins.push(cssPlugin);
4644
+ plugins.push(ShebangPlugin(logger, cwd, nameLabel, isDualFormat));
4645
+ if (globImport) plugins.push(importGlobPlugin({ root: cwd }));
4646
+ }
4647
+ if (report && LogLevels[logger.level] >= 3) plugins.push(ReportPlugin(report, logger, cwd, cjsDts, nameLabel, isDualFormat));
4648
+ if (watch) plugins.push(WatchPlugin(configFiles, bundle));
4649
+ if (!cjsDts) plugins.push(userPlugins);
4650
+ const define = {
4651
+ ...config.define,
4652
+ ...Object.keys(env).reduce((acc, key) => {
4653
+ const value = JSON.stringify(env[key]);
4654
+ acc[`process.env.${key}`] = value;
4655
+ acc[`import.meta.env.${key}`] = value;
4656
+ return acc;
4657
+ }, Object.create(null))
4658
+ };
4659
+ const inject = shims && !cjsDts ? getShimsInject(format, platform) : void 0;
4660
+ return await mergeUserOptions({
4661
+ input: entry,
4662
+ cwd,
4663
+ external,
4664
+ resolve: { alias },
4665
+ tsconfig: tsconfig || void 0,
4666
+ treeshake,
4667
+ platform: cjsDts || format === "cjs" ? "node" : platform,
4668
+ transform: {
4669
+ target,
4670
+ define,
4671
+ inject
4672
+ },
4673
+ plugins,
4674
+ moduleTypes: loader,
4675
+ logLevel: logger.level === "error" ? "silent" : logger.level,
4676
+ onLog: cjsDefault ? (level, log, defaultHandler) => {
4677
+ if (log.code === "MIXED_EXPORT") return;
4678
+ defaultHandler(level, log);
4679
+ } : void 0,
4680
+ devtools: devtools || void 0,
4681
+ checks
4682
+ }, config.inputOptions, [format, { cjsDts }]);
4683
+ }
4684
+ async function resolveOutputOptions(inputOptions, config, format, cjsDts) {
4685
+ const { banner, cjsDefault, entry, footer, minify, outDir, sourcemap, unbundle } = config;
4686
+ const [entryFileNames, chunkFileNames] = resolveChunkFilename(config, inputOptions, format);
4687
+ return await mergeUserOptions({
4688
+ format: cjsDts ? "es" : format,
4689
+ name: config.globalName,
4690
+ sourcemap,
4691
+ dir: outDir,
4692
+ exports: cjsDefault ? "auto" : "named",
4693
+ minify: !cjsDts && minify,
4694
+ entryFileNames,
4695
+ chunkFileNames,
4696
+ preserveModules: unbundle,
4697
+ preserveModulesRoot: unbundle ? lowestCommonAncestor(...Object.values(entry)) : void 0,
4698
+ postBanner: resolveChunkAddon(banner, format),
4699
+ postFooter: resolveChunkAddon(footer, format)
4700
+ }, config.outputOptions, [format, { cjsDts }]);
4701
+ }
4702
+ async function getDebugRolldownDir() {
4703
+ if (!debug.enabled) return;
4704
+ return await mkdtemp(path.join(tmpdir(), "tsdown-config-"));
4705
+ }
4706
+ async function debugBuildOptions(dir, name, format, buildOptions) {
4707
+ const outFile = path.join(dir, `rolldown.config.${format}.js`);
4708
+ handlePluginInspect(buildOptions.plugins);
4709
+ const serialized = formatWithOptions({
4710
+ depth: null,
4711
+ maxArrayLength: null,
4712
+ maxStringLength: null
4713
+ }, buildOptions);
4714
+ await writeFile(outFile, `/*
4715
+ Auto-generated rolldown config for tsdown debug purposes
4716
+ tsdown v${version}, rolldown v${VERSION}
4717
+ Generated on ${(/* @__PURE__ */ new Date()).toISOString()}
4718
+ Package name: ${name || "not specified"}
4719
+ */
4720
+
4721
+ export default ${serialized}\n`);
4722
+ debug("Wrote debug rolldown config for \"%s\" (%s) -> %s", name || "default name", format, outFile);
4723
+ }
4724
+ function handlePluginInspect(plugins) {
4725
+ if (Array.isArray(plugins)) for (const plugin of plugins) handlePluginInspect(plugin);
4726
+ else if (typeof plugins === "object" && plugins !== null && "name" in plugins) plugins[inspect.custom] = function(depth, options, inspect) {
4727
+ if ("_options" in plugins) return inspect({
4728
+ name: plugins.name,
4729
+ options: plugins._options
4730
+ }, options);
4731
+ else return `"rolldown plugin: ${plugins.name}"`;
4732
+ };
4733
+ }
4734
+ function shortcuts(restart) {
4735
+ let actionRunning = false;
4736
+ async function onInput(input) {
4737
+ if (actionRunning) return;
4738
+ input = input.trim().toLowerCase();
4739
+ const SHORTCUTS = [
4740
+ {
4741
+ key: "r",
4742
+ description: "reload config and rebuild",
4743
+ action() {
4744
+ restart();
4745
+ }
4746
+ },
4747
+ {
4748
+ key: "c",
4749
+ description: "clear console",
4750
+ action() {
4751
+ console.clear();
4752
+ }
4753
+ },
4754
+ {
4755
+ key: "q",
4756
+ description: "quit",
4757
+ action() {
4758
+ process$1.exit(0);
4759
+ }
4760
+ }
4761
+ ];
4762
+ if (input === "h") {
4763
+ const loggedKeys = /* @__PURE__ */ new Set();
4764
+ globalLogger.info(" Shortcuts");
4765
+ for (const shortcut of SHORTCUTS) {
4766
+ if (loggedKeys.has(shortcut.key)) continue;
4767
+ loggedKeys.add(shortcut.key);
4768
+ if (shortcut.action == null) continue;
4769
+ globalLogger.info(dim` press ` + bold`${shortcut.key} + enter` + dim` to ${shortcut.description}`);
4770
+ }
4771
+ return;
4772
+ }
4773
+ const shortcut = SHORTCUTS.find((shortcut) => shortcut.key === input);
4774
+ if (!shortcut) return;
4775
+ actionRunning = true;
4776
+ await shortcut.action();
4777
+ actionRunning = false;
4778
+ }
4779
+ const rl = readline.createInterface({ input: process$1.stdin });
4780
+ rl.on("line", onInput);
4781
+ return () => rl.close();
4782
+ }
4783
+ var build_exports = /* @__PURE__ */ __exportAll$1({
4784
+ build: () => build$1,
4785
+ buildWithConfigs: () => buildWithConfigs
4786
+ });
4787
+ const asyncDispose = Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose");
4788
+ /**
4789
+ * Build with tsdown.
4790
+ */
4791
+ async function build$1(inlineConfig = {}) {
4792
+ globalLogger.level = inlineConfig.logLevel || "info";
4793
+ const { configs, files: configFiles } = await resolveConfig(inlineConfig);
4794
+ return buildWithConfigs(configs, configFiles, () => build$1(inlineConfig));
4795
+ }
4796
+ /**
4797
+ * Build with `ResolvedConfigs`.
4798
+ *
4799
+ * **Internal API, not for public use**
4800
+ * @private
4801
+ */
4802
+ async function buildWithConfigs(configs, configFiles, _restart) {
4803
+ let cleanPromise;
4804
+ const clean = () => {
4805
+ if (cleanPromise) return cleanPromise;
4806
+ return cleanPromise = cleanOutDir(configs);
4807
+ };
4808
+ const disposeCbs = [];
4809
+ let restarting = false;
4810
+ async function restart() {
4811
+ if (restarting) return;
4812
+ restarting = true;
4813
+ await Promise.all(disposeCbs.map((cb) => cb()));
4814
+ clearRequireCache();
4815
+ _restart();
4816
+ }
4817
+ const configChunksByPkg = initBundleByPkg(configs);
4818
+ function done(bundle) {
4819
+ return bundleDone(configChunksByPkg, bundle);
4820
+ }
4821
+ globalLogger.info("Build start");
4822
+ const bundles = await Promise.all(configs.map((options) => {
4823
+ return buildSingle(options, configFiles, options.pkg ? configChunksByPkg[options.pkg.packageJsonPath].formats.size > 1 : true, clean, restart, done);
4824
+ }));
4825
+ const firstDevtoolsConfig = configs.find((config) => config.devtools && config.devtools.ui);
4826
+ if (configs.some((config) => config.watch)) {
4827
+ disposeCbs.push(shortcuts(restart));
4828
+ for (const bundle of bundles) disposeCbs.push(bundle[asyncDispose]);
4829
+ } else if (firstDevtoolsConfig) startDevtoolsUI(firstDevtoolsConfig.devtools);
4830
+ return bundles;
4831
+ }
4832
+ /**
4833
+ * Build a single configuration, without watch and shortcuts features.
4834
+ * @param config Resolved options
4835
+ */
4836
+ async function buildSingle(config, configFiles, isDualFormat, clean, restart, done) {
4837
+ const { format, dts, watch: watch$1, logger, outDir } = config;
4838
+ const { hooks, context } = await createHooks(config);
4839
+ warnLegacyCJS(config);
4840
+ const startTime = performance.now();
4841
+ await hooks.callHook("build:prepare", context);
4842
+ await clean();
4843
+ const debugRolldownConfigDir = await getDebugRolldownDir();
4844
+ const chunks = [];
4845
+ let watcher;
4846
+ let ab;
4847
+ let updated = false;
4848
+ const bundle = {
4849
+ chunks,
4850
+ config,
4851
+ async [asyncDispose]() {
4852
+ ab?.abort();
4853
+ await watcher?.close();
4854
+ }
4855
+ };
4856
+ const configs = await initBuildOptions();
4857
+ if (watch$1) {
4858
+ watcher = watch(configs);
4859
+ handleWatcher(watcher);
4860
+ } else {
4861
+ const outputs = await build(configs);
4862
+ for (const { output } of outputs) chunks.push(...addOutDirToChunks(output, outDir));
4863
+ }
4864
+ if (!watch$1) {
4865
+ logger.success(config.nameLabel, `Build complete in ${green(`${Math.round(performance.now() - startTime)}ms`)}`);
4866
+ await postBuild();
4867
+ }
4868
+ return bundle;
4869
+ function handleWatcher(watcher) {
4870
+ const changedFile = [];
4871
+ let hasError = false;
4872
+ watcher.on("change", (id, event) => {
4873
+ if (event.event === "update") changedFile.push(id);
4874
+ if (configFiles.includes(id) || endsWithConfig.test(id)) {
4875
+ globalLogger.info(`Reload config: ${id}, restarting...`);
4876
+ restart();
4877
+ }
4878
+ });
4879
+ watcher.on("event", async (event) => {
4880
+ switch (event.code) {
4881
+ case "START":
4882
+ if (config.clean.length) await cleanChunks(config.outDir, chunks);
4883
+ chunks.length = 0;
4884
+ hasError = false;
4885
+ break;
4886
+ case "END":
4887
+ if (!hasError) await postBuild();
4888
+ break;
4889
+ case "BUNDLE_START":
4890
+ if (changedFile.length) {
4891
+ logger.clearScreen("info");
4892
+ logger.info(`Found ${bold(changedFile.join(", "))} changed, rebuilding...`);
4893
+ }
4894
+ changedFile.length = 0;
4895
+ break;
4896
+ case "BUNDLE_END":
4897
+ await event.result.close();
4898
+ logger.success(config.nameLabel, `Rebuilt in ${event.duration}ms.`);
4899
+ break;
4900
+ case "ERROR":
4901
+ await event.result.close();
4902
+ logger.error(event.error);
4903
+ hasError = true;
4904
+ break;
4905
+ }
4906
+ });
4907
+ }
4908
+ async function initBuildOptions() {
4909
+ const buildOptions = await getBuildOptions(config, format, configFiles, bundle, false, isDualFormat);
4910
+ await hooks.callHook("build:before", {
4911
+ ...context,
4912
+ buildOptions
4913
+ });
4914
+ if (debugRolldownConfigDir) await debugBuildOptions(debugRolldownConfigDir, config.name, format, buildOptions);
4915
+ const configs = [buildOptions];
4916
+ if (format === "cjs" && dts) configs.push(await getBuildOptions(config, format, configFiles, bundle, true, isDualFormat));
4917
+ return configs;
4918
+ }
4919
+ async function postBuild() {
4920
+ await copy(config);
4921
+ if (!updated) await done(bundle);
4922
+ await hooks.callHook("build:done", {
4923
+ ...context,
4924
+ chunks
4925
+ });
4926
+ updated = true;
4927
+ ab?.abort();
4928
+ ab = executeOnSuccess(config);
4929
+ }
4930
+ }
4931
+
4932
+ //#endregion
4933
+ export { resolveUserConfig as a, mergeConfig as i, buildWithConfigs as n, build_l5WhXg4M_exports as r, build$1 as t };