@voidzero-dev/vite-plus-core 0.0.0-6bf6b4c1b360fa4f7f1cee975103c16c21053c72

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