weapp-vite 7.5.0 → 7.6.0

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 (93) hide show
  1. package/README.md +8 -2
  2. package/THIRD_PARTY_NOTICES.md +60 -0
  3. package/dist/action-B3YZMA-h.mjs +255 -0
  4. package/dist/action-BELcDNNv.mjs +139 -0
  5. package/dist/action-BOk3vGI7.mjs +1110 -0
  6. package/dist/action-DlC6JYpt.mjs +95 -0
  7. package/dist/action-zEDY7oh_.mjs +247 -0
  8. package/dist/{analyze-ZJUvEdaY.mjs → analyze-DN79YOAH.mjs} +1 -65
  9. package/dist/artifacts-BOyC9Fy-.mjs +106 -0
  10. package/dist/assets-C5_YYXNk.mjs +637 -0
  11. package/dist/auto-routes.mjs +2 -2
  12. package/dist/{budget-BD7VqLCl.d.mts → budget-CTLOHwgI.d.mts} +1 -2
  13. package/dist/budget-EOeEycc_.mjs +65 -0
  14. package/dist/builtProject-C29udgXY.mjs +541 -0
  15. package/dist/{chunkStrategy-DRA5WpB-.mjs → chunkStrategy-DY_LZIIe.mjs} +15 -3
  16. package/dist/{package-7swhyLmf.mjs → classifier-DBJY__kg.mjs} +4 -7
  17. package/dist/cli-acceptance.mjs +1 -1
  18. package/dist/cli.mjs +110 -4506
  19. package/dist/{config-V0L-IAJf.d.mts → config-Bf6DWhyb.d.mts} +136 -49
  20. package/dist/config.d.mts +2 -2
  21. package/dist/{createCompilerContextInstance-DJH_P_nZ.mjs → createCompilerContextInstance-aYwi8wQt.mjs} +15235 -9523
  22. package/dist/{createContext-BqYzHhY9.mjs → createContext-tApLtII-.mjs} +6 -3
  23. package/dist/dashboard/analyze.d.mts +1 -1
  24. package/dist/dashboard/analyze.mjs +3 -1
  25. package/dist/dashboard/vite.d.mts +1 -1
  26. package/dist/dashboard.d.mts +2 -2
  27. package/dist/dashboard.mjs +1749 -1
  28. package/dist/dashboardTransport-C_Y6jMp-.mjs +16 -0
  29. package/dist/{dashboardViteBridge-Dy3nAD4m.mjs → dashboardViteBridge-DCGR43aM.mjs} +8 -5
  30. package/dist/{dev-fR5GiJRO.mjs → dev-C2fgr_Xd.mjs} +5 -1
  31. package/dist/devProvider-D-hTfsEO.mjs +3027 -0
  32. package/dist/docs/README.md +8 -2
  33. package/dist/docs/mcp.md +10 -0
  34. package/dist/docs/troubleshooting.md +8 -0
  35. package/dist/docs/vue-sfc.md +25 -2
  36. package/dist/doctor-worker.mjs +3 -2
  37. package/dist/doctor.d.mts +2 -2
  38. package/dist/doctor.mjs +15 -13
  39. package/dist/engine-C66J0HLz.mjs +54 -0
  40. package/dist/{file-sC3jD7Fh.mjs → file-CcIOmqhC.mjs} +47 -19
  41. package/dist/file-DtcteQ4G.mjs +1 -0
  42. package/dist/forwardConsole-B0Reo8Lf.mjs +511 -0
  43. package/dist/getInstance-BAIaU2y9.mjs +1 -0
  44. package/dist/{getInstance-DiGSzBNI.mjs → getInstance-Dt9IQDKr.mjs} +1 -1
  45. package/dist/history-BIiRCzbq.mjs +784 -0
  46. package/dist/i18n.d.mts +1 -1
  47. package/dist/{index-C9HjUX5c.d.mts → index-D5rgBzYZ.d.mts} +1 -2
  48. package/dist/index.d.mts +3 -3
  49. package/dist/index.mjs +2 -2
  50. package/dist/json.d.mts +1 -1
  51. package/dist/lib-DjccSI1B.mjs +143 -0
  52. package/dist/{lifecycle-BROTlwSL.mjs → lifecycle-C36WSbQS.mjs} +120 -27
  53. package/dist/{loadConfig-C3BQhz7F.mjs → loadConfig-BWIsDXR4.mjs} +1 -1
  54. package/dist/loadConfig-D-BpBgsk.mjs +1 -0
  55. package/dist/logBuildAppFinish-ChjwATMv.mjs +57 -0
  56. package/dist/mcp-CYgX9HpO.mjs +86 -0
  57. package/dist/mcp.d.mts +1 -1
  58. package/dist/mcpClient-DVLvFLZv.mjs +287 -0
  59. package/dist/{processCleanup-B6KA30Zc.mjs → metadata-hwF7QRcS.mjs} +1 -19
  60. package/dist/nodeEnv-BmH8UZPR.mjs +7 -0
  61. package/dist/openIde-CroqOgk5.mjs +648 -0
  62. package/dist/options-jqFwfD1G.mjs +34 -0
  63. package/dist/package-Cmakyy3J.mjs +4 -0
  64. package/dist/path-CYYIQGS7.mjs +44 -0
  65. package/dist/processCleanup-BQn2kTcK.mjs +19 -0
  66. package/dist/{protocol-vg8HGJ4n.mjs → protocol-Cg6Jdlvb.mjs} +42 -39
  67. package/dist/reader-sh_POQ9-.mjs +93 -0
  68. package/dist/realpathScope-Tf9mz-fh.mjs +23 -0
  69. package/dist/report-hyonPGbZ.mjs +107 -0
  70. package/dist/{path-doV773b7.mjs → resolvedId-CiDl7SC1.mjs} +3 -46
  71. package/dist/runtime-CLUhQsdA.mjs +43 -0
  72. package/dist/{runtime-Ee2HY6gR.d.mts → runtime-DpVf714f.d.mts} +1 -1
  73. package/dist/runtime.d.mts +1 -1
  74. package/dist/schematics-kO26eQRT.mjs +91 -0
  75. package/dist/{session-PskhD-nZ.mjs → session-D3zsdzIy.mjs} +71 -9
  76. package/dist/test.mjs +10 -8
  77. package/dist/{types-CgZn5X6j.d.mts → types-D-kfuyVa.d.mts} +1 -2
  78. package/dist/types-D0FFexRF.d.mts +39 -0
  79. package/dist/types.d.mts +2 -2
  80. package/dist/{upload-D4msblBf.mjs → upload-DozK8UdN.mjs} +109 -5
  81. package/dist/upload-worker.mjs +1 -1
  82. package/dist/{utils-CJSCgEj6.mjs → utils-Dy51PYAC.mjs} +56 -116
  83. package/dist/vite.d.mts +1 -1
  84. package/dist/vite.mjs +51 -12
  85. package/dist/wxs-BT8btflA.mjs +112 -0
  86. package/dist/wxs-Z4VQDeJ_.mjs +1 -0
  87. package/package.json +52 -46
  88. package/dist/dashboard-DvqF3Key.mjs +0 -1842
  89. package/dist/devProvider-BGBkw28J.mjs +0 -1050
  90. package/dist/file-DRb4eWqw.mjs +0 -1
  91. package/dist/getInstance-SiE6WZRh.mjs +0 -1
  92. package/dist/loadConfig-VGtBF4qm.mjs +0 -1
  93. package/dist/mcp-D3Yh24Cj.mjs +0 -529
@@ -0,0 +1,3027 @@
1
+ import { n as withRealpathScope, t as resolveRealpath } from "./realpathScope-Tf9mz-fh.mjs";
2
+ import { n as normalizeFsResolvedId, t as isSkippableResolvedId } from "./resolvedId-CiDl7SC1.mjs";
3
+ import { a as parseSidecarModuleId, c as resolveVirtualModuleId, i as parseLogicalEntryId, n as createSidecarModuleId, o as parseSidecarSourceMetadata, r as createSidecarSourceSpecifier, s as parseSidecarSourceRequest } from "./protocol-Cg6Jdlvb.mjs";
4
+ import { a as normalizeWatchPath, n as normalizePath$1, s as toPosixPath, t as isPathInside } from "./path-CYYIQGS7.mjs";
5
+ import { a as getPlatformNpmDistDirName, h as resolveMiniPlatformWithDefault } from "./platform-CnkySBKz.mjs";
6
+ import process$1 from "node:process";
7
+ import { WEAPP_VITE_RUNTIME_VIRTUAL_ID, WEVU_AUTO_ROUTES_MODULE_ID as WEVU_AUTO_ROUTES_MODULE_ID$1, WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID as WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1, WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID as WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1 } from "@weapp-core/constants";
8
+ import path from "pathe";
9
+ import { readlinkSync, stat, unwatchFile, watch, watchFile } from "node:fs";
10
+ import * as sp from "node:path";
11
+ import path$1, { join, resolve, sep } from "node:path";
12
+ import picomatch from "picomatch";
13
+ import { readAndParseSfc } from "wevu/compiler";
14
+ import { lstat, open, readdir, realpath, stat as stat$1 } from "node:fs/promises";
15
+ import { createLogger, createServer, transformWithOxc } from "vite";
16
+ import { EventEmitter, once } from "node:events";
17
+ import { Readable } from "node:stream";
18
+ import { type } from "node:os";
19
+ import { getPackageInfoSync } from "local-pkg";
20
+ //#region src/moduleGraph/traversal.ts
21
+ function normalizeSourceId(id) {
22
+ const normalized = normalizeFsResolvedId(id);
23
+ if (isSkippableResolvedId(normalized)) return normalized;
24
+ try {
25
+ return normalizeFsResolvedId(resolveRealpath(normalized));
26
+ } catch {
27
+ if (!path$1.isAbsolute(normalized) && path$1.win32.isAbsolute(normalized)) return normalized;
28
+ let candidate = normalized;
29
+ let links;
30
+ for (;;) {
31
+ let target;
32
+ try {
33
+ target = readlinkSync(candidate);
34
+ } catch {
35
+ break;
36
+ }
37
+ links ??= /* @__PURE__ */ new Set();
38
+ if (links.has(candidate)) return normalized;
39
+ links.add(candidate);
40
+ candidate = path$1.resolve(path$1.dirname(candidate), target);
41
+ }
42
+ try {
43
+ return normalizeFsResolvedId(path$1.join(resolveRealpath(path$1.dirname(candidate)), path$1.basename(candidate)));
44
+ } catch {
45
+ return normalizeFsResolvedId(candidate);
46
+ }
47
+ }
48
+ }
49
+ /** 逻辑入口与源码按同一真实路径比较,避免 junction 或原生分隔符制造第二个输出归属。 */
50
+ function isLogicalEntrySource(id, importers = []) {
51
+ let normalizedSource;
52
+ for (const importer of importers) {
53
+ const logicalEntry = parseLogicalEntryId(importer);
54
+ if (!logicalEntry) continue;
55
+ normalizedSource ??= normalizeSourceId(id);
56
+ if (logicalEntry.sourceId === normalizedSource) return true;
57
+ }
58
+ return false;
59
+ }
60
+ function moduleIdMatchesFile(id, file) {
61
+ const sidecarSource = parseSidecarSourceRequest(id);
62
+ if (sidecarSource) return normalizeSourceId(sidecarSource.sourceId) === file;
63
+ const sidecar = parseSidecarModuleId(id);
64
+ if (sidecar) return normalizeSourceId(sidecar.sourceId) === file;
65
+ const logicalEntry = parseLogicalEntryId(id);
66
+ if (logicalEntry) return normalizeSourceId(logicalEntry.sourceId) === file;
67
+ return normalizeSourceId(id) === file;
68
+ }
69
+ /** 存在性查询首次命中即返回,不为布尔结果收集全部模块。 */
70
+ function hasBuildModule(context, file) {
71
+ return withRealpathScope(() => {
72
+ for (const id of context.getModuleIds?.() ?? []) if (moduleIdMatchesFile(id, file)) return true;
73
+ return false;
74
+ });
75
+ }
76
+ /** 优先查询当前文件索引;未命中时仍按完整协议与真实路径查找别名。 */
77
+ function hasDevModule(server, file) {
78
+ return withRealpathScope(() => {
79
+ if (server.moduleGraph.getModulesByFile(file)?.size) return true;
80
+ for (const [id] of server.moduleGraph.idToModuleMap ?? []) if (moduleIdMatchesFile(id, file)) return true;
81
+ return false;
82
+ });
83
+ }
84
+ function collectBuildStartIds(context, file) {
85
+ return withRealpathScope(() => {
86
+ const ids = /* @__PURE__ */ new Set();
87
+ if (typeof context.getModuleIds !== "function") return ids;
88
+ for (const id of context.getModuleIds()) if (moduleIdMatchesFile(id, file)) ids.add(id);
89
+ return ids;
90
+ });
91
+ }
92
+ function collectDevStartNodes(server, file) {
93
+ return withRealpathScope(() => {
94
+ const nodes = new Set(server.moduleGraph.getModulesByFile(file) ?? []);
95
+ for (const [id, node] of server.moduleGraph.idToModuleMap ?? []) if (moduleIdMatchesFile(id, file)) nodes.add(node);
96
+ return nodes;
97
+ });
98
+ }
99
+ //#endregion
100
+ //#region src/utils/regexp.ts
101
+ const CSS_LANGS_RE = /\.(wxss|css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
102
+ function isCSSRequest(request) {
103
+ return CSS_LANGS_RE.test(request);
104
+ }
105
+ function isRegexp(value) {
106
+ return Object.prototype.toString.call(value) === "[object RegExp]";
107
+ }
108
+ //#endregion
109
+ //#region src/runtime/autoRoutesPlugin/matcher.ts
110
+ const DEFAULT_AUTO_ROUTE_INCLUDE = ["pages/**"];
111
+ const GLOB_MAGIC_PATTERN = /[*?[\]{}()!]/;
112
+ const RELATIVE_PREFIX_PATTERN = /^\.?\//;
113
+ const LEADING_SLASH_PATTERN = /^\/+/;
114
+ function toArray(include) {
115
+ if (include == null) return [...DEFAULT_AUTO_ROUTE_INCLUDE];
116
+ return Array.isArray(include) ? [...include] : [include];
117
+ }
118
+ function normalizeRuleCandidate(candidate) {
119
+ return toPosixPath(candidate.replace(RELATIVE_PREFIX_PATTERN, "").replace(LEADING_SLASH_PATTERN, ""));
120
+ }
121
+ function createRule(pattern) {
122
+ if (pattern instanceof RegExp) return {
123
+ pattern,
124
+ match(candidate) {
125
+ pattern.lastIndex = 0;
126
+ return pattern.test(candidate);
127
+ }
128
+ };
129
+ return {
130
+ pattern,
131
+ match: picomatch(pattern, { dot: true })
132
+ };
133
+ }
134
+ function isDefaultAutoRouteInclude(include) {
135
+ return include.length === DEFAULT_AUTO_ROUTE_INCLUDE.length && include.every((pattern, index) => pattern === DEFAULT_AUTO_ROUTE_INCLUDE[index]);
136
+ }
137
+ function extractStaticPrefix(pattern) {
138
+ const normalized = normalizeRuleCandidate(pattern);
139
+ if (!normalized) return;
140
+ const segments = normalized.split("/");
141
+ const staticSegments = [];
142
+ for (const segment of segments) {
143
+ if (!segment || GLOB_MAGIC_PATTERN.test(segment)) break;
144
+ staticSegments.push(segment);
145
+ }
146
+ if (staticSegments.length === 0) return;
147
+ return staticSegments.join("/");
148
+ }
149
+ function createAutoRoutesMatcher(include, subPackageRoots = []) {
150
+ const normalizedInclude = toArray(include);
151
+ const rules = normalizedInclude.map(createRule);
152
+ const isDefault = isDefaultAutoRouteInclude(normalizedInclude);
153
+ const normalizedSubPackageRoots = [...subPackageRoots].filter(Boolean).map((root) => normalizeRuleCandidate(root)).filter(Boolean);
154
+ function matches(candidate) {
155
+ const normalizedCandidate = normalizeRuleCandidate(candidate);
156
+ if (!normalizedCandidate) return false;
157
+ if (isDefault) {
158
+ if (normalizedCandidate.startsWith("pages/")) return true;
159
+ return normalizedSubPackageRoots.some((root) => {
160
+ return normalizedCandidate.startsWith(`${root}/`);
161
+ });
162
+ }
163
+ return rules.some((rule) => rule.match(normalizedCandidate));
164
+ }
165
+ function getRoots(absoluteSrcRoot) {
166
+ if (isDefault) {
167
+ const roots = /* @__PURE__ */ new Set([path.join(absoluteSrcRoot, "pages")]);
168
+ for (const root of normalizedSubPackageRoots) roots.add(path.join(absoluteSrcRoot, root));
169
+ return Array.from(roots, (root) => normalizePath$1(root));
170
+ }
171
+ const roots = /* @__PURE__ */ new Set();
172
+ for (const rule of rules) {
173
+ if (rule.pattern instanceof RegExp) {
174
+ roots.add(absoluteSrcRoot);
175
+ continue;
176
+ }
177
+ const prefix = extractStaticPrefix(rule.pattern);
178
+ if (!prefix) {
179
+ roots.add(absoluteSrcRoot);
180
+ continue;
181
+ }
182
+ roots.add(path.resolve(absoluteSrcRoot, prefix));
183
+ }
184
+ if (roots.size === 0) roots.add(absoluteSrcRoot);
185
+ return Array.from(roots, (root) => normalizePath$1(root));
186
+ }
187
+ return {
188
+ include: normalizedInclude,
189
+ isDefault,
190
+ matches,
191
+ matchesRelativePath(relativePath) {
192
+ return matches(relativePath);
193
+ },
194
+ getSearchRoots(absoluteSrcRoot) {
195
+ return getRoots(absoluteSrcRoot);
196
+ },
197
+ getWatchRoots(absoluteSrcRoot) {
198
+ return getRoots(absoluteSrcRoot);
199
+ }
200
+ };
201
+ }
202
+ //#endregion
203
+ //#region src/autoRoutesConfig.ts
204
+ function resolveWeappAutoRoutesConfig(config) {
205
+ if (config == null || config === false) return {
206
+ enabled: false,
207
+ typedRouter: false,
208
+ include: [...DEFAULT_AUTO_ROUTE_INCLUDE],
209
+ persistentCache: false,
210
+ watch: false
211
+ };
212
+ const record = typeof config === "object" && config ? config : {};
213
+ return {
214
+ enabled: config === true || record.enabled !== false,
215
+ typedRouter: record.typedRouter !== false,
216
+ include: record.include == null ? [...DEFAULT_AUTO_ROUTE_INCLUDE] : Array.isArray(record.include) ? [...record.include] : [record.include],
217
+ ...record.extensions?.length ? { extensions: [...new Set(record.extensions.map((extension) => extension.replace(/^\./, "")))] } : {},
218
+ persistentCache: typeof record.persistentCache === "string" || record.persistentCache === true,
219
+ persistentCachePath: typeof record.persistentCache === "string" ? record.persistentCache : void 0,
220
+ watch: record.watch !== false
221
+ };
222
+ }
223
+ //#endregion
224
+ //#region src/runtime/autoRoutesPlugin/generatedPaths.ts
225
+ const AUTO_ROUTES_CACHE_FILE = ".weapp-vite/auto-routes.cache.json";
226
+ const TYPED_ROUTER_OUTPUT_FILE = ".weapp-vite/typed-router.d.ts";
227
+ const GENERATED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
228
+ ".cache",
229
+ ".rolldown-require",
230
+ ".rolldown-require-cache",
231
+ ".tmp",
232
+ ".weapp-vite",
233
+ ".wevu-config",
234
+ "__temp__",
235
+ "coverage",
236
+ "dist",
237
+ "miniprogram_npm",
238
+ "node_modules"
239
+ ]);
240
+ const GENERATED_FILE_NAMES = /* @__PURE__ */ new Set([path.basename(AUTO_ROUTES_CACHE_FILE), path.basename(TYPED_ROUTER_OUTPUT_FILE)]);
241
+ function stripQuery(candidate) {
242
+ return candidate.split("?")[0];
243
+ }
244
+ function resolveGeneratedCandidatePath(candidate, cwd) {
245
+ const pathWithoutQuery = stripQuery(candidate);
246
+ if (!pathWithoutQuery) return;
247
+ return normalizePath$1(path.isAbsolute(pathWithoutQuery) ? pathWithoutQuery : path.resolve(cwd, pathWithoutQuery));
248
+ }
249
+ function isAutoRoutesGeneratedDirectoryName(name) {
250
+ return GENERATED_DIRECTORY_NAMES.has(name);
251
+ }
252
+ function isAutoRoutesGeneratedFileName(fileName) {
253
+ return GENERATED_FILE_NAMES.has(fileName) || fileName.includes(".auto-routes.") || fileName.includes(".auto-routes-");
254
+ }
255
+ function isAutoRoutesGeneratedRelativePath(relativePath) {
256
+ const segments = toPosixPath(relativePath).split("/").filter(Boolean);
257
+ if (segments.some(isAutoRoutesGeneratedDirectoryName)) return true;
258
+ const fileName = segments[segments.length - 1];
259
+ return Boolean(fileName && isAutoRoutesGeneratedFileName(fileName));
260
+ }
261
+ function resolveAutoRoutesManagedOutputPaths(ctx) {
262
+ const configService = ctx.configService;
263
+ const outputPaths = /* @__PURE__ */ new Set();
264
+ if (!configService) return outputPaths;
265
+ const baseDir = typeof configService.configFilePath === "string" ? path.dirname(configService.configFilePath) : configService.cwd;
266
+ if (!baseDir) return outputPaths;
267
+ outputPaths.add(normalizePath$1(path.resolve(baseDir, TYPED_ROUTER_OUTPUT_FILE)));
268
+ outputPaths.add(normalizePath$1(path.resolve(baseDir, AUTO_ROUTES_CACHE_FILE)));
269
+ const autoRoutesConfig = resolveWeappAutoRoutesConfig(configService.weappViteConfig?.autoRoutes);
270
+ if (autoRoutesConfig.persistentCache) outputPaths.add(normalizePath$1(path.resolve(baseDir, autoRoutesConfig.persistentCachePath ?? AUTO_ROUTES_CACHE_FILE)));
271
+ return outputPaths;
272
+ }
273
+ function isAutoRoutesGeneratedPath(candidate, options) {
274
+ const absolutePath = resolveGeneratedCandidatePath(candidate, options.cwd);
275
+ if (!absolutePath) return false;
276
+ for (const outputPath of options.managedOutputPaths ?? []) if (absolutePath === normalizePath$1(outputPath)) return true;
277
+ const normalizedSrcRoot = normalizePath$1(options.absoluteSrcRoot);
278
+ const relativePath = toPosixPath(path.relative(normalizedSrcRoot, absolutePath));
279
+ if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) return false;
280
+ return isAutoRoutesGeneratedRelativePath(relativePath);
281
+ }
282
+ //#endregion
283
+ //#region ../../node_modules/.pnpm/readdirp@5.1.1/node_modules/readdirp/index.js
284
+ const EntryTypes = {
285
+ FILE_TYPE: "files",
286
+ DIR_TYPE: "directories",
287
+ FILE_DIR_TYPE: "files_directories",
288
+ EVERYTHING_TYPE: "all"
289
+ };
290
+ const defaultOptions = {
291
+ root: ".",
292
+ fileFilter: (_entryInfo) => true,
293
+ directoryFilter: (_entryInfo) => true,
294
+ type: EntryTypes.FILE_TYPE,
295
+ lstat: false,
296
+ depth: 2147483648,
297
+ alwaysStat: false,
298
+ highWaterMark: 256
299
+ };
300
+ Object.freeze(defaultOptions);
301
+ const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
302
+ const NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set([
303
+ "ENOENT",
304
+ "EPERM",
305
+ "EACCES",
306
+ "ELOOP",
307
+ RECURSIVE_ERROR_CODE
308
+ ]);
309
+ const ALL_TYPES = [
310
+ EntryTypes.DIR_TYPE,
311
+ EntryTypes.EVERYTHING_TYPE,
312
+ EntryTypes.FILE_DIR_TYPE,
313
+ EntryTypes.FILE_TYPE
314
+ ];
315
+ const DIR_TYPES = /* @__PURE__ */ new Set([
316
+ EntryTypes.DIR_TYPE,
317
+ EntryTypes.EVERYTHING_TYPE,
318
+ EntryTypes.FILE_DIR_TYPE
319
+ ]);
320
+ const FILE_TYPES = /* @__PURE__ */ new Set([
321
+ EntryTypes.EVERYTHING_TYPE,
322
+ EntryTypes.FILE_DIR_TYPE,
323
+ EntryTypes.FILE_TYPE
324
+ ]);
325
+ const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
326
+ const wantBigintFsStats = process.platform === "win32";
327
+ const emptyFn = (_entryInfo) => true;
328
+ const normalizeFilter = (filter) => {
329
+ if (filter === void 0) return emptyFn;
330
+ if (typeof filter === "function") return filter;
331
+ if (typeof filter === "string") {
332
+ const fl = filter.trim();
333
+ return (entry) => entry.basename === fl;
334
+ }
335
+ if (Array.isArray(filter)) {
336
+ const trItems = filter.map((item) => item.trim());
337
+ return (entry) => trItems.some((f) => entry.basename === f);
338
+ }
339
+ return emptyFn;
340
+ };
341
+ var ReaddirpStream = class extends Readable {
342
+ /**
343
+ * Directories discovered but not yet emitted from. Listings are read
344
+ * lazily (on pop, plus one prefetch) instead of eagerly on discovery:
345
+ * keeping whole listings for every queued dir balloons RAM on wide trees.
346
+ */
347
+ parents;
348
+ reading;
349
+ parent;
350
+ _stat;
351
+ _maxDepth;
352
+ _wantsDir;
353
+ _wantsFile;
354
+ _wantsEverything;
355
+ _root;
356
+ _isDirent;
357
+ _statsProp;
358
+ _rdOptions;
359
+ _fileFilter;
360
+ _directoryFilter;
361
+ _relStart;
362
+ constructor(options = {}) {
363
+ super({
364
+ objectMode: true,
365
+ autoDestroy: true,
366
+ highWaterMark: options.highWaterMark ?? defaultOptions.highWaterMark
367
+ });
368
+ const opts = {
369
+ ...defaultOptions,
370
+ ...options
371
+ };
372
+ const root = opts.root ?? defaultOptions.root;
373
+ const type = opts.type ?? defaultOptions.type;
374
+ this._fileFilter = normalizeFilter(opts.fileFilter);
375
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
376
+ const statMethod = opts.lstat ? lstat : stat$1;
377
+ if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
378
+ else this._stat = statMethod;
379
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
380
+ this._wantsDir = DIR_TYPES.has(type);
381
+ this._wantsFile = FILE_TYPES.has(type);
382
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
383
+ this._root = resolve(root);
384
+ this._relStart = this._root.endsWith(sep) ? this._root.length : this._root.length + 1;
385
+ this._isDirent = !opts.alwaysStat;
386
+ this._statsProp = this._isDirent ? "dirent" : "stats";
387
+ this._rdOptions = {
388
+ encoding: "utf8",
389
+ withFileTypes: this._isDirent
390
+ };
391
+ const rootDir = {
392
+ path: this._root,
393
+ depth: 1
394
+ };
395
+ rootDir.pending = this._exploreDir(this._root, 1);
396
+ this.parents = [rootDir];
397
+ this.reading = false;
398
+ this.parent = void 0;
399
+ }
400
+ async _read(batch) {
401
+ if (this.reading) return;
402
+ this.reading = true;
403
+ try {
404
+ while (!this.destroyed && batch > 0) {
405
+ const par = this.parent;
406
+ const fil = par && par.files;
407
+ if (fil && fil.length > 0) {
408
+ const { path, depth } = par;
409
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
410
+ const awaited = this._isDirent ? slice : await Promise.all(slice);
411
+ for (const entry of awaited) {
412
+ if (!entry) continue;
413
+ if (this.destroyed) return;
414
+ let entryType = this._getEntryType(entry);
415
+ if (typeof entryType !== "string") entryType = await entryType;
416
+ if (entryType === "directory" && this._directoryFilter(entry)) {
417
+ if (depth <= this._maxDepth) this.parents.push({
418
+ path: entry.fullPath,
419
+ depth: depth + 1
420
+ });
421
+ if (this._wantsDir) {
422
+ this.push(entry);
423
+ batch--;
424
+ }
425
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
426
+ if (this._wantsFile) {
427
+ this.push(entry);
428
+ batch--;
429
+ }
430
+ }
431
+ }
432
+ } else {
433
+ const parent = this.parents.pop();
434
+ if (!parent) {
435
+ this.push(null);
436
+ break;
437
+ }
438
+ const dir = parent.pending ?? this._exploreDir(parent.path, parent.depth);
439
+ const next = this.parents[this.parents.length - 1];
440
+ if (next && !next.pending) next.pending = this._exploreDir(next.path, next.depth);
441
+ this.parent = await dir;
442
+ if (this.destroyed) return;
443
+ }
444
+ }
445
+ } catch (error) {
446
+ this.destroy(error);
447
+ } finally {
448
+ this.reading = false;
449
+ }
450
+ }
451
+ async _exploreDir(path, depth) {
452
+ let files;
453
+ try {
454
+ files = await readdir(path, this._rdOptions);
455
+ } catch (error) {
456
+ this._onError(error);
457
+ }
458
+ return {
459
+ files,
460
+ depth,
461
+ path
462
+ };
463
+ }
464
+ _formatEntry(dirent, path) {
465
+ const basename = this._isDirent ? dirent.name : dirent;
466
+ const fullPath = join(path, basename);
467
+ const entry = {
468
+ path: fullPath.slice(this._relStart),
469
+ fullPath,
470
+ basename
471
+ };
472
+ if (this._isDirent) {
473
+ entry.dirent = dirent;
474
+ return entry;
475
+ }
476
+ return this._stat(fullPath).then((stats) => {
477
+ entry.stats = stats;
478
+ return entry;
479
+ }, (err) => {
480
+ this._onError(err);
481
+ });
482
+ }
483
+ _onError(err) {
484
+ if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
485
+ else this.destroy(err);
486
+ }
487
+ _getEntryType(entry) {
488
+ if (!entry || !(this._statsProp in entry)) return "";
489
+ const stats = entry[this._statsProp];
490
+ if (stats.isFile()) return "file";
491
+ if (stats.isDirectory()) return "directory";
492
+ if (stats.isSymbolicLink()) return this._getSymlinkEntryType(entry);
493
+ return "";
494
+ }
495
+ async _getSymlinkEntryType(entry) {
496
+ const full = entry.fullPath;
497
+ try {
498
+ const entryRealPath = await realpath(full);
499
+ const entryRealPathStats = await lstat(entryRealPath);
500
+ if (entryRealPathStats.isFile()) return "file";
501
+ if (entryRealPathStats.isDirectory()) {
502
+ const len = entryRealPath.length;
503
+ if (full.startsWith(entryRealPath) && full[len] === sep) {
504
+ const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
505
+ recursiveError.code = RECURSIVE_ERROR_CODE;
506
+ this._onError(recursiveError);
507
+ return "";
508
+ }
509
+ return "directory";
510
+ }
511
+ } catch (error) {
512
+ this._onError(error);
513
+ }
514
+ return "";
515
+ }
516
+ _includeAsFile(entry) {
517
+ const stats = entry && entry[this._statsProp];
518
+ return stats && this._wantsEverything && !stats.isDirectory();
519
+ }
520
+ };
521
+ /**
522
+ * Streaming version: Reads all files and directories in given root recursively.
523
+ * Consumes ~constant small amount of RAM.
524
+ * @param root Root directory
525
+ * @param options Options to specify root (start directory), filters and recursion depth
526
+ */
527
+ function readdirp(root, options = {}) {
528
+ let type = options.entryType || options.type;
529
+ if (type === "both") type = EntryTypes.FILE_DIR_TYPE;
530
+ if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
531
+ else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
532
+ else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
533
+ const opts = {
534
+ ...options,
535
+ root
536
+ };
537
+ if (type) opts.type = type;
538
+ return new ReaddirpStream(opts);
539
+ }
540
+ //#endregion
541
+ //#region ../../node_modules/.pnpm/chokidar@5.0.0_patch_hash=fafb20ce736d8edb3357d9d04cebccbd6e05ecc1bc10aa26a7484d2369016811/node_modules/chokidar/handler.js
542
+ const STR_DATA = "data";
543
+ const STR_CLOSE = "close";
544
+ const EMPTY_FN = () => {};
545
+ const pl = process.platform;
546
+ const isWindows = pl === "win32";
547
+ const isMacos = pl === "darwin";
548
+ const isLinux = pl === "linux";
549
+ const isFreeBSD = pl === "freebsd";
550
+ const isIBMi = type() === "OS400";
551
+ const EVENTS = {
552
+ ALL: "all",
553
+ READY: "ready",
554
+ ADD: "add",
555
+ CHANGE: "change",
556
+ ADD_DIR: "addDir",
557
+ UNLINK: "unlink",
558
+ UNLINK_DIR: "unlinkDir",
559
+ RAW: "raw",
560
+ ERROR: "error"
561
+ };
562
+ const EV = EVENTS;
563
+ const THROTTLE_MODE_WATCH = "watch";
564
+ const clearPreviousRemoveThrottle = (fsw, path, throttler) => {
565
+ if (!throttler) return;
566
+ if (fsw._throttled.get("remove")?.get(path) === throttler) throttler.clear();
567
+ else clearTimeout(throttler.timeoutObject);
568
+ };
569
+ const statMethods = {
570
+ lstat,
571
+ stat: stat$1
572
+ };
573
+ const KEY_LISTENERS = "listeners";
574
+ const KEY_ERR = "errHandlers";
575
+ const KEY_RAW = "rawEmitters";
576
+ const HANDLER_KEYS = [
577
+ KEY_LISTENERS,
578
+ KEY_ERR,
579
+ KEY_RAW
580
+ ];
581
+ const binaryExtensions = /* @__PURE__ */ new Set([
582
+ "3dm",
583
+ "3ds",
584
+ "3g2",
585
+ "3gp",
586
+ "7z",
587
+ "a",
588
+ "aac",
589
+ "adp",
590
+ "afdesign",
591
+ "afphoto",
592
+ "afpub",
593
+ "ai",
594
+ "aif",
595
+ "aiff",
596
+ "alz",
597
+ "ape",
598
+ "apk",
599
+ "appimage",
600
+ "ar",
601
+ "arj",
602
+ "asf",
603
+ "au",
604
+ "avi",
605
+ "bak",
606
+ "baml",
607
+ "bh",
608
+ "bin",
609
+ "bk",
610
+ "bmp",
611
+ "btif",
612
+ "bz2",
613
+ "bzip2",
614
+ "cab",
615
+ "caf",
616
+ "cgm",
617
+ "class",
618
+ "cmx",
619
+ "cpio",
620
+ "cr2",
621
+ "cur",
622
+ "dat",
623
+ "dcm",
624
+ "deb",
625
+ "dex",
626
+ "djvu",
627
+ "dll",
628
+ "dmg",
629
+ "dng",
630
+ "doc",
631
+ "docm",
632
+ "docx",
633
+ "dot",
634
+ "dotm",
635
+ "dra",
636
+ "DS_Store",
637
+ "dsk",
638
+ "dts",
639
+ "dtshd",
640
+ "dvb",
641
+ "dwg",
642
+ "dxf",
643
+ "ecelp4800",
644
+ "ecelp7470",
645
+ "ecelp9600",
646
+ "egg",
647
+ "eol",
648
+ "eot",
649
+ "epub",
650
+ "exe",
651
+ "f4v",
652
+ "fbs",
653
+ "fh",
654
+ "fla",
655
+ "flac",
656
+ "flatpak",
657
+ "fli",
658
+ "flv",
659
+ "fpx",
660
+ "fst",
661
+ "fvt",
662
+ "g3",
663
+ "gh",
664
+ "gif",
665
+ "graffle",
666
+ "gz",
667
+ "gzip",
668
+ "h261",
669
+ "h263",
670
+ "h264",
671
+ "icns",
672
+ "ico",
673
+ "ief",
674
+ "img",
675
+ "ipa",
676
+ "iso",
677
+ "jar",
678
+ "jpeg",
679
+ "jpg",
680
+ "jpgv",
681
+ "jpm",
682
+ "jxr",
683
+ "key",
684
+ "ktx",
685
+ "lha",
686
+ "lib",
687
+ "lvp",
688
+ "lz",
689
+ "lzh",
690
+ "lzma",
691
+ "lzo",
692
+ "m3u",
693
+ "m4a",
694
+ "m4v",
695
+ "mar",
696
+ "mdi",
697
+ "mht",
698
+ "mid",
699
+ "midi",
700
+ "mj2",
701
+ "mka",
702
+ "mkv",
703
+ "mmr",
704
+ "mng",
705
+ "mobi",
706
+ "mov",
707
+ "movie",
708
+ "mp3",
709
+ "mp4",
710
+ "mp4a",
711
+ "mpeg",
712
+ "mpg",
713
+ "mpga",
714
+ "mxu",
715
+ "nef",
716
+ "npx",
717
+ "numbers",
718
+ "nupkg",
719
+ "o",
720
+ "odp",
721
+ "ods",
722
+ "odt",
723
+ "oga",
724
+ "ogg",
725
+ "ogv",
726
+ "otf",
727
+ "ott",
728
+ "pages",
729
+ "pbm",
730
+ "pcx",
731
+ "pdb",
732
+ "pdf",
733
+ "pea",
734
+ "pgm",
735
+ "pic",
736
+ "png",
737
+ "pnm",
738
+ "pot",
739
+ "potm",
740
+ "potx",
741
+ "ppa",
742
+ "ppam",
743
+ "ppm",
744
+ "pps",
745
+ "ppsm",
746
+ "ppsx",
747
+ "ppt",
748
+ "pptm",
749
+ "pptx",
750
+ "psd",
751
+ "pya",
752
+ "pyc",
753
+ "pyo",
754
+ "pyv",
755
+ "qt",
756
+ "rar",
757
+ "ras",
758
+ "raw",
759
+ "resources",
760
+ "rgb",
761
+ "rip",
762
+ "rlc",
763
+ "rmf",
764
+ "rmvb",
765
+ "rpm",
766
+ "rtf",
767
+ "rz",
768
+ "s3m",
769
+ "s7z",
770
+ "scpt",
771
+ "sgi",
772
+ "shar",
773
+ "snap",
774
+ "sil",
775
+ "sketch",
776
+ "slk",
777
+ "smv",
778
+ "snk",
779
+ "so",
780
+ "stl",
781
+ "suo",
782
+ "sub",
783
+ "swf",
784
+ "tar",
785
+ "tbz",
786
+ "tbz2",
787
+ "tga",
788
+ "tgz",
789
+ "thmx",
790
+ "tif",
791
+ "tiff",
792
+ "tlz",
793
+ "ttc",
794
+ "ttf",
795
+ "txz",
796
+ "udf",
797
+ "uvh",
798
+ "uvi",
799
+ "uvm",
800
+ "uvp",
801
+ "uvs",
802
+ "uvu",
803
+ "viv",
804
+ "vob",
805
+ "war",
806
+ "wav",
807
+ "wax",
808
+ "wbmp",
809
+ "wdp",
810
+ "weba",
811
+ "webm",
812
+ "webp",
813
+ "whl",
814
+ "wim",
815
+ "wm",
816
+ "wma",
817
+ "wmv",
818
+ "wmx",
819
+ "woff",
820
+ "woff2",
821
+ "wrm",
822
+ "wvx",
823
+ "xbm",
824
+ "xif",
825
+ "xla",
826
+ "xlam",
827
+ "xls",
828
+ "xlsb",
829
+ "xlsm",
830
+ "xlsx",
831
+ "xlt",
832
+ "xltm",
833
+ "xltx",
834
+ "xm",
835
+ "xmind",
836
+ "xpi",
837
+ "xpm",
838
+ "xwd",
839
+ "xz",
840
+ "z",
841
+ "zip",
842
+ "zipx"
843
+ ]);
844
+ const isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
845
+ const foreach = (val, fn) => {
846
+ if (val instanceof Set) val.forEach(fn);
847
+ else fn(val);
848
+ };
849
+ const addAndConvert = (main, prop, item) => {
850
+ let container = main[prop];
851
+ if (!(container instanceof Set)) main[prop] = container = /* @__PURE__ */ new Set([container]);
852
+ container.add(item);
853
+ };
854
+ const clearItem = (cont) => (key) => {
855
+ const set = cont[key];
856
+ if (set instanceof Set) set.clear();
857
+ else delete cont[key];
858
+ };
859
+ const delFromSet = (main, prop, item) => {
860
+ const container = main[prop];
861
+ if (container instanceof Set) container.delete(item);
862
+ else if (container === item) delete main[prop];
863
+ };
864
+ const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
865
+ const FsWatchInstances = /* @__PURE__ */ new Map();
866
+ const NATIVE_SUBSCRIPTION = Symbol();
867
+ const sameInode = (binding, stats) => binding && stats && binding.dev !== void 0 && binding.ino !== void 0 && binding.dev === stats.dev && binding.ino === stats.ino;
868
+ /**
869
+ * Instantiates the fs_watch interface
870
+ * @param path to be watched
871
+ * @param options to be passed to fs_watch
872
+ * @param listener main event handler
873
+ * @param errHandler emits info about errors
874
+ * @param emitRaw emits raw event data
875
+ * @returns {NativeFsWatcher}
876
+ */
877
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw, isActive = () => true) {
878
+ const handleEvent = (rawEvent, evPath) => {
879
+ if (!isActive()) return;
880
+ listener(path);
881
+ if (!isActive()) return;
882
+ emitRaw(rawEvent, evPath, { watchedPath: path });
883
+ if (!isActive()) return;
884
+ if (evPath && path !== evPath) fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));
885
+ };
886
+ try {
887
+ return watch(path, { persistent: options.persistent }, handleEvent);
888
+ } catch (error) {
889
+ errHandler(error);
890
+ return;
891
+ }
892
+ }
893
+ /**
894
+ * Helper for passing fs_watch event data to a collection of listeners
895
+ * @param fullPath absolute path bound to fs_watch instance
896
+ */
897
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3, expectedBinding) => {
898
+ const cont = FsWatchInstances.get(fullPath);
899
+ if (!cont) return;
900
+ const isCurrent = () => FsWatchInstances.get(fullPath) === cont && (!expectedBinding || cont.binding === expectedBinding && !expectedBinding.closed);
901
+ foreach(cont[listenerType], (listener) => {
902
+ if (isCurrent()) listener(val1, val2, val3);
903
+ });
904
+ };
905
+ /** 为同一个共享容器取得下一代原生句柄,发布前的回调保持失活。 */
906
+ const createPersistentBinding = (path, fullPath, options, cont, acquireErrorHandler, stats) => {
907
+ const binding = {
908
+ watcher: void 0,
909
+ generation: (cont.binding?.generation || 0) + 1,
910
+ dev: stats?.dev,
911
+ ino: stats?.ino,
912
+ closed: false,
913
+ close: EMPTY_FN
914
+ };
915
+ const isCurrent = () => FsWatchInstances.get(fullPath) === cont && cont.binding === binding && !binding.closed;
916
+ const broadcastError = (error) => fsWatchBroadcast(fullPath, KEY_ERR, error, void 0, void 0, binding);
917
+ const watcher = createFsWatchInstance(path, options, (changedPath) => fsWatchBroadcast(fullPath, KEY_LISTENERS, changedPath, void 0, void 0, binding), acquireErrorHandler, (event, eventPath, details) => fsWatchBroadcast(fullPath, KEY_RAW, event, eventPath, details, binding), isCurrent);
918
+ if (!watcher) return;
919
+ binding.watcher = watcher;
920
+ binding.close = () => {
921
+ if (binding.closed) return;
922
+ binding.closed = true;
923
+ watcher.close();
924
+ };
925
+ watcher.on(EV.ERROR, async (error) => {
926
+ if (!isCurrent()) return;
927
+ cont.watcherUnusable = true;
928
+ if (isWindows && error.code === "EPERM") try {
929
+ await (await open(path, "r")).close();
930
+ if (isCurrent()) broadcastError(error);
931
+ } catch (err) {}
932
+ else broadcastError(error);
933
+ });
934
+ return binding;
935
+ };
936
+ /**
937
+ * Instantiates the fs_watch interface or binds listeners
938
+ * to an existing one covering the same file system entry
939
+ * @param path
940
+ * @param fullPath absolute path
941
+ * @param options to be passed to fs_watch
942
+ * @param handlers container for event listener functions
943
+ */
944
+ const setFsWatchListener = (path, fullPath, options, handlers, registrationErrorHandler) => {
945
+ const { listener, errHandler, rawEmitter } = handlers;
946
+ const acquireErrorHandler = registrationErrorHandler || errHandler;
947
+ let cont = FsWatchInstances.get(fullPath);
948
+ if (!options.persistent) {
949
+ let active = true;
950
+ const watcher = createFsWatchInstance(path, options, listener, acquireErrorHandler, rawEmitter, () => active);
951
+ if (!watcher) return;
952
+ return () => {
953
+ if (!active) return;
954
+ active = false;
955
+ watcher.close();
956
+ };
957
+ }
958
+ if (cont) {
959
+ addAndConvert(cont, KEY_LISTENERS, listener);
960
+ addAndConvert(cont, KEY_ERR, errHandler);
961
+ addAndConvert(cont, KEY_RAW, rawEmitter);
962
+ } else {
963
+ cont = {
964
+ listeners: /* @__PURE__ */ new Set([listener]),
965
+ errHandlers: /* @__PURE__ */ new Set([errHandler]),
966
+ rawEmitters: /* @__PURE__ */ new Set([rawEmitter]),
967
+ watcher: void 0,
968
+ binding: void 0
969
+ };
970
+ const binding = createPersistentBinding(path, fullPath, options, cont, acquireErrorHandler, options.stats);
971
+ if (!binding) return;
972
+ cont.binding = binding;
973
+ cont.watcher = binding.watcher;
974
+ FsWatchInstances.set(fullPath, cont);
975
+ }
976
+ let active = true;
977
+ const close = () => {
978
+ if (!active) return;
979
+ active = false;
980
+ delFromSet(cont, KEY_LISTENERS, listener);
981
+ delFromSet(cont, KEY_ERR, errHandler);
982
+ delFromSet(cont, KEY_RAW, rawEmitter);
983
+ if (isEmptySet(cont.listeners)) {
984
+ const binding = cont.binding;
985
+ cont.binding = void 0;
986
+ if (FsWatchInstances.get(fullPath) === cont) FsWatchInstances.delete(fullPath);
987
+ binding?.close();
988
+ HANDLER_KEYS.forEach(clearItem(cont));
989
+ cont.watcher = void 0;
990
+ Object.freeze(cont);
991
+ }
992
+ };
993
+ const isOwned = () => active && FsWatchInstances.get(fullPath) === cont && cont.binding !== void 0;
994
+ close[NATIVE_SUBSCRIPTION] = {
995
+ snapshot: () => isOwned() ? cont.binding : void 0,
996
+ accepts: (observed, stats) => isOwned() && (cont.binding === observed || sameInode(cont.binding, stats)),
997
+ rebind: (stats) => {
998
+ if (!isOwned()) return false;
999
+ const previous = cont.binding;
1000
+ if (sameInode(previous, stats)) return true;
1001
+ let failed = false;
1002
+ let failure;
1003
+ const replacement = createPersistentBinding(path, fullPath, options, cont, (error) => {
1004
+ failed = true;
1005
+ failure = error;
1006
+ }, stats);
1007
+ if (failed) throw failure;
1008
+ if (!replacement) return false;
1009
+ if (FsWatchInstances.get(fullPath) !== cont || cont.binding !== previous || isEmptySet(cont.listeners)) {
1010
+ replacement.close();
1011
+ return false;
1012
+ }
1013
+ cont.binding = replacement;
1014
+ cont.watcher = replacement.watcher;
1015
+ cont.watcherUnusable = false;
1016
+ previous.close();
1017
+ return true;
1018
+ }
1019
+ };
1020
+ return close;
1021
+ };
1022
+ const FsWatchFileInstances = /* @__PURE__ */ new Map();
1023
+ const createFsWatchFileBinding = (path, fullPath, options, cont) => {
1024
+ const binding = {
1025
+ closed: false,
1026
+ watcher: void 0,
1027
+ close: EMPTY_FN
1028
+ };
1029
+ const listener = (curr, prev) => {
1030
+ if (binding.closed || FsWatchFileInstances.get(fullPath) !== cont || cont.binding !== binding) return;
1031
+ const rawEmitters = [...cont.rawEmitters];
1032
+ const listeners = [...cont.listeners];
1033
+ rawEmitters.forEach((rawEmitter) => {
1034
+ if (FsWatchFileInstances.get(fullPath) === cont && cont.rawEmitters.has(rawEmitter)) rawEmitter(EV.CHANGE, fullPath, {
1035
+ curr,
1036
+ prev
1037
+ });
1038
+ });
1039
+ const currmtime = curr.mtimeMs;
1040
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) listeners.forEach((listener) => {
1041
+ if (FsWatchFileInstances.get(fullPath) === cont && cont.listeners.has(listener)) listener(path, curr);
1042
+ });
1043
+ };
1044
+ binding.watcher = watchFile(fullPath, options, listener);
1045
+ binding.close = () => {
1046
+ if (binding.closed) return;
1047
+ binding.closed = true;
1048
+ unwatchFile(fullPath, listener);
1049
+ };
1050
+ return binding;
1051
+ };
1052
+ /**
1053
+ * Instantiates the fs_watchFile interface or binds listeners
1054
+ * to an existing one covering the same file system entry
1055
+ * @param path to be watched
1056
+ * @param fullPath absolute path
1057
+ * @param options options to be passed to fs_watchFile
1058
+ * @param handlers container for event listener functions
1059
+ * @returns closer
1060
+ */
1061
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
1062
+ const { listener, rawEmitter } = handlers;
1063
+ let cont = FsWatchFileInstances.get(fullPath);
1064
+ const copts = cont && cont.options;
1065
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
1066
+ const merged = {
1067
+ ...options,
1068
+ persistent: copts.persistent || options.persistent,
1069
+ interval: Math.min(copts.interval, options.interval)
1070
+ };
1071
+ cont.binding.close();
1072
+ try {
1073
+ cont.binding = createFsWatchFileBinding(path, fullPath, merged, cont);
1074
+ } catch (error) {
1075
+ try {
1076
+ cont.binding = createFsWatchFileBinding(path, fullPath, copts, cont);
1077
+ cont.watcher = cont.binding.watcher;
1078
+ } catch (restoreError) {
1079
+ throw new AggregateError([error, restoreError], "polling watcher 升级与恢复均失败");
1080
+ }
1081
+ throw error;
1082
+ }
1083
+ cont.watcher = cont.binding.watcher;
1084
+ cont.options = merged;
1085
+ }
1086
+ if (cont) {
1087
+ addAndConvert(cont, KEY_LISTENERS, listener);
1088
+ addAndConvert(cont, KEY_RAW, rawEmitter);
1089
+ } else {
1090
+ cont = {
1091
+ listeners: /* @__PURE__ */ new Set([listener]),
1092
+ rawEmitters: /* @__PURE__ */ new Set([rawEmitter]),
1093
+ options,
1094
+ watcher: void 0,
1095
+ binding: void 0
1096
+ };
1097
+ cont.binding = createFsWatchFileBinding(path, fullPath, options, cont);
1098
+ cont.watcher = cont.binding.watcher;
1099
+ FsWatchFileInstances.set(fullPath, cont);
1100
+ }
1101
+ let active = true;
1102
+ return () => {
1103
+ if (!active) return;
1104
+ active = false;
1105
+ delFromSet(cont, KEY_LISTENERS, listener);
1106
+ delFromSet(cont, KEY_RAW, rawEmitter);
1107
+ if (isEmptySet(cont.listeners)) {
1108
+ if (FsWatchFileInstances.get(fullPath) === cont) FsWatchFileInstances.delete(fullPath);
1109
+ cont.binding.close();
1110
+ cont.binding = void 0;
1111
+ cont.options = cont.watcher = void 0;
1112
+ Object.freeze(cont);
1113
+ }
1114
+ };
1115
+ };
1116
+ /**
1117
+ * @mixin
1118
+ */
1119
+ var NodeFsHandler = class {
1120
+ fsw;
1121
+ _boundHandleError;
1122
+ constructor(fsW) {
1123
+ this.fsw = fsW;
1124
+ this._boundHandleError = (error) => fsW._handleError(error);
1125
+ }
1126
+ /**
1127
+ * Watch file for changes with fs_watchFile or fs_watch.
1128
+ * @param path to file or dir
1129
+ * @param listener on fs change
1130
+ * @returns closer for the watcher instance
1131
+ */
1132
+ _watchWithNodeFs(path, listener, throwRegistrationError = false, stats) {
1133
+ const opts = this.fsw.options;
1134
+ const directory = sp.dirname(path);
1135
+ const basename = sp.basename(path);
1136
+ if (!throwRegistrationError) this.fsw._getWatchedDir(directory).add(basename);
1137
+ const absolutePath = sp.resolve(path);
1138
+ const options = {
1139
+ persistent: opts.persistent,
1140
+ stats
1141
+ };
1142
+ if (!listener) listener = EMPTY_FN;
1143
+ let closer;
1144
+ if (opts.usePolling) {
1145
+ options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
1146
+ closer = setFsWatchFileListener(path, absolutePath, options, {
1147
+ listener,
1148
+ rawEmitter: this.fsw._emitRaw
1149
+ });
1150
+ } else {
1151
+ let registrationFailed = false;
1152
+ let registrationError;
1153
+ const onRegistrationError = throwRegistrationError ? (error) => {
1154
+ registrationFailed = true;
1155
+ registrationError = error;
1156
+ } : void 0;
1157
+ closer = setFsWatchListener(path, absolutePath, options, {
1158
+ listener,
1159
+ errHandler: this._boundHandleError,
1160
+ rawEmitter: this.fsw._emitRaw
1161
+ }, onRegistrationError);
1162
+ if (registrationFailed) throw registrationError;
1163
+ }
1164
+ return closer;
1165
+ }
1166
+ /**
1167
+ * Watch a file and emit add event if warranted.
1168
+ * @returns closer for the watcher instance
1169
+ */
1170
+ _handleFile(file, stats, initialAdd) {
1171
+ if (this.fsw.closed) return;
1172
+ const dirname = sp.dirname(file);
1173
+ const basename = sp.basename(file);
1174
+ const parentPath = sp.resolve(dirname);
1175
+ const parent = this.fsw._getWatchedDir(dirname);
1176
+ let prevStats = stats;
1177
+ if (parent.has(basename)) return;
1178
+ const removePath = sp.join(dirname, basename);
1179
+ const previousRemoveThrottle = this.fsw._throttled.get("remove")?.get(removePath);
1180
+ let ownerActive = true;
1181
+ let currentBinding;
1182
+ const isCurrentBinding = (binding) => ownerActive && binding.active && currentBinding === binding && !this.fsw.closed && this.fsw._watched.get(parentPath) === parent && parent.has(basename);
1183
+ const closeOwner = () => {
1184
+ if (!ownerActive) return;
1185
+ ownerActive = false;
1186
+ const binding = currentBinding;
1187
+ currentBinding = void 0;
1188
+ if (binding) binding.close();
1189
+ };
1190
+ const subscribe = () => {
1191
+ if (!ownerActive || this.fsw.closed) return;
1192
+ const binding = {
1193
+ active: false,
1194
+ close: EMPTY_FN
1195
+ };
1196
+ let nativeControl;
1197
+ const listener = async (path, newStats) => {
1198
+ if (!isCurrentBinding(binding) || !this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
1199
+ const observedNative = nativeControl?.snapshot();
1200
+ if (!newStats || newStats.mtimeMs === 0) {
1201
+ let currentStats;
1202
+ try {
1203
+ currentStats = await stat$1(file);
1204
+ } catch (error) {
1205
+ if (isCurrentBinding(binding) && (!nativeControl || nativeControl.accepts(observedNative))) this.fsw._remove(dirname, basename);
1206
+ return;
1207
+ }
1208
+ if (!isCurrentBinding(binding) || nativeControl && !nativeControl.accepts(observedNative, currentStats)) return;
1209
+ const at = currentStats.atimeMs;
1210
+ const mt = currentStats.mtimeMs;
1211
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, currentStats);
1212
+ if (!isCurrentBinding(binding)) return;
1213
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== currentStats.ino) {
1214
+ if (nativeControl) try {
1215
+ if (!nativeControl.rebind(currentStats)) return;
1216
+ } catch (error) {
1217
+ if (isCurrentBinding(binding)) this._boundHandleError(error);
1218
+ return;
1219
+ }
1220
+ else if (!this.fsw.options.usePolling) {
1221
+ binding.close();
1222
+ prevStats = currentStats;
1223
+ subscribe();
1224
+ return;
1225
+ }
1226
+ }
1227
+ if (isCurrentBinding(binding)) prevStats = currentStats;
1228
+ } else {
1229
+ const at = newStats.atimeMs;
1230
+ const mt = newStats.mtimeMs;
1231
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
1232
+ if (isCurrentBinding(binding)) prevStats = newStats;
1233
+ }
1234
+ };
1235
+ const nativeCloser = this._watchWithNodeFs(file, listener, false, prevStats);
1236
+ if (!nativeCloser) return;
1237
+ nativeControl = nativeCloser[NATIVE_SUBSCRIPTION];
1238
+ let closed = false;
1239
+ binding.close = () => {
1240
+ if (closed) return;
1241
+ closed = true;
1242
+ binding.active = false;
1243
+ if (currentBinding === binding) currentBinding = void 0;
1244
+ nativeCloser();
1245
+ };
1246
+ if (!ownerActive || this.fsw.closed || this.fsw._watched.get(parentPath) !== parent || !parent.has(basename)) {
1247
+ binding.close();
1248
+ return;
1249
+ }
1250
+ binding.active = true;
1251
+ currentBinding = binding;
1252
+ return binding;
1253
+ };
1254
+ const binding = subscribe();
1255
+ if (binding && isCurrentBinding(binding)) clearPreviousRemoveThrottle(this.fsw, removePath, previousRemoveThrottle);
1256
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
1257
+ if (this.fsw._throttle(EV.ADD, file, 0)) this.fsw._emit(EV.ADD, file, stats);
1258
+ }
1259
+ if (binding && !isCurrentBinding(binding)) {
1260
+ closeOwner();
1261
+ return;
1262
+ }
1263
+ return binding ? closeOwner : void 0;
1264
+ }
1265
+ /**
1266
+ * Handle symlinks encountered while reading a dir.
1267
+ * @param entry returned by readdirp
1268
+ * @param directory path of dir being read
1269
+ * @param path of this item
1270
+ * @param item basename of this item
1271
+ * @returns true if no more processing is needed for this entry.
1272
+ */
1273
+ async _handleSymlink(entry, directory, path, item, isActive = () => true) {
1274
+ if (this.fsw.closed) return;
1275
+ const full = entry.fullPath;
1276
+ const dir = this.fsw._getWatchedDir(directory);
1277
+ if (!this.fsw.options.followSymlinks) {
1278
+ this.fsw._incrReadyCount();
1279
+ let linkPath;
1280
+ try {
1281
+ linkPath = await realpath(path);
1282
+ } catch (e) {
1283
+ this.fsw._emitReady();
1284
+ return true;
1285
+ }
1286
+ if (this.fsw.closed) return;
1287
+ if (!isActive()) {
1288
+ this.fsw._emitReady();
1289
+ return true;
1290
+ }
1291
+ if (dir.has(item)) {
1292
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
1293
+ this.fsw._symlinkPaths.set(full, linkPath);
1294
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
1295
+ }
1296
+ } else {
1297
+ dir.add(item);
1298
+ this.fsw._symlinkPaths.set(full, linkPath);
1299
+ this.fsw._emit(EV.ADD, path, entry.stats);
1300
+ }
1301
+ this.fsw._emitReady();
1302
+ return true;
1303
+ }
1304
+ if (this.fsw._symlinkPaths.has(full)) return true;
1305
+ this.fsw._symlinkPaths.set(full, true);
1306
+ }
1307
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler, isActive = () => true, registerRead) {
1308
+ if (this.fsw.closed || !isActive()) return;
1309
+ directory = sp.join(directory, "");
1310
+ const throttleKey = target ? `${directory}:${target}` : directory;
1311
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
1312
+ if (!throttler) return;
1313
+ let stream;
1314
+ let finished = false;
1315
+ let unregisterRead = EMPTY_FN;
1316
+ let resolveRead;
1317
+ const completion = new Promise((resolve) => {
1318
+ resolveRead = resolve;
1319
+ });
1320
+ const finish = () => {
1321
+ if (finished) return false;
1322
+ finished = true;
1323
+ const currentThrottle = this.fsw._throttled.get("readdir")?.get(throttleKey);
1324
+ const wasThrottled = currentThrottle === throttler ? throttler.clear() : false;
1325
+ if (currentThrottle !== throttler) clearTimeout(throttler.timeoutObject);
1326
+ unregisterRead();
1327
+ unregisterRead = EMPTY_FN;
1328
+ stream = void 0;
1329
+ resolveRead(void 0);
1330
+ return wasThrottled;
1331
+ };
1332
+ const cancel = () => {
1333
+ const ownedStream = stream;
1334
+ finish();
1335
+ if (ownedStream && !ownedStream.destroyed) ownedStream.destroy();
1336
+ };
1337
+ if (registerRead) {
1338
+ unregisterRead = registerRead(cancel);
1339
+ if (finished) {
1340
+ unregisterRead();
1341
+ return completion;
1342
+ }
1343
+ }
1344
+ const previous = this.fsw._getWatchedDir(wh.path);
1345
+ const current = /* @__PURE__ */ new Set();
1346
+ let missingDirectory = false;
1347
+ try {
1348
+ stream = this.fsw._readdirp(directory, {
1349
+ fileFilter: (entry) => wh.filterPath(entry),
1350
+ directoryFilter: (entry) => wh.filterDir(entry)
1351
+ });
1352
+ } catch (error) {
1353
+ finish();
1354
+ throw error;
1355
+ }
1356
+ if (!stream) {
1357
+ finish();
1358
+ return completion;
1359
+ }
1360
+ stream.on(STR_DATA, async (entry) => {
1361
+ if (this.fsw.closed || !isActive()) return;
1362
+ const item = entry.path;
1363
+ let path = sp.join(directory, item);
1364
+ current.add(item);
1365
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item, isActive)) return;
1366
+ if (this.fsw.closed || !isActive()) return;
1367
+ if (item === target || !target && !previous.has(item)) {
1368
+ this.fsw._incrReadyCount();
1369
+ path = sp.join(dir, sp.relative(dir, path));
1370
+ this._addToNodeFs(path, initialAdd, wh, depth + 1, void 0, isActive);
1371
+ }
1372
+ }).on("warn", (error) => {
1373
+ if (error?.code === "ENOENT" && typeof error.path === "string" && sp.resolve(error.path) === sp.resolve(directory)) missingDirectory = true;
1374
+ }).on(EV.ERROR, this._boundHandleError).once(STR_CLOSE, finish).once("end", () => {
1375
+ const wasThrottled = finish();
1376
+ if (this.fsw.closed || !isActive()) return;
1377
+ if (missingDirectory) {
1378
+ this.fsw._remove(sp.dirname(directory), sp.basename(directory), true);
1379
+ return;
1380
+ }
1381
+ previous.getChildren().filter((item) => {
1382
+ return item !== directory && !current.has(item);
1383
+ }).forEach((item) => {
1384
+ if (!this.fsw.closed && isActive()) this.fsw._remove(directory, item);
1385
+ });
1386
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler, isActive, registerRead);
1387
+ });
1388
+ return completion;
1389
+ }
1390
+ /**
1391
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
1392
+ * @param dir fs path
1393
+ * @param stats
1394
+ * @param initialAdd
1395
+ * @param depth relative to user-supplied path
1396
+ * @param target child path targeted for watch
1397
+ * @param wh Common watch helpers for this path
1398
+ * @param realpath
1399
+ * @returns 用于后续异步提交的当前目录归属检查。
1400
+ */
1401
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath, registerCloser, isActive = () => true) {
1402
+ const parentPath = sp.resolve(sp.dirname(dir));
1403
+ const basename = sp.basename(dir);
1404
+ const tracked = this.fsw._watched.get(parentPath)?.has(basename);
1405
+ const removePath = sp.join(sp.dirname(dir), basename);
1406
+ const previousRemoveThrottle = !tracked ? this.fsw._throttled.get("remove")?.get(removePath) : void 0;
1407
+ const fullPath = sp.resolve(dir);
1408
+ let directoryEntry;
1409
+ let active = true;
1410
+ const reads = /* @__PURE__ */ new Set();
1411
+ const isCurrentDirectory = () => active && !this.fsw.closed && isActive() && directoryEntry !== void 0 && this.fsw._watched.get(fullPath) === directoryEntry;
1412
+ const registerRead = (cancel) => {
1413
+ if (!isCurrentDirectory()) {
1414
+ cancel();
1415
+ return EMPTY_FN;
1416
+ }
1417
+ reads.add(cancel);
1418
+ return () => {
1419
+ reads.delete(cancel);
1420
+ };
1421
+ };
1422
+ let throttler;
1423
+ const oDepth = this.fsw.options.depth;
1424
+ const shouldWatch = (oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath);
1425
+ if (shouldWatch) {
1426
+ const closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
1427
+ if (!isCurrentDirectory() || stats && stats.mtimeMs === 0) return;
1428
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler, isCurrentDirectory, registerRead);
1429
+ }, true);
1430
+ if (!closer) throw new Error("Directory watcher registration returned no closer");
1431
+ registerCloser(() => {
1432
+ if (!active) return;
1433
+ active = false;
1434
+ try {
1435
+ for (const cancel of [...reads]) cancel();
1436
+ } finally {
1437
+ reads.clear();
1438
+ closer();
1439
+ }
1440
+ });
1441
+ }
1442
+ this.fsw._getWatchedDir(parentPath).add(basename);
1443
+ directoryEntry = this.fsw._getWatchedDir(dir);
1444
+ if (shouldWatch && !tracked && isCurrentDirectory()) clearPreviousRemoveThrottle(this.fsw, removePath, previousRemoveThrottle);
1445
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
1446
+ if (shouldWatch && !target && isCurrentDirectory()) await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler, isCurrentDirectory, registerRead);
1447
+ return isCurrentDirectory;
1448
+ }
1449
+ /**
1450
+ * Handle added file, directory, or glob pattern.
1451
+ * Delegates call to _handleFile / _handleDir after checks.
1452
+ * @param path to file or ir
1453
+ * @param initialAdd was the file added at watch instantiation?
1454
+ * @param priorWh depth relative to user-supplied path
1455
+ * @param depth Child path actually targeted for watch
1456
+ * @param target Child path actually targeted for watch
1457
+ */
1458
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target, isActive = () => true) {
1459
+ const ready = this.fsw._emitReady;
1460
+ const completeMissing = () => {
1461
+ if (priorWh) {
1462
+ ready();
1463
+ return false;
1464
+ }
1465
+ return path;
1466
+ };
1467
+ if (this.fsw._isIgnored(path) || this.fsw.closed || !isActive()) {
1468
+ ready();
1469
+ return false;
1470
+ }
1471
+ const wh = this.fsw._getWatchHelpers(path);
1472
+ if (priorWh) {
1473
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
1474
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
1475
+ }
1476
+ let directoryWatchPath;
1477
+ const registerCloser = (closer) => this.fsw._addPathCloser(path, closer);
1478
+ try {
1479
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
1480
+ if (this.fsw.closed) return;
1481
+ if (!isActive() || this.fsw._isIgnored(wh.watchPath, stats)) {
1482
+ ready();
1483
+ return false;
1484
+ }
1485
+ const follow = this.fsw.options.followSymlinks;
1486
+ let closer;
1487
+ if (stats.isDirectory()) {
1488
+ const absPath = sp.resolve(path);
1489
+ const targetPath = follow ? await realpath(path) : path;
1490
+ if (this.fsw.closed) return;
1491
+ if (!isActive()) {
1492
+ ready();
1493
+ return false;
1494
+ }
1495
+ directoryWatchPath = wh.watchPath;
1496
+ const isCurrentDirectory = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath, registerCloser, isActive);
1497
+ if (this.fsw.closed) return;
1498
+ if (!isCurrentDirectory()) {
1499
+ ready();
1500
+ return false;
1501
+ }
1502
+ if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
1503
+ } else if (stats.isSymbolicLink()) {
1504
+ const targetPath = follow ? await realpath(path) : path;
1505
+ if (this.fsw.closed) return;
1506
+ if (!isActive()) {
1507
+ ready();
1508
+ return false;
1509
+ }
1510
+ const parent = sp.dirname(wh.watchPath);
1511
+ directoryWatchPath = parent;
1512
+ const isCurrentDirectory = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath, registerCloser, isActive);
1513
+ if (this.fsw.closed) return;
1514
+ if (!isCurrentDirectory()) {
1515
+ ready();
1516
+ return false;
1517
+ }
1518
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
1519
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
1520
+ if (targetPath !== void 0) this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);
1521
+ } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
1522
+ ready();
1523
+ if (closer) this.fsw._addPathCloser(path, closer);
1524
+ return false;
1525
+ } catch (error) {
1526
+ if (this.fsw.closed) return;
1527
+ if (!isActive()) {
1528
+ ready();
1529
+ return false;
1530
+ }
1531
+ if (isWindows && !this.fsw.options.usePolling && directoryWatchPath !== void 0 && error?.code === "EPERM" && error.syscall === "watch" && typeof error.path === "string" && sp.resolve(error.path) === sp.resolve(directoryWatchPath)) {
1532
+ let missing = false;
1533
+ try {
1534
+ await lstat(directoryWatchPath);
1535
+ } catch (probeError) {
1536
+ missing = probeError?.code === "ENOENT" || probeError?.code === "ENOTDIR";
1537
+ }
1538
+ if (this.fsw.closed) return;
1539
+ if (!isActive()) {
1540
+ ready();
1541
+ return false;
1542
+ }
1543
+ if (missing) return completeMissing();
1544
+ }
1545
+ if (this.fsw._handleError(error)) return completeMissing();
1546
+ }
1547
+ }
1548
+ };
1549
+ //#endregion
1550
+ //#region ../../node_modules/.pnpm/chokidar@5.0.0_patch_hash=fafb20ce736d8edb3357d9d04cebccbd6e05ecc1bc10aa26a7484d2369016811/node_modules/chokidar/index.js
1551
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
1552
+ const SLASH = "/";
1553
+ const SLASH_SLASH = "//";
1554
+ const ONE_DOT = ".";
1555
+ const TWO_DOTS = "..";
1556
+ const STRING_TYPE = "string";
1557
+ const BACK_SLASH_RE = /\\/g;
1558
+ const DOUBLE_SLASH_RE = /\/\//g;
1559
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1560
+ const REPLACER_RE = /^\.[/\\]/;
1561
+ function arrify(item) {
1562
+ return Array.isArray(item) ? item : [item];
1563
+ }
1564
+ const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1565
+ function createPattern(matcher) {
1566
+ if (typeof matcher === "function") return matcher;
1567
+ if (typeof matcher === "string") return (string) => matcher === string;
1568
+ if (matcher instanceof RegExp) return (string) => matcher.test(string);
1569
+ if (typeof matcher === "object" && matcher !== null) return (string) => {
1570
+ if (matcher.path === string) return true;
1571
+ if (matcher.recursive) {
1572
+ const relative = sp.relative(matcher.path, string);
1573
+ if (!relative) return false;
1574
+ return !relative.startsWith("..") && !sp.isAbsolute(relative);
1575
+ }
1576
+ return false;
1577
+ };
1578
+ return () => false;
1579
+ }
1580
+ function normalizePath(path) {
1581
+ if (typeof path !== "string") throw new Error("string expected");
1582
+ path = sp.normalize(path);
1583
+ path = path.replace(/\\/g, "/");
1584
+ let prepend = false;
1585
+ if (path.startsWith("//")) prepend = true;
1586
+ path = path.replace(DOUBLE_SLASH_RE, "/");
1587
+ if (prepend) path = "/" + path;
1588
+ return path;
1589
+ }
1590
+ function matchPatterns(patterns, testString, stats) {
1591
+ const path = normalizePath(testString);
1592
+ for (let index = 0; index < patterns.length; index++) {
1593
+ const pattern = patterns[index];
1594
+ if (pattern(path, stats)) return true;
1595
+ }
1596
+ return false;
1597
+ }
1598
+ function anymatch(matchers, testString) {
1599
+ if (matchers == null) throw new TypeError("anymatch: specify first argument");
1600
+ const patterns = arrify(matchers).map((matcher) => createPattern(matcher));
1601
+ if (testString == null) return (testString, stats) => {
1602
+ return matchPatterns(patterns, testString, stats);
1603
+ };
1604
+ return matchPatterns(patterns, testString);
1605
+ }
1606
+ const unifyPaths = (paths_) => {
1607
+ const paths = arrify(paths_).flat();
1608
+ if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
1609
+ return paths.map(normalizePathToUnix);
1610
+ };
1611
+ const toUnix = (string) => {
1612
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1613
+ let prepend = false;
1614
+ if (str.startsWith(SLASH_SLASH)) prepend = true;
1615
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
1616
+ if (prepend) str = SLASH + str;
1617
+ return str;
1618
+ };
1619
+ const normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));
1620
+ const normalizeIgnored = (cwd = "") => (path) => {
1621
+ if (typeof path === "string") return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));
1622
+ else return path;
1623
+ };
1624
+ const getAbsolutePath = (path, cwd) => {
1625
+ if (sp.isAbsolute(path)) return path;
1626
+ return sp.join(cwd, path);
1627
+ };
1628
+ const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1629
+ /**
1630
+ * Directory entry.
1631
+ */
1632
+ var DirEntry = class {
1633
+ path;
1634
+ _removeWatcher;
1635
+ items;
1636
+ constructor(dir, removeWatcher) {
1637
+ this.path = dir;
1638
+ this._removeWatcher = removeWatcher;
1639
+ this.items = /* @__PURE__ */ new Set();
1640
+ }
1641
+ add(item) {
1642
+ const { items } = this;
1643
+ if (!items) return;
1644
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
1645
+ }
1646
+ async remove(item) {
1647
+ const { items } = this;
1648
+ if (!items) return;
1649
+ items.delete(item);
1650
+ if (items.size > 0) return;
1651
+ const dir = this.path;
1652
+ try {
1653
+ await readdir(dir);
1654
+ } catch (err) {
1655
+ if (this._removeWatcher) this._removeWatcher(sp.dirname(dir), sp.basename(dir));
1656
+ }
1657
+ }
1658
+ has(item) {
1659
+ const { items } = this;
1660
+ if (!items) return;
1661
+ return items.has(item);
1662
+ }
1663
+ getChildren() {
1664
+ const { items } = this;
1665
+ if (!items) return [];
1666
+ return [...items.values()];
1667
+ }
1668
+ dispose() {
1669
+ this.items.clear();
1670
+ this.path = "";
1671
+ this._removeWatcher = EMPTY_FN;
1672
+ this.items = EMPTY_SET;
1673
+ Object.freeze(this);
1674
+ }
1675
+ };
1676
+ const STAT_METHOD_F = "stat";
1677
+ const STAT_METHOD_L = "lstat";
1678
+ var WatchHelper = class {
1679
+ fsw;
1680
+ path;
1681
+ watchPath;
1682
+ fullWatchPath;
1683
+ dirParts;
1684
+ followSymlinks;
1685
+ statMethod;
1686
+ constructor(path, follow, fsw) {
1687
+ this.fsw = fsw;
1688
+ const watchPath = path;
1689
+ this.path = path = path.replace(REPLACER_RE, "");
1690
+ this.watchPath = watchPath;
1691
+ this.fullWatchPath = sp.resolve(watchPath);
1692
+ this.dirParts = [];
1693
+ this.dirParts.forEach((parts) => {
1694
+ if (parts.length > 1) parts.pop();
1695
+ });
1696
+ this.followSymlinks = follow;
1697
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1698
+ }
1699
+ entryPath(entry) {
1700
+ return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));
1701
+ }
1702
+ filterPath(entry) {
1703
+ const { stats } = entry;
1704
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1705
+ const resolvedPath = this.entryPath(entry);
1706
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1707
+ }
1708
+ filterDir(entry) {
1709
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1710
+ }
1711
+ };
1712
+ /**
1713
+ * Watches files & directories for changes. Emitted events:
1714
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1715
+ *
1716
+ * new FSWatcher()
1717
+ * .add(directories)
1718
+ * .on('add', path => log('File', path, 'was added'))
1719
+ */
1720
+ var FSWatcher = class extends EventEmitter {
1721
+ closed;
1722
+ options;
1723
+ _closers;
1724
+ _ignoredPaths;
1725
+ _throttled;
1726
+ _streams;
1727
+ _symlinkPaths;
1728
+ _watched;
1729
+ _pendingWrites;
1730
+ _pendingUnlinks;
1731
+ _readyCount;
1732
+ _emitReady;
1733
+ _closePromise;
1734
+ _userIgnored;
1735
+ _readyEmitted;
1736
+ _emitRaw;
1737
+ _boundRemove;
1738
+ _nodeFsHandler;
1739
+ constructor(_opts = {}) {
1740
+ super();
1741
+ this.closed = false;
1742
+ this._closers = /* @__PURE__ */ new Map();
1743
+ this._ignoredPaths = /* @__PURE__ */ new Set();
1744
+ this._throttled = /* @__PURE__ */ new Map();
1745
+ this._streams = /* @__PURE__ */ new Set();
1746
+ this._symlinkPaths = /* @__PURE__ */ new Map();
1747
+ this._watched = /* @__PURE__ */ new Map();
1748
+ this._pendingWrites = /* @__PURE__ */ new Map();
1749
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
1750
+ this._readyCount = 0;
1751
+ this._readyEmitted = false;
1752
+ const awf = _opts.awaitWriteFinish;
1753
+ const DEF_AWF = {
1754
+ stabilityThreshold: 2e3,
1755
+ pollInterval: 100
1756
+ };
1757
+ const opts = {
1758
+ persistent: true,
1759
+ ignoreInitial: false,
1760
+ ignorePermissionErrors: false,
1761
+ interval: 100,
1762
+ binaryInterval: 300,
1763
+ followSymlinks: true,
1764
+ usePolling: false,
1765
+ atomic: true,
1766
+ ..._opts,
1767
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1768
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? {
1769
+ ...DEF_AWF,
1770
+ ...awf
1771
+ } : false
1772
+ };
1773
+ if (isIBMi) opts.usePolling = true;
1774
+ if (opts.atomic === void 0) opts.atomic = !opts.usePolling;
1775
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1776
+ if (envPoll !== void 0) {
1777
+ const envLower = envPoll.toLowerCase();
1778
+ if (envLower === "false" || envLower === "0") opts.usePolling = false;
1779
+ else if (envLower === "true" || envLower === "1") opts.usePolling = true;
1780
+ else opts.usePolling = !!envLower;
1781
+ }
1782
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1783
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1784
+ let readyCalls = 0;
1785
+ this._emitReady = () => {
1786
+ readyCalls++;
1787
+ if (readyCalls >= this._readyCount) {
1788
+ this._emitReady = EMPTY_FN;
1789
+ this._readyEmitted = true;
1790
+ process.nextTick(() => this.emit(EVENTS.READY));
1791
+ }
1792
+ };
1793
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1794
+ this._boundRemove = this._remove.bind(this);
1795
+ this.options = opts;
1796
+ this._nodeFsHandler = new NodeFsHandler(this);
1797
+ Object.freeze(opts);
1798
+ }
1799
+ _addIgnoredPath(matcher) {
1800
+ if (isMatcherObject(matcher)) {
1801
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
1802
+ }
1803
+ this._ignoredPaths.add(matcher);
1804
+ }
1805
+ _removeIgnoredPath(matcher) {
1806
+ this._ignoredPaths.delete(matcher);
1807
+ if (typeof matcher === "string") {
1808
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
1809
+ }
1810
+ }
1811
+ /**
1812
+ * Adds paths to be watched on an existing FSWatcher instance.
1813
+ * @param paths_ file or file list. Other arguments are unused
1814
+ */
1815
+ add(paths_, _origAdd, _internal) {
1816
+ const { cwd } = this.options;
1817
+ this.closed = false;
1818
+ this._closePromise = void 0;
1819
+ let paths = unifyPaths(paths_);
1820
+ if (cwd) paths = paths.map((path) => {
1821
+ return getAbsolutePath(path, cwd);
1822
+ });
1823
+ paths.forEach((path) => {
1824
+ this._removeIgnoredPath(path);
1825
+ });
1826
+ this._userIgnored = void 0;
1827
+ if (!this._readyCount) this._readyCount = 0;
1828
+ this._readyCount += paths.length;
1829
+ Promise.all(paths.map(async (path) => {
1830
+ return this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1831
+ })).then((results) => {
1832
+ if (this.closed) return;
1833
+ results.forEach((item) => {
1834
+ if (item) {
1835
+ this.add(sp.dirname(item), sp.basename(_origAdd || item));
1836
+ this._emitReady();
1837
+ }
1838
+ });
1839
+ });
1840
+ return this;
1841
+ }
1842
+ /**
1843
+ * Close watchers or start ignoring events from specified paths.
1844
+ */
1845
+ unwatch(paths_) {
1846
+ if (this.closed) return this;
1847
+ const paths = unifyPaths(paths_);
1848
+ const { cwd } = this.options;
1849
+ paths.forEach((path) => {
1850
+ if (!sp.isAbsolute(path) && !this._closers.has(path)) {
1851
+ if (cwd) path = sp.join(cwd, path);
1852
+ path = sp.resolve(path);
1853
+ }
1854
+ this._closePath(path);
1855
+ this._addIgnoredPath(path);
1856
+ if (this._watched.has(path)) this._addIgnoredPath({
1857
+ path,
1858
+ recursive: true
1859
+ });
1860
+ this._userIgnored = void 0;
1861
+ });
1862
+ return this;
1863
+ }
1864
+ /**
1865
+ * Close watchers and remove all listeners from watched paths.
1866
+ */
1867
+ close() {
1868
+ if (this._closePromise) return this._closePromise;
1869
+ this.closed = true;
1870
+ this.removeAllListeners();
1871
+ const closers = [];
1872
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
1873
+ const promise = closer();
1874
+ if (promise instanceof Promise) closers.push(promise);
1875
+ }));
1876
+ this._streams.forEach((stream) => stream.destroy());
1877
+ this._userIgnored = void 0;
1878
+ this._readyCount = 0;
1879
+ this._readyEmitted = false;
1880
+ this._watched.forEach((dirent) => dirent.dispose());
1881
+ this._closers.clear();
1882
+ this._watched.clear();
1883
+ this._streams.clear();
1884
+ this._symlinkPaths.clear();
1885
+ this._throttled.clear();
1886
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1887
+ return this._closePromise;
1888
+ }
1889
+ /**
1890
+ * Expose list of watched paths
1891
+ * @returns for chaining
1892
+ */
1893
+ getWatched() {
1894
+ const watchList = {};
1895
+ this._watched.forEach((entry, dir) => {
1896
+ const index = (this.options.cwd ? sp.relative(this.options.cwd, dir) : dir) || ONE_DOT;
1897
+ watchList[index] = entry.getChildren().sort();
1898
+ });
1899
+ return watchList;
1900
+ }
1901
+ emitWithAll(event, args) {
1902
+ this.emit(event, ...args);
1903
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1904
+ }
1905
+ /**
1906
+ * Normalize and emit events.
1907
+ * Calling _emit DOES NOT MEAN emit() would be called!
1908
+ * @param event Type of event
1909
+ * @param path File or directory path
1910
+ * @param stats arguments to be passed with event
1911
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1912
+ */
1913
+ async _emit(event, path, stats) {
1914
+ if (this.closed) return;
1915
+ const opts = this.options;
1916
+ if (isWindows) path = sp.normalize(path);
1917
+ if (opts.cwd) path = sp.relative(opts.cwd, path);
1918
+ const args = [path];
1919
+ if (stats != null) args.push(stats);
1920
+ const awf = opts.awaitWriteFinish;
1921
+ let pw;
1922
+ if (awf && (pw = this._pendingWrites.get(path))) {
1923
+ pw.lastChange = /* @__PURE__ */ new Date();
1924
+ return this;
1925
+ }
1926
+ if (opts.atomic) {
1927
+ if (event === EVENTS.UNLINK) {
1928
+ this._pendingUnlinks.set(path, [event, ...args]);
1929
+ setTimeout(() => {
1930
+ this._pendingUnlinks.forEach((entry, path) => {
1931
+ this.emit(...entry);
1932
+ this.emit(EVENTS.ALL, ...entry);
1933
+ this._pendingUnlinks.delete(path);
1934
+ });
1935
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
1936
+ return this;
1937
+ }
1938
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1939
+ event = EVENTS.CHANGE;
1940
+ this._pendingUnlinks.delete(path);
1941
+ }
1942
+ }
1943
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1944
+ const awfEmit = (err, stats) => {
1945
+ if (err) {
1946
+ event = EVENTS.ERROR;
1947
+ args[0] = err;
1948
+ this.emitWithAll(event, args);
1949
+ } else if (stats) {
1950
+ if (args.length > 1) args[1] = stats;
1951
+ else args.push(stats);
1952
+ this.emitWithAll(event, args);
1953
+ }
1954
+ };
1955
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1956
+ return this;
1957
+ }
1958
+ if (event === EVENTS.CHANGE) {
1959
+ if (!this._throttle(EVENTS.CHANGE, path, 50)) return this;
1960
+ }
1961
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1962
+ const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;
1963
+ let stats;
1964
+ try {
1965
+ stats = await stat$1(fullPath);
1966
+ } catch (err) {}
1967
+ if (!stats || this.closed) return;
1968
+ args.push(stats);
1969
+ }
1970
+ this.emitWithAll(event, args);
1971
+ return this;
1972
+ }
1973
+ /**
1974
+ * Common handler for errors
1975
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1976
+ */
1977
+ _handleError(error) {
1978
+ const code = error && error.code;
1979
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error);
1980
+ return error || this.closed;
1981
+ }
1982
+ /**
1983
+ * Helper utility for throttling
1984
+ * @param actionType type being throttled
1985
+ * @param path being acted upon
1986
+ * @param timeout duration of time to suppress duplicate actions
1987
+ * @returns tracking object or false if action should be suppressed
1988
+ */
1989
+ _throttle(actionType, path, timeout) {
1990
+ if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
1991
+ const action = this._throttled.get(actionType);
1992
+ if (!action) throw new Error("invalid throttle");
1993
+ const actionPath = action.get(path);
1994
+ if (actionPath) {
1995
+ actionPath.count++;
1996
+ return false;
1997
+ }
1998
+ let timeoutObject;
1999
+ const clear = () => {
2000
+ const item = action.get(path);
2001
+ const count = item ? item.count : 0;
2002
+ action.delete(path);
2003
+ clearTimeout(timeoutObject);
2004
+ if (item) clearTimeout(item.timeoutObject);
2005
+ return count;
2006
+ };
2007
+ timeoutObject = setTimeout(clear, timeout);
2008
+ const thr = {
2009
+ timeoutObject,
2010
+ clear,
2011
+ count: 0
2012
+ };
2013
+ action.set(path, thr);
2014
+ return thr;
2015
+ }
2016
+ _incrReadyCount() {
2017
+ return this._readyCount++;
2018
+ }
2019
+ /**
2020
+ * Awaits write operation to finish.
2021
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
2022
+ * @param path being acted upon
2023
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
2024
+ * @param event
2025
+ * @param awfEmit Callback to be called when ready for event to be emitted.
2026
+ */
2027
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
2028
+ const awf = this.options.awaitWriteFinish;
2029
+ if (typeof awf !== "object") return;
2030
+ const pollInterval = awf.pollInterval;
2031
+ let timeoutHandler;
2032
+ let fullPath = path;
2033
+ if (this.options.cwd && !sp.isAbsolute(path)) fullPath = sp.join(this.options.cwd, path);
2034
+ const now = /* @__PURE__ */ new Date();
2035
+ const writes = this._pendingWrites;
2036
+ function awaitWriteFinishFn(prevStat) {
2037
+ stat(fullPath, (err, curStat) => {
2038
+ if (err || !writes.has(path)) {
2039
+ if (err && err.code !== "ENOENT") awfEmit(err);
2040
+ return;
2041
+ }
2042
+ const now = Number(/* @__PURE__ */ new Date());
2043
+ if (prevStat && curStat.size !== prevStat.size) writes.get(path).lastChange = now;
2044
+ if (now - writes.get(path).lastChange >= threshold) {
2045
+ writes.delete(path);
2046
+ awfEmit(void 0, curStat);
2047
+ } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
2048
+ });
2049
+ }
2050
+ if (!writes.has(path)) {
2051
+ writes.set(path, {
2052
+ lastChange: now,
2053
+ cancelWait: () => {
2054
+ writes.delete(path);
2055
+ clearTimeout(timeoutHandler);
2056
+ return event;
2057
+ }
2058
+ });
2059
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
2060
+ }
2061
+ }
2062
+ /**
2063
+ * Determines whether user has asked to ignore this path.
2064
+ */
2065
+ _isIgnored(path, stats) {
2066
+ if (this.options.atomic && DOT_RE.test(path)) return true;
2067
+ if (!this._userIgnored) {
2068
+ const { cwd } = this.options;
2069
+ const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd));
2070
+ const list = [...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored];
2071
+ this._userIgnored = anymatch(list, void 0);
2072
+ }
2073
+ return this._userIgnored(path, stats);
2074
+ }
2075
+ _isntIgnored(path, stat) {
2076
+ return !this._isIgnored(path, stat);
2077
+ }
2078
+ /**
2079
+ * Provides a set of common helpers and properties relating to symlink handling.
2080
+ * @param path file or directory pattern being watched
2081
+ */
2082
+ _getWatchHelpers(path) {
2083
+ return new WatchHelper(path, this.options.followSymlinks, this);
2084
+ }
2085
+ /**
2086
+ * Provides directory tracking objects
2087
+ * @param directory path of the directory
2088
+ */
2089
+ _getWatchedDir(directory) {
2090
+ const dir = sp.resolve(directory);
2091
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
2092
+ return this._watched.get(dir);
2093
+ }
2094
+ /**
2095
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
2096
+ */
2097
+ _hasReadPermissions(stats) {
2098
+ if (this.options.ignorePermissionErrors) return true;
2099
+ return Boolean(Number(stats.mode) & 256);
2100
+ }
2101
+ /**
2102
+ * Handles emitting unlink events for
2103
+ * files and directories, and via recursion, for
2104
+ * files and directories within directories that are unlinked
2105
+ * @param directory within which the following item is located
2106
+ * @param item base path of item/directory
2107
+ */
2108
+ _remove(directory, item, isDirectory) {
2109
+ const path = sp.join(directory, item);
2110
+ const fullPath = sp.resolve(path);
2111
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
2112
+ if (!this._throttle("remove", path, 100)) return;
2113
+ if (!isDirectory && this._watched.size === 1) this.add(directory, item, true);
2114
+ this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
2115
+ const parent = this._getWatchedDir(directory);
2116
+ const wasTracked = parent.has(item);
2117
+ parent.remove(item);
2118
+ if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
2119
+ let relPath = path;
2120
+ if (this.options.cwd) relPath = sp.relative(this.options.cwd, path);
2121
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
2122
+ if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return;
2123
+ }
2124
+ this._watched.delete(path);
2125
+ this._watched.delete(fullPath);
2126
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
2127
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
2128
+ this._closePath(path);
2129
+ }
2130
+ /**
2131
+ * Closes all watchers for a path
2132
+ */
2133
+ _closePath(path) {
2134
+ this._closeFile(path);
2135
+ const dir = sp.dirname(path);
2136
+ this._getWatchedDir(dir).remove(sp.basename(path));
2137
+ }
2138
+ /**
2139
+ * Closes only file-specific watchers
2140
+ */
2141
+ _closeFile(path) {
2142
+ const closers = this._closers.get(path);
2143
+ if (!closers) return;
2144
+ closers.forEach((closer) => closer());
2145
+ this._closers.delete(path);
2146
+ }
2147
+ _addPathCloser(path, closer) {
2148
+ if (!closer) return;
2149
+ let list = this._closers.get(path);
2150
+ if (!list) {
2151
+ list = [];
2152
+ this._closers.set(path, list);
2153
+ }
2154
+ list.push(closer);
2155
+ }
2156
+ _readdirp(root, opts) {
2157
+ if (this.closed) return;
2158
+ let stream = readdirp(root, {
2159
+ type: EVENTS.ALL,
2160
+ alwaysStat: true,
2161
+ lstat: true,
2162
+ ...opts,
2163
+ depth: 0
2164
+ });
2165
+ this._streams.add(stream);
2166
+ stream.once(STR_CLOSE, () => {
2167
+ if (stream) this._streams.delete(stream);
2168
+ stream = void 0;
2169
+ });
2170
+ stream.once("end", () => {
2171
+ if (stream) {
2172
+ this._streams.delete(stream);
2173
+ stream = void 0;
2174
+ }
2175
+ });
2176
+ return stream;
2177
+ }
2178
+ };
2179
+ /**
2180
+ * Instantiates watcher with paths to be tracked.
2181
+ * @param paths file / directory paths
2182
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
2183
+ * @returns an instance of FSWatcher for chaining.
2184
+ * @example
2185
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
2186
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
2187
+ */
2188
+ function watch$1(paths, options = {}) {
2189
+ const watcher = new FSWatcher(options);
2190
+ watcher.add(paths);
2191
+ return watcher;
2192
+ }
2193
+ var chokidar_default = {
2194
+ watch: watch$1,
2195
+ FSWatcher
2196
+ };
2197
+ //#endregion
2198
+ //#region src/plugins/autoRoutes.shared.ts
2199
+ const AUTO_ROUTES_ID = "weapp-vite/auto-routes";
2200
+ const VIRTUAL_MODULE_ID = "virtual:weapp-vite-auto-routes";
2201
+ const RESOLVED_VIRTUAL_ID = "\0weapp-vite:auto-routes";
2202
+ /**
2203
+ * 判断当前是否应按 watch 模式为 auto-routes 注册依赖文件。
2204
+ */
2205
+ function isAutoRoutesWatchMode(configService) {
2206
+ return Boolean(configService?.isDev || configService?.inlineConfig?.build?.watch);
2207
+ }
2208
+ /**
2209
+ * 合并 service 与 matcher 提供的监听目录,并去重保留顺序。
2210
+ */
2211
+ function collectAutoRoutesWatchDirs(watchDirectories, matcherWatchRoots) {
2212
+ const watchDirs = /* @__PURE__ */ new Set();
2213
+ for (const dir of watchDirectories) watchDirs.add(dir);
2214
+ for (const dir of matcherWatchRoots) watchDirs.add(dir);
2215
+ return [...watchDirs];
2216
+ }
2217
+ /**
2218
+ * 过滤出真正需要交给 auto-routes watcher 处理的路由源文件。
2219
+ * 已知声明依赖不受普通页面发现扩展名限制,其他文件仍沿用发现规则。
2220
+ */
2221
+ function isAutoRoutesWatchFile(filePath, allowedExtensions, isPagesRelatedPath, isPageDeclarationSource) {
2222
+ if (isAutoRoutesGeneratedFileName(path.basename(filePath))) return false;
2223
+ if (isPageDeclarationSource(filePath)) return true;
2224
+ return allowedExtensions.has(path.extname(filePath)) && isPagesRelatedPath(filePath);
2225
+ }
2226
+ /**
2227
+ * 判断是否满足 auto-routes sidecar watcher 的启动前置条件。
2228
+ */
2229
+ function shouldStartAutoRoutesWatcher(options) {
2230
+ if (options.routeWatcherStarted) return false;
2231
+ if (!options.isDev) return false;
2232
+ if (!options.autoRoutesEnabled || !options.autoRoutesWatch || !options.serviceEnabled) return false;
2233
+ return options.watchDirsLength > 0;
2234
+ }
2235
+ /**
2236
+ * 初扫完成前阻止路由构建发布;关闭时主动释放等待,不依赖物理 watcher 的 close 事件。
2237
+ */
2238
+ function createAutoRoutesSidecarWatcher(watcher) {
2239
+ let settleReady;
2240
+ const ready = new Promise((resolve, reject) => {
2241
+ const listeners = {
2242
+ cleanup() {
2243
+ watcher.off("ready", listeners.ready);
2244
+ watcher.off("error", listeners.error);
2245
+ },
2246
+ ready() {
2247
+ listeners.cleanup();
2248
+ resolve();
2249
+ },
2250
+ error(error) {
2251
+ listeners.cleanup();
2252
+ reject(error);
2253
+ }
2254
+ };
2255
+ settleReady = listeners.ready;
2256
+ watcher.once("ready", listeners.ready);
2257
+ watcher.once("error", listeners.error);
2258
+ });
2259
+ let closing;
2260
+ return {
2261
+ ready,
2262
+ close() {
2263
+ closing ??= (async () => {
2264
+ settleReady();
2265
+ await watcher.close();
2266
+ })();
2267
+ return closing;
2268
+ }
2269
+ };
2270
+ }
2271
+ /**
2272
+ * 向插件上下文注册 auto-routes 相关 watch 目标,忽略单个 addWatchFile 失败。
2273
+ */
2274
+ function addAutoRoutesWatchTargets(pluginCtx, targets) {
2275
+ for (const file of targets.files) try {
2276
+ pluginCtx.addWatchFile?.(normalizeWatchPath(file));
2277
+ } catch {}
2278
+ for (const dir of targets.directories) try {
2279
+ pluginCtx.addWatchFile?.(normalizeWatchPath(dir));
2280
+ } catch {}
2281
+ }
2282
+ function invalidateAutoRoutesVirtualModules(server, resolvedIds) {
2283
+ if (!server) return;
2284
+ const seen = /* @__PURE__ */ new Set();
2285
+ const invalidateModuleWithImporters = (module) => {
2286
+ if (seen.has(module)) return;
2287
+ seen.add(module);
2288
+ server.moduleGraph.invalidateModule(module);
2289
+ for (const importer of module.importers) invalidateModuleWithImporters(importer);
2290
+ };
2291
+ for (const id of resolvedIds) {
2292
+ const virtualModule = server.moduleGraph.getModuleById(id);
2293
+ if (virtualModule) invalidateModuleWithImporters(virtualModule);
2294
+ }
2295
+ }
2296
+ /**
2297
+ * 统一解析 auto-routes 虚拟模块与 alias 入口的命中关系。
2298
+ */
2299
+ function resolveAutoRoutesVirtualId(id, aliasTargets) {
2300
+ if (id === WEVU_AUTO_ROUTES_MODULE_ID$1 || id === WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1 || id === WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1) return WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1;
2301
+ if (id === "weapp-vite/auto-routes" || id === "virtual:weapp-vite-auto-routes" || id === "\0weapp-vite:auto-routes") return RESOLVED_VIRTUAL_ID;
2302
+ return aliasTargets?.has(id) ? RESOLVED_VIRTUAL_ID : null;
2303
+ }
2304
+ /**
2305
+ * 将 create/delete 这类结构性变化映射为 auto-routes 的全量重扫语义。
2306
+ */
2307
+ function resolveAutoRoutesWatchChangeEvent(event) {
2308
+ if (event === "create" || event === "delete") return "rename";
2309
+ }
2310
+ /**
2311
+ * 判断某次热更新是否需要触发 auto-routes 虚拟模块失效。
2312
+ */
2313
+ function resolveAutoRoutesHotUpdateAction(command, options) {
2314
+ if (command === "serve") return options.isRouteFile ? {
2315
+ shouldHandle: true,
2316
+ shouldUpdateRouteFile: true
2317
+ } : {
2318
+ shouldHandle: false,
2319
+ shouldUpdateRouteFile: false
2320
+ };
2321
+ if (options.isRouteFile || options.isPagesRelatedPath) return {
2322
+ shouldHandle: true,
2323
+ shouldUpdateRouteFile: false
2324
+ };
2325
+ return {
2326
+ shouldHandle: false,
2327
+ shouldUpdateRouteFile: false
2328
+ };
2329
+ }
2330
+ /**
2331
+ * Web 路由表在创建 router 时完成快照,必须越过 SFC 自接受边界重新加载入口。
2332
+ * 入口排在前面,避免依赖失效先将生成的入口降为仅更新时间戳的软失效。
2333
+ */
2334
+ function collectAutoRoutesReloadModules(modules) {
2335
+ const pending = [...modules];
2336
+ const visited = new Set(pending);
2337
+ const reloadModules = /* @__PURE__ */ new Set();
2338
+ for (const module of pending) {
2339
+ if (module.importers.size === 0) reloadModules.add(module);
2340
+ for (const importer of module.importers) if (!visited.has(importer)) {
2341
+ visited.add(importer);
2342
+ pending.push(importer);
2343
+ }
2344
+ }
2345
+ for (const module of modules) reloadModules.add(module);
2346
+ return [...reloadModules];
2347
+ }
2348
+ //#endregion
2349
+ //#region src/runtime/npmPlugin/packageResolution.ts
2350
+ /** 保留目录尾斜线,确保当前工程优先,并避免缺失包的目录回退把真实文件当作目录。 */
2351
+ function packageSearchOptions(resolveFrom) {
2352
+ return resolveFrom ? { paths: [`${path.resolve(resolveFrom).replace(/\/$/, "")}/`] } : void 0;
2353
+ }
2354
+ //#endregion
2355
+ //#region src/runtime/npmPlugin/service/dependencies.ts
2356
+ const DEFAULT_NPM_STRATEGY = "explicit";
2357
+ function dedupeDependencies(dependencies) {
2358
+ return [...new Set(dependencies)];
2359
+ }
2360
+ function matchDependencyName(patterns, dep) {
2361
+ return patterns.some((pattern) => {
2362
+ if (typeof pattern === "string") return pattern === dep;
2363
+ pattern.lastIndex = 0;
2364
+ return pattern.test(dep);
2365
+ });
2366
+ }
2367
+ function createDependencyRecord(dependencies) {
2368
+ if (dependencies.length === 0) return;
2369
+ return Object.fromEntries(dependencies.map((dep) => [dep, "*"]));
2370
+ }
2371
+ function resolveNpmStrategy(ctx) {
2372
+ return ctx.configService?.weappViteConfig?.npm?.strategy ?? DEFAULT_NPM_STRATEGY;
2373
+ }
2374
+ function resolveConfiguredDependencyPatterns(ctx) {
2375
+ const npmConfig = ctx.configService?.weappViteConfig?.npm;
2376
+ const patterns = [...npmConfig?.include ?? []];
2377
+ if (ctx.configService?.pluginOnly) {
2378
+ if (Array.isArray(npmConfig?.pluginPackage?.dependencies)) patterns.push(...npmConfig.pluginPackage.dependencies);
2379
+ return patterns;
2380
+ }
2381
+ if (Array.isArray(npmConfig?.mainPackage?.dependencies)) patterns.push(...npmConfig.mainPackage.dependencies);
2382
+ for (const config of Object.values(npmConfig?.subPackages ?? {})) if (Array.isArray(config?.dependencies)) patterns.push(...config.dependencies);
2383
+ return patterns;
2384
+ }
2385
+ function resolveDeclaredDependencies(pkgJson) {
2386
+ return dedupeDependencies([...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})]);
2387
+ }
2388
+ function isMiniprogramPackage(pkg) {
2389
+ return Reflect.has(pkg, "miniprogram") && typeof pkg.miniprogram === "string";
2390
+ }
2391
+ function resolveMiniprogramCandidateDependenciesSync(allDependencies, cwd) {
2392
+ return allDependencies.filter((dep) => {
2393
+ let packageInfo = null;
2394
+ try {
2395
+ packageInfo = getPackageInfoSync(dep, packageSearchOptions(cwd));
2396
+ } catch {
2397
+ packageInfo = null;
2398
+ }
2399
+ return !!packageInfo && isMiniprogramPackage(packageInfo.packageJson);
2400
+ });
2401
+ }
2402
+ function resolveMainPackageDependencyPatterns(ctx) {
2403
+ return ctx.configService?.weappViteConfig?.npm?.mainPackage?.dependencies;
2404
+ }
2405
+ function resolvePluginPackageDependencyPatterns(ctx) {
2406
+ return ctx.configService?.weappViteConfig?.npm?.pluginPackage?.dependencies;
2407
+ }
2408
+ function resolveTargetDependencies(allDependencies, patterns) {
2409
+ if (patterns === false) return [];
2410
+ if (!Array.isArray(patterns)) return allDependencies;
2411
+ const selected = /* @__PURE__ */ new Set();
2412
+ for (const dep of allDependencies) if (matchDependencyName(patterns, dep)) selected.add(dep);
2413
+ for (const pattern of patterns) if (typeof pattern === "string") selected.add(pattern);
2414
+ return [...selected];
2415
+ }
2416
+ function resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson, resolveFrom = ctx.configService?.cwd) {
2417
+ if (resolveNpmStrategy(ctx) === "legacy") return Object.keys(pkgJson.dependencies ?? {});
2418
+ const declaredDependencies = resolveDeclaredDependencies(pkgJson);
2419
+ const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredDependencyPatterns(ctx));
2420
+ return dedupeDependencies([...resolveMiniprogramCandidateDependenciesSync(declaredDependencies, resolveFrom), ...explicitlyIncludedDependencies]);
2421
+ }
2422
+ function resolveNpmBuildCandidateDependencyRecordSync(ctx, pkgJson) {
2423
+ if (!pkgJson) return;
2424
+ return createDependencyRecord(resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson));
2425
+ }
2426
+ function hasLocalSubPackageNpmConfig(ctx) {
2427
+ const npmSubPackages = ctx.configService?.weappViteConfig?.npm?.subPackages;
2428
+ if (npmSubPackages && Object.values(npmSubPackages).some((config) => Array.isArray(config?.dependencies) && config.dependencies.length > 0)) return true;
2429
+ return false;
2430
+ }
2431
+ function resolveNpmDistDirName(configService) {
2432
+ return getPlatformNpmDistDirName(resolveMiniPlatformWithDefault(configService?.platform), { alipayNpmMode: configService?.weappViteConfig?.npm?.alipayNpmMode });
2433
+ }
2434
+ function resolveMainBuildDependencyPatterns(ctx) {
2435
+ return ctx.configService?.pluginOnly ? resolvePluginPackageDependencyPatterns(ctx) : resolveMainPackageDependencyPatterns(ctx);
2436
+ }
2437
+ function dedupeNpmDependencies(dependencies) {
2438
+ return dedupeDependencies(dependencies);
2439
+ }
2440
+ function resolveConfiguredNpmDependencyPatterns(ctx) {
2441
+ return resolveConfiguredDependencyPatterns(ctx);
2442
+ }
2443
+ function resolveDeclaredNpmDependencies(pkgJson) {
2444
+ return resolveDeclaredDependencies(pkgJson);
2445
+ }
2446
+ function resolveNpmStrategyMode(ctx) {
2447
+ return resolveNpmStrategy(ctx);
2448
+ }
2449
+ //#endregion
2450
+ //#region src/runtime/watch/options.ts
2451
+ /**
2452
+ * 解析主 watcher 与 sidecar watcher 共享的轮询配置。
2453
+ */
2454
+ function resolvePollingWatchOptions(configService) {
2455
+ const buildWatch = configService.inlineConfig?.build?.watch;
2456
+ const chokidar = buildWatch && typeof buildWatch === "object" && "chokidar" in buildWatch ? buildWatch.chokidar : void 0;
2457
+ const serverWatch = configService.inlineConfig?.server?.watch;
2458
+ const envUsePolling = process$1.env.CHOKIDAR_USEPOLLING;
2459
+ const envInterval = process$1.env.CHOKIDAR_INTERVAL;
2460
+ const envBinaryInterval = process$1.env.CHOKIDAR_BINARY_INTERVAL;
2461
+ const usePollingCandidate = chokidar?.usePolling ?? serverWatch?.usePolling ?? (envUsePolling === "1" || envUsePolling === "true" ? true : envUsePolling === "0" || envUsePolling === "false" ? false : void 0);
2462
+ const intervalCandidate = chokidar?.interval ?? serverWatch?.interval ?? (envInterval ? Number(envInterval) : void 0);
2463
+ const binaryIntervalCandidate = chokidar?.binaryInterval ?? serverWatch?.binaryInterval ?? (envBinaryInterval ? Number(envBinaryInterval) : void 0);
2464
+ return {
2465
+ usePolling: typeof usePollingCandidate === "boolean" ? usePollingCandidate : void 0,
2466
+ interval: typeof intervalCandidate === "number" && Number.isFinite(intervalCandidate) ? intervalCandidate : void 0,
2467
+ binaryInterval: typeof binaryIntervalCandidate === "number" && Number.isFinite(binaryIntervalCandidate) ? binaryIntervalCandidate : void 0
2468
+ };
2469
+ }
2470
+ function createSidecarWatchOptions(configService, input) {
2471
+ const polling = resolvePollingWatchOptions(configService);
2472
+ return {
2473
+ ...input,
2474
+ ...polling.usePolling !== void 0 ? { usePolling: polling.usePolling } : {},
2475
+ ...typeof polling.interval === "number" ? { interval: polling.interval } : {},
2476
+ ...typeof polling.binaryInterval === "number" ? { binaryInterval: polling.binaryInterval } : {}
2477
+ };
2478
+ }
2479
+ /**
2480
+ * 合并用户配置并排除 Vite 开发服务器不应监听的构建输出目录。
2481
+ */
2482
+ function createViteWatchIgnored(root, outDir, ignored) {
2483
+ const normalizedRoot = normalizeFsResolvedId(root);
2484
+ const normalizedOutDir = normalizeFsResolvedId(path.isAbsolute(outDir) ? outDir : path.resolve(root, outDir));
2485
+ return [...ignored === void 0 ? [] : Array.isArray(ignored) ? ignored : [ignored], (id) => {
2486
+ const normalizedId = normalizeFsResolvedId(path.isAbsolute(id) ? id : path.resolve(normalizedRoot, id));
2487
+ return isPathInside(normalizedOutDir, normalizedId);
2488
+ }];
2489
+ }
2490
+ //#endregion
2491
+ //#region src/wxml/processing/registry.ts
2492
+ /** 引用计数同时覆盖已发布、在途和失败恢复集合,单次注册不扫描整个工程。 */
2493
+ function retainDependency(state, files, file) {
2494
+ if (files.has(file)) return;
2495
+ files.add(file);
2496
+ const count = state.references.get(file) ?? 0;
2497
+ state.references.set(file, count + 1);
2498
+ if (!count) for (const listener of state.listeners) listener([file]);
2499
+ }
2500
+ function releaseDependencies(state, templates) {
2501
+ for (const files of templates.values()) for (const file of files) {
2502
+ const count = state.references.get(file);
2503
+ if (count === 1) state.references.delete(file);
2504
+ else state.references.set(file, count - 1);
2505
+ }
2506
+ }
2507
+ /** 只释放成功覆盖的模板,局部恢复不能丢失其他失败模板的监听。 */
2508
+ function releaseCoveredDependencies(state, templates, covered) {
2509
+ if (!covered) {
2510
+ releaseDependencies(state, templates);
2511
+ templates.clear();
2512
+ return;
2513
+ }
2514
+ for (const name of covered.keys()) {
2515
+ const files = templates.get(name);
2516
+ if (files) {
2517
+ releaseDependencies(state, /* @__PURE__ */ new Map([[name, files]]));
2518
+ templates.delete(name);
2519
+ }
2520
+ }
2521
+ }
2522
+ //#endregion
2523
+ //#region src/wxml/processing/dependencies.ts
2524
+ const deferredCommits = /* @__PURE__ */ new WeakMap();
2525
+ /** 转换阶段登记的依赖只在本轮输出成功后提交。 */
2526
+ function deferWxmlDependencyCommit(ctx, commit) {
2527
+ deferredCommits.get(ctx)?.fail();
2528
+ if (commit) deferredCommits.set(ctx, commit);
2529
+ else deferredCommits.delete(ctx);
2530
+ }
2531
+ function failWxmlDependencies(ctx) {
2532
+ deferredCommits.get(ctx)?.fail();
2533
+ deferredCommits.delete(ctx);
2534
+ }
2535
+ function commitWxmlDependencies(ctx) {
2536
+ deferredCommits.get(ctx)?.();
2537
+ deferredCommits.delete(ctx);
2538
+ }
2539
+ const borrowedRegistries = /* @__PURE__ */ new WeakSet();
2540
+ /** 隔离快照和独立分包借用开发会话的依赖集合,由拥有者统一释放。 */
2541
+ function shareWxmlDependencies(owner, child) {
2542
+ child.runtimeState.wxmlProcessing = owner.runtimeState.wxmlProcessing;
2543
+ borrowedRegistries.add(child.runtimeState);
2544
+ }
2545
+ function clearWxmlDependencies(ctx) {
2546
+ if (borrowedRegistries.has(ctx.runtimeState)) return;
2547
+ ctx.runtimeState.wxmlProcessing?.dependencies.clear();
2548
+ ctx.runtimeState.wxmlProcessing?.pending.clear();
2549
+ ctx.runtimeState.wxmlProcessing?.failed.clear();
2550
+ ctx.runtimeState.wxmlProcessing?.references.clear();
2551
+ deferredCommits.delete(ctx);
2552
+ ctx.runtimeState.wxmlProcessing?.listeners.clear();
2553
+ }
2554
+ function getWxmlWatchFiles(ctx) {
2555
+ return [...ctx.runtimeState?.wxmlProcessing?.references.keys() ?? []];
2556
+ }
2557
+ function isWxmlDependency(ctx, file) {
2558
+ return ctx.runtimeState?.wxmlProcessing?.references.has(normalizeFsResolvedId(file)) ?? false;
2559
+ }
2560
+ function observeWxmlDependencies(ctx, listener) {
2561
+ const state = ctx.runtimeState?.wxmlProcessing;
2562
+ if (!state) return () => {};
2563
+ state.listeners.add(listener);
2564
+ listener(getWxmlWatchFiles(ctx));
2565
+ return () => {
2566
+ state.listeners.delete(listener);
2567
+ };
2568
+ }
2569
+ /** 注册立即生效以支持失败恢复,成功后再提交本轮各模板的依赖集合。 */
2570
+ function beginWxmlDependencies(ctx, scope, partial, stage = "transform") {
2571
+ const state = ctx.runtimeState?.wxmlProcessing;
2572
+ const pending = /* @__PURE__ */ new Map();
2573
+ const key = `${stage}:${scope}`;
2574
+ const token = Symbol(key);
2575
+ let completed = false;
2576
+ const root = ctx.configService.cwd;
2577
+ let output;
2578
+ state?.pending.set(token, {
2579
+ scope,
2580
+ stage,
2581
+ templates: pending
2582
+ });
2583
+ const fail = () => {
2584
+ if (!state || completed || !state.pending.has(token)) return;
2585
+ completed = true;
2586
+ const recovery = state.failed.get(key) ?? /* @__PURE__ */ new Map();
2587
+ for (const [name, files] of pending) {
2588
+ if (!files.size) continue;
2589
+ const retained = recovery.get(name) ?? /* @__PURE__ */ new Set();
2590
+ recovery.set(name, retained);
2591
+ for (const file of files) retainDependency(state, retained, file);
2592
+ }
2593
+ if (recovery.size) state.failed.set(key, recovery);
2594
+ releaseDependencies(state, pending);
2595
+ state.pending.delete(token);
2596
+ };
2597
+ const commit = () => {
2598
+ if (!state || completed || !state.pending.has(token)) return;
2599
+ completed = true;
2600
+ const next = state.dependencies.get(key) ?? /* @__PURE__ */ new Map();
2601
+ releaseCoveredDependencies(state, next, partial ? pending : void 0);
2602
+ for (const [name, files] of pending) if (files.size) next.set(name, files);
2603
+ if (next.size) state.dependencies.set(key, next);
2604
+ else state.dependencies.delete(key);
2605
+ const recovery = state.failed.get(key);
2606
+ if (recovery) {
2607
+ releaseCoveredDependencies(state, recovery, partial ? pending : void 0);
2608
+ if (!recovery.size) state.failed.delete(key);
2609
+ }
2610
+ state.pending.delete(token);
2611
+ if (scope === "main" && !partial && ctx.scanService?.independentSubPackageMap) {
2612
+ const activeScopes = new Set([...ctx.scanService.independentSubPackageMap.keys()].map((root) => `independent:${root}`));
2613
+ for (const groups of [state.dependencies, state.failed]) for (const [registered, templates] of groups) {
2614
+ const registeredScope = registered.slice(registered.indexOf(":") + 1);
2615
+ if (registeredScope.startsWith("independent:") && !activeScopes.has(registeredScope)) {
2616
+ releaseDependencies(state, templates);
2617
+ groups.delete(registered);
2618
+ }
2619
+ }
2620
+ }
2621
+ };
2622
+ return {
2623
+ fail,
2624
+ commit,
2625
+ publish: Object.assign(commit, { fail }),
2626
+ template(fileName) {
2627
+ const files = pending.get(fileName) ?? /* @__PURE__ */ new Set();
2628
+ pending.set(fileName, files);
2629
+ return (file) => {
2630
+ if (completed || state && !state.pending.has(token)) throw new Error("The template dependency transaction has already completed.");
2631
+ if (typeof file !== "string" || !file.trim()) throw new TypeError("addWatchFile expects a nonempty file path.");
2632
+ output ??= normalizeFsResolvedId(ctx.configService.outDir);
2633
+ const resolved = normalizeFsResolvedId(path.resolve(root, file));
2634
+ if (resolved === output || resolved.startsWith(`${output}/`)) throw new Error("addWatchFile cannot watch generated output.");
2635
+ if (state) retainDependency(state, files, resolved);
2636
+ return resolved;
2637
+ };
2638
+ }
2639
+ };
2640
+ }
2641
+ //#endregion
2642
+ //#region src/wxml/processing/watch.ts
2643
+ const externalOwners = /* @__PURE__ */ new WeakMap();
2644
+ function ownsExternalWxmlWatch(ctx, file) {
2645
+ const normalized = normalizeFsResolvedId(file);
2646
+ return (externalOwners.get(ctx)?.has(normalized) ?? false) && isWxmlDependency(ctx, normalized);
2647
+ }
2648
+ /** 根外输入按父目录浅层监听,保留删除后的路径身份;根内输入继续由 Vite 监听。 */
2649
+ function bindWxmlDependencyWatch(ctx, server, onChange) {
2650
+ const root = server.config?.root ?? ctx.configService?.cwd;
2651
+ const external = /* @__PURE__ */ new Set();
2652
+ const parents = /* @__PURE__ */ new Set();
2653
+ let watcher;
2654
+ let closed;
2655
+ let ready = Promise.resolve();
2656
+ externalOwners.set(ctx, external);
2657
+ const unobserve = observeWxmlDependencies(ctx, (files) => {
2658
+ for (const file of files) {
2659
+ const relative = root ? path.relative(root, file) : "";
2660
+ if (root && (relative === ".." || relative.startsWith("../") || path.isAbsolute(relative))) external.add(file);
2661
+ }
2662
+ if (!external.size || server.config?.server.watch === null) return;
2663
+ const options = server.config?.server.watch ?? {};
2664
+ if (!watcher) {
2665
+ watcher = watch$1([], {
2666
+ ...options,
2667
+ ignoreInitial: true,
2668
+ depth: 0,
2669
+ ignored: [...Array.isArray(options.ignored) ? options.ignored : options.ignored ? [options.ignored] : [], (file, stats) => {
2670
+ const normalized = normalizeFsResolvedId(file);
2671
+ return !parents.has(normalized) && (!parents.has(path.dirname(normalized)) || Boolean(stats?.isDirectory()));
2672
+ }]
2673
+ }).on("all", (event, file) => {
2674
+ const normalized = normalizeFsResolvedId(file);
2675
+ if (!external.has(normalized) || !isWxmlDependency(ctx, normalized)) return;
2676
+ if (event === "add" || event === "change" || event === "unlink") onChange({
2677
+ event: event === "add" ? "create" : event === "unlink" ? "delete" : "update",
2678
+ file: normalized
2679
+ });
2680
+ }).on("error", (error) => server.config.logger.error(`[weapp-vite] WXML dependency watch failed: ${error instanceof Error ? error.message : String(error)}`));
2681
+ ready = once(watcher, "ready");
2682
+ }
2683
+ for (const file of external) {
2684
+ const parent = path.dirname(file);
2685
+ if (!parents.has(parent)) {
2686
+ parents.add(parent);
2687
+ watcher.add(parent);
2688
+ }
2689
+ }
2690
+ });
2691
+ const close = () => {
2692
+ closed ??= (async () => {
2693
+ unobserve();
2694
+ if (externalOwners.get(ctx) === external) externalOwners.delete(ctx);
2695
+ external.clear();
2696
+ await watcher?.close();
2697
+ })();
2698
+ return closed;
2699
+ };
2700
+ return Object.assign(close, { ready });
2701
+ }
2702
+ //#endregion
2703
+ //#region src/moduleGraph/host.ts
2704
+ const hosts = /* @__PURE__ */ new WeakMap();
2705
+ /** 显式借用宿主图;释放借用不会关闭宿主服务器。 */
2706
+ function attachDevModuleGraphHost(context, server, onBuild) {
2707
+ if (hosts.has(context)) throw new Error("[weapp-vite] 编译上下文已经绑定开发宿主。");
2708
+ const host = {
2709
+ server,
2710
+ onBuild,
2711
+ pending: []
2712
+ };
2713
+ hosts.set(context, host);
2714
+ return () => {
2715
+ if (hosts.get(context) === host) hosts.delete(context);
2716
+ };
2717
+ }
2718
+ function notifyDevModuleGraphHost(context, change) {
2719
+ const host = hosts.get(context);
2720
+ if (host?.onChange) host.onChange(change);
2721
+ else host?.pending.push(change);
2722
+ }
2723
+ function reportDevModuleGraphBuild(context, successful) {
2724
+ hosts.get(context)?.onBuild?.(successful);
2725
+ }
2726
+ function hasDevModuleGraphHost(context) {
2727
+ return hosts.has(context);
2728
+ }
2729
+ function connectDevModuleGraphHost(context, onChange) {
2730
+ const host = hosts.get(context);
2731
+ if (!host) return;
2732
+ host.onChange = onChange;
2733
+ const release = context.moduleGraphService.bindDevServer(host.server);
2734
+ for (const change of host.pending.splice(0)) onChange(change);
2735
+ let closed = false;
2736
+ return { async close() {
2737
+ if (closed) return;
2738
+ closed = true;
2739
+ if (host.onChange === onChange) host.onChange = void 0;
2740
+ release();
2741
+ } };
2742
+ }
2743
+ //#endregion
2744
+ //#region src/moduleGraph/logicalEntry.ts
2745
+ function createLogicalEntryModuleCode(entry, dependencies, options = {}) {
2746
+ const source = JSON.stringify(entry.sourceId);
2747
+ const isVueLikeEntry = /\.(?:vue|jsx|tsx)$/.test(entry.sourceId);
2748
+ const delegatesComponentRegistration = entry.type === "component" && isVueLikeEntry;
2749
+ const forwardsDefault = entry.type !== "app" && isVueLikeEntry;
2750
+ const imports = delegatesComponentRegistration ? [
2751
+ `import { createWevuComponent as __weappViteCreateWevuComponent } from ${JSON.stringify(WEAPP_VITE_RUNTIME_VIRTUAL_ID)};`,
2752
+ `import __weappViteComponentOptions from ${source};`,
2753
+ `__weappViteCreateWevuComponent(__weappViteComponentOptions);`,
2754
+ `export default __weappViteComponentOptions;`
2755
+ ] : [forwardsDefault ? `export { default } from ${source};` : `import ${source};`];
2756
+ const dependencyIds = /* @__PURE__ */ new Set();
2757
+ withRealpathScope(() => {
2758
+ for (const dependency of dependencies) dependencyIds.add(createSidecarModuleId(entry.sourceId, dependency.sourceId, dependency.kind));
2759
+ });
2760
+ for (const dependencyId of [...dependencyIds].sort()) imports.push(`import ${JSON.stringify(dependencyId)};`);
2761
+ imports.push(`export * from ${source};`);
2762
+ if (options.includeStatefulHmrAccept && entry.type !== "component") imports.push("if (import.meta.hot) import.meta.hot.accept();");
2763
+ return `${imports.join("\n")}\n`;
2764
+ }
2765
+ function createSidecarModuleCode(ownerId, sourceId, kind) {
2766
+ const sourceRequest = createSidecarSourceSpecifier(ownerId, sourceId, kind, kind === "style");
2767
+ return `import ${JSON.stringify(sourceRequest)};\nexport default ${JSON.stringify(sourceId)};\n`;
2768
+ }
2769
+ //#endregion
2770
+ //#region src/utils/hmrProfile.ts
2771
+ const DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH = ".weapp-vite/hmr-profile.jsonl";
2772
+ const HMR_PROFILE_JSON_ENV = "WEAPP_VITE_HMR_PROFILE_JSON";
2773
+ /**
2774
+ * @description 解析 HMR profile JSONL 输出路径。
2775
+ */
2776
+ function resolveHmrProfileJsonPath(options) {
2777
+ const fallbackToDefault = options.fallbackToDefault ?? false;
2778
+ if (options.option === true) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
2779
+ if (typeof options.option === "string") {
2780
+ const trimmed = options.option.trim();
2781
+ if (trimmed) return path.isAbsolute(trimmed) ? trimmed : path.resolve(options.cwd, trimmed);
2782
+ }
2783
+ if (fallbackToDefault) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
2784
+ }
2785
+ /**
2786
+ * @description 从环境变量解析 HMR profile JSONL 输出选项。
2787
+ */
2788
+ function resolveHmrProfileJsonEnvOption(env = process$1.env) {
2789
+ const raw = env[HMR_PROFILE_JSON_ENV]?.trim();
2790
+ if (!raw) return;
2791
+ if (raw === "1" || raw.toLowerCase() === "true") return true;
2792
+ if (raw === "0" || raw.toLowerCase() === "false") return;
2793
+ return raw;
2794
+ }
2795
+ /** 统一写入方与监听边界的 profile 输出选择,保持环境变量优先级一致。 */
2796
+ function resolveActiveHmrProfileJsonPath(options, env = process$1.env) {
2797
+ return resolveHmrProfileJsonPath({
2798
+ ...options,
2799
+ option: resolveHmrProfileJsonEnvOption(env) ?? options.option
2800
+ });
2801
+ }
2802
+ let hmrProfileEventSequence = 0;
2803
+ /**
2804
+ * @description 创建 HMR profile 事件 id,用于把 watcher 事件、JSONL 样本和外部审计场景稳定关联。
2805
+ */
2806
+ function createHmrProfileEventId() {
2807
+ hmrProfileEventSequence += 1;
2808
+ return `${Date.now().toString(36)}-${hmrProfileEventSequence.toString(36)}`;
2809
+ }
2810
+ /**
2811
+ * @description 为 HMR profile 累加阶段耗时。
2812
+ */
2813
+ function recordHmrProfileDuration(profile, key, durationMs) {
2814
+ if (!profile || !Number.isFinite(durationMs) || durationMs < 0) return;
2815
+ profile[key] = (profile[key] ?? 0) + durationMs;
2816
+ }
2817
+ /**
2818
+ * @description 为 HMR profile 累加操作次数。
2819
+ */
2820
+ function recordHmrProfileOperation(profile, key, count = 1) {
2821
+ if (!profile || !Number.isFinite(count) || count <= 0) return;
2822
+ profile[key] = (profile[key] ?? 0) + count;
2823
+ }
2824
+ /** 连续记录同一插件内已完成的阶段;停用时不读取时钟,不引入额外异步调度。 */
2825
+ function createHmrProfileCheckpoint(profile) {
2826
+ let previous = profile ? performance.now() : 0;
2827
+ return (key) => {
2828
+ if (!profile) return;
2829
+ const now = performance.now();
2830
+ recordHmrProfileDuration(profile, key, now - previous);
2831
+ previous = now;
2832
+ };
2833
+ }
2834
+ //#endregion
2835
+ //#region src/moduleGraph/profileOutput.ts
2836
+ /** 仅识别当前启用的自身 profile 文件,不屏蔽同目录或同名用户输入。 */
2837
+ function createProfileOutputMatcher(configService) {
2838
+ return (file) => {
2839
+ if (!configService) return false;
2840
+ const output = resolveActiveHmrProfileJsonPath({
2841
+ cwd: configService.cwd,
2842
+ option: configService.weappViteConfig?.hmr?.profileJson
2843
+ });
2844
+ if (!output) return false;
2845
+ const normalize = (value) => {
2846
+ const normalized = normalizePath$1(path.resolve(configService.cwd, normalizePath$1(value)));
2847
+ return process$1.platform === "win32" ? normalized.toLowerCase() : normalized;
2848
+ };
2849
+ return normalize(file) === normalize(output);
2850
+ };
2851
+ }
2852
+ //#endregion
2853
+ //#region src/moduleGraph/devProvider.ts
2854
+ const DEV_EXTERNAL_PREFIX = "\0weapp-vite:module-graph-external:";
2855
+ function isInternalPlugin(plugin) {
2856
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
2857
+ const name = plugin.name;
2858
+ return typeof name === "string" && (name.startsWith("weapp-vite:") || name.startsWith("weapp-runtime:"));
2859
+ }
2860
+ function collectResolverPlugins(config) {
2861
+ return (Array.isArray(config.plugins) ? config.plugins : config.plugins ? [config.plugins] : []).filter((plugin) => !isInternalPlugin(plugin));
2862
+ }
2863
+ async function transformVueSource(code, id, config) {
2864
+ const { descriptor, errors } = await readAndParseSfc(id, { source: code });
2865
+ if (errors.length) throw errors[0];
2866
+ const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block?.content || block?.src);
2867
+ const source = blocks.map((block) => block.src ? `import ${JSON.stringify(block.src)};` : block.content).join("\n") || "export default {}";
2868
+ const lang = blocks.some((block) => block?.lang === "tsx") ? "tsx" : blocks.some((block) => block?.lang === "ts") ? "ts" : "js";
2869
+ return await transformWithOxc(source, id, {
2870
+ lang,
2871
+ sourcemap: false,
2872
+ target: "esnext",
2873
+ tsconfig: false,
2874
+ typescript: { onlyRemoveTypeImports: true }
2875
+ }, void 0, config);
2876
+ }
2877
+ async function isExternalRequest(source, importer, config) {
2878
+ const buildOptions = config.build;
2879
+ const external = buildOptions?.rolldownOptions?.external ?? buildOptions?.rollupOptions?.external;
2880
+ if (typeof external === "function") return await external(source, importer, false);
2881
+ return (Array.isArray(external) ? external : external ? [external] : []).some((pattern) => {
2882
+ if (typeof pattern === "string") return pattern === source;
2883
+ pattern.lastIndex = 0;
2884
+ return pattern.test(source);
2885
+ });
2886
+ }
2887
+ function createDevModuleGraphPlugin(ctx, config, onChange) {
2888
+ const isProfileOutput = createProfileOutputMatcher(ctx.configService);
2889
+ const npmExternalPackages = new Set(ctx.configService?.packageJson ? resolveNpmBuildCandidateDependenciesSync(ctx, ctx.configService.packageJson) : []);
2890
+ return {
2891
+ name: "weapp-vite:module-graph-provider",
2892
+ enforce: "pre",
2893
+ config() {
2894
+ return {
2895
+ server: { watch: { ignored: [isProfileOutput] } },
2896
+ resolve: { alias: [{
2897
+ find: WEVU_AUTO_ROUTES_MODULE_ID$1,
2898
+ replacement: WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1
2899
+ }, {
2900
+ find: AUTO_ROUTES_ID,
2901
+ replacement: VIRTUAL_MODULE_ID
2902
+ }] }
2903
+ };
2904
+ },
2905
+ async resolveId(id, importer) {
2906
+ const autoRoutesId = resolveAutoRoutesVirtualId(id);
2907
+ if (autoRoutesId) return autoRoutesId;
2908
+ const virtualId = resolveVirtualModuleId(id);
2909
+ if (virtualId) return virtualId;
2910
+ if (parseSidecarSourceMetadata(id)) return id;
2911
+ if (Array.from(npmExternalPackages).some((pkg) => id === pkg || id.startsWith(`${pkg}/`))) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
2912
+ if (await isExternalRequest(id, importer, config)) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
2913
+ if (!id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !/^[a-z]:[\\/]/i.test(id)) {
2914
+ const resolved = await this.resolve(id, importer, { skipSelf: true });
2915
+ if (!resolved || resolved.external) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
2916
+ return resolved;
2917
+ }
2918
+ return null;
2919
+ },
2920
+ load(id) {
2921
+ const autoRoutesId = resolveAutoRoutesVirtualId(id);
2922
+ const service = ctx.autoRoutesService;
2923
+ if (autoRoutesId && service) return service.ensureFresh().then(() => autoRoutesId === WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1 ? service.getNamedModuleCode() : service.getModuleCode());
2924
+ if (id.startsWith(DEV_EXTERNAL_PREFIX)) return "export default {}";
2925
+ const logicalEntry = parseLogicalEntryId(id);
2926
+ if (logicalEntry) return createLogicalEntryModuleCode(logicalEntry, ctx.moduleGraphService.getEntryDependencies(logicalEntry.sourceId));
2927
+ const sidecar = parseSidecarModuleId(id);
2928
+ if (sidecar) {
2929
+ if (sidecar.kind === "style") {
2930
+ const source = createSidecarSourceSpecifier(sidecar.ownerId, sidecar.sourceId, "style");
2931
+ return `import ${JSON.stringify(source)};\nexport default ${JSON.stringify(sidecar.sourceId)};\n`;
2932
+ }
2933
+ return createSidecarModuleCode(sidecar.ownerId, sidecar.sourceId, sidecar.kind);
2934
+ }
2935
+ const sidecarSource = parseSidecarSourceRequest(id);
2936
+ if (sidecarSource) {
2937
+ if (sidecarSource.kind === "style" && !sidecarSource.dependencyOnly) return null;
2938
+ return `export default ${JSON.stringify(sidecarSource.sourceId)};`;
2939
+ }
2940
+ return null;
2941
+ },
2942
+ async transform(code, id) {
2943
+ if (isCSSRequest(id) && !id.startsWith("\0")) this.addWatchFile(normalizeSourceId(id));
2944
+ for (const dependency of ctx.moduleGraphService.getTransformDependencies?.(id) ?? []) this.addWatchFile(dependency);
2945
+ if (!id.endsWith(".vue")) return null;
2946
+ return await transformVueSource(code, id, this?.environment?.config);
2947
+ },
2948
+ async hotUpdate({ type, file, read }) {
2949
+ if (this.environment.name !== "client" || isProfileOutput(file) || ownsExternalWxmlWatch(ctx, file)) return;
2950
+ if (type === "delete") {
2951
+ onChange({
2952
+ event: type,
2953
+ file
2954
+ });
2955
+ return;
2956
+ }
2957
+ try {
2958
+ await read();
2959
+ } catch (error) {
2960
+ if (error.code === "ENOENT") return;
2961
+ throw error;
2962
+ }
2963
+ onChange({
2964
+ event: type,
2965
+ file
2966
+ });
2967
+ }
2968
+ };
2969
+ }
2970
+ async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
2971
+ const host = connectDevModuleGraphHost(ctx, onChange);
2972
+ if (host) return host;
2973
+ const configService = ctx.configService;
2974
+ const userWatch = buildConfig.server?.watch;
2975
+ const pollingWatchOptions = resolvePollingWatchOptions({ inlineConfig: configService?.inlineConfig ?? {} });
2976
+ const ignored = configService?.outDir ? createViteWatchIgnored(buildConfig.root ?? configService.cwd, configService.outDir, userWatch?.ignored) : userWatch?.ignored;
2977
+ const server = await createServer({
2978
+ ...buildConfig,
2979
+ root: buildConfig.root ?? configService?.cwd,
2980
+ appType: "custom",
2981
+ configFile: false,
2982
+ customLogger: createLogger("silent"),
2983
+ plugins: [createDevModuleGraphPlugin(ctx, buildConfig, onChange), ...collectResolverPlugins(buildConfig)],
2984
+ server: {
2985
+ ...buildConfig.server ?? {},
2986
+ hmr: true,
2987
+ middlewareMode: true,
2988
+ watch: {
2989
+ ...userWatch ?? {},
2990
+ ...Object.fromEntries(Object.entries(pollingWatchOptions).filter(([, value]) => value !== void 0)),
2991
+ ...ignored !== void 0 ? { ignored } : {}
2992
+ }
2993
+ },
2994
+ build: {
2995
+ ...buildConfig.build ?? {},
2996
+ watch: void 0,
2997
+ write: false
2998
+ }
2999
+ });
3000
+ const releaseServer = ctx.moduleGraphService.bindDevServer(server);
3001
+ const unobserveWxml = bindWxmlDependencyWatch(ctx, server, onChange);
3002
+ try {
3003
+ await unobserveWxml.ready;
3004
+ } catch (error) {
3005
+ await unobserveWxml();
3006
+ try {
3007
+ await server.close();
3008
+ } finally {
3009
+ releaseServer();
3010
+ }
3011
+ throw error;
3012
+ }
3013
+ let closePromise;
3014
+ return { close() {
3015
+ closePromise ??= (async () => {
3016
+ await unobserveWxml();
3017
+ try {
3018
+ await server.close();
3019
+ } finally {
3020
+ releaseServer();
3021
+ }
3022
+ })();
3023
+ return closePromise;
3024
+ } };
3025
+ }
3026
+ //#endregion
3027
+ export { isAutoRoutesGeneratedDirectoryName as $, resolveConfiguredNpmDependencyPatterns as A, WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1 as B, isWxmlDependency as C, resolvePollingWatchOptions as D, createViteWatchIgnored as E, resolveNpmDistDirName as F, invalidateAutoRoutesVirtualModules as G, collectAutoRoutesReloadModules as H, resolveNpmStrategyMode as I, resolveAutoRoutesHotUpdateAction as J, isAutoRoutesWatchFile as K, resolveTargetDependencies as L, resolveMainBuildDependencyPatterns as M, resolveNpmBuildCandidateDependenciesSync as N, dedupeNpmDependencies as O, resolveNpmBuildCandidateDependencyRecordSync as P, chokidar_default as Q, packageSearchOptions as R, getWxmlWatchFiles as S, createSidecarWatchOptions as T, collectAutoRoutesWatchDirs as U, addAutoRoutesWatchTargets as V, createAutoRoutesSidecarWatcher as W, resolveAutoRoutesWatchChangeEvent as X, resolveAutoRoutesVirtualId as Y, shouldStartAutoRoutesWatcher as Z, beginWxmlDependencies as _, recordHmrProfileDuration as a, isCSSRequest as at, deferWxmlDependencyCommit as b, resolveHmrProfileJsonEnvOption as c, collectDevStartNodes as ct, createSidecarModuleCode as d, isLogicalEntrySource as dt, isAutoRoutesGeneratedPath as et, attachDevModuleGraphHost as f, normalizeSourceId as ft, bindWxmlDependencyWatch as g, reportDevModuleGraphBuild as h, createHmrProfileEventId as i, createAutoRoutesMatcher as it, resolveDeclaredNpmDependencies as j, hasLocalSubPackageNpmConfig as k, resolveHmrProfileJsonPath as l, hasBuildModule as lt, notifyDevModuleGraphHost as m, createDevModuleGraphProvider as n, resolveAutoRoutesManagedOutputPaths as nt, recordHmrProfileOperation as o, isRegexp as ot, hasDevModuleGraphHost as p, isAutoRoutesWatchMode as q, createHmrProfileCheckpoint as r, resolveWeappAutoRoutesConfig as rt, resolveActiveHmrProfileJsonPath as s, collectBuildStartIds as st, createDevModuleGraphPlugin as t, isAutoRoutesGeneratedRelativePath as tt, createLogicalEntryModuleCode as u, hasDevModule as ut, clearWxmlDependencies as v, shareWxmlDependencies as w, failWxmlDependencies as x, commitWxmlDependencies as y, RESOLVED_VIRTUAL_ID as z };