@outerlayer/cli 0.36.0-next.20261102124202 → 0.36.0-next.20261102135508

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 (178) hide show
  1. package/dist/agent-setup-Q3HDN23U.js +39 -0
  2. package/dist/agent-subcommand-Z6SOLWZW.js +25 -0
  3. package/dist/{bridge-DFG2GTXQ.js → bridge-4KPODDN7.js} +6 -4
  4. package/dist/{build-THAD3B4Q.js → build-KYXFZQ33.js} +13 -11
  5. package/dist/{build-disk-HO2VPIBJ.js → build-disk-W6AL5WHI.js} +11 -9
  6. package/dist/build-info.json +1 -1
  7. package/dist/{builder-AXJNIF4S.js → builder-IMNOEYV7.js} +10 -8
  8. package/dist/caller-NLRE272L.js +22 -0
  9. package/dist/{check-SF2OVZXB.js → check-WWX32IGY.js} +60 -58
  10. package/dist/{chunk-KN4VIK53.js → chunk-2YC3TXWX.js} +1 -1
  11. package/dist/{chunk-4TNUQLXH.js → chunk-3UFX6KH2.js} +12 -11
  12. package/dist/{chunk-5FIOUQGC.js → chunk-3YEPLVNW.js} +8 -8
  13. package/dist/chunk-4DLJ343I.js +38 -0
  14. package/dist/{chunk-5WYT3PPE.js → chunk-4OD45RBP.js} +4 -1
  15. package/dist/{chunk-OYKAOHX5.js → chunk-4XXBV37R.js} +6 -6
  16. package/dist/{chunk-RSRZDF3K.js → chunk-6B3V6EGQ.js} +11 -9
  17. package/dist/{chunk-XABJMU5A.js → chunk-6HDXRDC5.js} +2 -2
  18. package/dist/{chunk-TWYHSMHM.js → chunk-6JLYU322.js} +3 -2
  19. package/dist/{chunk-5GHJFETA.js → chunk-6KH3NMIT.js} +3010 -1196
  20. package/dist/{chunk-QJDX6VJS.js → chunk-AQE6E54X.js} +10 -9
  21. package/dist/{chunk-564Q2STF.js → chunk-ATKCHMFD.js} +1 -1
  22. package/dist/{chunk-PQDFW422.js → chunk-B2P72DAE.js} +1 -1
  23. package/dist/{chunk-GZ75FRLB.js → chunk-B36NSEUM.js} +1 -1
  24. package/dist/{chunk-XHFSBSIA.js → chunk-B5SWBFVE.js} +3 -2
  25. package/dist/{chunk-NC3QAHOS.js → chunk-BSPJI5T7.js} +4 -2
  26. package/dist/{chunk-I6FRCBMU.js → chunk-BUYXEU7J.js} +8 -8
  27. package/dist/{chunk-A5Y2HBVU.js → chunk-BZSJ77MO.js} +1 -1
  28. package/dist/{chunk-C3JWWPLC.js → chunk-CDG475ZP.js} +8 -7
  29. package/dist/{chunk-TYCZVJTB.js → chunk-CSBW4LGL.js} +5 -5
  30. package/dist/{chunk-EUDG754F.js → chunk-CSVJGW3I.js} +2 -2
  31. package/dist/{chunk-M2NIHHQI.js → chunk-CXJC3JLN.js} +3 -2
  32. package/dist/{chunk-XE3DIJJT.js → chunk-D4VGJQY7.js} +1 -1
  33. package/dist/{chunk-PKO5IDW4.js → chunk-D5I5SSPU.js} +7 -7
  34. package/dist/{chunk-WDQPBAFV.js → chunk-D6EXW4EB.js} +2 -1
  35. package/dist/{chunk-GSXGA6KF.js → chunk-DG3M5DZU.js} +1 -1
  36. package/dist/{chunk-GD6KIHOS.js → chunk-DTCTXDJP.js} +1 -1
  37. package/dist/{chunk-J7Y3PCO2.js → chunk-DTQPDMHG.js} +2 -1
  38. package/dist/{chunk-PT34C6SU.js → chunk-E3TP4QTM.js} +1 -1
  39. package/dist/{chunk-NWBB2SQ4.js → chunk-ENBOAE2W.js} +24 -24
  40. package/dist/{chunk-LSXHTBAM.js → chunk-ENMX3VQ7.js} +7 -7
  41. package/dist/{chunk-XLOM2BNL.js → chunk-FOSYM7TQ.js} +1 -1
  42. package/dist/{chunk-4CTVN3C5.js → chunk-FRMAQ3C4.js} +5 -5
  43. package/dist/{chunk-PTPF36Q7.js → chunk-FTP7SE6Y.js} +3 -3
  44. package/dist/{chunk-IP7BIBXJ.js → chunk-FWSVWPMS.js} +16 -7
  45. package/dist/{chunk-K3X3L5YW.js → chunk-GFZ7PELR.js} +6 -6
  46. package/dist/{chunk-WLMAGMTU.js → chunk-H2NJG3TE.js} +4 -3
  47. package/dist/{chunk-T5Z22NA6.js → chunk-HRHWA6TZ.js} +1 -1
  48. package/dist/chunk-HTRDL42C.js +45 -0
  49. package/dist/{chunk-YBAVN6WS.js → chunk-I4DM7SNX.js} +7 -7
  50. package/dist/{chunk-CKPQOQFC.js → chunk-I6U6QPN6.js} +769 -101
  51. package/dist/{chunk-6JJITHBI.js → chunk-IKFAJTLZ.js} +1 -1
  52. package/dist/{chunk-FIO6PIZ6.js → chunk-J2OMKFYB.js} +3 -3
  53. package/dist/{chunk-Q42K6XZ6.js → chunk-K2G3VB7W.js} +1 -1
  54. package/dist/{chunk-L3JXQDVH.js → chunk-K7N6LAPC.js} +4 -4
  55. package/dist/{chunk-RK4JQRVT.js → chunk-KRCU66AM.js} +9 -9
  56. package/dist/{chunk-RPZIHELI.js → chunk-LHHDX7FB.js} +5 -5
  57. package/dist/{chunk-FUJUFLDC.js → chunk-LO4CK734.js} +8 -14
  58. package/dist/chunk-LSLK4RS4.js +82 -0
  59. package/dist/{chunk-I626B72C.js → chunk-LSZUTI6O.js} +1 -1
  60. package/dist/{chunk-H2FFONRY.js → chunk-MVPOYQQY.js} +1 -1
  61. package/dist/{chunk-JVCQZDQ6.js → chunk-NXQK2I3G.js} +1 -1
  62. package/dist/{chunk-EBIYRRJW.js → chunk-O3MJAHLI.js} +80 -94
  63. package/dist/{chunk-VRQM4A64.js → chunk-PBGNX3PS.js} +1 -1
  64. package/dist/{chunk-CJJDJ7AT.js → chunk-PIZA7OG2.js} +5 -3
  65. package/dist/{chunk-772ILTCK.js → chunk-PMA67TIN.js} +3 -3
  66. package/dist/{chunk-GDZTL6BI.js → chunk-QKOJ22OV.js} +123 -277
  67. package/dist/{chunk-WNYH42PF.js → chunk-RF4JHGGB.js} +7 -7
  68. package/dist/{chunk-WQB3XOEP.js → chunk-SJJXDU2J.js} +6 -6
  69. package/dist/chunk-T5QBWM6M.js +113 -0
  70. package/dist/{chunk-LYFLUNWK.js → chunk-TJIFYV2Z.js} +7 -7
  71. package/dist/{chunk-OZOATEK3.js → chunk-TKY3SDXH.js} +6 -6
  72. package/dist/{chunk-CVGQ3BNF.js → chunk-ULBYRPAP.js} +1 -1
  73. package/dist/{chunk-LVXR37OG.js → chunk-URHS76GV.js} +9 -8
  74. package/dist/{chunk-J7TCTARR.js → chunk-VAYVTUU4.js} +5 -5
  75. package/dist/{chunk-5FND4PIU.js → chunk-VUH7KKVD.js} +3 -3
  76. package/dist/{chunk-NTMRMBLM.js → chunk-WACPWYMH.js} +4 -4
  77. package/dist/{chunk-AAGU5FJF.js → chunk-WGC7UFRM.js} +1 -1
  78. package/dist/{chunk-XAOIHYPS.js → chunk-WVAXJOWG.js} +5 -4
  79. package/dist/{chunk-6LO62EQ5.js → chunk-XEWG4AB2.js} +28 -28
  80. package/dist/{chunk-AYLYAOHH.js → chunk-XIDDJSQU.js} +3 -2
  81. package/dist/{chunk-ESSJPSJ2.js → chunk-Y4E7IS7H.js} +2 -2
  82. package/dist/{chunk-HIN4BMRW.js → chunk-YJQ7YA7J.js} +5 -5
  83. package/dist/{chunk-LCOQN6NR.js → chunk-YMVRCSKD.js} +4 -4
  84. package/dist/{chunk-JXXHLQQR.js → chunk-YYQ5NOT5.js} +3 -3
  85. package/dist/chunk-ZHQC43NH.js +130 -0
  86. package/dist/{chunk-3FSKTGM6.js → chunk-ZSRMJOAK.js} +3 -3
  87. package/dist/{claude-launcher-LXZPTDNC.js → claude-launcher-LGKJZH33.js} +82 -108
  88. package/dist/{cli-QFUT3UQS.js → cli-Q5L64EEG.js} +323 -293
  89. package/dist/{command-45RZT4CK.js → command-CGEFJZNC.js} +55 -53
  90. package/dist/{config-WYQPXLOP.js → config-T22KVOOT.js} +12 -10
  91. package/dist/{connect-cmd-LUCQ7FSV.js → connect-cmd-RUBP466E.js} +12 -10
  92. package/dist/{container-start-T776VI3M.js → container-start-JRF3SBUA.js} +53 -51
  93. package/dist/{context-cleanup-QE2MIO2Q.js → context-cleanup-3K2AOECJ.js} +4 -2
  94. package/dist/{context-show-cmd-7QEHUOEL.js → context-show-cmd-4UXO5WQJ.js} +13 -11
  95. package/dist/{control-plane-launch-THUH6YU5.js → control-plane-launch-AAH4YH56.js} +25 -21
  96. package/dist/{demo-record-cmd-SBERRQNW.js → demo-record-cmd-2OKCGST7.js} +7 -5
  97. package/dist/{demo-voice-cmd-VM3FITZU.js → demo-voice-cmd-GEPX7GIG.js} +24 -22
  98. package/dist/{dist-6KGTCWKR.js → dist-VVZIGSAF.js} +1 -1
  99. package/dist/{docker-MQNLK4OO.js → docker-5VWK335X.js} +10 -8
  100. package/dist/{doctor-NQOSPJGS.js → doctor-EQM3JRZI.js} +55 -53
  101. package/dist/emit-artifact-cmd-TA3MPHLU.js +43 -0
  102. package/dist/{emit-cmd-ZPFCPVSR.js → emit-cmd-RO4L4PFZ.js} +7 -5
  103. package/dist/emit-criteria-cmd-NMTUV2KM.js +34 -0
  104. package/dist/{emit-demo-cmd-PMQGNNVX.js → emit-demo-cmd-Y2Y6LEL7.js} +24 -22
  105. package/dist/{emit-finding-cmd-MYWQN5WW.js → emit-finding-cmd-VECM64UR.js} +17 -15
  106. package/dist/{emit-result-cmd-GXK3KMAP.js → emit-result-cmd-2ERWFDUN.js} +22 -20
  107. package/dist/{emit-step-cmd-ZV2XTUVT.js → emit-step-cmd-V2ET66N4.js} +17 -15
  108. package/dist/{exec-client-P7RFRUCK.js → exec-client-54XKNPTI.js} +7 -5
  109. package/dist/find-unit-CNAPU7XQ.js +23 -0
  110. package/dist/{findings-cmd-OGMBVVSM.js → findings-cmd-QJPPF6BY.js} +17 -15
  111. package/dist/{fleet-readiness-4RBKLXBQ.js → fleet-readiness-DKAPHAZN.js} +13 -11
  112. package/dist/{governing-source-XJMXFSAR.js → governing-source-7PZ6DAJU.js} +21 -19
  113. package/dist/{guest-init-XZHRPIMG.js → guest-init-5QZRGP62.js} +8 -6
  114. package/dist/{hook-fast-ZOWGWCPO.js → hook-fast-VXROB4KF.js} +4 -2
  115. package/dist/{pending-YU2GE2UV.js → hook-install-GDNRMML4.js} +5 -5
  116. package/dist/{hook-wrap-fast-545QJSBJ.js → hook-wrap-fast-LWWKKPGK.js} +4 -2
  117. package/dist/host-checks-WAPO5X7X.js +78 -0
  118. package/dist/host-key-HLLV37NV.js +16 -0
  119. package/dist/{image-tag-E4JK2APF.js → image-tag-PBWQBATH.js} +7 -5
  120. package/dist/index.js +8 -9
  121. package/dist/init-EK3PUU6W.js +78 -0
  122. package/dist/{init-LO6U7YTW.js → init-Y2URPVVY.js} +51 -49
  123. package/dist/{init-cmd-2JANO5EN.js → init-cmd-XNANUDIW.js} +35 -29
  124. package/dist/{init-update-D6PRTGNE.js → init-update-EFCTKF6D.js} +24 -22
  125. package/dist/{install-cmd-SJMBNQEH.js → install-cmd-RHFUZFV4.js} +9 -7
  126. package/dist/{layout-AQHIMJMO.js → layout-7XMC7S6K.js} +4 -2
  127. package/dist/{logs-NE55HOET.js → logs-E7MGQINH.js} +6 -4
  128. package/dist/loop-L6TX6OR4.js +89 -0
  129. package/dist/machine-VJKAY2GX.js +78 -0
  130. package/dist/{machine-skills-KK2HXYMR.js → machine-skills-HR4RNRNR.js} +4 -2
  131. package/dist/{mcp-install-cmd-2QAS3AQZ.js → mcp-install-cmd-SMPLT43Q.js} +4 -2
  132. package/dist/{mcp-serve-cmd-U6USKHYR.js → mcp-serve-cmd-XXERT673.js} +8 -6
  133. package/dist/{paths-O7LCWY33.js → paths-F2ZR2EKC.js} +6 -4
  134. package/dist/pending-VOFQRXP4.js +16 -0
  135. package/dist/{pidfile-5GDCQ5HA.js → pidfile-7M7O2M7T.js} +7 -5
  136. package/dist/{record-NETSDAO6.js → record-YCJ6DZOY.js} +7 -5
  137. package/dist/{relay-VZ733BVJ.js → relay-I2T43PPB.js} +4 -2
  138. package/dist/{relay-protocol-24GEUGCO.js → relay-protocol-GI2GC2AM.js} +4 -2
  139. package/dist/runner-env-YW55JVU7.js +23 -0
  140. package/dist/{runner-identity-PSCZBILD.js → runner-identity-Y5ZFCC7V.js} +10 -8
  141. package/dist/{runner-key-VM2LYVRK.js → runner-key-R47C6374.js} +51 -49
  142. package/dist/{session-sender-P2RHDM6U.js → session-sender-UPACLRGG.js} +23 -21
  143. package/dist/{shell-function-NRD4KVUK.js → shell-function-GYD2ZQQG.js} +2 -1
  144. package/dist/{spec-cmd-LGKP6MT7.js → spec-cmd-7QRE2SZK.js} +18 -16
  145. package/dist/{starter-pack-SMK6UPRL.js → starter-pack-IMKIUA56.js} +5 -3
  146. package/dist/state-VAHBIMS5.js +16 -0
  147. package/dist/{status-HEHCNIDS.js → status-BQEYEG2V.js} +51 -49
  148. package/dist/{statusline-fast-E7RWVREA.js → statusline-fast-NUVHCNRX.js} +4 -2
  149. package/dist/{sync-cmd-HKN45HXL.js → sync-cmd-NBLYEPQG.js} +22 -20
  150. package/dist/update-steps-VGKNGWTZ.js +79 -0
  151. package/dist/{watch-RGZCUCR3.js → watch-IHV4V3HZ.js} +22 -20
  152. package/dist/{work-claim-cmd-6DSPGCZE.js → work-claim-cmd-WGTSU5IT.js} +21 -19
  153. package/dist/{work-cmd-GPLYLWY7.js → work-cmd-HKOJU5FJ.js} +15 -13
  154. package/dist/{work-comment-cmd-V5WM7LAW.js → work-comment-cmd-H3JCWQ2J.js} +18 -16
  155. package/dist/{work-demo-cmd-SWWI6AGD.js → work-demo-cmd-J4AZAIVP.js} +15 -13
  156. package/dist/{work-launch-TTGSHLY4.js → work-launch-LWDQXLGI.js} +1 -1
  157. package/dist/{work-logs-cmd-CTFBOPCI.js → work-logs-cmd-UOO4JVLG.js} +15 -13
  158. package/dist/{work-open-pr-cmd-HX2U3YBR.js → work-open-pr-cmd-QFRDDBAM.js} +17 -15
  159. package/dist/{work-pr-cmd-EI2R4FQG.js → work-pr-cmd-3Q2D5RQT.js} +16 -14
  160. package/dist/{work-proofs-cmd-QXNPHLYC.js → work-proofs-cmd-7Y3HGT7C.js} +18 -16
  161. package/dist/{work-proofs-record-72OKWEES.js → work-proofs-record-QPUM6DY4.js} +28 -26
  162. package/dist/{work-stop-cmd-7M7ZYUN2.js → work-stop-cmd-SD2ZRMSY.js} +15 -13
  163. package/package.json +1 -1
  164. package/dist/agent-setup-AOB76EDJ.js +0 -37
  165. package/dist/caller-GOY2X6QT.js +0 -20
  166. package/dist/chunk-KYDEBGJG.js +0 -402
  167. package/dist/emit-artifact-cmd-6E365VBQ.js +0 -41
  168. package/dist/emit-criteria-cmd-HWQOYZZ4.js +0 -32
  169. package/dist/find-unit-63SXQ7IM.js +0 -21
  170. package/dist/host-checks-WHW24PJR.js +0 -76
  171. package/dist/host-key-MWLXB5U5.js +0 -14
  172. package/dist/init-EZIAHBMH.js +0 -76
  173. package/dist/loop-2E34CGCX.js +0 -87
  174. package/dist/machine-6ALGG4IO.js +0 -76
  175. package/dist/runner-env-KHCONH2R.js +0 -21
  176. package/dist/settings-XB2HYBKO.js +0 -7
  177. package/dist/state-RJR4PMMX.js +0 -14
  178. package/dist/update-steps-7E4RD47J.js +0 -77
@@ -2,12 +2,12 @@
2
2
  import { createRequire } from 'node:module';
3
3
  import { EVENT_TYPES, isHumanUserTurn, INPUT_BAND_BOUNDARIES, parseAgentSession, SCHEMA_VERSION, SPEED_MAX_LENGTH, inputBandOf, BUCKET_MODEL_MAX_LENGTH } from './chunk-WUKLQWGY.js';
4
4
  import { createHash } from 'crypto';
5
- import { readFileSync, mkdirSync, statSync, copyFileSync, renameSync, unlinkSync, writeFileSync, readdirSync, stat as stat$1, unwatchFile, watchFile, watch as watch$1 } from 'fs';
5
+ import { readFileSync, mkdirSync, statSync, copyFileSync, renameSync, unlinkSync, writeFileSync, readdirSync, realpathSync, watch as watch$1 } from 'fs';
6
6
  import { type, homedir } from 'os';
7
- import * as sp2 from 'path';
7
+ import * as sp5 from 'path';
8
8
  import { join, relative, dirname, sep, resolve } from 'path';
9
9
  import { EventEmitter } from 'events';
10
- import { stat, realpath, lstat, readdir, open } from 'fs/promises';
10
+ import { readdir, stat, lstat, readlink, realpath, open } from 'fs/promises';
11
11
  import { Readable } from 'stream';
12
12
  import { execFileSync } from 'child_process';
13
13
 
@@ -26,7 +26,9 @@ var defaultOptions = {
26
26
  lstat: false,
27
27
  depth: 2147483648,
28
28
  alwaysStat: false,
29
- highWaterMark: 4096
29
+ // Throughput is flat from 16 to 65536 (traversal is I/O-bound), but
30
+ // batches of 1024+ entries survive young-gen GC and bloat RSS ~20-60%.
31
+ highWaterMark: 256
30
32
  };
31
33
  Object.freeze(defaultOptions);
32
34
  var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
@@ -66,6 +68,11 @@ var normalizeFilter = (filter) => {
66
68
  return emptyFn;
67
69
  };
68
70
  var ReaddirpStream = class extends Readable {
71
+ /**
72
+ * Directories discovered but not yet emitted from. Listings are read
73
+ * lazily (on pop, plus one prefetch) instead of eagerly on discovery:
74
+ * keeping whole listings for every queued dir balloons RAM on wide trees.
75
+ */
69
76
  parents;
70
77
  reading;
71
78
  parent;
@@ -80,14 +87,16 @@ var ReaddirpStream = class extends Readable {
80
87
  _rdOptions;
81
88
  _fileFilter;
82
89
  _directoryFilter;
90
+ _relStart;
83
91
  constructor(options = {}) {
84
92
  super({
85
93
  objectMode: true,
86
94
  autoDestroy: true,
87
- highWaterMark: options.highWaterMark
95
+ highWaterMark: options.highWaterMark ?? defaultOptions.highWaterMark
88
96
  });
89
97
  const opts = { ...defaultOptions, ...options };
90
- const { root, type } = opts;
98
+ const root = opts.root ?? defaultOptions.root;
99
+ const type = opts.type ?? defaultOptions.type;
91
100
  this._fileFilter = normalizeFilter(opts.fileFilter);
92
101
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
93
102
  const statMethod = opts.lstat ? lstat : stat;
@@ -97,14 +106,17 @@ var ReaddirpStream = class extends Readable {
97
106
  this._stat = statMethod;
98
107
  }
99
108
  this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
100
- this._wantsDir = type ? DIR_TYPES.has(type) : false;
101
- this._wantsFile = type ? FILE_TYPES.has(type) : false;
109
+ this._wantsDir = DIR_TYPES.has(type);
110
+ this._wantsFile = FILE_TYPES.has(type);
102
111
  this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
103
112
  this._root = resolve(root);
113
+ this._relStart = this._root.endsWith(sep) ? this._root.length : this._root.length + 1;
104
114
  this._isDirent = !opts.alwaysStat;
105
115
  this._statsProp = this._isDirent ? "dirent" : "stats";
106
116
  this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
107
- this.parents = [this._exploreDir(root, 1)];
117
+ const rootDir = { path: this._root, depth: 1 };
118
+ rootDir.pending = this._exploreDir(this._root, 1);
119
+ this.parents = [rootDir];
108
120
  this.reading = false;
109
121
  this.parent = void 0;
110
122
  }
@@ -119,16 +131,18 @@ var ReaddirpStream = class extends Readable {
119
131
  if (fil && fil.length > 0) {
120
132
  const { path, depth } = par;
121
133
  const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
122
- const awaited = await Promise.all(slice);
134
+ const awaited = this._isDirent ? slice : await Promise.all(slice);
123
135
  for (const entry of awaited) {
124
136
  if (!entry)
125
137
  continue;
126
138
  if (this.destroyed)
127
139
  return;
128
- const entryType = await this._getEntryType(entry);
140
+ let entryType = this._getEntryType(entry);
141
+ if (typeof entryType !== "string")
142
+ entryType = await entryType;
129
143
  if (entryType === "directory" && this._directoryFilter(entry)) {
130
144
  if (depth <= this._maxDepth) {
131
- this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
145
+ this.parents.push({ path: entry.fullPath, depth: depth + 1 });
132
146
  }
133
147
  if (this._wantsDir) {
134
148
  this.push(entry);
@@ -147,7 +161,12 @@ var ReaddirpStream = class extends Readable {
147
161
  this.push(null);
148
162
  break;
149
163
  }
150
- this.parent = await parent;
164
+ const dir = parent.pending ?? this._exploreDir(parent.path, parent.depth);
165
+ const next = this.parents[this.parents.length - 1];
166
+ if (next && !next.pending) {
167
+ next.pending = this._exploreDir(next.path, next.depth);
168
+ }
169
+ this.parent = await dir;
151
170
  if (this.destroyed)
152
171
  return;
153
172
  }
@@ -158,6 +177,18 @@ var ReaddirpStream = class extends Readable {
158
177
  this.reading = false;
159
178
  }
160
179
  }
180
+ // NOTE: native `readdir(path, { recursive: true })` was evaluated as a
181
+ // replacement for this per-directory traversal and rejected:
182
+ // - Not faster: node implements it in JS, walking directories sequentially
183
+ // just like this loop, but with extra path bookkeeping. Benchmarks
184
+ // (node 24): ~10% slower on wide trees, ~40% slower on small ones,
185
+ // parity on deep ones.
186
+ // - Much more RAM: it buffers the entire subtree listing in one array,
187
+ // instead of one directory at a time, defeating streaming.
188
+ // - Semantics diverge: it can't limit depth, can't skip directories a
189
+ // directoryFilter rejects, doesn't follow symlinked dirs, and fails
190
+ // wholesale (all entries lost) if anything in the subtree is unreadable,
191
+ // instead of emitting a 'warn' and continuing.
161
192
  async _exploreDir(path, depth) {
162
193
  let files;
163
194
  try {
@@ -167,18 +198,22 @@ var ReaddirpStream = class extends Readable {
167
198
  }
168
199
  return { files, depth, path };
169
200
  }
170
- async _formatEntry(dirent, path) {
171
- let entry;
172
- const basename3 = this._isDirent ? dirent.name : dirent;
173
- try {
174
- const fullPath = resolve(join(path, basename3));
175
- entry = { path: relative(this._root, fullPath), fullPath, basename: basename3 };
176
- entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
177
- } catch (err) {
178
- this._onError(err);
179
- return;
201
+ // Synchronous in dirent mode; returns a promise only when stats are needed.
202
+ _formatEntry(dirent, path) {
203
+ const basename5 = this._isDirent ? dirent.name : dirent;
204
+ const fullPath = join(path, basename5);
205
+ const entry = { path: fullPath.slice(this._relStart), fullPath, basename: basename5 };
206
+ if (this._isDirent) {
207
+ entry.dirent = dirent;
208
+ return entry;
180
209
  }
181
- return entry;
210
+ return this._stat(fullPath).then((stats) => {
211
+ entry.stats = stats;
212
+ return entry;
213
+ }, (err) => {
214
+ this._onError(err);
215
+ return void 0;
216
+ });
182
217
  }
183
218
  _onError(err) {
184
219
  if (isNormalFlowError(err) && !this.destroyed) {
@@ -187,8 +222,10 @@ var ReaddirpStream = class extends Readable {
187
222
  this.destroy(err);
188
223
  }
189
224
  }
190
- async _getEntryType(entry) {
191
- if (!entry && this._statsProp in entry) {
225
+ // Synchronous for regular files and directories; returns a promise only for
226
+ // symlinks, which need realpath() to be classified.
227
+ _getEntryType(entry) {
228
+ if (!entry || !(this._statsProp in entry)) {
192
229
  return "";
193
230
  }
194
231
  const stats = entry[this._statsProp];
@@ -196,28 +233,32 @@ var ReaddirpStream = class extends Readable {
196
233
  return "file";
197
234
  if (stats.isDirectory())
198
235
  return "directory";
199
- if (stats && stats.isSymbolicLink()) {
200
- const full = entry.fullPath;
201
- try {
202
- const entryRealPath = await realpath(full);
203
- const entryRealPathStats = await lstat(entryRealPath);
204
- if (entryRealPathStats.isFile()) {
205
- return "file";
206
- }
207
- if (entryRealPathStats.isDirectory()) {
208
- const len = entryRealPath.length;
209
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
210
- const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
211
- recursiveError.code = RECURSIVE_ERROR_CODE;
212
- return this._onError(recursiveError);
213
- }
214
- return "directory";
236
+ if (stats.isSymbolicLink())
237
+ return this._getSymlinkEntryType(entry);
238
+ return "";
239
+ }
240
+ async _getSymlinkEntryType(entry) {
241
+ const full = entry.fullPath;
242
+ try {
243
+ const entryRealPath = await realpath(full);
244
+ const entryRealPathStats = await lstat(entryRealPath);
245
+ if (entryRealPathStats.isFile()) {
246
+ return "file";
247
+ }
248
+ if (entryRealPathStats.isDirectory()) {
249
+ const len = entryRealPath.length;
250
+ if (full.startsWith(entryRealPath) && full[len] === sep) {
251
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
252
+ recursiveError.code = RECURSIVE_ERROR_CODE;
253
+ this._onError(recursiveError);
254
+ return "";
215
255
  }
216
- } catch (error62) {
217
- this._onError(error62);
218
- return "";
256
+ return "directory";
219
257
  }
258
+ } catch (error62) {
259
+ this._onError(error62);
220
260
  }
261
+ return "";
221
262
  }
222
263
  _includeAsFile(entry) {
223
264
  const stats = entry && entry[this._statsProp];
@@ -228,8 +269,6 @@ function readdirp(root, options = {}) {
228
269
  let type = options.entryType || options.type;
229
270
  if (type === "both")
230
271
  type = EntryTypes.FILE_DIR_TYPE;
231
- if (type)
232
- options.type = type;
233
272
  if (!root) {
234
273
  throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
235
274
  } else if (typeof root !== "string") {
@@ -237,20 +276,46 @@ function readdirp(root, options = {}) {
237
276
  } else if (type && !ALL_TYPES.includes(type)) {
238
277
  throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
239
278
  }
240
- options.root = root;
241
- return new ReaddirpStream(options);
279
+ const opts = { ...options, root };
280
+ if (type)
281
+ opts.type = type;
282
+ return new ReaddirpStream(opts);
242
283
  }
243
- var STR_DATA = "data";
244
- var STR_END = "end";
245
- var STR_CLOSE = "close";
246
- var EMPTY_FN = () => {
247
- };
248
- var pl = process.platform;
249
- var isWindows = pl === "win32";
250
- var isMacos = pl === "darwin";
251
- var isLinux = pl === "linux";
252
- var isFreeBSD = pl === "freebsd";
284
+ var platform = process.platform;
285
+ var isWindows = platform === "win32";
286
+ var isMacos = platform === "darwin";
287
+ var isLinux = platform === "linux";
253
288
  var isIBMi = type() === "OS400";
289
+ function errorCode(error62) {
290
+ return error62?.code;
291
+ }
292
+ function classifyError(error62) {
293
+ const code = errorCode(error62);
294
+ if (code === "ENOENT" || code === "ENOTDIR")
295
+ return "missing";
296
+ if (code === "EPERM" || code === "EACCES")
297
+ return "permission";
298
+ if (code === "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM")
299
+ return "recursive-unsupported";
300
+ return "other";
301
+ }
302
+ function isMissingError(error62) {
303
+ return classifyError(error62) === "missing";
304
+ }
305
+ function isPermissionError(error62) {
306
+ return classifyError(error62) === "permission";
307
+ }
308
+ function isRecursiveWatchUnsupported(error62) {
309
+ return classifyError(error62) === "recursive-unsupported";
310
+ }
311
+ var systemScheduler = Object.freeze({
312
+ now: () => Date.now(),
313
+ setTimeout: (callback, delay) => setTimeout(callback, delay),
314
+ clearTimeout: (timer) => {
315
+ if (timer)
316
+ clearTimeout(timer);
317
+ }
318
+ });
254
319
  var EVENTS = {
255
320
  ALL: "all",
256
321
  READY: "ready",
@@ -262,530 +327,1567 @@ var EVENTS = {
262
327
  RAW: "raw",
263
328
  ERROR: "error"
264
329
  };
265
- var EV = EVENTS;
266
- var THROTTLE_MODE_WATCH = "watch";
267
- var statMethods = { lstat: lstat, stat: stat };
268
- var KEY_LISTENERS = "listeners";
269
- var KEY_ERR = "errHandlers";
270
- var KEY_RAW = "rawEmitters";
271
- var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
272
- var binaryExtensions = /* @__PURE__ */ new Set([
273
- "3dm",
274
- "3ds",
275
- "3g2",
276
- "3gp",
277
- "7z",
278
- "a",
279
- "aac",
280
- "adp",
281
- "afdesign",
282
- "afphoto",
283
- "afpub",
284
- "ai",
285
- "aif",
286
- "aiff",
287
- "alz",
288
- "ape",
289
- "apk",
290
- "appimage",
291
- "ar",
292
- "arj",
293
- "asf",
294
- "au",
295
- "avi",
296
- "bak",
297
- "baml",
298
- "bh",
299
- "bin",
300
- "bk",
301
- "bmp",
302
- "btif",
303
- "bz2",
304
- "bzip2",
305
- "cab",
306
- "caf",
307
- "cgm",
308
- "class",
309
- "cmx",
310
- "cpio",
311
- "cr2",
312
- "cur",
313
- "dat",
314
- "dcm",
315
- "deb",
316
- "dex",
317
- "djvu",
318
- "dll",
319
- "dmg",
320
- "dng",
321
- "doc",
322
- "docm",
323
- "docx",
324
- "dot",
325
- "dotm",
326
- "dra",
327
- "DS_Store",
328
- "dsk",
329
- "dts",
330
- "dtshd",
331
- "dvb",
332
- "dwg",
333
- "dxf",
334
- "ecelp4800",
335
- "ecelp7470",
336
- "ecelp9600",
337
- "egg",
338
- "eol",
339
- "eot",
340
- "epub",
341
- "exe",
342
- "f4v",
343
- "fbs",
344
- "fh",
345
- "fla",
346
- "flac",
347
- "flatpak",
348
- "fli",
349
- "flv",
350
- "fpx",
351
- "fst",
352
- "fvt",
353
- "g3",
354
- "gh",
355
- "gif",
356
- "graffle",
357
- "gz",
358
- "gzip",
359
- "h261",
360
- "h263",
361
- "h264",
362
- "icns",
363
- "ico",
364
- "ief",
365
- "img",
366
- "ipa",
367
- "iso",
368
- "jar",
369
- "jpeg",
370
- "jpg",
371
- "jpgv",
372
- "jpm",
373
- "jxr",
374
- "key",
375
- "ktx",
376
- "lha",
377
- "lib",
378
- "lvp",
379
- "lz",
380
- "lzh",
381
- "lzma",
382
- "lzo",
383
- "m3u",
384
- "m4a",
385
- "m4v",
386
- "mar",
387
- "mdi",
388
- "mht",
389
- "mid",
390
- "midi",
391
- "mj2",
392
- "mka",
393
- "mkv",
394
- "mmr",
395
- "mng",
396
- "mobi",
397
- "mov",
398
- "movie",
399
- "mp3",
400
- "mp4",
401
- "mp4a",
402
- "mpeg",
403
- "mpg",
404
- "mpga",
405
- "mxu",
406
- "nef",
407
- "npx",
408
- "numbers",
409
- "nupkg",
410
- "o",
411
- "odp",
412
- "ods",
413
- "odt",
414
- "oga",
415
- "ogg",
416
- "ogv",
417
- "otf",
418
- "ott",
419
- "pages",
420
- "pbm",
421
- "pcx",
422
- "pdb",
423
- "pdf",
424
- "pea",
425
- "pgm",
426
- "pic",
427
- "png",
428
- "pnm",
429
- "pot",
430
- "potm",
431
- "potx",
432
- "ppa",
433
- "ppam",
434
- "ppm",
435
- "pps",
436
- "ppsm",
437
- "ppsx",
438
- "ppt",
439
- "pptm",
440
- "pptx",
441
- "psd",
442
- "pya",
443
- "pyc",
444
- "pyo",
445
- "pyv",
446
- "qt",
447
- "rar",
448
- "ras",
449
- "raw",
450
- "resources",
451
- "rgb",
452
- "rip",
453
- "rlc",
454
- "rmf",
455
- "rmvb",
456
- "rpm",
457
- "rtf",
458
- "rz",
459
- "s3m",
460
- "s7z",
461
- "scpt",
462
- "sgi",
463
- "shar",
464
- "snap",
465
- "sil",
466
- "sketch",
467
- "slk",
468
- "smv",
469
- "snk",
470
- "so",
471
- "stl",
472
- "suo",
473
- "sub",
474
- "swf",
475
- "tar",
476
- "tbz",
477
- "tbz2",
478
- "tga",
479
- "tgz",
480
- "thmx",
481
- "tif",
482
- "tiff",
483
- "tlz",
484
- "ttc",
485
- "ttf",
486
- "txz",
487
- "udf",
488
- "uvh",
489
- "uvi",
490
- "uvm",
491
- "uvp",
492
- "uvs",
493
- "uvu",
494
- "viv",
495
- "vob",
496
- "war",
497
- "wav",
498
- "wax",
499
- "wbmp",
500
- "wdp",
501
- "weba",
502
- "webm",
503
- "webp",
504
- "whl",
505
- "wim",
506
- "wm",
507
- "wma",
508
- "wmv",
509
- "wmx",
510
- "woff",
511
- "woff2",
512
- "wrm",
513
- "wvx",
514
- "xbm",
515
- "xif",
516
- "xla",
517
- "xlam",
518
- "xls",
519
- "xlsb",
520
- "xlsm",
521
- "xlsx",
522
- "xlt",
523
- "xltm",
524
- "xltx",
525
- "xm",
526
- "xmind",
527
- "xpi",
528
- "xpm",
529
- "xwd",
530
- "xz",
531
- "z",
532
- "zip",
533
- "zipx"
534
- ]);
535
- var isBinaryPath = (filePath) => binaryExtensions.has(sp2.extname(filePath).slice(1).toLowerCase());
536
- var foreach = (val, fn) => {
537
- if (val instanceof Set) {
538
- val.forEach(fn);
539
- } else {
540
- fn(val);
330
+ var BACK_SLASH_RE = /\\/g;
331
+ var DOUBLE_SLASH_RE = /\/\//g;
332
+ function normalizePath(path) {
333
+ if (typeof path !== "string")
334
+ throw new TypeError("string expected");
335
+ const unix = path.replace(BACK_SLASH_RE, "/");
336
+ const unc = unix.startsWith("//");
337
+ let normalized = sp5.normalize(unix).replace(BACK_SLASH_RE, "/").replace(DOUBLE_SLASH_RE, "/");
338
+ if (unc && !normalized.startsWith("//"))
339
+ normalized = `/${normalized}`;
340
+ return normalized;
341
+ }
342
+ function statIdentity(stats) {
343
+ if (typeof stats.mtimeMs !== "bigint")
344
+ return stats;
345
+ const big = stats;
346
+ const sec = big.mtimeNs / 1000000000n;
347
+ const nsec = big.mtimeNs % 1000000000n;
348
+ const mtimeMs = Number(sec) * 1e3 + Number(nsec) / 1e6;
349
+ return { size: Number(big.size), mtimeMs, ino: Number(big.ino) };
350
+ }
351
+ function logicalPathKey(path) {
352
+ const resolved = sp5.resolve(path);
353
+ return isWindows || !resolved.includes("\\") ? resolved.replace(BACK_SLASH_RE, "/") : normalizePath(resolved);
354
+ }
355
+ function isInsideRelativePath(relative7) {
356
+ return relative7 !== ".." && !relative7.startsWith(`..${sp5.sep}`) && !sp5.isAbsolute(relative7);
357
+ }
358
+ function isSameOrInside(root, candidate) {
359
+ const relative7 = sp5.relative(root, candidate);
360
+ return relative7 === "" || isInsideRelativePath(relative7);
361
+ }
362
+ function isStrictlyInside(root, candidate) {
363
+ const relative7 = sp5.relative(root, candidate);
364
+ return relative7 !== "" && isInsideRelativePath(relative7);
365
+ }
366
+ function isMatcherObject(matcher) {
367
+ return typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
368
+ }
369
+ function cloneOwnedMatcher(matcher) {
370
+ if (matcher instanceof RegExp)
371
+ return new RegExp(matcher.source, matcher.flags);
372
+ if (isMatcherObject(matcher))
373
+ return Object.freeze({ ...matcher });
374
+ return matcher;
375
+ }
376
+ function compileMatcher(matcher) {
377
+ if (typeof matcher === "function")
378
+ return matcher;
379
+ if (typeof matcher === "string")
380
+ return (candidate) => matcher === candidate;
381
+ if (matcher instanceof RegExp) {
382
+ return (candidate) => {
383
+ matcher.lastIndex = 0;
384
+ return matcher.test(candidate);
385
+ };
541
386
  }
542
- };
543
- var addAndConvert = (main, prop, item) => {
544
- let container = main[prop];
545
- if (!(container instanceof Set)) {
546
- main[prop] = container = /* @__PURE__ */ new Set([container]);
387
+ if (isMatcherObject(matcher)) {
388
+ return (candidate) => matcher.path === candidate || Boolean(matcher.recursive && isStrictlyInside(matcher.path, candidate));
547
389
  }
548
- container.add(item);
549
- };
550
- var clearItem = (cont) => (key) => {
551
- const set2 = cont[key];
552
- if (set2 instanceof Set) {
553
- set2.clear();
554
- } else {
555
- delete cont[key];
390
+ return () => false;
391
+ }
392
+ function compileMatchers(matchers) {
393
+ const patterns = matchers.map(compileMatcher);
394
+ return (candidate, stats) => {
395
+ if (patterns.length === 0)
396
+ return false;
397
+ const normalized = normalizePath(candidate);
398
+ return patterns.some((pattern) => pattern(normalized, stats));
399
+ };
400
+ }
401
+ function normalizeMatcher(matcher, cwd = process.cwd()) {
402
+ if (typeof matcher === "string") {
403
+ return normalizePath(sp5.isAbsolute(matcher) ? matcher : sp5.join(cwd, matcher));
556
404
  }
557
- };
558
- var delFromSet = (main, prop, item) => {
559
- const container = main[prop];
560
- if (container instanceof Set) {
561
- container.delete(item);
562
- } else if (container === item) {
563
- delete main[prop];
405
+ if (isMatcherObject(matcher)) {
406
+ return {
407
+ path: normalizePath(sp5.isAbsolute(matcher.path) ? matcher.path : sp5.join(cwd, matcher.path)),
408
+ recursive: matcher.recursive
409
+ };
410
+ }
411
+ return matcher;
412
+ }
413
+ var REPLACER_RE = /^\.[/\\]/;
414
+ var WatchHelper = class _WatchHelper {
415
+ watchPath;
416
+ followSymlinks;
417
+ recursiveRoot;
418
+ recursiveDisabled;
419
+ observationTrigger;
420
+ realpathAncestry;
421
+ pathGeneration;
422
+ context;
423
+ constructor(path, follow, context) {
424
+ this.context = context;
425
+ this.watchPath = path.replace(REPLACER_RE, "");
426
+ this.followSymlinks = follow;
427
+ this.realpathAncestry = /* @__PURE__ */ new Set();
428
+ this.pathGeneration = context.capturePathGeneration();
429
+ }
430
+ fork(path) {
431
+ const helper = new _WatchHelper(path, this.followSymlinks, this.context);
432
+ helper.recursiveRoot = this.recursiveRoot;
433
+ helper.recursiveDisabled = this.recursiveDisabled;
434
+ helper.observationTrigger = this.observationTrigger;
435
+ helper.realpathAncestry = new Set(this.realpathAncestry);
436
+ helper.pathGeneration = this.pathGeneration;
437
+ return helper;
438
+ }
439
+ withObservation(trigger) {
440
+ const helper = Object.create(this);
441
+ helper.observationTrigger = trigger;
442
+ return helper;
443
+ }
444
+ filterPath(entry) {
445
+ return entry.stats?.isSymbolicLink() ? this.filterDir(entry) : this.context.isntIgnored(sp5.join(this.watchPath, entry.path), entry.stats);
446
+ }
447
+ filterDir(entry) {
448
+ return this.context.isntIgnored(sp5.join(this.watchPath, entry.path), entry.stats);
564
449
  }
565
450
  };
566
- var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
567
- var FsWatchInstances = /* @__PURE__ */ new Map();
568
- function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
569
- const handleEvent = (rawEvent, evPath) => {
570
- listener(path);
571
- emitRaw(rawEvent, evPath, { watchedPath: path });
572
- if (evPath && path !== evPath) {
573
- fsWatchBroadcast(sp2.resolve(path, evPath), KEY_LISTENERS, sp2.join(path, evPath));
451
+
452
+ // ../../node_modules/chokidar/backend.js
453
+ var nextGeneration = 0;
454
+ function allocateSharedResourceGeneration() {
455
+ return ++nextGeneration;
456
+ }
457
+ function attachSharedSubscriber(resource, subscriber) {
458
+ if (resource.closed)
459
+ return false;
460
+ resource.subscribers.add(subscriber);
461
+ return true;
462
+ }
463
+ function detachSharedSubscriber(resource, subscriber) {
464
+ if (resource.closed || !resource.subscribers.delete(subscriber))
465
+ return;
466
+ return resource.subscribers.size > 0 ? "remaining" : "last";
467
+ }
468
+ function invalidateSharedResource(resource) {
469
+ if (resource.closed)
470
+ return;
471
+ resource.closed = true;
472
+ const subscribers = [...resource.subscribers];
473
+ resource.subscribers.clear();
474
+ return subscribers;
475
+ }
476
+ function reconfigureWatcherPersistence(resource) {
477
+ const persistent = [...resource.subscribers].some((subscriber) => subscriber.persistent);
478
+ if (persistent)
479
+ resource.watcher.ref();
480
+ else
481
+ resource.watcher.unref();
482
+ }
483
+ function invalidateWatcherResource(resource, registry2) {
484
+ const subscribers = invalidateSharedResource(resource);
485
+ if (!subscribers)
486
+ return;
487
+ if (registry2.get(resource.resource) === resource)
488
+ registry2.delete(resource.resource);
489
+ resource.watcher.close();
490
+ return subscribers;
491
+ }
492
+ function attachWatcherSubscriber(resource, subscriber) {
493
+ attachSharedSubscriber(resource, subscriber);
494
+ reconfigureWatcherPersistence(resource);
495
+ }
496
+ function createWatcherSubscription(resource, subscriber, registry2) {
497
+ let closed = false;
498
+ return {
499
+ resource: resource.resource,
500
+ close: () => {
501
+ if (closed)
502
+ return;
503
+ closed = true;
504
+ const remaining = detachSharedSubscriber(resource, subscriber);
505
+ if (remaining === "remaining")
506
+ reconfigureWatcherPersistence(resource);
507
+ else if (remaining === "last" && registry2.get(resource.resource) === resource) {
508
+ invalidateWatcherResource(resource, registry2);
509
+ }
574
510
  }
575
511
  };
512
+ }
513
+ function selectBackend(options) {
514
+ const preferRecursive = options.backend === "native-recursive" || options.backend === "auto" && (isMacos || isWindows);
515
+ const kind = options.backend === "polling" ? "polling" : preferRecursive && options.depth === void 0 ? "native-recursive-preferred" : "native-per-directory";
516
+ return Object.freeze({
517
+ kind,
518
+ polling: kind === "polling",
519
+ recursive: kind === "native-recursive-preferred",
520
+ perDirectory: kind === "native-per-directory"
521
+ });
522
+ }
523
+ var EV = EVENTS;
524
+ var POLL_DIRECTORY_RECHECK_DELAY = 1e3;
525
+ function backendNow() {
526
+ return performance.now();
527
+ }
528
+ function toNativeWatchPath(path) {
529
+ const nativePath = sp5.normalize(path);
530
+ if (!isWindows)
531
+ return nativePath;
576
532
  try {
577
- return watch$1(path, {
533
+ return realpathSync.native(nativePath);
534
+ } catch {
535
+ return nativePath;
536
+ }
537
+ }
538
+ function projectNativeRelativePath(nativeRoot, relativePath) {
539
+ if (!isWindows || relativePath === null || !sp5.isAbsolute(relativePath))
540
+ return relativePath;
541
+ const root = sp5.normalize(sp5.toNamespacedPath(nativeRoot));
542
+ const candidate = sp5.normalize(sp5.toNamespacedPath(relativePath));
543
+ const projected = sp5.relative(root, candidate);
544
+ if (!isSameOrInside(root, candidate))
545
+ return relativePath;
546
+ return projected || null;
547
+ }
548
+ var FsWatchInstances = /* @__PURE__ */ new Map();
549
+ function systemNativeWatchFactory(path, options, listener) {
550
+ return watch$1(path, options, listener);
551
+ }
552
+ var nativeWatchFactory = systemNativeWatchFactory;
553
+ var RecursiveWatchInstances = /* @__PURE__ */ new Map();
554
+ var recursiveWatchUnsupported = false;
555
+ function systemRecursiveWatchFactory(path, options, listener) {
556
+ return watch$1(path, options, listener);
557
+ }
558
+ var recursiveWatchFactory = systemRecursiveWatchFactory;
559
+ function failRecursiveResource(resource, error62) {
560
+ const subscribers = invalidateWatcherResource(resource, RecursiveWatchInstances);
561
+ if (!subscribers)
562
+ return;
563
+ subscribers.forEach((subscriber) => subscriber.failure(error62));
564
+ }
565
+ function subscribeRecursiveNative(path, persistent, handlers, signal) {
566
+ if (recursiveWatchUnsupported)
567
+ return { kind: "unsupported" };
568
+ const resourceKey = sp5.resolve(path);
569
+ const subscriber = {
570
+ ...handlers,
571
+ watchedPath: path,
572
+ persistent
573
+ };
574
+ let resource = RecursiveWatchInstances.get(resourceKey);
575
+ if (!resource) {
576
+ let watcher;
577
+ let created;
578
+ const nativePath = toNativeWatchPath(path);
579
+ try {
580
+ watcher = recursiveWatchFactory(nativePath, { persistent, recursive: true }, (rawEvent, relativePath) => {
581
+ const active = created;
582
+ if (!active || active.closed)
583
+ return;
584
+ if (RecursiveWatchInstances.get(resourceKey) !== active)
585
+ return;
586
+ const trigger = {
587
+ kind: "native",
588
+ resource: resourceKey,
589
+ rawEvent,
590
+ relativePath: projectNativeRelativePath(nativePath, relativePath),
591
+ sequence: ++active.sequence,
592
+ observedAt: backendNow()
593
+ };
594
+ active.subscribers.forEach((current) => {
595
+ current.rawEmitter(rawEvent, relativePath, { watchedPath: current.watchedPath });
596
+ current.publish(trigger);
597
+ });
598
+ });
599
+ } catch (error62) {
600
+ if (isRecursiveWatchUnsupported(error62)) {
601
+ recursiveWatchUnsupported = true;
602
+ return { kind: "unsupported" };
603
+ }
604
+ return { kind: "failed", error: error62 };
605
+ }
606
+ created = resource = {
607
+ resource: resourceKey,
608
+ generation: allocateSharedResourceGeneration(),
609
+ subscribers: /* @__PURE__ */ new Set(),
610
+ closed: false,
611
+ watcher,
612
+ sequence: 0
613
+ };
614
+ RecursiveWatchInstances.set(resourceKey, resource);
615
+ watcher.on(EV.ERROR, (error62) => failRecursiveResource(resource, error62));
616
+ }
617
+ attachWatcherSubscriber(resource, subscriber);
618
+ const subscription = createWatcherSubscription(resource, subscriber, RecursiveWatchInstances);
619
+ if (signal.aborted)
620
+ void subscription.close();
621
+ return { kind: "subscribed", subscription };
622
+ }
623
+ function createFsWatchInstance(path, options, listener, errHandler) {
624
+ try {
625
+ return nativeWatchFactory(path, {
578
626
  persistent: options.persistent
579
- }, handleEvent);
627
+ }, listener);
580
628
  } catch (error62) {
581
629
  errHandler(error62);
582
630
  return void 0;
583
631
  }
584
632
  }
585
- var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
586
- const cont = FsWatchInstances.get(fullPath);
587
- if (!cont)
633
+ function publishNativeTrigger(cont, rawEvent, relativePath, emitRaw, rawRelativePath = relativePath) {
634
+ if (cont.closed || FsWatchInstances.get(cont.resource) !== cont)
588
635
  return;
589
- foreach(cont[listenerType], (listener) => {
590
- listener(val1, val2, val3);
636
+ const trigger = {
637
+ kind: "native",
638
+ resource: cont.resource,
639
+ rawEvent,
640
+ relativePath,
641
+ sequence: ++cont.sequence,
642
+ observedAt: backendNow()
643
+ };
644
+ cont.subscribers.forEach((subscriber) => {
645
+ if (emitRaw) {
646
+ subscriber.rawEmitter(rawEvent, rawRelativePath, { watchedPath: subscriber.watchedPath });
647
+ }
648
+ subscriber.publish(trigger);
591
649
  });
592
- };
593
- var setFsWatchListener = (path, fullPath, options, handlers) => {
594
- const { listener, errHandler, rawEmitter } = handlers;
595
- let cont = FsWatchInstances.get(fullPath);
596
- let watcher;
597
- if (!options.persistent) {
598
- watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
599
- if (!watcher)
650
+ }
651
+ function broadcastNativeError(cont, error62) {
652
+ if (cont.closed || FsWatchInstances.get(cont.resource) !== cont)
653
+ return;
654
+ cont.subscribers.forEach((subscriber) => subscriber.errHandler(error62));
655
+ }
656
+ function closeFailedNativeResource(cont, error62) {
657
+ const subscribers = invalidateWatcherResource(cont, FsWatchInstances);
658
+ subscribers?.forEach((subscriber) => subscriber.failure?.(error62));
659
+ }
660
+ async function handleNativeError(path, cont, error62) {
661
+ if (isWindows && error62.code === "EPERM") {
662
+ try {
663
+ const fd = await open(path, "r");
664
+ await fd.close();
665
+ broadcastNativeError(cont, error62);
666
+ } catch {
667
+ publishNativeTrigger(cont, "rename", null, false);
668
+ }
669
+ } else {
670
+ broadcastNativeError(cont, error62);
671
+ }
672
+ closeFailedNativeResource(cont, error62);
673
+ }
674
+ async function retireIfSelfRemoved(cont, nativePath) {
675
+ try {
676
+ await lstat(sp5.join(nativePath, sp5.basename(nativePath)));
677
+ return;
678
+ } catch (error62) {
679
+ if (!isMissingError(error62))
600
680
  return;
601
- return watcher.close.bind(watcher);
602
681
  }
682
+ try {
683
+ if (!(await stat(nativePath)).isDirectory())
684
+ return;
685
+ } catch {
686
+ return;
687
+ }
688
+ if (cont.closed || FsWatchInstances.get(cont.resource) !== cont)
689
+ return;
690
+ closeFailedNativeResource(cont, new Error(`Watched directory was replaced: ${nativePath}`));
691
+ }
692
+ function createNativeContainer(path, nativePath, resourceKey, options, subscriber) {
693
+ let cont;
694
+ const watcher = createFsWatchInstance(nativePath, options, (rawEvent, relativePath) => {
695
+ const projectedPath = projectNativeRelativePath(nativePath, relativePath);
696
+ publishNativeTrigger(cont, rawEvent, projectedPath, true, relativePath);
697
+ if (isLinux && rawEvent === "rename" && relativePath === sp5.basename(nativePath)) {
698
+ void retireIfSelfRemoved(cont, nativePath);
699
+ }
700
+ }, subscriber.errHandler);
701
+ if (!watcher)
702
+ return;
703
+ cont = {
704
+ resource: resourceKey,
705
+ generation: allocateSharedResourceGeneration(),
706
+ subscribers: /* @__PURE__ */ new Set([subscriber]),
707
+ closed: false,
708
+ watcher,
709
+ sequence: 0
710
+ };
711
+ FsWatchInstances.set(resourceKey, cont);
712
+ watcher.on(EV.ERROR, (error62) => {
713
+ void handleNativeError(path, cont, error62);
714
+ });
715
+ return cont;
716
+ }
717
+ function setFsWatchListener(path, fullPath, options, handlers, signal) {
718
+ const resourceKey = fullPath;
719
+ const subscriber = {
720
+ ...handlers,
721
+ watchedPath: path,
722
+ persistent: options.persistent ?? true
723
+ };
724
+ let cont = FsWatchInstances.get(resourceKey);
603
725
  if (cont) {
604
- addAndConvert(cont, KEY_LISTENERS, listener);
605
- addAndConvert(cont, KEY_ERR, errHandler);
606
- addAndConvert(cont, KEY_RAW, rawEmitter);
726
+ attachWatcherSubscriber(cont, subscriber);
607
727
  } else {
608
- watcher = createFsWatchInstance(
609
- path,
610
- options,
611
- fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
612
- errHandler,
613
- // no need to use broadcast here
614
- fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
615
- );
616
- if (!watcher)
728
+ cont = createNativeContainer(path, toNativeWatchPath(path), resourceKey, options, subscriber);
729
+ if (!cont)
617
730
  return;
618
- watcher.on(EV.ERROR, async (error62) => {
619
- const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
620
- if (cont)
621
- cont.watcherUnusable = true;
622
- if (isWindows && error62.code === "EPERM") {
731
+ }
732
+ const subscription = createWatcherSubscription(cont, subscriber, FsWatchInstances);
733
+ if (signal.aborted) {
734
+ void subscription.close();
735
+ return;
736
+ }
737
+ return subscription;
738
+ }
739
+ var MISSING_POLL_OBSERVATION = Object.freeze({ missing: true });
740
+ var PollingInstances = /* @__PURE__ */ new Map();
741
+ function isMissingObservation(observation) {
742
+ return "missing" in observation;
743
+ }
744
+ function observationsDiffer(previous, current) {
745
+ const previousMissing = isMissingObservation(previous);
746
+ const currentMissing = isMissingObservation(current);
747
+ if (previousMissing || currentMissing)
748
+ return previousMissing !== currentMissing;
749
+ const reliableInodeChanged = !isWindows && previous.ino !== 0 && current.ino !== 0 && previous.ino !== current.ino;
750
+ return previous.size !== current.size || previous.mtimeMs !== current.mtimeMs || reliableInodeChanged;
751
+ }
752
+ function setTimerPersistence(resource) {
753
+ if (!resource.timer)
754
+ return;
755
+ if (resource.persistent)
756
+ resource.timer.ref();
757
+ else
758
+ resource.timer.unref();
759
+ }
760
+ function schedulePoll(resource, delay = resource.interval) {
761
+ if (resource.closed || resource.subscribers.size === 0)
762
+ return;
763
+ resource.timer = resource.scheduler.setTimeout(() => {
764
+ resource.timer = void 0;
765
+ const currentPoll = pollResource(resource);
766
+ resource.currentPoll = currentPoll;
767
+ void currentPoll.then(() => {
768
+ if (resource.currentPoll === currentPoll)
769
+ resource.currentPoll = void 0;
770
+ }, () => {
771
+ if (resource.currentPoll === currentPoll)
772
+ resource.currentPoll = void 0;
773
+ });
774
+ }, delay);
775
+ setTimerPersistence(resource);
776
+ }
777
+ async function pollResource(resource) {
778
+ if (resource.closed || resource.running || resource.subscribers.size === 0)
779
+ return;
780
+ resource.running = true;
781
+ const startedAt = resource.scheduler.now();
782
+ let current;
783
+ try {
784
+ current = await stat(resource.resource);
785
+ } catch (error62) {
786
+ if (isMissingError(error62)) {
787
+ current = MISSING_POLL_OBSERVATION;
788
+ } else {
789
+ resource.subscribers.forEach((subscriber) => subscriber.errHandler(error62));
790
+ }
791
+ }
792
+ if (!resource.closed && current) {
793
+ const previous = resource.previous;
794
+ resource.previous = current;
795
+ const now = resource.scheduler.now();
796
+ const changed = previous && observationsDiffer(previous, current);
797
+ const directoryReplayDue = resource.directoryReplayAt !== void 0 && now >= resource.directoryReplayAt;
798
+ if (!isMissingObservation(current) && current.isDirectory()) {
799
+ if (changed)
800
+ resource.directoryReplayAt = now + POLL_DIRECTORY_RECHECK_DELAY;
801
+ else if (directoryReplayDue)
802
+ resource.directoryReplayAt = void 0;
803
+ } else {
804
+ resource.directoryReplayAt = void 0;
805
+ }
806
+ if (previous && (changed || directoryReplayDue)) {
807
+ const trigger = {
808
+ kind: "poll",
809
+ resource: resource.resource,
810
+ current,
811
+ previous,
812
+ sequence: ++resource.sequence,
813
+ observedAt: resource.scheduler.now()
814
+ };
815
+ resource.subscribers.forEach((subscriber) => {
816
+ subscriber.rawEmitter(EV.CHANGE, resource.resource, { current, previous });
817
+ subscriber.publish(trigger);
818
+ });
819
+ }
820
+ }
821
+ resource.running = false;
822
+ if (!resource.closed && resource.subscribers.size > 0) {
823
+ const elapsed = resource.scheduler.now() - startedAt;
824
+ schedulePoll(resource, Math.max(0, resource.interval - elapsed));
825
+ }
826
+ }
827
+ function reconfigurePollResource(resource) {
828
+ if (resource.closed || resource.subscribers.size === 0)
829
+ return;
830
+ const interval = Math.min(...[...resource.subscribers].map((subscriber) => subscriber.interval));
831
+ const persistent = [...resource.subscribers].some((subscriber) => subscriber.persistent);
832
+ const intervalChanged = resource.interval !== interval;
833
+ resource.interval = interval;
834
+ resource.persistent = persistent;
835
+ if (resource.timer && intervalChanged) {
836
+ resource.scheduler.clearTimeout(resource.timer);
837
+ resource.timer = void 0;
838
+ schedulePoll(resource);
839
+ } else if (resource.timer) {
840
+ setTimerPersistence(resource);
841
+ } else if (!resource.running) {
842
+ schedulePoll(resource);
843
+ }
844
+ }
845
+ function setPollingListener(path, fullPath, options, scheduler, handlers, initialStats, signal) {
846
+ const resourceKey = fullPath;
847
+ const subscriber = { watchedPath: path, ...options, ...handlers };
848
+ let resources = PollingInstances.get(resourceKey);
849
+ if (!resources) {
850
+ resources = /* @__PURE__ */ new Map();
851
+ PollingInstances.set(resourceKey, resources);
852
+ }
853
+ let resource = resources.get(scheduler);
854
+ if (!resource) {
855
+ resource = {
856
+ resource: resourceKey,
857
+ generation: allocateSharedResourceGeneration(),
858
+ scheduler,
859
+ subscribers: /* @__PURE__ */ new Set(),
860
+ interval: options.interval,
861
+ persistent: options.persistent,
862
+ previous: initialStats,
863
+ running: false,
864
+ closed: false,
865
+ sequence: 0
866
+ };
867
+ resources.set(scheduler, resource);
868
+ } else if (!resource.previous && initialStats) {
869
+ resource.previous = initialStats;
870
+ }
871
+ resource.subscribers.add(subscriber);
872
+ reconfigurePollResource(resource);
873
+ let closed = false;
874
+ let closePromise;
875
+ const subscription = {
876
+ resource: resourceKey,
877
+ close: () => {
878
+ if (closePromise)
879
+ return closePromise;
880
+ closePromise = (async () => {
881
+ if (closed)
882
+ return;
883
+ closed = true;
884
+ resource.subscribers.delete(subscriber);
885
+ if (resource.subscribers.size > 0) {
886
+ reconfigurePollResource(resource);
887
+ return;
888
+ }
889
+ if (resource.closed)
890
+ return;
891
+ resource.closed = true;
892
+ if (resource.timer)
893
+ resource.scheduler.clearTimeout(resource.timer);
894
+ resource.timer = void 0;
895
+ const currentResources = PollingInstances.get(resourceKey);
896
+ if (currentResources?.get(scheduler) === resource) {
897
+ currentResources.delete(scheduler);
898
+ if (currentResources.size === 0)
899
+ PollingInstances.delete(resourceKey);
900
+ }
901
+ if (resource.currentPoll) {
902
+ await Promise.allSettled([resource.currentPoll]);
903
+ }
904
+ })();
905
+ return closePromise;
906
+ }
907
+ };
908
+ if (signal.aborted) {
909
+ void subscription.close();
910
+ return;
911
+ }
912
+ return subscription;
913
+ }
914
+ var LifecycleScope = class {
915
+ state = "OPEN";
916
+ generation = 0;
917
+ abortController = new AbortController();
918
+ tasks = /* @__PURE__ */ new Set();
919
+ closers = /* @__PURE__ */ new Map();
920
+ onTaskSettled;
921
+ onTaskError;
922
+ constructor(onTaskSettled, onTaskError) {
923
+ this.onTaskSettled = onTaskSettled;
924
+ this.onTaskError = onTaskError;
925
+ }
926
+ isActive(generation) {
927
+ return this.state === "OPEN" && this.generation === generation;
928
+ }
929
+ track(task) {
930
+ const tracked = Promise.resolve(task).finally(() => {
931
+ this.tasks.delete(tracked);
932
+ this.onTaskSettled();
933
+ });
934
+ this.tasks.add(tracked);
935
+ void tracked.catch(this.onTaskError);
936
+ return tracked;
937
+ }
938
+ addCloser(key, closer) {
939
+ const existing = this.closers.get(key);
940
+ if (existing)
941
+ existing.push(closer);
942
+ else
943
+ this.closers.set(key, [closer]);
944
+ }
945
+ takeClosers(key) {
946
+ const closers = this.closers.get(key) ?? [];
947
+ this.closers.delete(key);
948
+ return closers;
949
+ }
950
+ beginClose() {
951
+ if (this.state !== "OPEN")
952
+ return [];
953
+ this.state = "CLOSING";
954
+ this.generation += 1;
955
+ this.abortController.abort();
956
+ const closing = [];
957
+ this.closers.forEach((closers) => {
958
+ closers.forEach((closer) => {
623
959
  try {
624
- const fd = await open(path, "r");
625
- await fd.close();
626
- broadcastErr(error62);
627
- } catch (err) {
960
+ closing.push(Promise.resolve(closer()));
961
+ } catch (error62) {
962
+ closing.push(Promise.reject(error62));
628
963
  }
629
- } else {
630
- broadcastErr(error62);
631
- }
964
+ });
632
965
  });
633
- cont = {
634
- listeners: listener,
635
- errHandlers: errHandler,
636
- rawEmitters: rawEmitter,
637
- watcher
966
+ this.closers.clear();
967
+ return closing;
968
+ }
969
+ async drain() {
970
+ while (this.tasks.size > 0) {
971
+ await Promise.allSettled([...this.tasks]);
972
+ }
973
+ }
974
+ finishClose() {
975
+ this.state = "CLOSED";
976
+ }
977
+ };
978
+ function IGNORE_RECONCILIATION_ERROR() {
979
+ }
980
+ function resolveRecursiveCandidate(root, relativePath) {
981
+ if (sp5.isAbsolute(relativePath))
982
+ return;
983
+ const absoluteRoot = sp5.resolve(root);
984
+ const absoluteCandidate = sp5.resolve(absoluteRoot, relativePath);
985
+ if (!isSameOrInside(absoluteRoot, absoluteCandidate))
986
+ return;
987
+ return sp5.join(root, relativePath);
988
+ }
989
+ var ReconciliationQueue = class {
990
+ queues = /* @__PURE__ */ new Map();
991
+ pending = /* @__PURE__ */ new Map();
992
+ lifecycle;
993
+ constructor(lifecycle) {
994
+ this.lifecycle = lifecycle;
995
+ }
996
+ enqueue(scope, work, coalescePath = scope) {
997
+ const key = logicalPathKey(scope);
998
+ const pendingKey = coalescePath === false ? void 0 : `${key}\0${logicalPathKey(coalescePath)}`;
999
+ const existing = pendingKey ? this.pending.get(pendingKey) : void 0;
1000
+ if (existing) {
1001
+ existing.work = work;
1002
+ existing.replay = true;
1003
+ return existing.promise;
1004
+ }
1005
+ const generation = this.lifecycle.generation;
1006
+ const reconciliation = {
1007
+ promise: Promise.resolve(),
1008
+ work,
1009
+ replay: false
638
1010
  };
639
- FsWatchInstances.set(fullPath, cont);
640
- }
641
- return () => {
642
- delFromSet(cont, KEY_LISTENERS, listener);
643
- delFromSet(cont, KEY_ERR, errHandler);
644
- delFromSet(cont, KEY_RAW, rawEmitter);
645
- if (isEmptySet(cont.listeners)) {
646
- cont.watcher.close();
647
- FsWatchInstances.delete(fullPath);
648
- HANDLER_KEYS.forEach(clearItem(cont));
649
- cont.watcher = void 0;
650
- Object.freeze(cont);
1011
+ const previous = this.queues.get(key) ?? Promise.resolve();
1012
+ const task = previous.catch(IGNORE_RECONCILIATION_ERROR).then(async () => {
1013
+ do {
1014
+ const currentWork = reconciliation.work;
1015
+ reconciliation.replay = false;
1016
+ if (!this.lifecycle.isActive(generation))
1017
+ return;
1018
+ await currentWork();
1019
+ } while (reconciliation.replay);
1020
+ }).finally(() => {
1021
+ if (this.queues.get(key) === task)
1022
+ this.queues.delete(key);
1023
+ if (pendingKey && this.pending.get(pendingKey) === reconciliation) {
1024
+ this.pending.delete(pendingKey);
1025
+ }
1026
+ });
1027
+ this.queues.set(key, task);
1028
+ const tracked = this.lifecycle.track(task);
1029
+ reconciliation.promise = tracked;
1030
+ if (pendingKey)
1031
+ this.pending.set(pendingKey, reconciliation);
1032
+ return tracked;
1033
+ }
1034
+ forgetPending(predicate) {
1035
+ for (const key of this.pending.keys()) {
1036
+ const [scope, candidate] = key.split("\0", 2);
1037
+ if (predicate(scope, candidate))
1038
+ this.pending.delete(key);
651
1039
  }
652
- };
1040
+ }
1041
+ clear() {
1042
+ this.queues.clear();
1043
+ this.pending.clear();
1044
+ }
653
1045
  };
654
- var FsWatchFileInstances = /* @__PURE__ */ new Map();
655
- var setFsWatchFileListener = (path, fullPath, options, handlers) => {
656
- const { listener, rawEmitter } = handlers;
657
- let cont = FsWatchFileInstances.get(fullPath);
658
- const copts = cont && cont.options;
659
- if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
660
- unwatchFile(fullPath);
661
- cont = void 0;
1046
+ var CURRENT = ".";
1047
+ var PARENT = "..";
1048
+ var RECURSIVE_CREATE_BURST_WINDOW = 25;
1049
+ var RECURSIVE_WRITE_BURST_WINDOW = 10;
1050
+ var INITIAL_OBSERVATION_FACT = Object.freeze({
1051
+ size: 0,
1052
+ mtimeMs: 0,
1053
+ ino: 0,
1054
+ kind: "other",
1055
+ initialRecursive: true
1056
+ });
1057
+ function statKind(stats) {
1058
+ return stats.isSymbolicLink() ? "symlink" : stats.isDirectory() ? "directory" : stats.isFile() ? "file" : "other";
1059
+ }
1060
+ function sameStatFact(fact, stats) {
1061
+ const current = statIdentity(stats);
1062
+ return fact?.size === current.size && fact.mtimeMs === current.mtimeMs && fact.ino === current.ino && fact.kind === statKind(stats);
1063
+ }
1064
+ function withinWindow(fact, trigger, window) {
1065
+ return fact?.observedAt !== void 0 && trigger.observedAt >= fact.observedAt && trigger.observedAt - fact.observedAt <= window;
1066
+ }
1067
+ var DirEntry = class {
1068
+ path;
1069
+ items = /* @__PURE__ */ new Set();
1070
+ constructor(dir) {
1071
+ this.path = dir;
662
1072
  }
663
- if (cont) {
664
- addAndConvert(cont, KEY_LISTENERS, listener);
665
- addAndConvert(cont, KEY_RAW, rawEmitter);
666
- } else {
667
- cont = {
668
- listeners: listener,
669
- rawEmitters: rawEmitter,
670
- options,
671
- watcher: watchFile(fullPath, options, (curr, prev) => {
672
- foreach(cont.rawEmitters, (rawEmitter2) => {
673
- rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
674
- });
675
- const currmtime = curr.mtimeMs;
676
- if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
677
- foreach(cont.listeners, (listener2) => listener2(path, curr));
1073
+ add(item) {
1074
+ if (item !== CURRENT && item !== PARENT && item !== "")
1075
+ this.items.add(item);
1076
+ }
1077
+ /** Returns true when removing `item` left the directory empty. */
1078
+ remove(item) {
1079
+ return this.items.delete(item) && this.items.size === 0;
1080
+ }
1081
+ has(item) {
1082
+ return this.items.has(item);
1083
+ }
1084
+ getChildren() {
1085
+ return [...this.items];
1086
+ }
1087
+ dispose() {
1088
+ this.items.clear();
1089
+ this.path = "";
1090
+ }
1091
+ };
1092
+ var TreeState = class {
1093
+ watched = /* @__PURE__ */ new Map();
1094
+ observed = /* @__PURE__ */ new Map();
1095
+ symlinkPaths = /* @__PURE__ */ new Map();
1096
+ recursiveRoots = /* @__PURE__ */ new Set();
1097
+ observesNative;
1098
+ constructor(observesNative) {
1099
+ this.observesNative = observesNative;
1100
+ }
1101
+ getDirectory(directory) {
1102
+ const dir = sp5.resolve(directory);
1103
+ const key = logicalPathKey(dir);
1104
+ let entry = this.watched.get(key);
1105
+ if (!entry) {
1106
+ entry = new DirEntry(dir);
1107
+ this.watched.set(key, entry);
1108
+ }
1109
+ return entry;
1110
+ }
1111
+ /** Looks up a directory entry without creating one. */
1112
+ peekDirectory(directory) {
1113
+ return this.watched.get(logicalPathKey(sp5.resolve(directory)));
1114
+ }
1115
+ recordObserved(path, stats, transition, trigger, initialRecursive = false, retainWithoutTrigger = false) {
1116
+ if (!this.observesNative())
1117
+ return;
1118
+ if (!trigger && !initialRecursive && !retainWithoutTrigger)
1119
+ return;
1120
+ const { size, mtimeMs, ino } = statIdentity(stats);
1121
+ this.observed.set(logicalPathKey(path), {
1122
+ size,
1123
+ mtimeMs,
1124
+ ino,
1125
+ kind: statKind(stats),
1126
+ transition,
1127
+ rawEvent: trigger?.rawEvent,
1128
+ relativePath: trigger?.relativePath,
1129
+ observedAt: trigger?.observedAt,
1130
+ initialRecursive
1131
+ });
1132
+ }
1133
+ consumeInitialCreate(path, stats, trigger, ignoreInitial) {
1134
+ const previous = this.observed.get(logicalPathKey(path));
1135
+ if (!previous?.initialRecursive || trigger.rawEvent !== "rename")
1136
+ return;
1137
+ this.recordObserved(path, stats, "add", trigger);
1138
+ if (!ignoreInitial)
1139
+ return false;
1140
+ return stats.isDirectory() ? EVENTS.ADD_DIR : EVENTS.ADD;
1141
+ }
1142
+ markInitialCreate(path) {
1143
+ const key = logicalPathKey(path);
1144
+ const fact = this.observed.get(key);
1145
+ if (fact)
1146
+ fact.initialRecursive = true;
1147
+ else
1148
+ this.observed.set(key, { ...INITIAL_OBSERVATION_FACT });
1149
+ }
1150
+ clearInitialCreate(path) {
1151
+ const fact = this.observed.get(logicalPathKey(path));
1152
+ if (fact)
1153
+ fact.initialRecursive = false;
1154
+ }
1155
+ clearInitialCreates(root) {
1156
+ const rootKey = logicalPathKey(root);
1157
+ for (const [path, fact] of this.observed) {
1158
+ if (isSameOrInside(rootKey, path) && fact.initialRecursive)
1159
+ fact.initialRecursive = false;
1160
+ }
1161
+ }
1162
+ /** True when a tracked directory path now names a different directory inode. */
1163
+ replacedSinceObserved(path, stats) {
1164
+ const previous = this.observed.get(logicalPathKey(path));
1165
+ const { ino } = statIdentity(stats);
1166
+ return previous?.kind === "directory" && stats.isDirectory() && previous.ino !== 0 && ino !== 0 && previous.ino !== ino;
1167
+ }
1168
+ /** True when `stats` no longer matches a recorded fact of the same kind. */
1169
+ changedSinceObserved(path, stats) {
1170
+ const previous = this.observed.get(logicalPathKey(path));
1171
+ return previous !== void 0 && previous.kind === statKind(stats) && !sameStatFact(previous, stats);
1172
+ }
1173
+ isDuplicateObservation(path, stats, trigger) {
1174
+ const previous = this.observed.get(logicalPathKey(path));
1175
+ const sameFact = sameStatFact(previous, stats);
1176
+ const duplicateCreate = sameFact && previous?.transition === "add" && previous?.relativePath === trigger.relativePath && previous.rawEvent === "rename" && trigger.rawEvent === "change" && withinWindow(previous, trigger, RECURSIVE_CREATE_BURST_WINDOW);
1177
+ const duplicateUnchanged = sameFact && stats.isFile() && !previous?.initialRecursive && (previous?.transition === "add" || trigger.relativePath === null);
1178
+ const duplicateWrite = sameFact && previous?.transition === "change" && previous.relativePath === trigger.relativePath && withinWindow(previous, trigger, RECURSIVE_WRITE_BURST_WINDOW) && previous.rawEvent === trigger.rawEvent;
1179
+ const duplicate = duplicateUnchanged || duplicateCreate || duplicateWrite;
1180
+ const transition = duplicateWrite ? void 0 : duplicateUnchanged ? previous?.transition : "change";
1181
+ this.recordObserved(path, stats, transition, trigger);
1182
+ return duplicate;
1183
+ }
1184
+ dispose() {
1185
+ this.watched.forEach((entry) => entry.dispose());
1186
+ this.watched.clear();
1187
+ this.observed.clear();
1188
+ this.symlinkPaths.clear();
1189
+ this.recursiveRoots.clear();
1190
+ }
1191
+ };
1192
+
1193
+ // ../../node_modules/chokidar/policy.js
1194
+ var EMPTY_FILE_HOLD = 10;
1195
+ function isEmptyFile(stats) {
1196
+ return stats !== void 0 && stats.isFile() && statIdentity(stats).size === 0;
1197
+ }
1198
+ function sameChangeStats(left, right) {
1199
+ if (left === void 0 || right === void 0)
1200
+ return false;
1201
+ const a = statIdentity(left);
1202
+ const b = statIdentity(right);
1203
+ return a.size === b.size && a.mtimeMs === b.mtimeMs && a.ino === b.ino;
1204
+ }
1205
+ var EventPolicy = class {
1206
+ pendingWrites = /* @__PURE__ */ new Map();
1207
+ pendingUnlinks = /* @__PURE__ */ new Map();
1208
+ pendingChanges = /* @__PURE__ */ new Map();
1209
+ heldAdds = /* @__PURE__ */ new Map();
1210
+ throttled = /* @__PURE__ */ new Map();
1211
+ context;
1212
+ constructor(context) {
1213
+ this.context = context;
1214
+ }
1215
+ presentPath(path) {
1216
+ if (isWindows)
1217
+ path = sp5.normalize(path);
1218
+ return this.context.options.cwd ? sp5.relative(this.context.options.cwd, path) : path;
1219
+ }
1220
+ dropHeldAdd(logicalKey) {
1221
+ const held = this.heldAdds.get(logicalKey);
1222
+ if (held)
1223
+ this.context.scheduler.clearTimeout(held.timer);
1224
+ this.heldAdds.delete(logicalKey);
1225
+ }
1226
+ dropPendingChange(logicalKey) {
1227
+ const pending = this.pendingChanges.get(logicalKey);
1228
+ if (pending?.held)
1229
+ this.context.scheduler.clearTimeout(pending.held.timer);
1230
+ this.pendingChanges.delete(logicalKey);
1231
+ }
1232
+ setTimeout(callback, delay) {
1233
+ const timer = this.context.scheduler.setTimeout(callback, delay);
1234
+ if (!this.context.options.persistent)
1235
+ timer.unref();
1236
+ return timer;
1237
+ }
1238
+ async emit(event, path, stats) {
1239
+ if (this.context.isClosed())
1240
+ return;
1241
+ const { options, scheduler } = this.context;
1242
+ const sourcePath = path;
1243
+ const logicalKey = logicalPathKey(path);
1244
+ const generation = this.context.lifecycle.generation;
1245
+ const pathGeneration = this.context.capturePathGeneration();
1246
+ path = this.presentPath(path);
1247
+ const args = [path];
1248
+ if (stats != null)
1249
+ args.push(stats);
1250
+ const heldAdd = this.heldAdds.get(logicalKey);
1251
+ if (heldAdd) {
1252
+ if (event === EVENTS.CHANGE) {
1253
+ heldAdd.path = sourcePath;
1254
+ if (stats)
1255
+ heldAdd.stats = stats;
1256
+ if (!isEmptyFile(stats))
1257
+ heldAdd.release();
1258
+ return;
1259
+ }
1260
+ heldAdd.release();
1261
+ }
1262
+ if (event === EVENTS.UNLINK || event === EVENTS.UNLINK_DIR) {
1263
+ this.dropPendingChange(logicalKey);
1264
+ this.throttled.get(EVENTS.CHANGE)?.get(logicalKey)?.clear(false);
1265
+ }
1266
+ const awf = options.awaitWriteFinish;
1267
+ const pendingWrite = awf ? this.pendingWrites.get(logicalKey) : void 0;
1268
+ if (pendingWrite) {
1269
+ pendingWrite.lastChange = scheduler.now();
1270
+ return;
1271
+ }
1272
+ if (options.atomic) {
1273
+ if (event === EVENTS.UNLINK) {
1274
+ const existing = this.pendingUnlinks.get(logicalKey);
1275
+ if (existing)
1276
+ scheduler.clearTimeout(existing.timer);
1277
+ const entry = [event, ...args];
1278
+ const timer = this.setTimeout(() => {
1279
+ const pending = this.pendingUnlinks.get(logicalKey);
1280
+ if (!pending || pending.timer !== timer)
1281
+ return;
1282
+ this.pendingUnlinks.delete(logicalKey);
1283
+ if (this.context.isClosed())
1284
+ return;
1285
+ const [pendingEvent, ...pendingArgs] = pending.event;
1286
+ this.context.publish(pendingEvent, pendingArgs);
1287
+ }, typeof options.atomic === "number" ? options.atomic : 100);
1288
+ this.pendingUnlinks.set(logicalKey, { event: entry, timer });
1289
+ return;
1290
+ }
1291
+ const pendingUnlink = this.pendingUnlinks.get(logicalKey);
1292
+ if (event === EVENTS.ADD && pendingUnlink) {
1293
+ event = EVENTS.CHANGE;
1294
+ scheduler.clearTimeout(pendingUnlink.timer);
1295
+ this.pendingUnlinks.delete(logicalKey);
1296
+ }
1297
+ }
1298
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this.context.isReady()) {
1299
+ const awfEmit = (error62, currentStats) => {
1300
+ if (this.context.isClosed())
1301
+ return;
1302
+ if (error62) {
1303
+ event = EVENTS.ERROR;
1304
+ args[0] = error62;
1305
+ this.context.publish(event, args);
1306
+ } else if (currentStats) {
1307
+ if (args.length > 1)
1308
+ args[1] = currentStats;
1309
+ else
1310
+ args.push(currentStats);
1311
+ this.context.publish(event, args);
1312
+ }
1313
+ };
1314
+ this.awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit, logicalKey);
1315
+ return;
1316
+ }
1317
+ if (event === EVENTS.ADD && isEmptyFile(stats) && this.context.isReady()) {
1318
+ const held = {
1319
+ path: sourcePath,
1320
+ stats,
1321
+ release: () => {
1322
+ this.context.scheduler.clearTimeout(held.timer);
1323
+ if (this.heldAdds.get(logicalKey) !== held)
1324
+ return;
1325
+ this.heldAdds.delete(logicalKey);
1326
+ if (this.context.isClosed() || !this.context.lifecycle.isActive(generation) || !this.context.isPathGenerationActive(logicalKey, pathGeneration)) {
1327
+ return;
1328
+ }
1329
+ const heldArgs = [this.presentPath(held.path)];
1330
+ if (held.stats)
1331
+ heldArgs.push(held.stats);
1332
+ this.context.publish(EVENTS.ADD, heldArgs);
1333
+ }
1334
+ };
1335
+ held.timer = this.setTimeout(held.release, EMPTY_FILE_HOLD);
1336
+ this.heldAdds.set(logicalKey, held);
1337
+ return;
1338
+ }
1339
+ if (event === EVENTS.CHANGE) {
1340
+ const throttler = this.throttle(EVENTS.CHANGE, sourcePath, 50, (suppressedCount) => {
1341
+ const pending2 = this.pendingChanges.get(logicalKey);
1342
+ this.dropPendingChange(logicalKey);
1343
+ if (suppressedCount > 0 && pending2?.replay && this.context.lifecycle.isActive(generation) && this.context.isPathGenerationActive(logicalKey, pathGeneration)) {
1344
+ void this.emit(EVENTS.CHANGE, pending2.path, pending2.stats);
1345
+ }
1346
+ });
1347
+ if (!throttler) {
1348
+ const pending2 = this.pendingChanges.get(logicalKey);
1349
+ if (pending2 && !sameChangeStats(pending2.stats, stats)) {
1350
+ pending2.path = sourcePath;
1351
+ pending2.stats = stats;
1352
+ pending2.replay = true;
1353
+ if (pending2.held && !isEmptyFile(stats))
1354
+ pending2.held.release();
678
1355
  }
679
- })
1356
+ return;
1357
+ }
1358
+ const pending = { path: sourcePath, stats, replay: false };
1359
+ this.pendingChanges.set(logicalKey, pending);
1360
+ if (isEmptyFile(stats)) {
1361
+ const release = () => {
1362
+ if (pending.held)
1363
+ this.context.scheduler.clearTimeout(pending.held.timer);
1364
+ pending.held = void 0;
1365
+ if (this.pendingChanges.get(logicalKey) !== pending || this.context.isClosed() || !this.context.lifecycle.isActive(generation) || !this.context.isPathGenerationActive(logicalKey, pathGeneration)) {
1366
+ return;
1367
+ }
1368
+ pending.replay = false;
1369
+ const heldArgs = [this.presentPath(pending.path)];
1370
+ if (pending.stats)
1371
+ heldArgs.push(pending.stats);
1372
+ this.context.publish(EVENTS.CHANGE, heldArgs);
1373
+ };
1374
+ pending.held = { timer: this.setTimeout(release, EMPTY_FILE_HOLD), release };
1375
+ return;
1376
+ }
1377
+ }
1378
+ if (options.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1379
+ const fullPath = options.cwd ? sp5.join(options.cwd, path) : path;
1380
+ try {
1381
+ stats = await stat(fullPath);
1382
+ } catch (error62) {
1383
+ this.context.handleError(error62);
1384
+ }
1385
+ if (!stats || !this.context.lifecycle.isActive(generation) || !this.context.isPathGenerationActive(logicalKey, pathGeneration)) {
1386
+ return;
1387
+ }
1388
+ args.push(stats);
1389
+ }
1390
+ this.context.publish(event, args);
1391
+ }
1392
+ throttle(actionType, path, timeout, onRelease) {
1393
+ let action = this.throttled.get(actionType);
1394
+ if (!action) {
1395
+ action = /* @__PURE__ */ new Map();
1396
+ this.throttled.set(actionType, action);
1397
+ }
1398
+ const key = actionType === "readdir" ? path : logicalPathKey(path);
1399
+ const active = action.get(key);
1400
+ if (active) {
1401
+ active.count += 1;
1402
+ return false;
1403
+ }
1404
+ let timeoutObject;
1405
+ const clear = (invokeRelease = true) => {
1406
+ const item = action.get(key);
1407
+ const count = item?.count ?? 0;
1408
+ action.delete(key);
1409
+ this.context.scheduler.clearTimeout(timeoutObject);
1410
+ if (item)
1411
+ this.context.scheduler.clearTimeout(item.timeoutObject);
1412
+ if (invokeRelease && onRelease)
1413
+ onRelease(count);
1414
+ return count;
680
1415
  };
681
- FsWatchFileInstances.set(fullPath, cont);
682
- }
683
- return () => {
684
- delFromSet(cont, KEY_LISTENERS, listener);
685
- delFromSet(cont, KEY_RAW, rawEmitter);
686
- if (isEmptySet(cont.listeners)) {
687
- FsWatchFileInstances.delete(fullPath);
688
- unwatchFile(fullPath);
689
- cont.options = cont.watcher = void 0;
690
- Object.freeze(cont);
1416
+ timeoutObject = this.setTimeout(clear, timeout);
1417
+ const throttler = { timeoutObject, clear, count: 0 };
1418
+ action.set(key, throttler);
1419
+ return throttler;
1420
+ }
1421
+ awaitWriteFinish(path, threshold, event, awfEmit, logicalKey) {
1422
+ const awf = this.context.options.awaitWriteFinish;
1423
+ if (typeof awf !== "object")
1424
+ return;
1425
+ const pollInterval = awf.pollInterval;
1426
+ let timeoutHandler;
1427
+ let fullPath = path;
1428
+ if (this.context.options.cwd && !sp5.isAbsolute(path)) {
1429
+ fullPath = sp5.join(this.context.options.cwd, path);
691
1430
  }
1431
+ const writeKey = logicalKey ?? logicalPathKey(fullPath);
1432
+ if (this.pendingWrites.has(writeKey))
1433
+ return;
1434
+ const generation = this.context.lifecycle.generation;
1435
+ const pending = {
1436
+ lastChange: this.context.scheduler.now(),
1437
+ cancelWait: () => {
1438
+ if (this.pendingWrites.get(writeKey) === pending)
1439
+ this.pendingWrites.delete(writeKey);
1440
+ this.context.scheduler.clearTimeout(timeoutHandler);
1441
+ return event;
1442
+ }
1443
+ };
1444
+ const isCurrent = () => this.context.lifecycle.isActive(generation) && this.pendingWrites.get(writeKey) === pending;
1445
+ const inspect = (previous) => {
1446
+ const task = (async () => {
1447
+ let current;
1448
+ try {
1449
+ current = await stat(fullPath);
1450
+ } catch (error62) {
1451
+ if (!isCurrent())
1452
+ return;
1453
+ if (isMissingError(error62)) {
1454
+ this.context.remove(sp5.dirname(fullPath), sp5.basename(fullPath));
1455
+ if (this.pendingWrites.get(writeKey) === pending)
1456
+ pending.cancelWait();
1457
+ } else {
1458
+ this.pendingWrites.delete(writeKey);
1459
+ awfEmit(error62);
1460
+ }
1461
+ return;
1462
+ }
1463
+ if (!isCurrent())
1464
+ return;
1465
+ const now = this.context.scheduler.now();
1466
+ if (previous && current.size !== previous.size)
1467
+ pending.lastChange = now;
1468
+ if (now - pending.lastChange >= threshold) {
1469
+ this.pendingWrites.delete(writeKey);
1470
+ awfEmit(void 0, current);
1471
+ } else {
1472
+ timeoutHandler = this.setTimeout(() => inspect(current), pollInterval);
1473
+ }
1474
+ })();
1475
+ this.context.lifecycle.track(task);
1476
+ };
1477
+ this.pendingWrites.set(writeKey, pending);
1478
+ timeoutHandler = this.setTimeout(inspect, pollInterval);
1479
+ }
1480
+ cancelPath(path) {
1481
+ const logicalKey = logicalPathKey(path);
1482
+ const pendingUnlink = this.pendingUnlinks.get(logicalKey);
1483
+ if (pendingUnlink) {
1484
+ this.context.scheduler.clearTimeout(pendingUnlink.timer);
1485
+ this.pendingUnlinks.delete(logicalKey);
1486
+ }
1487
+ this.pendingWrites.get(logicalKey)?.cancelWait();
1488
+ this.dropPendingChange(logicalKey);
1489
+ this.dropHeldAdd(logicalKey);
1490
+ ["watch", "add", "remove", "change"].forEach((actionType) => {
1491
+ this.throttled.get(actionType)?.get(logicalKey)?.clear(false);
1492
+ });
1493
+ const readdirEntries = this.throttled.get("readdir");
1494
+ readdirEntries?.get(logicalKey)?.clear(false);
1495
+ readdirEntries?.get(`${logicalPathKey(sp5.dirname(logicalKey))}\0${sp5.basename(logicalKey)}`)?.clear(false);
1496
+ }
1497
+ cancelWhere(contains) {
1498
+ const paths = /* @__PURE__ */ new Set([
1499
+ ...this.pendingUnlinks.keys(),
1500
+ ...this.pendingWrites.keys(),
1501
+ ...this.pendingChanges.keys(),
1502
+ ...this.heldAdds.keys()
1503
+ ]);
1504
+ [...paths].filter(contains).forEach((path) => this.cancelPath(path));
1505
+ this.throttled.forEach((entries, actionType) => {
1506
+ [...entries.keys()].filter((key) => contains(actionType === "readdir" ? key.split("\0", 1)[0] : key)).forEach((key) => entries.get(key)?.clear(false));
1507
+ });
1508
+ }
1509
+ close() {
1510
+ this.pendingWrites.forEach((pending) => pending.cancelWait());
1511
+ this.pendingUnlinks.forEach(({ timer }) => this.context.scheduler.clearTimeout(timer));
1512
+ this.pendingUnlinks.clear();
1513
+ this.pendingChanges.forEach(({ held }) => this.context.scheduler.clearTimeout(held?.timer));
1514
+ this.pendingChanges.clear();
1515
+ this.heldAdds.forEach(({ timer }) => this.context.scheduler.clearTimeout(timer));
1516
+ this.heldAdds.clear();
1517
+ this.throttled.forEach((entries) => {
1518
+ entries.forEach((throttler) => throttler.clear(false));
1519
+ });
1520
+ this.throttled.clear();
1521
+ }
1522
+ };
1523
+ var EV2 = EVENTS;
1524
+ var RECURSIVE_TRIGGER_BUFFER_LIMIT = 1024;
1525
+ var MAX_NATIVE_RESUBSCRIBES = 3;
1526
+ var FALLBACK_SUBSCRIBE_CONCURRENCY = 16;
1527
+ var EXACT_CANDIDATE = Object.freeze({});
1528
+ function recoveryTrigger(resource) {
1529
+ return {
1530
+ kind: "native",
1531
+ resource,
1532
+ rawEvent: EV2.CHANGE,
1533
+ relativePath: null,
1534
+ sequence: Number.MAX_SAFE_INTEGER,
1535
+ observedAt: backendNow()
692
1536
  };
1537
+ }
1538
+ function sameMappedFileSnapshot(left, right) {
1539
+ if (left === false || right === false)
1540
+ return left === right;
1541
+ return left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs && left.ino === right.ino && left.mode === right.mode;
1542
+ }
1543
+ var ReplayBuffer = class {
1544
+ entries = [];
1545
+ overflow;
1546
+ limit;
1547
+ constructor(limit) {
1548
+ this.limit = limit;
1549
+ }
1550
+ get overflowed() {
1551
+ return this.overflow !== void 0;
1552
+ }
1553
+ push(value) {
1554
+ if (this.entries.length < this.limit && !this.overflowed)
1555
+ this.entries.push(value);
1556
+ else
1557
+ this.overflow = value;
1558
+ }
1559
+ clear() {
1560
+ this.entries.length = 0;
1561
+ this.overflow = void 0;
1562
+ }
693
1563
  };
694
- var NodeFsHandler = class {
1564
+ function consumeDirectoryStream(stream, onEntry) {
1565
+ const tasks = [];
1566
+ stream.on("data", (entry) => {
1567
+ let result;
1568
+ try {
1569
+ result = onEntry(entry);
1570
+ } catch (error62) {
1571
+ result = Promise.reject(error62);
1572
+ }
1573
+ if (!result)
1574
+ return;
1575
+ tasks.push(Promise.resolve(result));
1576
+ });
1577
+ return new Promise((resolve6) => {
1578
+ stream.once("end", () => resolve6({ complete: true }));
1579
+ stream.once("close", () => resolve6({ complete: false }));
1580
+ stream.once(EV2.ERROR, (error62) => resolve6({ complete: false, error: error62 }));
1581
+ }).then(async ({ complete, error: error62 }) => {
1582
+ const settled = await Promise.allSettled(tasks);
1583
+ const failures = settled.filter((result) => result.status === "rejected").map((result) => result.reason);
1584
+ return { complete: complete && failures.length === 0, error: error62, failures };
1585
+ });
1586
+ }
1587
+ var binaryExtensions = new Set(`3dm 3ds 3g2 3gp 7z a aac adp afdesign afphoto afpub ai aif aiff alz ape apk appimage ar arj asf au avi bak baml bh bin bk bmp btif bz2 bzip2 cab caf cgm class cmx cpio cr2 cur dat dcm deb dex djvu dll dmg dng doc docm docx dot dotm dra ds_store dsk dts dtshd dvb dwg dxf ecelp4800 ecelp7470 ecelp9600 egg eol eot epub exe f4v fbs fh fla flac flatpak fli flv fpx fst fvt g3 gh gif graffle gz gzip h261 h263 h264 icns ico ief img ipa iso jar jpeg jpg jpgv jpm jxr key ktx lha lib lvp lz lzh lzma lzo m3u m4a m4v mar mdi mht mid midi mj2 mka mkv mmr mng mobi mov movie mp3 mp4 mp4a mpeg mpg mpga mxu nef npx numbers nupkg o odp ods odt oga ogg ogv otf ott pages pbm pcx pdb pdf pea pgm pic png pnm pot potm potx ppa ppam ppm pps ppsm ppsx ppt pptm pptx psd pya pyc pyo pyv qt rar ras raw resources rgb rip rlc rmf rmvb rpm rtf rz s3m s7z scpt sgi shar snap sil sketch slk smv snk so stl suo sub swf tar tbz tbz2 tga tgz thmx tif tiff tlz ttc ttf txz udf uvh uvi uvm uvp uvs uvu viv vob war wav wax wbmp wdp weba webm webp whl wim wm wma wmv wmx woff woff2 wrm wvx xbm xif xla xlam xls xlsb xlsm xlsx xlt xltm xltx xm xmind xpi xpm xwd xz z zip zipx`.split(" "));
1588
+ function isBinaryPath(filePath) {
1589
+ return binaryExtensions.has(sp5.extname(filePath).slice(1).toLowerCase());
1590
+ }
1591
+ var ObservationEngine = class {
695
1592
  fsw;
696
- _boundHandleError;
1593
+ reportError;
697
1594
  constructor(fsW) {
698
1595
  this.fsw = fsW;
699
- this._boundHandleError = (error62) => fsW._handleError(error62);
1596
+ this.reportError = (error62) => fsW.handleError(error62);
700
1597
  }
701
1598
  /**
702
- * Watch file for changes with fs_watchFile or fs_watch.
1599
+ * Watch a path with the owned polling scheduler or fs.watch.
703
1600
  * @param path to file or dir
704
1601
  * @param listener on fs change
705
1602
  * @returns closer for the watcher instance
706
1603
  */
707
- _watchWithNodeFs(path, listener) {
1604
+ subscribePath(path, listener, initialStats, mapRelative = false, queueScope = path) {
708
1605
  const opts = this.fsw.options;
709
- const directory = sp2.dirname(path);
710
- const basename3 = sp2.basename(path);
711
- const parent = this.fsw._getWatchedDir(directory);
712
- parent.add(basename3);
713
- const absolutePath = sp2.resolve(path);
1606
+ const basename5 = sp5.basename(path);
1607
+ const absolutePath = sp5.resolve(path);
714
1608
  const options = {
715
1609
  persistent: opts.persistent
716
1610
  };
717
- if (!listener)
718
- listener = EMPTY_FN;
719
- let closer;
720
- if (opts.usePolling) {
721
- const enableBin = opts.interval !== opts.binaryInterval;
722
- options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval;
723
- closer = setFsWatchFileListener(path, absolutePath, options, {
724
- listener,
725
- rawEmitter: this.fsw._emitRaw
726
- });
1611
+ const generation = this.fsw.lifecycle.generation;
1612
+ let active = true;
1613
+ const trackedListener = (watchedPath, stats, trigger) => {
1614
+ if (!active || !this.fsw.lifecycle.isActive(generation))
1615
+ return;
1616
+ return listener(watchedPath, stats, trigger);
1617
+ };
1618
+ const publish = (trigger) => {
1619
+ void this.reconcileBackendTrigger(path, mapRelative, trigger, (candidate) => trackedListener(candidate, trigger.kind === "poll" && !isMissingObservation(trigger.current) ? trigger.current : void 0, trigger), () => active && this.fsw.lifecycle.isActive(generation), true, queueScope);
1620
+ };
1621
+ let subscription;
1622
+ let resubscribes = 0;
1623
+ const subscribeNative = () => setFsWatchListener(path, absolutePath, options, {
1624
+ publish: (trigger) => {
1625
+ resubscribes = 0;
1626
+ publish(trigger);
1627
+ },
1628
+ errHandler: this.reportError,
1629
+ rawEmitter: (...args) => this.fsw.emitRaw(...args),
1630
+ failure: () => {
1631
+ if (!active || !this.fsw.lifecycle.isActive(generation))
1632
+ return;
1633
+ subscription = resubscribes++ < MAX_NATIVE_RESUBSCRIBES ? subscribeNative() : void 0;
1634
+ publish(recoveryTrigger(absolutePath));
1635
+ }
1636
+ }, this.fsw.lifecycle.abortController.signal);
1637
+ if (opts.backendCapabilities.polling) {
1638
+ const enableBin = opts.pollingInterval !== opts.pollingBinaryInterval;
1639
+ const pollingInterval = enableBin && isBinaryPath(basename5) ? opts.pollingBinaryInterval : opts.pollingInterval;
1640
+ subscription = setPollingListener(path, absolutePath, { interval: pollingInterval, persistent: opts.persistent }, this.fsw.scheduler, {
1641
+ publish,
1642
+ errHandler: this.reportError,
1643
+ rawEmitter: (...args) => this.fsw.emitRaw(...args)
1644
+ }, initialStats, this.fsw.lifecycle.abortController.signal);
727
1645
  } else {
728
- closer = setFsWatchListener(path, absolutePath, options, {
729
- listener,
730
- errHandler: this._boundHandleError,
731
- rawEmitter: this.fsw._emitRaw
732
- });
1646
+ subscription = subscribeNative();
1647
+ }
1648
+ if (!subscription)
1649
+ return;
1650
+ return () => {
1651
+ if (!active)
1652
+ return;
1653
+ active = false;
1654
+ return subscription?.close();
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Watch a followed file symlink through the target's parent directory.
1659
+ * macOS also starts a one-shot exact-target fallback: FSEvents can omit the
1660
+ * first directory callback immediately after a subscription is established.
1661
+ */
1662
+ subscribeMappedFile(logicalPath, targetPath, helper, depth, useExactFallback = isMacos) {
1663
+ if (this.fsw.options.backendCapabilities.polling)
1664
+ return;
1665
+ const targetDirectory = sp5.dirname(targetPath);
1666
+ const targetKey = logicalPathKey(targetPath);
1667
+ const logicalParent = sp5.dirname(logicalPath);
1668
+ const generation = this.fsw.lifecycle.generation;
1669
+ let active = true;
1670
+ let exactActive = useExactFallback;
1671
+ let suppressDirectoryEcho = false;
1672
+ let fallbackSnapshot;
1673
+ let directorySubscription;
1674
+ let exactSubscription;
1675
+ const isActive = () => active && this.fsw.lifecycle.isActive(generation) && this.isHelperActive(helper, logicalPath);
1676
+ const matchesTarget = (relativePath) => {
1677
+ if (relativePath === null)
1678
+ return true;
1679
+ const candidate = sp5.isAbsolute(relativePath) ? relativePath : sp5.resolve(targetDirectory, relativePath);
1680
+ const candidateKey = logicalPathKey(candidate);
1681
+ return isWindows ? candidateKey.toLowerCase() === targetKey.toLowerCase() : candidateKey === targetKey;
1682
+ };
1683
+ const retireExact = () => {
1684
+ if (!exactActive)
1685
+ return;
1686
+ exactActive = false;
1687
+ if (exactSubscription)
1688
+ void exactSubscription.close();
1689
+ };
1690
+ const publish = (source, trigger) => {
1691
+ if (trigger.kind !== "native" || !matchesTarget(trigger.relativePath) || !isActive())
1692
+ return;
1693
+ const deduplicateAgainstFallback = source === "directory" && suppressDirectoryEcho;
1694
+ if (source === "directory") {
1695
+ suppressDirectoryEcho = false;
1696
+ retireExact();
1697
+ } else if (directorySubscription) {
1698
+ suppressDirectoryEcho = true;
1699
+ retireExact();
1700
+ }
1701
+ void this.reconcileBackendTrigger(targetDirectory, true, trigger, async () => {
1702
+ if (deduplicateAgainstFallback && fallbackSnapshot !== void 0) {
1703
+ const current = await this.mappedFileSnapshot(targetPath);
1704
+ if (current !== void 0 && sameMappedFileSnapshot(fallbackSnapshot, current))
1705
+ return;
1706
+ }
1707
+ await this.reconcileNativeTrigger(logicalParent, helper, trigger, logicalPath, depth - 1, EXACT_CANDIDATE);
1708
+ if (source === "exact")
1709
+ fallbackSnapshot = await this.mappedFileSnapshot(targetPath);
1710
+ }, isActive, false, logicalPath);
1711
+ };
1712
+ let resubscribes = 0;
1713
+ const handlers = (source) => ({
1714
+ publish: (trigger) => {
1715
+ if (source === "directory")
1716
+ resubscribes = 0;
1717
+ publish(source, trigger);
1718
+ },
1719
+ errHandler: this.reportError,
1720
+ rawEmitter: (event, relativePath) => {
1721
+ if ((source === "directory" || exactActive) && matchesTarget(relativePath) && isActive()) {
1722
+ this.fsw.emitRaw(event, relativePath, { watchedPath: logicalPath });
1723
+ }
1724
+ },
1725
+ failure: () => {
1726
+ if (source === "exact") {
1727
+ exactSubscription = void 0;
1728
+ exactActive = false;
1729
+ return;
1730
+ }
1731
+ directorySubscription = void 0;
1732
+ if (!isActive())
1733
+ return;
1734
+ if (resubscribes++ < MAX_NATIVE_RESUBSCRIBES)
1735
+ directorySubscription = subscribe(source);
1736
+ publish(source, recoveryTrigger(sp5.resolve(targetDirectory)));
1737
+ }
1738
+ });
1739
+ const subscribe = (source) => {
1740
+ const path = source === "directory" ? targetDirectory : targetPath;
1741
+ return setFsWatchListener(path, sp5.resolve(path), { persistent: this.fsw.options.persistent }, handlers(source), this.fsw.lifecycle.abortController.signal);
1742
+ };
1743
+ directorySubscription = subscribe("directory");
1744
+ exactSubscription = useExactFallback ? subscribe("exact") : void 0;
1745
+ if (!exactSubscription)
1746
+ exactActive = false;
1747
+ if (!directorySubscription && !exactSubscription)
1748
+ return;
1749
+ return async () => {
1750
+ if (!active)
1751
+ return;
1752
+ active = false;
1753
+ const subscriptions = [directorySubscription, exactSubscription].filter((subscription) => subscription !== void 0);
1754
+ await Promise.allSettled(subscriptions.map((subscription) => subscription.close()));
1755
+ };
1756
+ }
1757
+ async mappedFileSnapshot(path) {
1758
+ try {
1759
+ return await lstat(path);
1760
+ } catch (error62) {
1761
+ if (isMissingError(error62))
1762
+ return false;
1763
+ this.reportError(error62);
1764
+ return;
733
1765
  }
734
- return closer;
1766
+ }
1767
+ /**
1768
+ * macOS can follow an exact symlink handle and miss the link's own removal.
1769
+ * Check only link existence so target-directory activity stays invisible when
1770
+ * followSymlinks is disabled.
1771
+ */
1772
+ watchSymlinkDeletion(path, force = false) {
1773
+ if (!isMacos && !force || this.fsw.options.backendCapabilities.polling)
1774
+ return;
1775
+ const fsw = this.fsw;
1776
+ const generation = fsw.lifecycle.generation;
1777
+ const directory = sp5.dirname(path);
1778
+ const basename5 = sp5.basename(path);
1779
+ let active = true;
1780
+ let timer;
1781
+ const schedule = () => {
1782
+ timer = fsw.scheduler.setTimeout(() => {
1783
+ timer = void 0;
1784
+ void (async () => {
1785
+ try {
1786
+ await lstat(path);
1787
+ } catch (error62) {
1788
+ if (!active || !fsw.lifecycle.isActive(generation))
1789
+ return;
1790
+ if (isMissingError(error62)) {
1791
+ active = false;
1792
+ fsw.removePath(directory, basename5);
1793
+ return;
1794
+ }
1795
+ this.reportError(error62);
1796
+ }
1797
+ if (active && fsw.lifecycle.isActive(generation))
1798
+ schedule();
1799
+ })();
1800
+ }, fsw.options.pollingInterval);
1801
+ if (!fsw.options.persistent)
1802
+ timer.unref();
1803
+ };
1804
+ schedule();
1805
+ return () => {
1806
+ if (!active)
1807
+ return;
1808
+ active = false;
1809
+ fsw.scheduler.clearTimeout(timer);
1810
+ timer = void 0;
1811
+ };
1812
+ }
1813
+ /**
1814
+ * Map one backend notification into a logical candidate and serialize its
1815
+ * filesystem reconciliation in the owning watcher instance.
1816
+ */
1817
+ reconcileBackendTrigger(scope, mapRelative, trigger, reconcile, isActive = () => true, coalesce = true, queueScope = scope) {
1818
+ let candidate = scope;
1819
+ if (mapRelative && trigger.kind === "native" && trigger.relativePath !== null) {
1820
+ const resolved = resolveRecursiveCandidate(scope, trigger.relativePath);
1821
+ if (!resolved) {
1822
+ this.reportError(new Error(`Watcher reported a path outside its root: ${trigger.relativePath}`));
1823
+ return Promise.resolve();
1824
+ }
1825
+ candidate = resolved;
1826
+ }
1827
+ if (!isActive() || this.fsw.isUnwatched(candidate))
1828
+ return Promise.resolve();
1829
+ const rootKey = logicalPathKey(queueScope);
1830
+ const candidateKey = logicalPathKey(candidate);
1831
+ return this.fsw.reconciliation.enqueue(rootKey, async () => {
1832
+ if (!isActive() || this.fsw.isUnwatched(candidateKey))
1833
+ return;
1834
+ await reconcile(candidate);
1835
+ }, coalesce ? candidateKey : false);
735
1836
  }
736
1837
  /**
737
1838
  * Watch a file and emit add event if warranted.
738
1839
  * @returns closer for the watcher instance
739
1840
  */
740
- _handleFile(file2, stats, initialAdd) {
1841
+ handleFile(file2, stats, initialAdd, watchResource = true, trigger, initialRecursive = false, retainObservation = false) {
741
1842
  if (this.fsw.closed) {
742
1843
  return;
743
1844
  }
744
- const dirname4 = sp2.dirname(file2);
745
- const basename3 = sp2.basename(file2);
746
- const parent = this.fsw._getWatchedDir(dirname4);
1845
+ const dirname5 = sp5.dirname(file2);
1846
+ const basename5 = sp5.basename(file2);
1847
+ const parent = this.fsw.tree.getDirectory(dirname5);
747
1848
  let prevStats = stats;
748
- if (parent.has(basename3))
1849
+ if (parent.has(basename5))
749
1850
  return;
750
- const listener = async (path, newStats) => {
751
- if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
752
- return;
1851
+ const pathGeneration = this.fsw.capturePathGeneration();
1852
+ const isActive = () => this.fsw.isPathGenerationActive(file2, pathGeneration);
1853
+ const listener = async (_path, newStats) => {
753
1854
  if (!newStats || newStats.mtimeMs === 0) {
754
1855
  try {
755
- const newStats2 = await stat(file2);
756
- if (this.fsw.closed)
1856
+ const newStats2 = prevStats.isSymbolicLink() && !this.fsw.options.followSymlinks ? await lstat(file2) : await stat(file2);
1857
+ if (!isActive())
757
1858
  return;
758
1859
  const at = newStats2.atimeMs;
759
1860
  const mt = newStats2.mtimeMs;
760
1861
  if (!at || at <= mt || mt !== prevStats.mtimeMs) {
761
- this.fsw._emit(EV.CHANGE, file2, newStats2);
1862
+ this.fsw.emitEvent(EV2.CHANGE, file2, newStats2);
762
1863
  }
763
- if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
764
- this.fsw._closeFile(path);
765
- prevStats = newStats2;
766
- const closer2 = this._watchWithNodeFs(file2, listener);
767
- if (closer2)
768
- this.fsw._addPathCloser(path, closer2);
1864
+ this.fsw.tree.recordObserved(file2, newStats2, "change");
1865
+ prevStats = newStats2;
1866
+ } catch (error62) {
1867
+ if (!isActive())
1868
+ return;
1869
+ if (isMissingError(error62)) {
1870
+ this.fsw.removePath(dirname5, basename5);
769
1871
  } else {
770
- prevStats = newStats2;
1872
+ this.reportError(error62);
771
1873
  }
772
- } catch (error62) {
773
- this.fsw._remove(dirname4, basename3);
774
1874
  }
775
- } else if (parent.has(basename3)) {
1875
+ } else if (parent.has(basename5)) {
776
1876
  const at = newStats.atimeMs;
777
1877
  const mt = newStats.mtimeMs;
778
1878
  if (!at || at <= mt || mt !== prevStats.mtimeMs) {
779
- this.fsw._emit(EV.CHANGE, file2, newStats);
1879
+ this.fsw.emitEvent(EV2.CHANGE, file2, newStats);
780
1880
  }
1881
+ this.fsw.tree.recordObserved(file2, newStats, "change");
781
1882
  prevStats = newStats;
782
1883
  }
783
1884
  };
784
- const closer = this._watchWithNodeFs(file2, listener);
785
- if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
786
- if (!this.fsw._throttle(EV.ADD, file2, 0))
787
- return;
788
- this.fsw._emit(EV.ADD, file2, stats);
1885
+ const watchesFile = watchResource && this.fsw.options.backendCapabilities.polling;
1886
+ const closer = watchesFile ? this.subscribePath(file2, listener, stats) : void 0;
1887
+ parent.add(basename5);
1888
+ this.fsw.tree.recordObserved(file2, stats, "add", trigger, initialRecursive, retainObservation);
1889
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !this.fsw.isIgnored(file2, stats)) {
1890
+ this.fsw.emitEvent(EV2.ADD, file2, stats);
789
1891
  }
790
1892
  return closer;
791
1893
  }
@@ -797,97 +1899,659 @@ var NodeFsHandler = class {
797
1899
  * @param item basename of this item
798
1900
  * @returns true if no more processing is needed for this entry.
799
1901
  */
800
- async _handleSymlink(entry, directory, path, item) {
801
- if (this.fsw.closed) {
1902
+ async handleSymlink(entry, directory, path, item, initialAdd, wh) {
1903
+ if (this.fsw.closed || wh && !this.isHelperActive(wh, path)) {
802
1904
  return;
803
1905
  }
804
- const full = entry.fullPath;
805
- const dir = this.fsw._getWatchedDir(directory);
1906
+ const full = logicalPathKey(entry.fullPath);
1907
+ const dir = this.fsw.tree.getDirectory(directory);
806
1908
  if (!this.fsw.options.followSymlinks) {
807
- this.fsw._incrReadyCount();
808
1909
  let linkPath;
809
1910
  try {
810
- linkPath = await realpath(path);
811
- } catch (e) {
812
- this.fsw._emitReady();
1911
+ linkPath = await readlink(path);
1912
+ } catch (error62) {
1913
+ if (!isMissingError(error62))
1914
+ this.reportError(error62);
1915
+ return true;
1916
+ }
1917
+ if (this.fsw.closed || wh && !this.isHelperActive(wh, path)) {
813
1918
  return true;
814
1919
  }
815
- if (this.fsw.closed)
816
- return;
817
1920
  if (dir.has(item)) {
818
- if (this.fsw._symlinkPaths.get(full) !== linkPath) {
819
- this.fsw._symlinkPaths.set(full, linkPath);
820
- this.fsw._emit(EV.CHANGE, path, entry.stats);
1921
+ if (this.fsw.tree.symlinkPaths.get(full) !== linkPath) {
1922
+ this.fsw.tree.symlinkPaths.set(full, linkPath);
1923
+ this.fsw.emitEvent(EV2.CHANGE, path, entry.stats);
821
1924
  }
822
1925
  } else {
823
1926
  dir.add(item);
824
- this.fsw._symlinkPaths.set(full, linkPath);
825
- this.fsw._emit(EV.ADD, path, entry.stats);
1927
+ this.fsw.tree.symlinkPaths.set(full, linkPath);
1928
+ this.fsw.tree.recordObserved(path, entry.stats, "add", wh?.observationTrigger, initialAdd && Boolean(wh?.recursiveRoot));
1929
+ if (!(initialAdd && this.fsw.options.ignoreInitial)) {
1930
+ this.fsw.emitEvent(EV2.ADD, path, entry.stats);
1931
+ }
826
1932
  }
827
- this.fsw._emitReady();
828
1933
  return true;
829
1934
  }
830
- if (this.fsw._symlinkPaths.has(full)) {
1935
+ if (this.fsw.tree.symlinkPaths.has(full)) {
831
1936
  return true;
832
1937
  }
833
- this.fsw._symlinkPaths.set(full, true);
1938
+ this.fsw.tree.symlinkPaths.set(full, true);
834
1939
  }
835
- _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
836
- directory = sp2.join(directory, "");
837
- const throttleKey = target ? `${directory}:${target}` : directory;
838
- throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
839
- if (!throttler)
1940
+ readDirectory(directory, initialAdd, wh, target, dir, depth) {
1941
+ if (!this.isHelperActive(wh, directory))
840
1942
  return;
841
- const previous = this.fsw._getWatchedDir(wh.path);
1943
+ directory = sp5.join(directory, "");
1944
+ const directoryKey = logicalPathKey(directory);
1945
+ const previous = this.fsw.tree.getDirectory(wh.watchPath);
842
1946
  const current = /* @__PURE__ */ new Set();
843
- let stream = this.fsw._readdirp(directory, {
1947
+ const stream = this.fsw.createScanStream(directory, {
844
1948
  fileFilter: (entry) => wh.filterPath(entry),
845
1949
  directoryFilter: (entry) => wh.filterDir(entry)
846
1950
  });
847
1951
  if (!stream)
848
1952
  return;
849
- stream.on(STR_DATA, async (entry) => {
850
- if (this.fsw.closed) {
851
- stream = void 0;
1953
+ const scan = consumeDirectoryStream(stream, (entry) => {
1954
+ if (!this.isHelperActive(wh, directory))
1955
+ return;
1956
+ const stats = entry.stats;
1957
+ if (!stats)
852
1958
  return;
853
- }
854
1959
  const item = entry.path;
855
- let path = sp2.join(directory, item);
1960
+ let path = sp5.join(directory, item);
1961
+ if (!this.isHelperActive(wh, path))
1962
+ return;
856
1963
  current.add(item);
857
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
1964
+ const shouldAdd = item === target || !target && !previous.has(item);
1965
+ if (target === void 0 && !stats.isSymbolicLink() && !stats.isDirectory()) {
1966
+ if (!shouldAdd)
1967
+ return;
1968
+ path = sp5.join(dir, sp5.relative(dir, path));
1969
+ const closer = this.handleFile(path, stats, initialAdd, !wh.recursiveRoot, wh.observationTrigger, initialAdd && Boolean(wh.recursiveRoot));
1970
+ if (closer)
1971
+ this.fsw.addPathCloser(path, closer);
858
1972
  return;
859
1973
  }
860
- if (this.fsw.closed) {
861
- stream = void 0;
1974
+ return (async () => {
1975
+ if (stats.isSymbolicLink() && await this.handleSymlink(entry, directory, path, item, initialAdd, wh)) {
1976
+ return;
1977
+ }
1978
+ if (!this.isHelperActive(wh, path))
1979
+ return;
1980
+ if (shouldAdd) {
1981
+ path = sp5.join(dir, sp5.relative(dir, path));
1982
+ await this.addPathOnce(path, initialAdd, wh, depth + 1);
1983
+ }
1984
+ })();
1985
+ });
1986
+ return scan.then(async ({ complete, error: error62, failures }) => {
1987
+ failures.forEach(this.reportError);
1988
+ if (error62) {
1989
+ if (isMissingError(error62) && this.isHelperActive(wh, directory)) {
1990
+ const affectedPath = target ? sp5.join(directory, target) : directory;
1991
+ let disappeared = false;
1992
+ let becameNonDirectory = false;
1993
+ try {
1994
+ const currentStats = target ? await lstat(affectedPath) : await stat(affectedPath);
1995
+ becameNonDirectory = !target && !currentStats.isDirectory();
1996
+ } catch (stateError) {
1997
+ if (isMissingError(stateError))
1998
+ disappeared = true;
1999
+ else
2000
+ this.reportError(stateError);
2001
+ }
2002
+ if (target) {
2003
+ if (disappeared && previous.has(target))
2004
+ this.fsw.removePath(directory, target);
2005
+ } else if ((disappeared || becameNonDirectory) && this.fsw.tree.watched.has(directoryKey)) {
2006
+ this.fsw.removePath(sp5.dirname(directory), sp5.basename(directory), true);
2007
+ if (becameNonDirectory) {
2008
+ await this.addPathOnce(directory, false, wh, depth);
2009
+ }
2010
+ }
2011
+ } else {
2012
+ this.reportError(error62);
2013
+ }
2014
+ }
2015
+ if (!complete || !this.isHelperActive(wh, directory)) {
862
2016
  return;
863
2017
  }
864
- if (item === target || !target && !previous.has(item)) {
865
- this.fsw._incrReadyCount();
866
- path = sp2.join(dir, sp2.relative(dir, path));
867
- this._addToNodeFs(path, initialAdd, wh, depth + 1);
868
- }
869
- }).on(EV.ERROR, this._boundHandleError);
870
- return new Promise((resolve3, reject) => {
871
- if (!stream)
872
- return reject();
873
- stream.once(STR_END, () => {
874
- if (this.fsw.closed) {
875
- stream = void 0;
876
- return;
2018
+ await Promise.all(previous.getChildren().filter((item) => !current.has(item)).map((item) => this.removeIfMissing(wh, directory, item, previous)));
2019
+ });
2020
+ }
2021
+ async removeIfMissing(wh, directory, item, entry) {
2022
+ const path = sp5.join(directory, item);
2023
+ if (!this.isHelperActive(wh, path))
2024
+ return;
2025
+ try {
2026
+ await lstat(path);
2027
+ return;
2028
+ } catch (error62) {
2029
+ if (!isMissingError(error62))
2030
+ return;
2031
+ }
2032
+ if (this.isHelperActive(wh, path) && entry.has(item))
2033
+ this.fsw.removePath(directory, item);
2034
+ }
2035
+ /**
2036
+ * Populate the logical directory tree beneath one native recursive watcher.
2037
+ * Regular entries are consumed synchronously from readdirp's stat-bearing
2038
+ * stream; only symlinks need the full per-path add machinery.
2039
+ */
2040
+ scanRecursiveTree(dir, initialAdd, wh, baseDepth, rescan) {
2041
+ if (!this.isHelperActive(wh, dir))
2042
+ return;
2043
+ const fsw = this.fsw;
2044
+ const maxDepth = fsw.options.depth;
2045
+ const remainingDepth = maxDepth === void 0 ? void 0 : maxDepth - baseDepth;
2046
+ const stream = fsw.createScanStream(dir, {
2047
+ fileFilter: (entry) => wh.filterPath(entry),
2048
+ directoryFilter: (entry) => !entry.stats?.isSymbolicLink() && wh.filterDir(entry),
2049
+ depth: remainingDepth
2050
+ });
2051
+ if (!stream)
2052
+ return;
2053
+ return consumeDirectoryStream(stream, (entry) => {
2054
+ if (!this.isHelperActive(wh, dir))
2055
+ return;
2056
+ const stats = entry.stats;
2057
+ if (!stats)
2058
+ return;
2059
+ const path = sp5.join(dir, entry.path);
2060
+ if (!this.isHelperActive(wh, path))
2061
+ return;
2062
+ const directory = sp5.dirname(path);
2063
+ const item = sp5.basename(path);
2064
+ if (rescan) {
2065
+ rescan.seen.add(logicalPathKey(path));
2066
+ if (stats.isDirectory())
2067
+ rescan.directories.push(path);
2068
+ }
2069
+ if (stats.isSymbolicLink()) {
2070
+ return (async () => {
2071
+ if (await this.handleSymlink(entry, directory, path, item, initialAdd, wh))
2072
+ return;
2073
+ if (!this.isHelperActive(wh, path))
2074
+ return;
2075
+ const entryDepth = baseDepth + entry.path.split(/[/\\]/).length;
2076
+ await this.addPathOnce(path, initialAdd, wh, entryDepth);
2077
+ })();
2078
+ }
2079
+ const parent = fsw.tree.getDirectory(directory);
2080
+ if (parent.has(item)) {
2081
+ if (rescan && stats.isFile() && fsw.tree.changedSinceObserved(path, stats)) {
2082
+ fsw.tree.recordObserved(path, stats, "change", void 0, false, true);
2083
+ fsw.emitEvent(EV2.CHANGE, path, stats);
877
2084
  }
878
- const wasThrottled = throttler ? throttler.clear() : false;
879
- resolve3(void 0);
880
- previous.getChildren().filter((item) => {
881
- return item !== directory && !current.has(item);
882
- }).forEach((item) => {
883
- this.fsw._remove(directory, item);
884
- });
885
- stream = void 0;
886
- if (wasThrottled)
887
- this._handleRead(directory, false, wh, target, dir, depth, throttler);
888
- });
2085
+ return;
2086
+ }
2087
+ parent.add(item);
2088
+ const isDirectory = stats.isDirectory();
2089
+ if (isDirectory)
2090
+ fsw.tree.getDirectory(path);
2091
+ fsw.tree.recordObserved(path, stats, "add", wh.observationTrigger, initialAdd);
2092
+ if (!(initialAdd && fsw.options.ignoreInitial)) {
2093
+ fsw.emitEvent(isDirectory ? EV2.ADD_DIR : EV2.ADD, path, stats);
2094
+ }
2095
+ }).then((outcome) => {
2096
+ if (outcome.error)
2097
+ this.reportError(outcome.error);
2098
+ outcome.failures.forEach(this.reportError);
2099
+ if (rescan)
2100
+ rescan.complete = outcome.complete;
889
2101
  });
890
2102
  }
2103
+ /**
2104
+ * Reconcile a whole recursive root after an invalidation that names no path
2105
+ * (a backend buffer overflow) or a replay buffer overflow. A shallow root
2106
+ * listing would miss every change below the first level.
2107
+ */
2108
+ async rescanRecursiveTree(dir, wh, baseDepth) {
2109
+ const rescan = { seen: /* @__PURE__ */ new Set(), directories: [dir], complete: false };
2110
+ await this.scanRecursiveTree(dir, false, wh, baseDepth, rescan);
2111
+ if (!rescan.complete || !this.isHelperActive(wh, dir))
2112
+ return;
2113
+ const missing = [];
2114
+ for (const directory of rescan.directories) {
2115
+ for (const item of this.fsw.tree.peekDirectory(directory)?.getChildren() ?? []) {
2116
+ const path = sp5.join(directory, item);
2117
+ if (!rescan.seen.has(logicalPathKey(path)))
2118
+ missing.push(path);
2119
+ }
2120
+ }
2121
+ missing.sort((left, right) => left.length - right.length);
2122
+ for (const path of missing) {
2123
+ const entry = this.fsw.tree.peekDirectory(sp5.dirname(path));
2124
+ if (entry?.has(sp5.basename(path))) {
2125
+ await this.removeIfMissing(wh, sp5.dirname(path), sp5.basename(path), entry);
2126
+ }
2127
+ }
2128
+ }
2129
+ isHelperActive(wh, path = wh.watchPath) {
2130
+ return this.fsw.isPathGenerationActive(path, wh.pathGeneration);
2131
+ }
2132
+ candidateDepth(root, candidate) {
2133
+ const relative7 = sp5.relative(root, candidate);
2134
+ return relative7 ? relative7.split(sp5.sep).length : 0;
2135
+ }
2136
+ candidateIgnored(root, candidate, stats) {
2137
+ const relative7 = sp5.relative(root, candidate);
2138
+ let ancestor = root;
2139
+ if (this.fsw.isIgnored(ancestor))
2140
+ return true;
2141
+ if (relative7) {
2142
+ const parts = relative7.split(sp5.sep);
2143
+ for (let index = 0; index < parts.length - 1; index++) {
2144
+ ancestor = sp5.join(ancestor, parts[index]);
2145
+ if (this.fsw.isIgnored(ancestor))
2146
+ return true;
2147
+ }
2148
+ }
2149
+ return this.fsw.isIgnored(candidate, stats);
2150
+ }
2151
+ async highestMissingPath(root, candidate) {
2152
+ let missing = candidate;
2153
+ let ancestor = sp5.dirname(candidate);
2154
+ while (true) {
2155
+ try {
2156
+ await lstat(ancestor);
2157
+ return missing;
2158
+ } catch (error62) {
2159
+ if (!isMissingError(error62)) {
2160
+ this.reportError(error62);
2161
+ return missing;
2162
+ }
2163
+ }
2164
+ missing = ancestor;
2165
+ if (ancestor === root)
2166
+ return missing;
2167
+ const parent = sp5.dirname(ancestor);
2168
+ if (parent === ancestor)
2169
+ return missing;
2170
+ ancestor = parent;
2171
+ }
2172
+ }
2173
+ async reconcileNativeTrigger(root, rootHelper, trigger, candidateOverride, baseDepth = 0, exact) {
2174
+ const fsw = this.fsw;
2175
+ if (!this.isHelperActive(rootHelper, root))
2176
+ return;
2177
+ let localHelper;
2178
+ const helper = () => localHelper ??= rootHelper.withObservation(trigger);
2179
+ const candidate = candidateOverride ?? (trigger.relativePath === null ? root : resolveRecursiveCandidate(root, trigger.relativePath));
2180
+ if (!candidate) {
2181
+ this.reportError(new Error(`Native watcher reported a path outside its root: ${trigger.relativePath}`));
2182
+ return;
2183
+ }
2184
+ const depth = baseDepth + this.candidateDepth(root, candidate);
2185
+ const maxDepth = fsw.options.depth;
2186
+ if (maxDepth !== void 0 && depth > maxDepth + 1)
2187
+ return;
2188
+ if (this.candidateIgnored(root, candidate))
2189
+ return;
2190
+ let stats;
2191
+ try {
2192
+ stats = await lstat(candidate);
2193
+ } catch (error62) {
2194
+ if (!isMissingError(error62)) {
2195
+ this.reportError(error62);
2196
+ if (exact)
2197
+ return;
2198
+ const ancestor = candidate === root ? root : sp5.dirname(candidate);
2199
+ const ancestorDepth = Math.max(0, baseDepth + this.candidateDepth(root, ancestor));
2200
+ await this.readDirectory(ancestor, false, helper().fork(ancestor), void 0, ancestor, ancestorDepth);
2201
+ return;
2202
+ }
2203
+ if (fsw.closed)
2204
+ return;
2205
+ const missingPath = candidate === root ? root : await this.highestMissingPath(root, candidate);
2206
+ if (fsw.closed)
2207
+ return;
2208
+ if (missingPath === root) {
2209
+ fsw.removePath(sp5.dirname(root), sp5.basename(root), true);
2210
+ exact?.onRootMissing?.();
2211
+ return;
2212
+ }
2213
+ const parentPath2 = sp5.dirname(missingPath);
2214
+ const item2 = sp5.basename(missingPath);
2215
+ if (fsw.tree.getDirectory(parentPath2).has(item2)) {
2216
+ fsw.removePath(parentPath2, item2);
2217
+ } else if (!exact) {
2218
+ await this.readDirectory(parentPath2, false, helper().fork(parentPath2), void 0, parentPath2, Math.max(0, baseDepth + this.candidateDepth(root, parentPath2)));
2219
+ }
2220
+ return;
2221
+ }
2222
+ if (!this.isHelperActive(rootHelper, candidate) || this.candidateIgnored(root, candidate, stats)) {
2223
+ return;
2224
+ }
2225
+ if (!stats.isDirectory() && !(stats.isSymbolicLink() && fsw.options.followSymlinks)) {
2226
+ const initialCreate = fsw.tree.consumeInitialCreate(candidate, stats, trigger, fsw.options.ignoreInitial);
2227
+ if (initialCreate !== void 0) {
2228
+ if (initialCreate)
2229
+ fsw.emitEvent(initialCreate, candidate, stats);
2230
+ return;
2231
+ }
2232
+ }
2233
+ if (candidate === root) {
2234
+ if (!stats.isDirectory())
2235
+ return;
2236
+ if (rootHelper.recursiveRoot === root) {
2237
+ await this.rescanRecursiveTree(root, helper(), baseDepth);
2238
+ } else {
2239
+ await this.readDirectory(root, false, helper(), void 0, root, baseDepth);
2240
+ }
2241
+ return;
2242
+ }
2243
+ const parentPath = sp5.dirname(candidate);
2244
+ const item = sp5.basename(candidate);
2245
+ const parent = fsw.tree.getDirectory(parentPath);
2246
+ const tracked = parent.has(item);
2247
+ if (stats.isSymbolicLink()) {
2248
+ if (!fsw.options.followSymlinks) {
2249
+ let target = true;
2250
+ try {
2251
+ target = await readlink(candidate);
2252
+ } catch {
2253
+ }
2254
+ if (!tracked)
2255
+ parent.add(item);
2256
+ fsw.tree.symlinkPaths.set(logicalPathKey(candidate), target);
2257
+ if (!tracked || !fsw.tree.isDuplicateObservation(candidate, stats, trigger)) {
2258
+ fsw.emitEvent(tracked ? EV2.CHANGE : EV2.ADD, candidate, stats);
2259
+ }
2260
+ if (!tracked)
2261
+ fsw.tree.recordObserved(candidate, stats, "add", trigger);
2262
+ return;
2263
+ }
2264
+ const logicalKey = logicalPathKey(candidate);
2265
+ const previousTarget = fsw.tree.symlinkPaths.get(logicalKey);
2266
+ let currentTarget;
2267
+ try {
2268
+ currentTarget = await realpath(candidate);
2269
+ } catch (error62) {
2270
+ if (!isMissingError(error62)) {
2271
+ this.reportError(error62);
2272
+ return;
2273
+ }
2274
+ }
2275
+ const targetChanged = tracked && typeof previousTarget === "string" && (currentTarget === void 0 || logicalPathKey(previousTarget) !== logicalPathKey(currentTarget));
2276
+ if (targetChanged) {
2277
+ const previousKind = fsw.tree.observed.get(logicalKey)?.kind;
2278
+ fsw.removePath(parentPath, item, previousKind === "directory");
2279
+ if (!currentTarget || !this.isHelperActive(rootHelper, candidate))
2280
+ return;
2281
+ const linkHelper = helper().fork(candidate);
2282
+ linkHelper.recursiveRoot = void 0;
2283
+ await this.addPathOnce(candidate, false, linkHelper, depth);
2284
+ return;
2285
+ }
2286
+ const initialCreate = fsw.tree.consumeInitialCreate(candidate, stats, trigger, fsw.options.ignoreInitial);
2287
+ if (initialCreate !== void 0) {
2288
+ if (initialCreate) {
2289
+ fsw.closePath(candidate, true);
2290
+ const linkHelper = helper().fork(candidate);
2291
+ linkHelper.recursiveRoot = void 0;
2292
+ await this.addPathOnce(candidate, false, linkHelper, depth);
2293
+ }
2294
+ return;
2295
+ }
2296
+ if (!tracked) {
2297
+ const linkHelper = helper().fork(candidate);
2298
+ linkHelper.recursiveRoot = void 0;
2299
+ await this.addPathOnce(candidate, false, linkHelper, depth);
2300
+ } else {
2301
+ fsw.emitEvent(EV2.CHANGE, candidate, stats);
2302
+ }
2303
+ return;
2304
+ }
2305
+ if (stats.isDirectory()) {
2306
+ const directoryHelper = helper().fork(candidate);
2307
+ const initialCreate = fsw.tree.consumeInitialCreate(candidate, stats, trigger, fsw.options.ignoreInitial);
2308
+ if (initialCreate !== void 0) {
2309
+ if (initialCreate) {
2310
+ fsw.closePath(candidate, true);
2311
+ await this.addPathOnce(candidate, false, directoryHelper, depth);
2312
+ }
2313
+ return;
2314
+ }
2315
+ if (!tracked) {
2316
+ await this.addPathOnce(candidate, false, directoryHelper, depth);
2317
+ } else if (fsw.tree.replacedSinceObserved(candidate, stats)) {
2318
+ fsw.removePath(parentPath, item, true);
2319
+ await this.addPathOnce(candidate, false, directoryHelper, depth);
2320
+ } else if (maxDepth === void 0 || depth <= maxDepth) {
2321
+ await this.readDirectory(candidate, false, directoryHelper, void 0, candidate, depth);
2322
+ }
2323
+ return;
2324
+ }
2325
+ if (!tracked) {
2326
+ await this.addPathOnce(candidate, false, helper(), depth);
2327
+ } else if (!fsw.tree.isDuplicateObservation(candidate, stats, trigger)) {
2328
+ fsw.emitEvent(EV2.CHANGE, candidate, stats);
2329
+ }
2330
+ }
2331
+ /**
2332
+ * Keep a Windows parent handle for a directly watched directory. Windows can
2333
+ * silently retire the directory's own handle when an empty root is removed;
2334
+ * its parent still receives the namespace transition and can reconcile it.
2335
+ */
2336
+ watchRootParent(dir, wh) {
2337
+ if (!this.fsw.options.backendCapabilities.perDirectory || !isWindows)
2338
+ return;
2339
+ const parentPath = sp5.dirname(dir);
2340
+ if (sp5.resolve(parentPath) === sp5.resolve(dir))
2341
+ return;
2342
+ const canonicalParent = sp5.normalize(sp5.toNamespacedPath(sp5.resolve(parentPath))).toLowerCase();
2343
+ const rootName = sp5.basename(dir).toLowerCase();
2344
+ const generation = this.fsw.lifecycle.generation;
2345
+ let active = true;
2346
+ const matchesRoot = (relativePath) => {
2347
+ if (relativePath === null)
2348
+ return true;
2349
+ const candidate = sp5.isAbsolute(relativePath) ? sp5.resolve(relativePath) : sp5.resolve(parentPath, relativePath);
2350
+ return sp5.normalize(sp5.toNamespacedPath(sp5.dirname(candidate))).toLowerCase() === canonicalParent && sp5.basename(candidate).toLowerCase() === rootName;
2351
+ };
2352
+ const isActive = () => active && this.fsw.lifecycle.isActive(generation) && this.isHelperActive(wh, dir);
2353
+ const publish = (trigger) => {
2354
+ if (trigger.kind !== "native" || !matchesRoot(trigger.relativePath) || !isActive())
2355
+ return;
2356
+ void this.reconcileBackendTrigger(dir, false, trigger, async () => {
2357
+ let rootStats;
2358
+ try {
2359
+ rootStats = await lstat(dir);
2360
+ } catch (error62) {
2361
+ if (isMissingError(error62)) {
2362
+ this.fsw.removePath(parentPath, sp5.basename(dir), true);
2363
+ } else {
2364
+ this.reportError(error62);
2365
+ }
2366
+ return;
2367
+ }
2368
+ if (!isActive())
2369
+ return;
2370
+ if (!rootStats.isDirectory()) {
2371
+ this.fsw.removePath(parentPath, sp5.basename(dir), true);
2372
+ await this.addPathOnce(dir, false, wh, 0);
2373
+ return;
2374
+ }
2375
+ await this.readDirectory(dir, false, wh, void 0, dir, 0);
2376
+ }, isActive);
2377
+ };
2378
+ const subscription = setFsWatchListener(parentPath, sp5.resolve(parentPath), { persistent: this.fsw.options.persistent }, {
2379
+ publish,
2380
+ errHandler: this.reportError,
2381
+ rawEmitter: (event, relativePath, details) => {
2382
+ if (matchesRoot(relativePath))
2383
+ this.fsw.emitRaw(event, relativePath, details);
2384
+ }
2385
+ }, this.fsw.lifecycle.abortController.signal);
2386
+ if (!subscription)
2387
+ return;
2388
+ return () => {
2389
+ if (!active)
2390
+ return;
2391
+ active = false;
2392
+ return subscription.close();
2393
+ };
2394
+ }
2395
+ async watchRecursiveDirectory(dir, initialAdd, depth, wh) {
2396
+ const fsw = this.fsw;
2397
+ const generation = fsw.lifecycle.generation;
2398
+ const rootKey = logicalPathKey(dir);
2399
+ const buffered = new ReplayBuffer(RECURSIVE_TRIGGER_BUFFER_LIMIT);
2400
+ const fallbackClosers = [];
2401
+ let phase = "scanning";
2402
+ let pendingFailure;
2403
+ let hasPendingFailure = false;
2404
+ let recovery;
2405
+ let subscription;
2406
+ const scopeActive = (path = dir) => fsw.lifecycle.isActive(generation) && fsw.isPathGenerationActive(path, wh.pathGeneration);
2407
+ const acceptsTrigger = (path = dir) => phase !== "recovering" && phase !== "closed" && scopeActive(path);
2408
+ const establishFallback = async (error62) => {
2409
+ if (!scopeActive())
2410
+ return;
2411
+ wh.recursiveRoot = void 0;
2412
+ wh.recursiveDisabled = true;
2413
+ let currentStats;
2414
+ try {
2415
+ currentStats = await lstat(dir);
2416
+ } catch (statError) {
2417
+ if (isMissingError(statError))
2418
+ fsw.removePath(sp5.dirname(dir), sp5.basename(dir), true);
2419
+ else
2420
+ this.reportError(statError);
2421
+ this.reportError(error62);
2422
+ return;
2423
+ }
2424
+ const closer = await this.handleDirectory(dir, currentStats, false, depth, void 0, wh);
2425
+ if (!scopeActive()) {
2426
+ if (closer)
2427
+ await closer();
2428
+ return;
2429
+ }
2430
+ if (closer)
2431
+ fallbackClosers.push(closer);
2432
+ await this.subscribeTrackedDirectories(dir, wh, depth);
2433
+ this.reportError(error62);
2434
+ };
2435
+ const handleFailure = (error62) => {
2436
+ if (!acceptsTrigger())
2437
+ return;
2438
+ const initializing = phase !== "live";
2439
+ phase = "recovering";
2440
+ fsw.tree.recursiveRoots.delete(rootKey);
2441
+ pendingFailure = error62;
2442
+ hasPendingFailure = true;
2443
+ if (!initializing) {
2444
+ recovery = fsw.reconciliation.enqueue(dir, () => establishFallback(error62), false);
2445
+ }
2446
+ };
2447
+ const processTrigger = (trigger) => {
2448
+ if (!acceptsTrigger())
2449
+ return;
2450
+ if (phase !== "live") {
2451
+ buffered.push(trigger);
2452
+ return;
2453
+ }
2454
+ const coalescePath = trigger.relativePath === null ? dir : resolveRecursiveCandidate(dir, trigger.relativePath) ?? dir;
2455
+ void this.reconcileBackendTrigger(dir, true, trigger, () => acceptsTrigger() ? this.reconcileNativeTrigger(dir, wh, trigger) : void 0, () => acceptsTrigger(coalescePath));
2456
+ };
2457
+ const result = subscribeRecursiveNative(dir, fsw.options.persistent, {
2458
+ publish: processTrigger,
2459
+ failure: handleFailure,
2460
+ rawEmitter: (...args) => fsw.emitRaw(...args)
2461
+ }, fsw.lifecycle.abortController.signal);
2462
+ if (result.kind === "unsupported")
2463
+ return false;
2464
+ if (result.kind === "failed")
2465
+ throw result.error;
2466
+ subscription = result.subscription;
2467
+ fsw.tree.recursiveRoots.add(rootKey);
2468
+ wh.recursiveRoot = dir;
2469
+ const close = async () => {
2470
+ if (phase === "closed")
2471
+ return;
2472
+ phase = "closed";
2473
+ fsw.tree.recursiveRoots.delete(rootKey);
2474
+ buffered.clear();
2475
+ await subscription?.close();
2476
+ if (recovery)
2477
+ await Promise.allSettled([recovery]);
2478
+ await Promise.allSettled(fallbackClosers.map((closer) => closer()));
2479
+ };
2480
+ try {
2481
+ await this.scanRecursiveTree(dir, initialAdd, wh, depth);
2482
+ if (!hasPendingFailure) {
2483
+ phase = "replaying";
2484
+ let index = 0;
2485
+ while (acceptsTrigger()) {
2486
+ if (buffered.overflowed) {
2487
+ buffered.clear();
2488
+ index = 0;
2489
+ const overflowTrigger = {
2490
+ kind: "native",
2491
+ resource: subscription.resource,
2492
+ rawEvent: EV2.CHANGE,
2493
+ relativePath: null,
2494
+ sequence: Number.MAX_SAFE_INTEGER,
2495
+ observedAt: backendNow()
2496
+ };
2497
+ await this.reconcileBackendTrigger(dir, true, overflowTrigger, () => this.reconcileNativeTrigger(dir, wh, overflowTrigger), () => acceptsTrigger(), false);
2498
+ continue;
2499
+ }
2500
+ if (index >= buffered.entries.length)
2501
+ break;
2502
+ const trigger = buffered.entries[index++];
2503
+ if (trigger.rawEvent === "rename" && trigger.relativePath !== null) {
2504
+ const candidate = resolveRecursiveCandidate(dir, trigger.relativePath);
2505
+ if (candidate && candidate !== dir && fsw.tree.getDirectory(sp5.dirname(candidate)).has(sp5.basename(candidate))) {
2506
+ fsw.tree.markInitialCreate(candidate);
2507
+ }
2508
+ }
2509
+ await this.reconcileBackendTrigger(dir, true, trigger, () => this.reconcileNativeTrigger(dir, wh, trigger), () => acceptsTrigger(), false);
2510
+ }
2511
+ if (phase !== "recovering")
2512
+ phase = "live";
2513
+ }
2514
+ if (hasPendingFailure) {
2515
+ buffered.clear();
2516
+ await establishFallback(pendingFailure);
2517
+ }
2518
+ buffered.clear();
2519
+ fsw.tree.clearInitialCreates(dir);
2520
+ } catch (error62) {
2521
+ await close();
2522
+ throw error62;
2523
+ }
2524
+ if (!scopeActive()) {
2525
+ await close();
2526
+ return;
2527
+ }
2528
+ return close;
2529
+ }
2530
+ /**
2531
+ * A recursive root that falls back to per-directory handles already tracks
2532
+ * every subdirectory, so the fallback scan sees none of them as new. Give
2533
+ * each its own subscription; existing entries emit nothing.
2534
+ */
2535
+ async subscribeTrackedDirectories(root, wh, baseDepth) {
2536
+ const fsw = this.fsw;
2537
+ const absoluteRoot = sp5.resolve(root);
2538
+ const needsSubscription = (path) => {
2539
+ const key = logicalPathKey(path);
2540
+ return this.isHelperActive(wh, path) && !fsw.lifecycle.closers.has(key) && !fsw.tree.symlinkPaths.has(key) && (fsw.tree.peekDirectory(sp5.dirname(path))?.has(sp5.basename(path)) ?? false);
2541
+ };
2542
+ const directories = [...fsw.tree.watched.values()].filter((entry) => isStrictlyInside(absoluteRoot, entry.path)).map((entry) => sp5.join(root, sp5.relative(absoluteRoot, entry.path))).filter(needsSubscription).sort((left, right) => left.length - right.length);
2543
+ let next = 0;
2544
+ const subscribeNext = async () => {
2545
+ while (next < directories.length) {
2546
+ const directory = directories[next++];
2547
+ if (!needsSubscription(directory))
2548
+ continue;
2549
+ await this.addPathOnce(directory, false, wh, baseDepth + this.candidateDepth(root, directory));
2550
+ }
2551
+ };
2552
+ const workers = Math.min(FALLBACK_SUBSCRIBE_CONCURRENCY, directories.length);
2553
+ await Promise.all(Array.from({ length: workers }, subscribeNext));
2554
+ }
891
2555
  /**
892
2556
  * Read directory to add / remove files from `@watched` list and re-read it on change.
893
2557
  * @param dir fs path
@@ -896,413 +2560,578 @@ var NodeFsHandler = class {
896
2560
  * @param depth relative to user-supplied path
897
2561
  * @param target child path targeted for watch
898
2562
  * @param wh Common watch helpers for this path
899
- * @param realpath
900
2563
  * @returns closer for the watcher instance.
901
2564
  */
902
- async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
903
- const parentDir = this.fsw._getWatchedDir(sp2.dirname(dir));
904
- const tracked = parentDir.has(sp2.basename(dir));
905
- if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
906
- this.fsw._emit(EV.ADD_DIR, dir, stats);
2565
+ async handleDirectory(dir, stats, initialAdd, depth, target, wh) {
2566
+ if (!this.isHelperActive(wh, dir))
2567
+ return;
2568
+ if (target) {
2569
+ this.fsw.tree.getDirectory(dir);
2570
+ } else {
2571
+ const parentDir = this.fsw.tree.getDirectory(sp5.dirname(dir));
2572
+ const tracked = parentDir.has(sp5.basename(dir));
2573
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !tracked) {
2574
+ this.fsw.emitEvent(EV2.ADD_DIR, dir, stats);
2575
+ }
2576
+ parentDir.add(sp5.basename(dir));
2577
+ this.fsw.tree.getDirectory(dir);
2578
+ this.fsw.tree.recordObserved(dir, stats, tracked ? void 0 : "add", wh.observationTrigger, initialAdd && Boolean(wh.recursiveRoot), true);
907
2579
  }
908
- parentDir.add(sp2.basename(dir));
909
- this.fsw._getWatchedDir(dir);
910
- let throttler;
911
2580
  let closer;
912
2581
  const oDepth = this.fsw.options.depth;
913
- if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
914
- if (!target) {
915
- await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
916
- if (this.fsw.closed)
917
- return;
2582
+ if (oDepth == null || depth <= oDepth) {
2583
+ if (this.fsw.options.backendCapabilities.recursive && depth === 0 && !target && !wh.recursiveRoot && !wh.recursiveDisabled) {
2584
+ const recursiveCloser = await this.watchRecursiveDirectory(dir, initialAdd, depth, wh);
2585
+ if (recursiveCloser !== false)
2586
+ return recursiveCloser;
2587
+ }
2588
+ if (wh.recursiveRoot) {
2589
+ if (!target) {
2590
+ await this.scanRecursiveTree(dir, initialAdd, wh, depth);
2591
+ }
2592
+ return;
918
2593
  }
919
- closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
920
- if (stats2 && stats2.mtimeMs === 0)
2594
+ const buffered = new ReplayBuffer(RECURSIVE_TRIGGER_BUFFER_LIMIT);
2595
+ const replayCreates = /* @__PURE__ */ new Set();
2596
+ let initializing = !target;
2597
+ let active = true;
2598
+ let rescanOnFirstCallback = isMacos && !target;
2599
+ const targetPath = target ? sp5.join(dir, target) : void 0;
2600
+ const rewatchTarget = () => {
2601
+ if (targetPath && active && this.isHelperActive(wh, targetPath)) {
2602
+ this.fsw.rewatchMissingPath(targetPath);
2603
+ }
2604
+ };
2605
+ const removeObserved = (dirPath) => {
2606
+ if (target) {
2607
+ if (this.fsw.tree.getDirectory(dirPath).has(target))
2608
+ this.fsw.removePath(dirPath, target);
2609
+ rewatchTarget();
921
2610
  return;
922
- this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
923
- });
2611
+ }
2612
+ this.fsw.removePath(sp5.dirname(dirPath), sp5.basename(dirPath), true);
2613
+ };
2614
+ const observeDirectory = async (dirPath, currentStats, trigger) => {
2615
+ if (!active || !this.isHelperActive(wh, dirPath))
2616
+ return;
2617
+ if (this.fsw.options.backendCapabilities.polling && !currentStats) {
2618
+ removeObserved(dirPath);
2619
+ return;
2620
+ }
2621
+ if (trigger.kind === "native") {
2622
+ let observedStats;
2623
+ try {
2624
+ const linkStats = await lstat(dirPath);
2625
+ observedStats = linkStats.isSymbolicLink() && this.fsw.options.followSymlinks ? await stat(dirPath) : linkStats;
2626
+ } catch (error62) {
2627
+ if (isMissingError(error62)) {
2628
+ removeObserved(dirPath);
2629
+ } else {
2630
+ this.reportError(error62);
2631
+ }
2632
+ return;
2633
+ }
2634
+ if (!observedStats.isDirectory()) {
2635
+ removeObserved(dirPath);
2636
+ if (!target)
2637
+ await this.addPathOnce(dirPath, false, wh, depth);
2638
+ return;
2639
+ }
2640
+ }
2641
+ await this.readDirectory(dirPath, false, wh, target, dir, depth);
2642
+ };
2643
+ const reconcile = (candidate, currentStats, trigger) => {
2644
+ if (!active || !this.isHelperActive(wh, candidate))
2645
+ return;
2646
+ if (initializing) {
2647
+ buffered.push({ path: candidate, stats: currentStats, trigger });
2648
+ return;
2649
+ }
2650
+ if (trigger.kind === "native" && !target) {
2651
+ if (rescanOnFirstCallback) {
2652
+ rescanOnFirstCallback = false;
2653
+ return (async () => {
2654
+ await this.reconcileNativeTrigger(dir, wh, trigger, candidate, depth);
2655
+ await observeDirectory(dir, void 0, trigger);
2656
+ })();
2657
+ }
2658
+ return this.reconcileNativeTrigger(dir, wh, trigger, candidate, depth);
2659
+ }
2660
+ if (trigger.kind === "native" && target) {
2661
+ const matchesTarget = candidate === dir || (isWindows ? sp5.basename(candidate).toLowerCase() === target.toLowerCase() : sp5.basename(candidate) === target);
2662
+ if (matchesTarget) {
2663
+ return this.reconcileNativeTrigger(dir, wh, trigger, targetPath, depth, {
2664
+ onRootMissing: rewatchTarget
2665
+ });
2666
+ }
2667
+ }
2668
+ return observeDirectory(dir, currentStats, trigger);
2669
+ };
2670
+ const rootParentCloser = depth === 0 && !target ? this.watchRootParent(dir, wh) : void 0;
2671
+ closer = this.subscribePath(dir, reconcile, stats.isDirectory() ? stats : void 0, true, target ? sp5.join(dir, target) : dir);
2672
+ if (target && targetPath && closer) {
2673
+ const check2 = recoveryTrigger(sp5.resolve(dir));
2674
+ await this.fsw.reconciliation.enqueue(targetPath, async () => {
2675
+ if (this.fsw.tree.getDirectory(dir).has(target))
2676
+ return;
2677
+ await reconcile(targetPath, void 0, check2);
2678
+ }, targetPath);
2679
+ }
2680
+ if (!target) {
2681
+ await this.readDirectory(dir, initialAdd, wh, target, dir, depth);
2682
+ let index = 0;
2683
+ while (!this.fsw.closed) {
2684
+ if (buffered.overflow) {
2685
+ const overflow = buffered.overflow;
2686
+ buffered.clear();
2687
+ index = 0;
2688
+ await observeDirectory(dir, overflow.stats, overflow.trigger);
2689
+ continue;
2690
+ }
2691
+ if (index >= buffered.entries.length)
2692
+ break;
2693
+ const event = buffered.entries[index++];
2694
+ if (event.trigger.kind === "native" && event.trigger.rawEvent === "rename" && event.path !== dir && this.fsw.tree.getDirectory(sp5.dirname(event.path)).has(sp5.basename(event.path))) {
2695
+ this.fsw.tree.markInitialCreate(event.path);
2696
+ replayCreates.add(event.path);
2697
+ }
2698
+ await this.reconcileBackendTrigger(dir, true, event.trigger, () => {
2699
+ if (event.trigger.kind === "native" && !target) {
2700
+ return this.reconcileNativeTrigger(dir, wh, event.trigger, event.path, depth);
2701
+ }
2702
+ return observeDirectory(dir, event.stats, event.trigger);
2703
+ }, () => active && this.isHelperActive(wh, event.path), false);
2704
+ }
2705
+ buffered.clear();
2706
+ replayCreates.forEach((path) => this.fsw.tree.clearInitialCreate(path));
2707
+ initializing = false;
2708
+ }
2709
+ if (!this.isHelperActive(wh, dir)) {
2710
+ active = false;
2711
+ if (closer)
2712
+ await closer();
2713
+ if (rootParentCloser)
2714
+ await rootParentCloser();
2715
+ return;
2716
+ }
2717
+ if (closer || rootParentCloser) {
2718
+ const backendClosers = [closer, rootParentCloser].filter((candidate) => candidate !== void 0);
2719
+ closer = async () => {
2720
+ if (!active)
2721
+ return;
2722
+ active = false;
2723
+ buffered.clear();
2724
+ await Promise.allSettled(backendClosers.map((backendCloser) => backendCloser()));
2725
+ };
2726
+ }
924
2727
  }
925
2728
  return closer;
926
2729
  }
927
2730
  /**
928
2731
  * Handle added file, directory, or glob pattern.
929
- * Delegates call to _handleFile / _handleDir after checks.
2732
+ * Delegates call to handleFile / handleDirectory after checks.
930
2733
  * @param path to file or ir
931
2734
  * @param initialAdd was the file added at watch instantiation?
932
2735
  * @param priorWh depth relative to user-supplied path
933
2736
  * @param depth Child path actually targeted for watch
934
2737
  * @param target Child path actually targeted for watch
935
2738
  */
936
- async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
937
- const ready = this.fsw._emitReady;
938
- if (this.fsw._isIgnored(path) || this.fsw.closed) {
939
- ready();
940
- return false;
2739
+ async addRoot(path, initialAdd, pathGeneration, target) {
2740
+ let candidate = path;
2741
+ let childTarget = target;
2742
+ const generation = this.fsw.lifecycle.generation;
2743
+ while (this.fsw.lifecycle.isActive(generation)) {
2744
+ const outcome = await this.addPathOnce(candidate, initialAdd, void 0, 0, childTarget, pathGeneration);
2745
+ if (outcome === "complete")
2746
+ return;
2747
+ const parent = sp5.dirname(candidate);
2748
+ if (parent === candidate)
2749
+ return;
2750
+ childTarget = sp5.basename(candidate);
2751
+ candidate = parent;
941
2752
  }
942
- const wh = this.fsw._getWatchHelpers(path);
943
- if (priorWh) {
944
- wh.filterPath = (entry) => priorWh.filterPath(entry);
945
- wh.filterDir = (entry) => priorWh.filterDir(entry);
2753
+ }
2754
+ async addPathOnce(path, initialAdd, priorWh, depth, target, pathGeneration) {
2755
+ if (this.fsw.isIgnored(path) || this.fsw.closed) {
2756
+ return "complete";
2757
+ }
2758
+ const wh = priorWh ? priorWh.fork(path) : this.fsw.createHelper(path);
2759
+ if (!priorWh && pathGeneration !== void 0)
2760
+ wh.pathGeneration = pathGeneration;
2761
+ if (!this.isHelperActive(wh)) {
2762
+ return "complete";
946
2763
  }
947
2764
  try {
948
- const stats = await statMethods[wh.statMethod](wh.watchPath);
949
- if (this.fsw.closed)
950
- return;
951
- if (this.fsw._isIgnored(wh.watchPath, stats)) {
952
- ready();
953
- return false;
2765
+ const linkStats = await lstat(wh.watchPath);
2766
+ if (!this.isHelperActive(wh)) {
2767
+ return "complete";
2768
+ }
2769
+ if (this.fsw.isIgnored(wh.watchPath, linkStats)) {
2770
+ return "complete";
954
2771
  }
955
2772
  const follow = this.fsw.options.followSymlinks;
2773
+ const isSymbolicLink = linkStats.isSymbolicLink();
2774
+ const stats = isSymbolicLink && follow ? await stat(wh.watchPath) : linkStats;
2775
+ const followedTarget = isSymbolicLink && follow ? await realpath(path) : void 0;
956
2776
  let closer;
957
2777
  if (stats.isDirectory()) {
958
- const absPath = sp2.resolve(path);
959
- const targetPath = follow ? await realpath(path) : path;
960
- if (this.fsw.closed)
961
- return;
962
- closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
963
- if (this.fsw.closed)
964
- return;
965
- if (absPath !== targetPath && targetPath !== void 0) {
966
- this.fsw._symlinkPaths.set(absPath, targetPath);
2778
+ const absPath = logicalPathKey(path);
2779
+ const ancestryPath = follow ? await realpath(path) : path;
2780
+ const targetPath = followedTarget ?? path;
2781
+ const targetKey = logicalPathKey(ancestryPath);
2782
+ if (!this.isHelperActive(wh)) {
2783
+ return "complete";
967
2784
  }
968
- } else if (stats.isSymbolicLink()) {
969
- const targetPath = follow ? await realpath(path) : path;
970
- if (this.fsw.closed)
971
- return;
972
- const parent = sp2.dirname(wh.watchPath);
973
- this.fsw._getWatchedDir(parent).add(wh.watchPath);
974
- this.fsw._emit(EV.ADD, wh.watchPath, stats);
975
- closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
976
- if (this.fsw.closed)
977
- return;
978
- if (targetPath !== void 0) {
979
- this.fsw._symlinkPaths.set(sp2.resolve(path), targetPath);
2785
+ if (isSymbolicLink && wh.realpathAncestry.has(targetKey)) {
2786
+ const parent = this.fsw.tree.getDirectory(sp5.dirname(wh.watchPath));
2787
+ parent.add(sp5.basename(wh.watchPath));
2788
+ this.fsw.tree.getDirectory(wh.watchPath);
2789
+ this.fsw.tree.symlinkPaths.set(absPath, targetPath);
2790
+ this.fsw.tree.recordObserved(wh.watchPath, stats, "add", wh.observationTrigger, initialAdd && Boolean(wh.recursiveRoot));
2791
+ if (!(initialAdd && this.fsw.options.ignoreInitial)) {
2792
+ this.fsw.emitEvent(EV2.ADD_DIR, wh.watchPath, stats);
2793
+ }
2794
+ return "complete";
980
2795
  }
2796
+ wh.realpathAncestry.add(targetKey);
2797
+ if (wh.recursiveRoot && isSymbolicLink) {
2798
+ wh.recursiveRoot = void 0;
2799
+ }
2800
+ if (isSymbolicLink)
2801
+ wh.recursiveDisabled = true;
2802
+ closer = await this.handleDirectory(wh.watchPath, stats, initialAdd, depth, target, wh);
2803
+ if (!this.isHelperActive(wh)) {
2804
+ if (closer)
2805
+ await closer();
2806
+ return "complete";
2807
+ }
2808
+ if (target && !closer)
2809
+ return "watch-parent";
2810
+ if (isSymbolicLink) {
2811
+ this.fsw.tree.symlinkPaths.set(absPath, targetPath);
2812
+ }
2813
+ } else if (isSymbolicLink && !follow) {
2814
+ const linkTarget = await readlink(path);
2815
+ const retainsNativeFact = !this.fsw.options.backendCapabilities.polling && !wh.recursiveRoot && !priorWh;
2816
+ const fileCloser = this.handleFile(wh.watchPath, stats, initialAdd, !wh.recursiveRoot, wh.observationTrigger, initialAdd && Boolean(wh.recursiveRoot), retainsNativeFact);
2817
+ if (wh.recursiveRoot) {
2818
+ this.fsw.tree.symlinkPaths.set(logicalPathKey(path), linkTarget);
2819
+ return "complete";
2820
+ }
2821
+ const parent = sp5.dirname(wh.watchPath);
2822
+ const parentStats = await stat(parent);
2823
+ const parentHelper = this.fsw.createHelper(parent);
2824
+ parentHelper.pathGeneration = wh.pathGeneration;
2825
+ const parentCloser = await this.handleDirectory(parent, parentStats, initialAdd, depth, sp5.basename(wh.watchPath), parentHelper);
2826
+ const deletionCloser = this.watchSymlinkDeletion(wh.watchPath);
2827
+ if (!this.isHelperActive(wh)) {
2828
+ if (fileCloser)
2829
+ await fileCloser();
2830
+ if (parentCloser)
2831
+ await parentCloser();
2832
+ if (deletionCloser)
2833
+ deletionCloser();
2834
+ return "complete";
2835
+ }
2836
+ closer = async () => {
2837
+ await Promise.allSettled([fileCloser, parentCloser, deletionCloser].filter((candidate) => candidate !== void 0).map((backendCloser) => backendCloser()));
2838
+ };
2839
+ this.fsw.tree.symlinkPaths.set(logicalPathKey(path), linkTarget);
981
2840
  } else {
982
- closer = this._handleFile(wh.watchPath, stats, initialAdd);
2841
+ if (followedTarget) {
2842
+ this.fsw.tree.symlinkPaths.set(logicalPathKey(path), followedTarget);
2843
+ }
2844
+ const retainsNativeFact = !this.fsw.options.backendCapabilities.polling && !wh.recursiveRoot && !priorWh;
2845
+ const fileCloser = this.handleFile(wh.watchPath, stats, initialAdd, !wh.recursiveRoot, wh.observationTrigger, initialAdd && Boolean(wh.recursiveRoot), retainsNativeFact);
2846
+ const targetPath = followedTarget ?? (retainsNativeFact ? wh.watchPath : void 0);
2847
+ const targetCloser = targetPath ? this.subscribeMappedFile(wh.watchPath, targetPath, wh, depth, isMacos && stats.isFile()) : void 0;
2848
+ let parentCloser;
2849
+ if (retainsNativeFact && followedTarget) {
2850
+ const parent = sp5.dirname(wh.watchPath);
2851
+ const parentStats = await stat(parent);
2852
+ const parentHelper = this.fsw.createHelper(parent);
2853
+ parentHelper.pathGeneration = wh.pathGeneration;
2854
+ parentCloser = await this.handleDirectory(parent, parentStats, initialAdd, depth, sp5.basename(wh.watchPath), parentHelper);
2855
+ }
2856
+ const fileClosers = [fileCloser, targetCloser, parentCloser].filter((candidate) => candidate !== void 0);
2857
+ closer = fileClosers.length === 0 ? void 0 : async () => {
2858
+ await Promise.allSettled(fileClosers.map((fileCloser2) => fileCloser2()));
2859
+ };
2860
+ }
2861
+ if (!this.isHelperActive(wh)) {
2862
+ if (closer)
2863
+ await closer();
2864
+ return "complete";
983
2865
  }
984
- ready();
985
2866
  if (closer)
986
- this.fsw._addPathCloser(path, closer);
987
- return false;
2867
+ this.fsw.addPathCloser(target ? sp5.join(path, target) : path, closer);
2868
+ return "complete";
988
2869
  } catch (error62) {
989
- if (this.fsw._handleError(error62)) {
990
- ready();
991
- return path;
2870
+ if (!this.isHelperActive(wh)) {
2871
+ return "complete";
992
2872
  }
2873
+ this.fsw.handleError(error62);
2874
+ return "watch-parent";
993
2875
  }
994
2876
  }
995
2877
  };
996
2878
 
997
2879
  // ../../node_modules/chokidar/index.js
998
- var SLASH = "/";
999
- var SLASH_SLASH = "//";
1000
- var ONE_DOT = ".";
1001
- var TWO_DOTS = "..";
1002
- var STRING_TYPE = "string";
1003
- var BACK_SLASH_RE = /\\/g;
1004
- var DOUBLE_SLASH_RE = /\/\//g;
1005
2880
  var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1006
- var REPLACER_RE = /^\.[/\\]/;
1007
- function arrify(item) {
1008
- return Array.isArray(item) ? item : [item];
1009
- }
1010
- var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1011
- function createPattern(matcher) {
1012
- if (typeof matcher === "function")
1013
- return matcher;
1014
- if (typeof matcher === "string")
1015
- return (string4) => matcher === string4;
1016
- if (matcher instanceof RegExp)
1017
- return (string4) => matcher.test(string4);
1018
- if (typeof matcher === "object" && matcher !== null) {
1019
- return (string4) => {
1020
- if (matcher.path === string4)
1021
- return true;
1022
- if (matcher.recursive) {
1023
- const relative4 = sp2.relative(matcher.path, string4);
1024
- if (!relative4) {
1025
- return false;
1026
- }
1027
- return !relative4.startsWith("..") && !sp2.isAbsolute(relative4);
1028
- }
1029
- return false;
1030
- };
1031
- }
1032
- return () => false;
1033
- }
1034
- function normalizePath(path) {
1035
- if (typeof path !== "string")
1036
- throw new Error("string expected");
1037
- path = sp2.normalize(path);
1038
- path = path.replace(/\\/g, "/");
1039
- let prepend = false;
1040
- if (path.startsWith("//"))
1041
- prepend = true;
1042
- path = path.replace(DOUBLE_SLASH_RE, "/");
1043
- if (prepend)
1044
- path = "/" + path;
1045
- return path;
1046
- }
1047
- function matchPatterns(patterns, testString, stats) {
1048
- const path = normalizePath(testString);
1049
- for (let index = 0; index < patterns.length; index++) {
1050
- const pattern = patterns[index];
1051
- if (pattern(path, stats)) {
1052
- return true;
1053
- }
2881
+ var WATCH_BACKENDS = /* @__PURE__ */ new Set(["auto", "native", "native-recursive", "polling"]);
2882
+ var DEF_AWF = Object.freeze({ stabilityThreshold: 2e3, pollInterval: 100 });
2883
+ function* ancestorKeys(path) {
2884
+ let current = sp5.resolve(path);
2885
+ for (let parent = sp5.dirname(current); parent !== current; parent = sp5.dirname(parent)) {
2886
+ yield logicalPathKey(parent);
2887
+ current = parent;
1054
2888
  }
1055
- return false;
1056
2889
  }
1057
- function anymatch(matchers, testString) {
1058
- if (matchers == null) {
1059
- throw new TypeError("anymatch: specify first argument");
1060
- }
1061
- const matchersArray = arrify(matchers);
1062
- const patterns = matchersArray.map((matcher) => createPattern(matcher));
1063
- {
1064
- return (testString2, stats) => {
1065
- return matchPatterns(patterns, testString2, stats);
1066
- };
1067
- }
2890
+ function arrify(item) {
2891
+ return Array.isArray(item) ? item : [item];
1068
2892
  }
1069
- var unifyPaths = (paths_) => {
2893
+ function unifyPaths(paths_) {
1070
2894
  const paths = arrify(paths_).flat();
1071
- if (!paths.every((p) => typeof p === STRING_TYPE)) {
2895
+ if (!paths.every((p) => typeof p === "string")) {
1072
2896
  throw new TypeError(`Non-string provided as watch path: ${paths}`);
1073
2897
  }
1074
- return paths.map(normalizePathToUnix);
1075
- };
1076
- var toUnix = (string4) => {
1077
- let str = string4.replace(BACK_SLASH_RE, SLASH);
1078
- let prepend = false;
1079
- if (str.startsWith(SLASH_SLASH)) {
1080
- prepend = true;
1081
- }
1082
- str = str.replace(DOUBLE_SLASH_RE, SLASH);
1083
- if (prepend) {
1084
- str = SLASH + str;
1085
- }
1086
- return str;
1087
- };
1088
- var normalizePathToUnix = (path) => toUnix(sp2.normalize(toUnix(path)));
1089
- var normalizeIgnored = (cwd = "") => (path) => {
1090
- if (typeof path === "string") {
1091
- return normalizePathToUnix(sp2.isAbsolute(path) ? path : sp2.join(cwd, path));
1092
- } else {
1093
- return path;
1094
- }
1095
- };
1096
- var getAbsolutePath = (path, cwd) => {
1097
- if (sp2.isAbsolute(path)) {
2898
+ return paths.map(normalizePath);
2899
+ }
2900
+ function getAbsolutePath(path, cwd) {
2901
+ if (sp5.isAbsolute(path)) {
1098
2902
  return path;
1099
2903
  }
1100
- return sp2.join(cwd, path);
1101
- };
1102
- var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1103
- var DirEntry = class {
1104
- path;
1105
- _removeWatcher;
1106
- items;
1107
- constructor(dir, removeWatcher) {
1108
- this.path = dir;
1109
- this._removeWatcher = removeWatcher;
1110
- this.items = /* @__PURE__ */ new Set();
1111
- }
1112
- add(item) {
1113
- const { items } = this;
1114
- if (!items)
1115
- return;
1116
- if (item !== ONE_DOT && item !== TWO_DOTS)
1117
- items.add(item);
1118
- }
1119
- async remove(item) {
1120
- const { items } = this;
1121
- if (!items)
1122
- return;
1123
- items.delete(item);
1124
- if (items.size > 0)
1125
- return;
1126
- const dir = this.path;
1127
- try {
1128
- await readdir(dir);
1129
- } catch (err) {
1130
- if (this._removeWatcher) {
1131
- this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
1132
- }
1133
- }
1134
- }
1135
- has(item) {
1136
- const { items } = this;
1137
- if (!items)
1138
- return;
1139
- return items.has(item);
1140
- }
1141
- getChildren() {
1142
- const { items } = this;
1143
- if (!items)
1144
- return [];
1145
- return [...items.values()];
1146
- }
1147
- dispose() {
1148
- this.items.clear();
1149
- this.path = "";
1150
- this._removeWatcher = EMPTY_FN;
1151
- this.items = EMPTY_SET;
1152
- Object.freeze(this);
2904
+ return sp5.join(cwd, path);
2905
+ }
2906
+ function validatePositiveFinite(name, value) {
2907
+ if (!Number.isFinite(value) || value <= 0) {
2908
+ throw new TypeError(`${name} must be a finite number greater than zero`);
1153
2909
  }
1154
- };
1155
- var STAT_METHOD_F = "stat";
1156
- var STAT_METHOD_L = "lstat";
1157
- var WatchHelper = class {
1158
- fsw;
1159
- path;
1160
- watchPath;
1161
- fullWatchPath;
1162
- dirParts;
1163
- followSymlinks;
1164
- statMethod;
1165
- constructor(path, follow, fsw) {
1166
- this.fsw = fsw;
1167
- const watchPath = path;
1168
- this.path = path = path.replace(REPLACER_RE, "");
1169
- this.watchPath = watchPath;
1170
- this.fullWatchPath = sp2.resolve(watchPath);
1171
- this.dirParts = [];
1172
- this.dirParts.forEach((parts) => {
1173
- if (parts.length > 1)
1174
- parts.pop();
1175
- });
1176
- this.followSymlinks = follow;
1177
- this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
2910
+ }
2911
+ function validateNonNegativeFinite(name, value) {
2912
+ if (!Number.isFinite(value) || value < 0) {
2913
+ throw new TypeError(`${name} must be a finite non-negative number`);
1178
2914
  }
1179
- entryPath(entry) {
1180
- return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
2915
+ }
2916
+ function validateOptions(opts) {
2917
+ validatePositiveFinite("pollingInterval", opts.pollingInterval);
2918
+ validatePositiveFinite("pollingBinaryInterval", opts.pollingBinaryInterval);
2919
+ if (typeof opts.atomic === "number")
2920
+ validateNonNegativeFinite("atomic", opts.atomic);
2921
+ else if (typeof opts.atomic !== "boolean") {
2922
+ throw new TypeError("atomic must be a boolean or finite non-negative number");
1181
2923
  }
1182
- filterPath(entry) {
1183
- const { stats } = entry;
1184
- if (stats && stats.isSymbolicLink())
1185
- return this.filterDir(entry);
1186
- const resolvedPath = this.entryPath(entry);
1187
- return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
2924
+ if (opts.depth !== void 0 && (!Number.isSafeInteger(opts.depth) || opts.depth < 0)) {
2925
+ throw new TypeError("depth must be a non-negative safe integer");
1188
2926
  }
1189
- filterDir(entry) {
1190
- return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
2927
+ if (opts.awaitWriteFinish) {
2928
+ validatePositiveFinite("awaitWriteFinish.pollInterval", opts.awaitWriteFinish.pollInterval);
2929
+ validateNonNegativeFinite("awaitWriteFinish.stabilityThreshold", opts.awaitWriteFinish.stabilityThreshold);
1191
2930
  }
1192
- };
2931
+ }
1193
2932
  var FSWatcher = class extends EventEmitter {
1194
- closed;
1195
2933
  options;
1196
- _closers;
1197
- _ignoredPaths;
1198
- _throttled;
1199
- _streams;
1200
- _symlinkPaths;
1201
- _watched;
1202
- _pendingWrites;
1203
- _pendingUnlinks;
1204
- _readyCount;
1205
- _emitReady;
1206
- _closePromise;
1207
- _userIgnored;
1208
- _readyEmitted;
1209
- _emitRaw;
1210
- _boundRemove;
1211
- _nodeFsHandler;
2934
+ /** @internal */
2935
+ lifecycle;
2936
+ /** @internal */
2937
+ tree;
2938
+ /** @internal */
2939
+ reconciliation;
2940
+ /** @internal */
2941
+ events;
2942
+ /** @internal */
2943
+ scheduler;
2944
+ /** @internal */
2945
+ handler;
2946
+ /** @internal */
2947
+ readyEmitted;
2948
+ /** @internal */
2949
+ streams;
2950
+ get closed() {
2951
+ return this.lifecycle !== void 0 && this.lifecycle.state !== "OPEN";
2952
+ }
2953
+ #ignoredPaths;
2954
+ #pendingAdds;
2955
+ #pathMutation;
2956
+ #pathBarriers;
2957
+ #closePromise;
2958
+ #userIgnored;
2959
+ #realDirs;
2960
+ #roots;
2961
+ #rootAncestors;
2962
+ #unwatchIgnored;
2963
+ #readyPending;
2964
+ #readyScheduled;
1212
2965
  // Not indenting methods for history sake; for now.
1213
- constructor(_opts = {}) {
2966
+ constructor(_opts = {}, scheduler = systemScheduler) {
1214
2967
  super();
1215
- this.closed = false;
1216
- this._closers = /* @__PURE__ */ new Map();
1217
- this._ignoredPaths = /* @__PURE__ */ new Set();
1218
- this._throttled = /* @__PURE__ */ new Map();
1219
- this._streams = /* @__PURE__ */ new Set();
1220
- this._symlinkPaths = /* @__PURE__ */ new Map();
1221
- this._watched = /* @__PURE__ */ new Map();
1222
- this._pendingWrites = /* @__PURE__ */ new Map();
1223
- this._pendingUnlinks = /* @__PURE__ */ new Map();
1224
- this._readyCount = 0;
1225
- this._readyEmitted = false;
2968
+ if (_opts.backend !== void 0 && !WATCH_BACKENDS.has(_opts.backend)) {
2969
+ throw new TypeError("backend must be auto, native, native-recursive, or polling");
2970
+ }
2971
+ this.#ignoredPaths = /* @__PURE__ */ new Set();
2972
+ this.streams = /* @__PURE__ */ new Set();
2973
+ this.#pendingAdds = /* @__PURE__ */ new Map();
2974
+ this.#pathMutation = 0;
2975
+ this.#pathBarriers = /* @__PURE__ */ new Map();
2976
+ this.#realDirs = /* @__PURE__ */ new Map();
2977
+ this.#roots = /* @__PURE__ */ new Set();
2978
+ this.#rootAncestors = /* @__PURE__ */ new Map();
2979
+ this.readyEmitted = false;
2980
+ this.#readyPending = false;
2981
+ this.#readyScheduled = false;
2982
+ this.scheduler = scheduler;
1226
2983
  const awf = _opts.awaitWriteFinish;
1227
- const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
1228
2984
  const opts = {
2985
+ ..._opts,
1229
2986
  // Defaults
1230
- persistent: true,
1231
- ignoreInitial: false,
1232
- ignorePermissionErrors: false,
2987
+ persistent: _opts.persistent ?? true,
2988
+ ignoreInitial: _opts.ignoreInitial ?? false,
2989
+ ignorePermissionErrors: _opts.ignorePermissionErrors ?? false,
2990
+ pollingInterval: _opts.pollingInterval ?? _opts.interval ?? 100,
2991
+ pollingBinaryInterval: _opts.pollingBinaryInterval ?? _opts.binaryInterval ?? 300,
1233
2992
  interval: 100,
1234
2993
  binaryInterval: 300,
1235
- followSymlinks: true,
1236
- usePolling: false,
2994
+ followSymlinks: _opts.followSymlinks ?? true,
2995
+ backend: _opts.backend ?? "auto",
2996
+ usePolling: _opts.usePolling ?? false,
2997
+ // `undefined` already means unlimited traversal. Preserve the common
2998
+ // `depth: Infinity` spelling without forcing the per-directory backend.
2999
+ depth: _opts.depth === Number.POSITIVE_INFINITY ? void 0 : _opts.depth,
3000
+ backendStrategy: "native-per-directory",
3001
+ backendCapabilities: void 0,
1237
3002
  // useAsync: false,
1238
- atomic: true,
1239
- // NOTE: overwritten later (depends on usePolling)
1240
- ..._opts,
3003
+ atomic: _opts.atomic ?? true,
1241
3004
  // Change format
1242
- ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1243
- awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
3005
+ ignored: Object.freeze(_opts.ignored ? arrify(_opts.ignored).map(cloneOwnedMatcher) : []),
3006
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? Object.freeze({ ...DEF_AWF, ...awf }) : false
1244
3007
  };
1245
- if (isIBMi)
1246
- opts.usePolling = true;
1247
- if (opts.atomic === void 0)
1248
- opts.atomic = !opts.usePolling;
3008
+ if (_opts.usePolling === true || isIBMi)
3009
+ opts.backend = "polling";
1249
3010
  const envPoll = process.env.CHOKIDAR_USEPOLLING;
1250
3011
  if (envPoll !== void 0) {
1251
3012
  const envLower = envPoll.toLowerCase();
1252
- if (envLower === "false" || envLower === "0")
1253
- opts.usePolling = false;
1254
- else if (envLower === "true" || envLower === "1")
1255
- opts.usePolling = true;
1256
- else
1257
- opts.usePolling = !!envLower;
3013
+ const envPolling = envLower === "false" || envLower === "0" ? false : envLower === "true" || envLower === "1" ? true : !!envLower;
3014
+ if (envPolling)
3015
+ opts.backend = "polling";
3016
+ else if (opts.backend === "polling")
3017
+ opts.backend = "auto";
1258
3018
  }
1259
3019
  const envInterval = process.env.CHOKIDAR_INTERVAL;
1260
- if (envInterval)
1261
- opts.interval = Number.parseInt(envInterval, 10);
1262
- let readyCalls = 0;
1263
- this._emitReady = () => {
1264
- readyCalls++;
1265
- if (readyCalls >= this._readyCount) {
1266
- this._emitReady = EMPTY_FN;
1267
- this._readyEmitted = true;
1268
- process.nextTick(() => this.emit(EVENTS.READY));
1269
- }
1270
- };
1271
- this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1272
- this._boundRemove = this._remove.bind(this);
3020
+ if (envInterval !== void 0)
3021
+ opts.pollingInterval = Number(envInterval);
3022
+ opts.interval = opts.pollingInterval;
3023
+ opts.binaryInterval = opts.pollingBinaryInterval;
3024
+ opts.usePolling = opts.backend === "polling";
3025
+ opts.backendCapabilities = selectBackend(opts);
3026
+ opts.backendStrategy = opts.backendCapabilities.kind;
3027
+ if (_opts.atomic === void 0)
3028
+ opts.atomic = !opts.usePolling;
3029
+ validateOptions(opts);
1273
3030
  this.options = opts;
1274
- this._nodeFsHandler = new NodeFsHandler(this);
3031
+ this.lifecycle = new LifecycleScope(() => {
3032
+ if (this.#readyPending)
3033
+ this.queueReady();
3034
+ }, (error62) => {
3035
+ if (!this.closed)
3036
+ this.handleError(error62 instanceof Error ? error62 : new Error(String(error62)));
3037
+ });
3038
+ this.tree = new TreeState(() => !this.options.backendCapabilities.polling);
3039
+ this.reconciliation = new ReconciliationQueue(this.lifecycle);
3040
+ this.events = new EventPolicy({
3041
+ options: this.options,
3042
+ scheduler: this.scheduler,
3043
+ lifecycle: this.lifecycle,
3044
+ isClosed: () => this.closed,
3045
+ capturePathGeneration: () => this.capturePathGeneration(),
3046
+ isPathGenerationActive: (path, generation) => this.isPathGenerationActive(path, generation),
3047
+ isReady: () => this.readyEmitted,
3048
+ remove: (directory, item) => this.removePath(directory, item),
3049
+ handleError: (error62) => this.handleError(error62),
3050
+ publish: (event, args) => this.emitWithAll(event, args)
3051
+ });
3052
+ this.handler = new ObservationEngine(this);
1275
3053
  Object.freeze(opts);
1276
3054
  }
1277
- _addIgnoredPath(matcher) {
3055
+ addIgnoredPath(matcher) {
3056
+ matcher = this.ignoredMatcher(matcher);
1278
3057
  if (isMatcherObject(matcher)) {
1279
- for (const ignored of this._ignoredPaths) {
3058
+ for (const ignored of this.#ignoredPaths) {
1280
3059
  if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
1281
3060
  return;
1282
3061
  }
1283
3062
  }
1284
3063
  }
1285
- this._ignoredPaths.add(matcher);
3064
+ this.#ignoredPaths.add(matcher);
3065
+ this.#unwatchIgnored = void 0;
1286
3066
  }
1287
- _removeIgnoredPath(matcher) {
1288
- this._ignoredPaths.delete(matcher);
3067
+ removeIgnoredPath(matcher) {
3068
+ matcher = this.ignoredMatcher(matcher);
3069
+ this.#ignoredPaths.delete(matcher);
1289
3070
  if (typeof matcher === "string") {
1290
- for (const ignored of this._ignoredPaths) {
3071
+ for (const ignored of this.#ignoredPaths) {
1291
3072
  if (isMatcherObject(ignored) && ignored.path === matcher) {
1292
- this._ignoredPaths.delete(ignored);
3073
+ this.#ignoredPaths.delete(ignored);
1293
3074
  }
1294
3075
  }
1295
3076
  }
3077
+ this.#unwatchIgnored = void 0;
3078
+ }
3079
+ ignoredMatcher(matcher) {
3080
+ if (typeof matcher === "string")
3081
+ return logicalPathKey(matcher);
3082
+ if (isMatcherObject(matcher)) {
3083
+ return { path: logicalPathKey(matcher.path), recursive: matcher.recursive };
3084
+ }
3085
+ return matcher;
3086
+ }
3087
+ /** @internal */
3088
+ capturePathGeneration() {
3089
+ return this.#pathMutation;
3090
+ }
3091
+ invalidatePath(path) {
3092
+ this.#pathBarriers.set(logicalPathKey(path), ++this.#pathMutation);
3093
+ }
3094
+ /** @internal */
3095
+ isPathGenerationActive(path, generation) {
3096
+ if (this.lifecycle.state !== "OPEN")
3097
+ return false;
3098
+ if (this.#pathBarriers.size === 0)
3099
+ return true;
3100
+ const logicalKey = logicalPathKey(path);
3101
+ for (const [barrier, barrierGeneration] of this.#pathBarriers) {
3102
+ if (barrierGeneration <= generation)
3103
+ continue;
3104
+ if (isSameOrInside(barrier, logicalKey))
3105
+ return false;
3106
+ }
3107
+ return true;
3108
+ }
3109
+ queueReady() {
3110
+ if (this.closed || this.readyEmitted)
3111
+ return;
3112
+ this.#readyPending = true;
3113
+ if (this.lifecycle.tasks.size > 0 || this.#readyScheduled)
3114
+ return;
3115
+ this.#readyScheduled = true;
3116
+ process.nextTick(() => {
3117
+ this.#readyScheduled = false;
3118
+ if (this.closed || this.readyEmitted || this.lifecycle.tasks.size > 0)
3119
+ return;
3120
+ this.#readyPending = false;
3121
+ this.readyEmitted = true;
3122
+ this.emit(EVENTS.READY);
3123
+ });
1296
3124
  }
1297
3125
  // Public methods
1298
3126
  /**
1299
3127
  * Adds paths to be watched on an existing FSWatcher instance.
1300
- * @param paths_ file or file list. Other arguments are unused
3128
+ * @param paths_ file or file list
1301
3129
  */
1302
- add(paths_, _origAdd, _internal) {
3130
+ add(paths_) {
3131
+ if (this.closed) {
3132
+ throw new Error("Cannot add paths after FSWatcher.close() has been called");
3133
+ }
1303
3134
  const { cwd } = this.options;
1304
- this.closed = false;
1305
- this._closePromise = void 0;
1306
3135
  let paths = unifyPaths(paths_);
1307
3136
  if (cwd) {
1308
3137
  paths = paths.map((path) => {
@@ -1311,25 +3140,28 @@ var FSWatcher = class extends EventEmitter {
1311
3140
  });
1312
3141
  }
1313
3142
  paths.forEach((path) => {
1314
- this._removeIgnoredPath(path);
3143
+ this.removeIgnoredPath(path);
3144
+ this.addRootAncestors(path);
1315
3145
  });
1316
- this._userIgnored = void 0;
1317
- if (!this._readyCount)
1318
- this._readyCount = 0;
1319
- this._readyCount += paths.length;
1320
- Promise.all(paths.map(async (path) => {
1321
- const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1322
- if (res)
1323
- this._emitReady();
1324
- return res;
1325
- })).then((results) => {
1326
- if (this.closed)
3146
+ if (!this.readyEmitted)
3147
+ this.#readyPending = true;
3148
+ const addTask = Promise.all(paths.map(async (path) => {
3149
+ const key = logicalPathKey(path);
3150
+ if (this.lifecycle.closers.has(key) || this.#pendingAdds.has(key))
1327
3151
  return;
1328
- results.forEach((item) => {
1329
- if (item)
1330
- this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
1331
- });
1332
- });
3152
+ const pendingToken = Symbol(key);
3153
+ const pathGeneration = this.capturePathGeneration();
3154
+ this.#pendingAdds.set(key, pendingToken);
3155
+ try {
3156
+ await this.handler.addRoot(path, true, pathGeneration);
3157
+ } finally {
3158
+ if (this.#pendingAdds.get(key) === pendingToken)
3159
+ this.#pendingAdds.delete(key);
3160
+ }
3161
+ }));
3162
+ this.lifecycle.track(addTask);
3163
+ if (!this.readyEmitted)
3164
+ this.queueReady();
1333
3165
  return this;
1334
3166
  }
1335
3167
  /**
@@ -1338,23 +3170,26 @@ var FSWatcher = class extends EventEmitter {
1338
3170
  unwatch(paths_) {
1339
3171
  if (this.closed)
1340
3172
  return this;
1341
- const paths = unifyPaths(paths_);
3173
+ let paths = unifyPaths(paths_);
1342
3174
  const { cwd } = this.options;
3175
+ if (cwd)
3176
+ paths = paths.map((path) => getAbsolutePath(path, cwd));
1343
3177
  paths.forEach((path) => {
1344
- if (!sp2.isAbsolute(path) && !this._closers.has(path)) {
1345
- if (cwd)
1346
- path = sp2.join(cwd, path);
1347
- path = sp2.resolve(path);
1348
- }
1349
- this._closePath(path);
1350
- this._addIgnoredPath(path);
1351
- if (this._watched.has(path)) {
1352
- this._addIgnoredPath({
1353
- path,
3178
+ const key = logicalPathKey(path);
3179
+ const isDirectory = this.tree.watched.has(key);
3180
+ this.invalidatePath(key);
3181
+ this.removeRootAncestors(key);
3182
+ this.#pendingAdds.delete(key);
3183
+ this.events.cancelPath(key);
3184
+ this.closePath(key, isDirectory);
3185
+ this.addIgnoredPath(key);
3186
+ if (isDirectory) {
3187
+ this.addIgnoredPath({
3188
+ path: key,
1354
3189
  recursive: true
1355
3190
  });
1356
3191
  }
1357
- this._userIgnored = void 0;
3192
+ this.#unwatchIgnored = void 0;
1358
3193
  });
1359
3194
  return this;
1360
3195
  }
@@ -1362,43 +3197,53 @@ var FSWatcher = class extends EventEmitter {
1362
3197
  * Close watchers and remove all listeners from watched paths.
1363
3198
  */
1364
3199
  close() {
1365
- if (this._closePromise) {
1366
- return this._closePromise;
3200
+ if (this.#closePromise) {
3201
+ return this.#closePromise;
1367
3202
  }
1368
- this.closed = true;
3203
+ const closers = this.lifecycle.beginClose();
1369
3204
  this.removeAllListeners();
1370
- const closers = [];
1371
- this._closers.forEach((closerList) => closerList.forEach((closer) => {
1372
- const promise2 = closer();
1373
- if (promise2 instanceof Promise)
1374
- closers.push(promise2);
1375
- }));
1376
- this._streams.forEach((stream) => stream.destroy());
1377
- this._userIgnored = void 0;
1378
- this._readyCount = 0;
1379
- this._readyEmitted = false;
1380
- this._watched.forEach((dirent) => dirent.dispose());
1381
- this._closers.clear();
1382
- this._watched.clear();
1383
- this._streams.clear();
1384
- this._symlinkPaths.clear();
1385
- this._throttled.clear();
1386
- this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1387
- return this._closePromise;
3205
+ this.events.close();
3206
+ this.#pendingAdds.clear();
3207
+ this.#roots.clear();
3208
+ this.#rootAncestors.clear();
3209
+ this.streams.forEach((stream) => stream.destroy());
3210
+ this.#userIgnored = void 0;
3211
+ this.#unwatchIgnored = void 0;
3212
+ this.readyEmitted = false;
3213
+ this.tree.dispose();
3214
+ this.#pathBarriers.clear();
3215
+ this.streams.clear();
3216
+ this.reconciliation.clear();
3217
+ this.#realDirs.clear();
3218
+ this.#closePromise = (async () => {
3219
+ const closerResults = await Promise.allSettled(closers);
3220
+ await this.lifecycle.drain();
3221
+ this.lifecycle.finishClose();
3222
+ const failed = closerResults.find((result) => result.status === "rejected");
3223
+ if (failed)
3224
+ throw failed.reason;
3225
+ })();
3226
+ return this.#closePromise;
1388
3227
  }
1389
3228
  /**
1390
- * Expose list of watched paths
1391
- * @returns for chaining
3229
+ * Expose list of watched paths. The result has a null prototype, so a
3230
+ * directory named `__proto__` is an ordinary own key.
1392
3231
  */
1393
3232
  getWatched() {
1394
- const watchList = {};
1395
- this._watched.forEach((entry, dir) => {
1396
- const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
1397
- const index = key || ONE_DOT;
3233
+ const watchList = /* @__PURE__ */ Object.create(null);
3234
+ this.tree.watched.forEach((entry) => {
3235
+ const dir = entry.path;
3236
+ const key = this.options.cwd ? sp5.relative(this.options.cwd, dir) : dir;
3237
+ const index = key || ".";
1398
3238
  watchList[index] = entry.getChildren().sort();
1399
3239
  });
1400
3240
  return watchList;
1401
3241
  }
3242
+ /** @internal */
3243
+ emitRaw(...args) {
3244
+ if (!this.closed)
3245
+ this.emit(EVENTS.RAW, ...args);
3246
+ }
1402
3247
  emitWithAll(event, args) {
1403
3248
  this.emit(event, ...args);
1404
3249
  if (event !== EVENTS.ERROR)
@@ -1408,315 +3253,284 @@ var FSWatcher = class extends EventEmitter {
1408
3253
  // --------------
1409
3254
  /**
1410
3255
  * Normalize and emit events.
1411
- * Calling _emit DOES NOT MEAN emit() would be called!
3256
+ * Calling emitEvent DOES NOT MEAN emit() would be called!
1412
3257
  * @param event Type of event
1413
3258
  * @param path File or directory path
1414
3259
  * @param stats arguments to be passed with event
1415
- * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
3260
+ * @internal
1416
3261
  */
1417
- async _emit(event, path, stats) {
3262
+ async emitEvent(event, path, stats) {
1418
3263
  if (this.closed)
1419
3264
  return;
1420
- const opts = this.options;
1421
- if (isWindows)
1422
- path = sp2.normalize(path);
1423
- if (opts.cwd)
1424
- path = sp2.relative(opts.cwd, path);
1425
- const args = [path];
1426
- if (stats != null)
1427
- args.push(stats);
1428
- const awf = opts.awaitWriteFinish;
1429
- let pw;
1430
- if (awf && (pw = this._pendingWrites.get(path))) {
1431
- pw.lastChange = /* @__PURE__ */ new Date();
1432
- return this;
1433
- }
1434
- if (opts.atomic) {
1435
- if (event === EVENTS.UNLINK) {
1436
- this._pendingUnlinks.set(path, [event, ...args]);
1437
- setTimeout(() => {
1438
- this._pendingUnlinks.forEach((entry, path2) => {
1439
- this.emit(...entry);
1440
- this.emit(EVENTS.ALL, ...entry);
1441
- this._pendingUnlinks.delete(path2);
1442
- });
1443
- }, typeof opts.atomic === "number" ? opts.atomic : 100);
1444
- return this;
1445
- }
1446
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1447
- event = EVENTS.CHANGE;
1448
- this._pendingUnlinks.delete(path);
1449
- }
1450
- }
1451
- if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1452
- const awfEmit = (err, stats2) => {
1453
- if (err) {
1454
- event = EVENTS.ERROR;
1455
- args[0] = err;
1456
- this.emitWithAll(event, args);
1457
- } else if (stats2) {
1458
- if (args.length > 1) {
1459
- args[1] = stats2;
1460
- } else {
1461
- args.push(stats2);
1462
- }
1463
- this.emitWithAll(event, args);
1464
- }
1465
- };
1466
- this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1467
- return this;
1468
- }
1469
- if (event === EVENTS.CHANGE) {
1470
- const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
1471
- if (isThrottled)
1472
- return this;
1473
- }
1474
- if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1475
- const fullPath = opts.cwd ? sp2.join(opts.cwd, path) : path;
1476
- let stats2;
1477
- try {
1478
- stats2 = await stat(fullPath);
1479
- } catch (err) {
1480
- }
1481
- if (!stats2 || this.closed)
1482
- return;
1483
- args.push(stats2);
1484
- }
1485
- this.emitWithAll(event, args);
1486
- return this;
3265
+ await this.events.emit(event, path, stats);
1487
3266
  }
1488
3267
  /**
1489
- * Common handler for errors
1490
- * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
3268
+ * Common handler for backend and reconciliation failures.
3269
+ * @internal
1491
3270
  */
1492
- _handleError(error62) {
1493
- const code = error62 && error62.code;
1494
- if (error62 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
1495
- this.emit(EVENTS.ERROR, error62);
3271
+ handleError(error62) {
3272
+ if (this.closed)
3273
+ return;
3274
+ const normalized = error62 instanceof Error ? error62 : new Error(String(error62));
3275
+ if (!isMissingError(normalized) && (!this.options.ignorePermissionErrors || !isPermissionError(normalized))) {
3276
+ this.emit(EVENTS.ERROR, normalized);
1496
3277
  }
1497
- return error62 || this.closed;
1498
3278
  }
1499
3279
  /**
1500
- * Helper utility for throttling
1501
- * @param actionType type being throttled
1502
- * @param path being acted upon
1503
- * @param timeout duration of time to suppress duplicate actions
1504
- * @returns tracking object or false if action should be suppressed
3280
+ * Determines whether user has asked to ignore this path.
3281
+ * @internal
1505
3282
  */
1506
- _throttle(actionType, path, timeout) {
1507
- if (!this._throttled.has(actionType)) {
1508
- this._throttled.set(actionType, /* @__PURE__ */ new Map());
3283
+ isIgnored(path, stats) {
3284
+ if (this.options.atomic && DOT_RE.test(path))
3285
+ return true;
3286
+ if (!this.#userIgnored) {
3287
+ const { cwd } = this.options;
3288
+ const ign = this.options.ignored;
3289
+ const ignored = (ign || []).map((matcher) => normalizeMatcher(matcher, cwd));
3290
+ const direct = compileMatchers(ignored);
3291
+ const pathMatchers = ignored.filter((matcher) => typeof matcher === "string" || isMatcherObject(matcher));
3292
+ const canonical = compileMatchers(pathMatchers);
3293
+ this.#userIgnored = (candidate, candidateStats) => {
3294
+ if (direct(candidate, candidateStats))
3295
+ return true;
3296
+ if (isWindows || pathMatchers.length === 0)
3297
+ return false;
3298
+ const absoluteCandidate = sp5.resolve(candidate);
3299
+ let realPath;
3300
+ if (candidateStats?.isDirectory()) {
3301
+ realPath = this.realDirectory(absoluteCandidate);
3302
+ } else {
3303
+ const realDir = this.realDirectory(sp5.dirname(absoluteCandidate));
3304
+ if (realDir !== void 0)
3305
+ realPath = sp5.join(realDir, sp5.basename(absoluteCandidate));
3306
+ }
3307
+ return realPath !== void 0 && realPath !== absoluteCandidate && canonical(realPath, candidateStats);
3308
+ };
1509
3309
  }
1510
- const action = this._throttled.get(actionType);
1511
- if (!action)
1512
- throw new Error("invalid throttle");
1513
- const actionPath = action.get(path);
1514
- if (actionPath) {
1515
- actionPath.count++;
3310
+ if (this.#userIgnored(path, stats) && !this.isRootAncestor(path, stats))
3311
+ return true;
3312
+ if (this.#ignoredPaths.size === 0)
1516
3313
  return false;
3314
+ if (!this.#unwatchIgnored) {
3315
+ this.#unwatchIgnored = compileMatchers([...this.#ignoredPaths]);
1517
3316
  }
1518
- let timeoutObject;
1519
- const clear = () => {
1520
- const item = action.get(path);
1521
- const count = item ? item.count : 0;
1522
- action.delete(path);
1523
- clearTimeout(timeoutObject);
1524
- if (item)
1525
- clearTimeout(item.timeoutObject);
1526
- return count;
1527
- };
1528
- timeoutObject = setTimeout(clear, timeout);
1529
- const thr = { timeoutObject, clear, count: 0 };
1530
- action.set(path, thr);
1531
- return thr;
3317
+ return this.#unwatchIgnored(logicalPathKey(path), stats);
1532
3318
  }
1533
- _incrReadyCount() {
1534
- return this._readyCount++;
3319
+ isRootAncestor(path, stats) {
3320
+ if (stats?.isFile())
3321
+ return false;
3322
+ return this.#rootAncestors.has(logicalPathKey(path));
1535
3323
  }
1536
- /**
1537
- * Awaits write operation to finish.
1538
- * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1539
- * @param path being acted upon
1540
- * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1541
- * @param event
1542
- * @param awfEmit Callback to be called when ready for event to be emitted.
1543
- */
1544
- _awaitWriteFinish(path, threshold, event, awfEmit) {
1545
- const awf = this.options.awaitWriteFinish;
1546
- if (typeof awf !== "object")
3324
+ /** Records every directory above a requested root; refcounted across roots. */
3325
+ addRootAncestors(path) {
3326
+ const key = logicalPathKey(path);
3327
+ if (this.#roots.has(key))
1547
3328
  return;
1548
- const pollInterval = awf.pollInterval;
1549
- let timeoutHandler;
1550
- let fullPath = path;
1551
- if (this.options.cwd && !sp2.isAbsolute(path)) {
1552
- fullPath = sp2.join(this.options.cwd, path);
3329
+ this.#roots.add(key);
3330
+ for (const ancestor of ancestorKeys(path)) {
3331
+ this.#rootAncestors.set(ancestor, (this.#rootAncestors.get(ancestor) ?? 0) + 1);
1553
3332
  }
1554
- const now = /* @__PURE__ */ new Date();
1555
- const writes = this._pendingWrites;
1556
- function awaitWriteFinishFn(prevStat) {
1557
- stat$1(fullPath, (err, curStat) => {
1558
- if (err || !writes.has(path)) {
1559
- if (err && err.code !== "ENOENT")
1560
- awfEmit(err);
1561
- return;
1562
- }
1563
- const now2 = Number(/* @__PURE__ */ new Date());
1564
- if (prevStat && curStat.size !== prevStat.size) {
1565
- writes.get(path).lastChange = now2;
1566
- }
1567
- const pw = writes.get(path);
1568
- const df = now2 - pw.lastChange;
1569
- if (df >= threshold) {
1570
- writes.delete(path);
1571
- awfEmit(void 0, curStat);
1572
- } else {
1573
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1574
- }
1575
- });
1576
- }
1577
- if (!writes.has(path)) {
1578
- writes.set(path, {
1579
- lastChange: now,
1580
- cancelWait: () => {
1581
- writes.delete(path);
1582
- clearTimeout(timeoutHandler);
1583
- return event;
1584
- }
1585
- });
1586
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
3333
+ }
3334
+ removeRootAncestors(path) {
3335
+ if (!this.#roots.delete(logicalPathKey(path)))
3336
+ return;
3337
+ for (const ancestor of ancestorKeys(path)) {
3338
+ const count = (this.#rootAncestors.get(ancestor) ?? 1) - 1;
3339
+ if (count > 0)
3340
+ this.#rootAncestors.set(ancestor, count);
3341
+ else
3342
+ this.#rootAncestors.delete(ancestor);
1587
3343
  }
1588
3344
  }
1589
- /**
1590
- * Determines whether user has asked to ignore this path.
1591
- */
1592
- _isIgnored(path, stats) {
1593
- if (this.options.atomic && DOT_RE.test(path))
1594
- return true;
1595
- if (!this._userIgnored) {
1596
- const { cwd } = this.options;
1597
- const ign = this.options.ignored;
1598
- const ignored = (ign || []).map(normalizeIgnored(cwd));
1599
- const ignoredPaths = [...this._ignoredPaths];
1600
- const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
1601
- this._userIgnored = anymatch(list);
3345
+ realDirectory(directory) {
3346
+ const key = logicalPathKey(directory);
3347
+ if (this.#realDirs.has(key))
3348
+ return this.#realDirs.get(key);
3349
+ let realPath;
3350
+ try {
3351
+ realPath = realpathSync.native(directory);
3352
+ } catch {
1602
3353
  }
1603
- return this._userIgnored(path, stats);
3354
+ this.#realDirs.set(key, realPath);
3355
+ return realPath;
1604
3356
  }
1605
- _isntIgnored(path, stat4) {
1606
- return !this._isIgnored(path, stat4);
3357
+ /** @internal */
3358
+ isUnwatched(path) {
3359
+ if (this.#ignoredPaths.size === 0)
3360
+ return false;
3361
+ if (!this.#unwatchIgnored) {
3362
+ this.#unwatchIgnored = compileMatchers([...this.#ignoredPaths]);
3363
+ }
3364
+ return this.#unwatchIgnored(logicalPathKey(path));
1607
3365
  }
1608
3366
  /**
1609
3367
  * Provides a set of common helpers and properties relating to symlink handling.
1610
3368
  * @param path file or directory pattern being watched
3369
+ * @internal
1611
3370
  */
1612
- _getWatchHelpers(path) {
1613
- return new WatchHelper(path, this.options.followSymlinks, this);
3371
+ createHelper(path) {
3372
+ return new WatchHelper(path, this.options.followSymlinks, {
3373
+ capturePathGeneration: () => this.capturePathGeneration(),
3374
+ isntIgnored: (candidate, stats) => !this.isIgnored(candidate, stats)
3375
+ });
1614
3376
  }
1615
- // Directory helpers
1616
- // -----------------
1617
- /**
1618
- * Provides directory tracking objects
1619
- * @param directory path of the directory
1620
- */
1621
- _getWatchedDir(directory) {
1622
- const dir = sp2.resolve(directory);
1623
- if (!this._watched.has(dir))
1624
- this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1625
- return this._watched.get(dir);
3377
+ removeTreeItem(directory, item) {
3378
+ const entry = this.tree.peekDirectory(directory);
3379
+ if (!entry?.remove(item))
3380
+ return;
3381
+ const path = entry.path;
3382
+ const generation = this.lifecycle.generation;
3383
+ this.lifecycle.track((async () => {
3384
+ try {
3385
+ await readdir(path);
3386
+ } catch (error62) {
3387
+ if (isMissingError(error62) && this.lifecycle.isActive(generation)) {
3388
+ this.removePath(sp5.dirname(path), sp5.basename(path));
3389
+ }
3390
+ }
3391
+ })());
1626
3392
  }
1627
3393
  // File helpers
1628
3394
  // ------------
1629
- /**
1630
- * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1631
- */
1632
- _hasReadPermissions(stats) {
1633
- if (this.options.ignorePermissionErrors)
1634
- return true;
1635
- return Boolean(Number(stats.mode) & 256);
1636
- }
1637
3395
  /**
1638
3396
  * Handles emitting unlink events for
1639
3397
  * files and directories, and via recursion, for
1640
3398
  * files and directories within directories that are unlinked
1641
3399
  * @param directory within which the following item is located
1642
3400
  * @param item base path of item/directory
3401
+ * @internal
1643
3402
  */
1644
- _remove(directory, item, isDirectory) {
1645
- const path = sp2.join(directory, item);
1646
- const fullPath = sp2.resolve(path);
1647
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1648
- if (!this._throttle("remove", path, 100))
1649
- return;
1650
- if (!isDirectory && this._watched.size === 1) {
1651
- this.add(directory, item, true);
3403
+ removePath(directory, item, isDirectory) {
3404
+ const path = sp5.join(directory, item);
3405
+ const logicalKey = logicalPathKey(path);
3406
+ isDirectory = isDirectory != null ? isDirectory : this.tree.watched.has(logicalKey);
3407
+ const nestedDirectoryChildren = this.tree.peekDirectory(path)?.getChildren() ?? [];
3408
+ for (const nested of nestedDirectoryChildren)
3409
+ this.removePath(path, nested);
3410
+ const wasTracked = this.tree.peekDirectory(directory)?.has(item) ?? false;
3411
+ const hadClosers = this.lifecycle.closers.has(logicalKey);
3412
+ this.removeTreeItem(directory, item);
3413
+ if (this.tree.symlinkPaths.has(logicalKey)) {
3414
+ this.tree.symlinkPaths.delete(logicalKey);
1652
3415
  }
1653
- const wp = this._getWatchedDir(path);
1654
- const nestedDirectoryChildren = wp.getChildren();
1655
- nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
1656
- const parent = this._getWatchedDir(directory);
1657
- const wasTracked = parent.has(item);
1658
- parent.remove(item);
1659
- if (this._symlinkPaths.has(fullPath)) {
1660
- this._symlinkPaths.delete(fullPath);
3416
+ const pendingWrite = this.events.pendingWrites.get(logicalKey);
3417
+ let suppressEvent = false;
3418
+ if (this.options.awaitWriteFinish && pendingWrite) {
3419
+ const event = pendingWrite.cancelWait();
3420
+ suppressEvent = event === EVENTS.ADD;
1661
3421
  }
1662
- let relPath = path;
1663
- if (this.options.cwd)
1664
- relPath = sp2.relative(this.options.cwd, path);
1665
- if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1666
- const event = this._pendingWrites.get(relPath).cancelWait();
1667
- if (event === EVENTS.ADD)
1668
- return;
1669
- }
1670
- this._watched.delete(path);
1671
- this._watched.delete(fullPath);
3422
+ this.tree.watched.delete(logicalKey);
3423
+ this.tree.observed.delete(logicalKey);
1672
3424
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1673
- if (wasTracked && !this._isIgnored(path))
1674
- this._emit(eventName, path);
1675
- this._closePath(path);
3425
+ if (wasTracked && !suppressEvent && !this.isIgnored(path))
3426
+ this.emitEvent(eventName, path);
3427
+ this.closePath(path);
3428
+ if ((wasTracked || hadClosers) && this.#roots.has(logicalKey))
3429
+ this.rewatchMissingPath(path);
3430
+ }
3431
+ /**
3432
+ * Replaces every watch keyed at `path` with a wait from its nearest existing
3433
+ * ancestor, so the path is reported again when it reappears.
3434
+ * @internal
3435
+ */
3436
+ rewatchMissingPath(path) {
3437
+ if (this.closed || this.isUnwatched(path))
3438
+ return;
3439
+ this.closePath(path);
3440
+ this.lifecycle.track(this.handler.addRoot(path, false, this.capturePathGeneration()));
1676
3441
  }
1677
3442
  /**
1678
3443
  * Closes all watchers for a path
3444
+ * @internal
1679
3445
  */
1680
- _closePath(path) {
1681
- this._closeFile(path);
1682
- const dir = sp2.dirname(path);
1683
- this._getWatchedDir(dir).remove(sp2.basename(path));
3446
+ closePath(path, recursive2 = false) {
3447
+ const logicalKey = logicalPathKey(path);
3448
+ const contains = (candidate) => {
3449
+ if (candidate === logicalKey)
3450
+ return true;
3451
+ if (!recursive2)
3452
+ return false;
3453
+ return isStrictlyInside(logicalKey, candidate);
3454
+ };
3455
+ [...this.lifecycle.closers.keys()].filter(contains).forEach((key) => this.closeFile(key));
3456
+ if (this.#realDirs.delete(logicalKey) || recursive2) {
3457
+ const prefix = logicalKey.endsWith("/") ? logicalKey : `${logicalKey}/`;
3458
+ for (const key of this.#realDirs.keys()) {
3459
+ if (key.startsWith(prefix))
3460
+ this.#realDirs.delete(key);
3461
+ }
3462
+ }
3463
+ if (recursive2) {
3464
+ for (const [key, entry] of this.tree.watched) {
3465
+ if (!contains(key))
3466
+ continue;
3467
+ entry.dispose();
3468
+ this.tree.watched.delete(key);
3469
+ }
3470
+ for (const key of this.tree.observed.keys()) {
3471
+ if (contains(key))
3472
+ this.tree.observed.delete(key);
3473
+ }
3474
+ for (const key of this.tree.symlinkPaths.keys()) {
3475
+ if (contains(key))
3476
+ this.tree.symlinkPaths.delete(key);
3477
+ }
3478
+ this.events.cancelWhere(contains);
3479
+ this.reconciliation.forgetPending((scope, candidate) => contains(scope) || contains(candidate));
3480
+ for (const key of this.#pendingAdds.keys()) {
3481
+ if (contains(key))
3482
+ this.#pendingAdds.delete(key);
3483
+ }
3484
+ }
3485
+ const dir = sp5.dirname(logicalKey);
3486
+ this.removeTreeItem(dir, sp5.basename(logicalKey));
1684
3487
  }
1685
3488
  /**
1686
3489
  * Closes only file-specific watchers
1687
3490
  */
1688
- _closeFile(path) {
1689
- const closers = this._closers.get(path);
1690
- if (!closers)
3491
+ closeFile(path) {
3492
+ const key = logicalPathKey(path);
3493
+ const closers = this.lifecycle.takeClosers(key);
3494
+ if (closers.length === 0)
1691
3495
  return;
1692
- closers.forEach((closer) => closer());
1693
- this._closers.delete(path);
3496
+ closers.forEach((closer) => {
3497
+ try {
3498
+ const result = closer();
3499
+ if (result instanceof Promise)
3500
+ this.lifecycle.track(result);
3501
+ } catch (error62) {
3502
+ this.lifecycle.track(Promise.reject(error62));
3503
+ }
3504
+ });
1694
3505
  }
1695
- _addPathCloser(path, closer) {
3506
+ /** @internal */
3507
+ addPathCloser(path, closer) {
1696
3508
  if (!closer)
1697
3509
  return;
1698
- let list = this._closers.get(path);
1699
- if (!list) {
1700
- list = [];
1701
- this._closers.set(path, list);
3510
+ if (this.closed || this.isUnwatched(path)) {
3511
+ try {
3512
+ const result = closer();
3513
+ if (result instanceof Promise)
3514
+ this.lifecycle.track(result);
3515
+ } catch (error62) {
3516
+ this.lifecycle.track(Promise.reject(error62));
3517
+ }
3518
+ return;
1702
3519
  }
1703
- list.push(closer);
3520
+ const key = logicalPathKey(path);
3521
+ this.lifecycle.addCloser(key, closer);
1704
3522
  }
1705
- _readdirp(root, opts) {
3523
+ /** @internal */
3524
+ createScanStream(root, opts) {
1706
3525
  if (this.closed)
1707
3526
  return;
1708
- const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
1709
- let stream = readdirp(root, options);
1710
- this._streams.add(stream);
1711
- stream.once(STR_CLOSE, () => {
1712
- stream = void 0;
1713
- });
1714
- stream.once(STR_END, () => {
1715
- if (stream) {
1716
- this._streams.delete(stream);
1717
- stream = void 0;
1718
- }
1719
- });
3527
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, depth: 0, ...opts };
3528
+ const stream = readdirp(root, options);
3529
+ this.streams.add(stream);
3530
+ const finalize2 = () => this.streams.delete(stream);
3531
+ stream.once("close", finalize2);
3532
+ stream.once("end", finalize2);
3533
+ stream.once(EVENTS.ERROR, finalize2);
1720
3534
  return stream;
1721
3535
  }
1722
3536
  };
@@ -6870,7 +8684,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6870
8684
  var NONE = 0;
6871
8685
  var ASSUMED = 1;
6872
8686
  var PROVEN = 2;
6873
- function isRecursive(inst, stack, resolve3) {
8687
+ function isRecursive(inst, stack, resolve6) {
6874
8688
  var _a5;
6875
8689
  const cached2 = recursive.get(inst);
6876
8690
  if (cached2 !== void 0)
@@ -6881,7 +8695,7 @@ function isRecursive(inst, stack, resolve3) {
6881
8695
  let result = NONE;
6882
8696
  const check2 = (child) => {
6883
8697
  if (result !== PROVEN && (child == null ? void 0 : child._zod)) {
6884
- const answer = isRecursive(child, stack, resolve3);
8698
+ const answer = isRecursive(child, stack, resolve6);
6885
8699
  if (answer > result)
6886
8700
  result = answer;
6887
8701
  }
@@ -6893,7 +8707,7 @@ function isRecursive(inst, stack, resolve3) {
6893
8707
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6894
8708
  if (!desc.enumerable)
6895
8709
  continue;
6896
- const child = desc.get ? ASSUMED : ((_a6 = desc.value) == null ? void 0 : _a6._zod) ? isRecursive(desc.value, stack, resolve3) : NONE;
8710
+ const child = desc.get ? ASSUMED : ((_a6 = desc.value) == null ? void 0 : _a6._zod) ? isRecursive(desc.value, stack, resolve6) : NONE;
6897
8711
  if (child > answer)
6898
8712
  answer = child;
6899
8713
  }
@@ -6957,7 +8771,7 @@ function isRecursive(inst, stack, resolve3) {
6957
8771
  break;
6958
8772
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6959
8773
  case "lazy": {
6960
- const inner = (_a5 = def._cachedInner) != null ? _a5 : resolve3 ? inst._zod.innerType : void 0;
8774
+ const inner = (_a5 = def._cachedInner) != null ? _a5 : resolve6 ? inst._zod.innerType : void 0;
6961
8775
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6962
8776
  break;
6963
8777
  }
@@ -70771,12 +72585,12 @@ var CaptureDaemon = class {
70771
72585
  ...this.watchOnly ? { ignored: (path, stats) => (stats == null ? void 0 : stats.isFile()) === true && !path.endsWith(".jsonl") } : {},
70772
72586
  awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }
70773
72587
  });
70774
- const ready = this.watchOnly ? new Promise((resolve3) => this.watcher.once("ready", () => resolve3())) : void 0;
72588
+ const ready = this.watchOnly ? new Promise((resolve6) => this.watcher.once("ready", () => resolve6())) : void 0;
70775
72589
  this.watcher.on("add", (f) => this.schedule(f));
70776
72590
  this.watcher.on("change", (f) => this.schedule(f));
70777
72591
  this.rescanTimer = setInterval(() => this.rescanNow(), this.rescanMs);
70778
72592
  await ready;
70779
- await new Promise((resolve3) => setImmediate(() => setImmediate(resolve3)));
72593
+ await new Promise((resolve6) => setImmediate(() => setImmediate(resolve6)));
70780
72594
  this.log({ type: "started" });
70781
72595
  }
70782
72596
  async stop() {
@@ -71271,7 +73085,7 @@ function setRepoRoot(root) {
71271
73085
  }
71272
73086
  function scrubRepoRoot(text) {
71273
73087
  if (!repoRootPattern) return text;
71274
- return text.replace(repoRootPattern, (_m, lead, sep2) => sep2 ? lead : `${lead}.`);
73088
+ return text.replace(repoRootPattern, (_m, lead, sep22) => sep22 ? lead : `${lead}.`);
71275
73089
  }
71276
73090
  function setLocalIdentity(identity) {
71277
73091
  localIdentity = [];