knarr 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +66 -107
  2. package/dist/add-B_xzUp5y.mjs +3 -0
  3. package/dist/add-flow-cvrMO_aV.mjs +5 -0
  4. package/dist/batch-push-DXtZxRx0.mjs +3 -0
  5. package/dist/build-detect-BTHh2OBm.mjs +3 -0
  6. package/dist/bundler-detect-Dq-QAbQj.mjs +3 -0
  7. package/dist/check-CbVdpTsw.mjs +3 -0
  8. package/dist/chokidar-BkIWf7Ix.mjs +3 -0
  9. package/dist/clean-CyDDqbBD.mjs +3 -0
  10. package/dist/cli.mjs +4 -4
  11. package/dist/config-BJsL6NqN.mjs +4 -0
  12. package/dist/console-CIiXr7ge.mjs +3 -0
  13. package/dist/console-CyaBcUd-.mjs +98 -0
  14. package/dist/dev-kqgY9NjI.mjs +3 -0
  15. package/dist/dist-CFkjiIqD.mjs +7 -0
  16. package/dist/doctor-D-S1P0UG.mjs +6 -0
  17. package/dist/dry-run-BkdMYSIx.mjs +3 -0
  18. package/dist/errors-BlOfexcH.mjs +3 -0
  19. package/dist/explain-9Y4SZHjC.mjs +3 -0
  20. package/dist/format-DRqD29u-.mjs +3 -0
  21. package/dist/fs-C4juVCTd.mjs +3 -0
  22. package/dist/fs-CPnWm9CR.mjs +3 -0
  23. package/dist/fs-DzsciYAL.mjs +757 -0
  24. package/dist/hints-Hz3V4h3A.mjs +3 -0
  25. package/dist/history-DRhLwzhq.mjs +3 -0
  26. package/dist/history-vS3w4EGu.mjs +3 -0
  27. package/dist/index.d.ts +249 -264
  28. package/dist/index.mjs +3426 -4668
  29. package/dist/init-TN84d5jM.mjs +4 -0
  30. package/dist/init-helpers-CYYWQm-P.mjs +15 -0
  31. package/dist/injector-nt40JxVt.mjs +3 -0
  32. package/dist/json-DbSkpxtr.mjs +3 -0
  33. package/dist/list-9hWJjw19.mjs +3 -0
  34. package/dist/logger-9C6B9Na8.mjs +3 -0
  35. package/dist/migrate-Co4qcFt6.mjs +5 -0
  36. package/dist/nextjs-config-BQgTWZ96.mjs +3 -0
  37. package/dist/nextjs-config-dUw2J6B9.mjs +4 -0
  38. package/dist/output-BxR2v-jn.mjs +3 -0
  39. package/dist/package-manager-DJ8CE0zL.mjs +13 -0
  40. package/dist/picomatch-B0_Pxgms.mjs +3 -0
  41. package/dist/preflight-BDsxR2Ct.mjs +3 -0
  42. package/dist/preflight-MzNjLXiy.mjs +3 -0
  43. package/dist/publish-C7ZUvHkE.mjs +3 -0
  44. package/dist/publisher-CvXTbkLP.mjs +4 -0
  45. package/dist/push-B5KrkILW.mjs +3 -0
  46. package/dist/push-engine-BpNr8qXR.mjs +3 -0
  47. package/dist/remove-DkOgVQMZ.mjs +3 -0
  48. package/dist/remove-J5tY_BFk.mjs +3 -0
  49. package/dist/reset-ClGouUb5.mjs +3 -0
  50. package/dist/restore-Bx2V59SL.mjs +3 -0
  51. package/dist/rollback-RPjHZWtG.mjs +3 -0
  52. package/dist/rolldown-runtime-BZbIAPMk.mjs +3 -0
  53. package/dist/shell-RQ7Hf1kp.mjs +3 -0
  54. package/dist/status-Rnvw6dG2.mjs +3 -0
  55. package/dist/store-DjPdOKqg.mjs +3 -0
  56. package/dist/tailwind-source-D1cUiG-t.mjs +5 -0
  57. package/dist/timer-DqgB175x.mjs +3 -0
  58. package/dist/topo-sort-DOCpHjT7.mjs +3 -0
  59. package/dist/topo-sort-yd4jxr_E.mjs +3 -0
  60. package/dist/tracker-89eW0ArT.mjs +3 -0
  61. package/dist/tracker-B3Fqx94J.mjs +3 -0
  62. package/dist/update-CAKFICZu.mjs +3 -0
  63. package/dist/use-CCx6J0mc.mjs +3 -0
  64. package/dist/vite-config-BHmawlD2.mjs +12 -0
  65. package/dist/vite-config-BRlYc4ni.mjs +3 -0
  66. package/dist/vite-plugin.d.ts +6 -5
  67. package/dist/vite-plugin.mjs +206 -211
  68. package/dist/watch-orchestrator-BfuCaZLA.mjs +3 -0
  69. package/dist/watcher-T123sBDg.mjs +3 -0
  70. package/dist/webpack-plugin.d.ts +29 -30
  71. package/dist/webpack-plugin.mjs +140 -138
  72. package/dist/workspace-CdLSxPFS.mjs +3 -0
  73. package/dist/workspace-DBxNrowu.mjs +3 -0
  74. package/dist/xxhash-wasm-D_QjdUuv.mjs +3 -0
  75. package/package.json +23 -31
  76. package/dist/add-LQ6WMCGD.mjs +0 -3
  77. package/dist/bell-SIN4ERLS.mjs +0 -2
  78. package/dist/check-7CJHAF6Y.mjs +0 -6
  79. package/dist/chokidar-2G63V464.mjs +0 -4
  80. package/dist/chunk-3SXN6MQL.mjs +0 -4
  81. package/dist/chunk-7GCKCCHU.mjs +0 -3
  82. package/dist/chunk-BH2WXCLS.mjs +0 -4
  83. package/dist/chunk-CBOYKBSM.mjs +0 -13
  84. package/dist/chunk-E3HZCU3S.mjs +0 -5
  85. package/dist/chunk-G7HFTV5Y.mjs +0 -3
  86. package/dist/chunk-HVN6HBWZ.mjs +0 -3
  87. package/dist/chunk-ICU4V73X.mjs +0 -3
  88. package/dist/chunk-IP5ROSRE.mjs +0 -3
  89. package/dist/chunk-J6HZHQVL.mjs +0 -3
  90. package/dist/chunk-K6OAYJKS.mjs +0 -6
  91. package/dist/chunk-KRX4JX6V.mjs +0 -4
  92. package/dist/chunk-KUQULMM6.mjs +0 -3
  93. package/dist/chunk-L7O2RSTN.mjs +0 -3
  94. package/dist/chunk-M3TRMEJV.mjs +0 -3
  95. package/dist/chunk-MN4DV2NO.mjs +0 -3
  96. package/dist/chunk-N3B2JO4H.mjs +0 -13
  97. package/dist/chunk-NGPAGRK4.mjs +0 -7
  98. package/dist/chunk-NV3ASN6X.mjs +0 -3
  99. package/dist/chunk-OQDZJP55.mjs +0 -3
  100. package/dist/chunk-QEH5VHRO.mjs +0 -13
  101. package/dist/chunk-QFHYSC3K.mjs +0 -3
  102. package/dist/chunk-QHNHLR6T.mjs +0 -3
  103. package/dist/chunk-RIHOZDFW.mjs +0 -22
  104. package/dist/chunk-SMR4HT6A.mjs +0 -3
  105. package/dist/chunk-SPHWZS5P.mjs +0 -3
  106. package/dist/chunk-U6O35NZ7.mjs +0 -3
  107. package/dist/chunk-W2MMKBWU.mjs +0 -3
  108. package/dist/chunk-WBTSRLB6.mjs +0 -7
  109. package/dist/chunk-WN3DOKIM.mjs +0 -3
  110. package/dist/chunk-XDWZZBCM.mjs +0 -3
  111. package/dist/chunk-Z5K6DFA6.mjs +0 -3
  112. package/dist/clean-EJIYYQZM.mjs +0 -3
  113. package/dist/dev-WU5KB5PJ.mjs +0 -3
  114. package/dist/doctor-W2G34POC.mjs +0 -6
  115. package/dist/explain-LZLNIMVZ.mjs +0 -5
  116. package/dist/fs-NU36NNEG.mjs +0 -2
  117. package/dist/history-MLJHRV3Q.mjs +0 -2
  118. package/dist/init-SNG5LBZK.mjs +0 -7
  119. package/dist/list-4PTHMIQ4.mjs +0 -5
  120. package/dist/migrate-USY26Y5R.mjs +0 -8
  121. package/dist/nextjs-config-T5D6LOJE.mjs +0 -2
  122. package/dist/preflight-IXICTR6G.mjs +0 -2
  123. package/dist/publish-2IH7IQV4.mjs +0 -3
  124. package/dist/push-W3TM2QYK.mjs +0 -3
  125. package/dist/remove-MVQOIN2I.mjs +0 -2
  126. package/dist/reset-BTOJ54MJ.mjs +0 -3
  127. package/dist/restore-TWOOF2BN.mjs +0 -3
  128. package/dist/rollback-CFYSE5YG.mjs +0 -3
  129. package/dist/status-3ZXM3CRH.mjs +0 -4
  130. package/dist/tailwind-source-HCTY2XDU.mjs +0 -5
  131. package/dist/topo-sort-ZNGR6D7M.mjs +0 -2
  132. package/dist/tracker-QAKEXYUJ.mjs +0 -2
  133. package/dist/update-TGGCUOOO.mjs +0 -3
  134. package/dist/use-4Z5KXRVR.mjs +0 -3
  135. package/dist/vite-config-XOGAKYGQ.mjs +0 -2
  136. package/dist/watch-orchestrator-6BQYU5YS.mjs +0 -3
  137. package/dist/watcher-ES2APFH4.mjs +0 -3
  138. package/dist/workspace-T6PNO4L3.mjs +0 -2
  139. package/dist/xxhash-wasm-I6Q3T2SL.mjs +0 -3
package/README.md CHANGED
@@ -1,166 +1,125 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark.png" width="360" alt="Knarr logo" />
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark.png" />
4
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark-light.png" width="360" alt="Knarr" />
5
+ </picture>
3
6
  </p>
4
7
 
5
8
  <p align="center">
6
9
  <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/v/knarr?color=blue" alt="npm version" /></a>
7
10
  <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/dm/knarr" alt="npm downloads" /></a>
8
- <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/unpacked-size/knarr" alt="unpacked size" /></a>
9
- <a href="https://bundlephobia.com/package/knarr"><img src="https://badgen.net/bundlephobia/minzip/knarr" alt="minzipped size" /></a>
10
- <br>
11
11
  <a href="https://github.com/oleg-kuibar/knarr/actions/workflows/ci.yml"><img src="https://github.com/oleg-kuibar/knarr/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
12
12
  <a href="https://github.com/oleg-kuibar/knarr/actions/workflows/compat.yml"><img src="https://github.com/oleg-kuibar/knarr/actions/workflows/compat.yml/badge.svg" alt="Compatibility" /></a>
13
13
  <a href="https://github.com/oleg-kuibar/knarr/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="license" /></a>
14
- <img src="https://img.shields.io/badge/node-%3E%3D22.12-brightgreen" alt="node version" />
14
+ <img src="https://img.shields.io/badge/node-%3E%3D22.22-brightgreen" alt="node version" />
15
15
  </p>
16
16
 
17
17
  # Knarr
18
18
 
19
- Test local npm packages in real apps without `npm link` symlink surprises or local package references in `package.json`.
19
+ **Test a local npm package in a real app, without `npm link`.**
20
20
 
21
- Knarr copies the package files you would publish into the consumer app's `node_modules/`, then keeps registered consumers updated. It detects npm, pnpm, Bun, and Yarn projects that use `node_modules` or Yarn's pnpm linker. Yarn PnP is not compatible because it removes `node_modules`.
21
+ Knarr copies the files your package would publish into the app's `node_modules/`, then keeps them in sync while you work. The app sees a normal installed package: one copy of React, no symlinks for the bundler to trip on, and no `file:` paths in `package.json` or the lockfile.
22
22
 
23
23
  ```bash
24
24
  cd my-app
25
- npx knarr use ../my-lib
25
+ npx knarr use ../my-lib # build, publish, and copy my-lib into my-app
26
26
 
27
27
  cd ../my-lib
28
- knarr dev
28
+ npx knarr dev # on every save: rebuild and push to my-app
29
29
  ```
30
30
 
31
- If you have not installed Knarr globally, use `npx knarr dev` for the second command too.
32
-
33
- ![Knarr local package workflow](https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-demo.gif)
31
+ <p align="center">
32
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/demo.svg" width="960" alt="Terminal: knarr use links my-lib into my-app, then knarr dev rebuilds and pushes my-lib on save" />
33
+ </p>
34
34
 
35
- ## Who this is for
35
+ ## Why not `npm link`?
36
36
 
37
- - Library and design-system authors testing packages inside real consumer apps
38
- - React developers avoiding duplicate dependency instances and invalid hook calls from symlinks
39
- - pnpm users who want updates copied into the existing virtual-store install when possible
40
- - Teams that want local package overrides to stay out of dependency specs and lockfiles
37
+ <p align="center">
38
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/symlink-vs-copy.svg" width="960" alt="npm link makes node_modules/my-lib a symlink, so my-lib loads its own React. Knarr copies real files, so my-lib uses the app's React." />
39
+ </p>
41
40
 
42
- ## Why Knarr?
41
+ A symlinked package resolves its imports from its own folder, so the app can end up with two copies of React (or any other peer dependency), and some bundlers won't follow the link outside the project. yalc copies files too, but it rewrites the app's dependency to a `file:` path. Knarr leaves the dependency spec alone.
43
42
 
44
- `npm link` creates symlinks that can break module resolution: duplicate dependency instances, peer dependency mismatches, and bundlers that cannot follow links outside the project root. yalc improves this by copying files, but its workflow can rewrite consumer dependency specs or require extra watch tooling.
43
+ If pnpm workspaces, `file:`, or pnpm's `injected` dependencies already fit your repo, use those. Knarr is for testing a package in an app it doesn't share a workspace with, exactly as it will be installed. See the [comparison](docs/comparison.md).
45
44
 
46
- Knarr keeps the local override out of your dependency spec. It publishes a local package into `~/.knarr/store/`, injects that package into every registered consumer, and can watch, rebuild, and push changes continuously. Setup helpers may still add `.knarr/`, `.gitignore`, a restore hook, or bundler config when needed.
45
+ ## How it works
47
46
 
48
- If pnpm workspaces, `file:`, or `dependenciesMeta.*.injected` already fit your repo, use those native features first. Knarr is for the narrower case where you want publishable package files copied into real consumers while their dependency specs stay normal.
47
+ <p align="center">
48
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/how-it-works.svg" width="960" alt="knarr publish copies my-lib's packed files into ~/.knarr/store. add or use copies them into each app's node_modules. knarr dev rebuilds, publishes, and pushes on save." />
49
+ </p>
49
50
 
50
- ## Quick Start
51
+ 1. **`publish`** picks files the way `npm pack` does (`files`, `.npmignore`, `publishConfig.directory`) and copies them into a store at `~/.knarr/store/<name>@<version>/`.
52
+ 2. **`add`** copies a package from the store into an app's `node_modules/` and registers the app. **`use`** does `publish` + `add` in one step.
53
+ 3. **`push`** publishes and updates every registered app. Only files whose contents changed are copied.
54
+ 4. **`dev`** watches the source, runs your build, and pushes after each change. `dev --all` does this for every package in a workspace, in dependency order.
51
55
 
52
- One command links a local package into the app you are testing:
56
+ ## What it changes in your app
53
57
 
54
- ```bash
55
- # In your app
56
- cd my-app
57
- npx knarr use ../my-lib
58
- ```
59
-
60
- Then run the continuous package dev loop from the library:
58
+ | | |
59
+ | --- | --- |
60
+ | `node_modules/<pkg>/` | Replaced with the published files. The original install is backed up, and `knarr remove` restores it. |
61
+ | `.knarr/` | Link state and the restore script. Added to `.gitignore`. |
62
+ | `package.json` | A `postinstall` hook that puts links back after `npm install` wipes them. It does nothing for teammates without Knarr. Dependencies are untouched. |
63
+ | Bundler config | Vite: adds the `knarr/vite` plugin. Next.js: adds the package to `transpilePackages`. Tailwind v4: adds an `@source` line. Each is skipped with instructions if the config is too complex to edit safely. |
64
+ | Lockfile | Untouched. |
61
65
 
62
- ```bash
63
- # In your library
64
- cd ../my-lib
65
- knarr dev
66
- ```
66
+ ## Compatibility
67
67
 
68
- If Knarr is not installed globally, run `npx knarr dev` instead.
68
+ | | |
69
+ | --- | --- |
70
+ | Package managers | npm, pnpm (including its virtual store), Yarn 4 with `node-modules` or `pnpm` linker, Bun. Yarn PnP isn't supported because it has no `node_modules`. |
71
+ | Bundlers | Vite, Webpack, rspack, Next.js. Others pick up the changed files in `node_modules` on their own. |
72
+ | Platforms | macOS, Linux, Windows. |
73
+ | Node.js | 22.22 or newer. |
69
74
 
70
- That is the everyday loop: edit `my-lib`, Knarr rebuilds it, pushes changed files into `my-app/node_modules/`, and your dev server sees normal file changes there.
75
+ CI runs the test suite on all three platforms, and links a package into real npm, pnpm, Yarn, Bun, Vite, Webpack, rspack, and Next.js apps (`pnpm compat:smoke`).
71
76
 
72
- If you prefer the explicit steps:
77
+ ## Install
73
78
 
74
79
  ```bash
75
- cd my-lib
76
- pnpm build
77
- knarr publish
78
-
79
- cd ../my-app
80
- knarr add my-lib
81
- ```
82
-
83
- ## How It Works
84
-
85
- ```mermaid
86
- graph LR
87
- A["my-lib/"] -- "knarr publish" --> B["~/.knarr/store/<br/>my-lib@1.0.0"]
88
- B -- "knarr use ../my-lib<br/>or knarr add my-lib" --> C["app/node_modules/<br/>my-lib/"]
89
- B -- "knarr push" --> D["app-2/node_modules/<br/>my-lib/"]
90
-
91
- style A fill:#2e7d32,stroke:#66bb6a,color:#e8f5e9
92
- style B fill:#1565c0,stroke:#64b5f6,color:#e3f2fd
93
- style C fill:#e65100,stroke:#ffb74d,color:#fff3e0
94
- style D fill:#e65100,stroke:#ffb74d,color:#fff3e0
80
+ npm install -g knarr # or: pnpm add -g knarr
95
81
  ```
96
82
 
97
- 1. `publish` copies built files to a local store at `~/.knarr/store/`
98
- 2. `use` publishes from a local path and links it into the current app
99
- 3. `add` links an already-published package from the store
100
- 4. `push` publishes and copies to all registered consumers
101
- 5. `dev` watches, builds, publishes, and pushes continuously
83
+ Or skip the install and run every command through `npx knarr`.
102
84
 
103
- ## What Knarr Does
85
+ ## Commands
104
86
 
105
- | Area | Behavior |
87
+ | Command | What it does |
106
88
  | --- | --- |
107
- | Store | `~/.knarr/store/<name>@<version>/package/`, or `KNARR_HOME/store/...` when `KNARR_HOME` is set |
108
- | Consumer copy | Copies package files into `node_modules/<package>/` and records link state in `.knarr/state.json` |
109
- | Package files | Uses npm-pack-compatible file resolution, including the `files` field and `publishConfig.directory` |
110
- | pnpm | Follows existing pnpm virtual-store symlinks when present; falls back to a direct `node_modules` path |
111
- | Watch loop | `knarr dev` runs an initial push, then watches, rebuilds, publishes, and pushes again |
112
- | Reinstall recovery | `knarr restore` re-injects registered packages after `node_modules` is replaced |
113
- | Bundlers | Vite plugin triggers reload/restart, Next.js uses `transpilePackages`, Webpack/rspack plugin invalidates watch/cache, and other bundlers rely on file changes under `node_modules` |
114
- | Incremental sync | Skips same size and mtime, hashes same-size changed-mtime files with xxHash64, and removes stale destination files |
89
+ | `knarr use <path>` | Build, publish, and link a local package into this app. |
90
+ | `knarr dev [--all]` | Watch, build, and push on every change. |
91
+ | `knarr publish` / `knarr push` | Copy into the store / and update every linked app. |
92
+ | `knarr add <pkg>` / `knarr remove <pkg>` | Link from the store / restore the original install. |
93
+ | `knarr status`, `knarr list`, `knarr explain` | What is linked where, and why. |
94
+ | `knarr restore`, `knarr update`, `knarr rollback` | Re-apply links, pull the latest build, go back to an earlier build. |
95
+ | `knarr doctor`, `knarr check` | Diagnose setup problems; check a package's `exports` and files. |
96
+ | `knarr init`, `knarr migrate`, `knarr clean`, `knarr reset` | Set up an app, move from yalc, prune the store, undo everything. |
115
97
 
116
- See [detailed comparison](docs/comparison.md) for native pnpm options, yalc, symlink workflows, and Knarr tradeoffs.
98
+ Every command takes `--dry-run`, `--json`, and `--verbose`. Full reference: [docs/commands.md](docs/commands.md).
117
99
 
118
- ## Migrate From yalc In 60 Seconds
100
+ ## Coming from yalc
119
101
 
120
102
  ```bash
121
103
  cd my-app
122
- npx knarr migrate
123
- npx knarr use ../my-lib
124
-
125
- cd ../my-lib
126
- knarr dev
127
- ```
128
-
129
- See [Migrating from yalc](docs/migrating-from-yalc.md) for the full guide.
130
-
131
- ## Install
132
-
133
- ```bash
134
- pnpm add -g knarr # or npm install -g knarr
135
- npx knarr init # optional consumer setup and repair helpers
104
+ npx knarr migrate --from ../my-lib # remove .yalc/, yalc.lock, and file:.yalc deps, then link my-lib
136
105
  ```
137
106
 
138
- ## Performance Notes
139
-
140
- Knarr uses Node's copy-on-write reflink mode when the current filesystem supports it, with automatic fallback to a normal copy. Reflink support is probed once per volume and cached. Incremental sync checks size and mtime first, then falls back to xxHash64 only when needed, so unchanged files are skipped quickly.
107
+ See [Migrating from yalc](docs/migrating-from-yalc.md).
141
108
 
142
109
  ## Documentation
143
110
 
144
- - [Getting Started](docs/getting-started.md)
111
+ - [Getting started](docs/getting-started.md)
145
112
  - [Commands](docs/commands.md)
146
- - [Comparison](docs/comparison.md)
147
- - [Troubleshooting](docs/troubleshooting.md)
148
- - [CI/CD](docs/ci-cd.md)
149
- - [Examples](examples/)
113
+ - [How it works](docs/how-it-works.md)
114
+ - [Bundlers](docs/bundlers.md) and [monorepos](docs/monorepo.md)
115
+ - [Troubleshooting](docs/troubleshooting.md) and [FAQ](docs/faq.md)
116
+ - [CI/CD](docs/ci-cd.md): Knarr is for local development; use canary releases in CI.
117
+ - [Programmatic API](docs/api.md) (experimental)
150
118
  - [Contributing](CONTRIBUTING.md)
151
119
 
152
- Additional guides for bundlers, CI, monorepos, internals, and the experimental programmatic API live in [docs/](docs/).
153
-
154
120
  ## Acknowledgments
155
121
 
156
- Knarr is built on top of excellent open-source projects:
157
-
158
- - [chokidar](https://github.com/paulmillr/chokidar) - file watching
159
- - [xxhash-wasm](https://github.com/nicolo-ribaudo/xxhash-wasm-legacy) - fast file hashing
160
- - [citty](https://github.com/unjs/citty) - CLI framework
161
- - [tsup](https://github.com/egoist/tsup) - TypeScript bundler
162
- - [vitest](https://vitest.dev) - test runner
163
- - [Vite](https://vite.dev) - frontend tooling
122
+ Built on [chokidar](https://github.com/paulmillr/chokidar) (file watching), [xxhash-wasm](https://github.com/jungomi/xxhash-wasm) (hashing), [citty](https://github.com/unjs/citty) (CLI), and [picomatch](https://github.com/micromatch/picomatch) (globs), bundled with [tsdown](https://tsdown.dev) and tested with [Vitest](https://vitest.dev).
164
123
 
165
124
  ## License
166
125
 
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./timer-DqgB175x.mjs";import{n}from"./output-BxR2v-jn.mjs";import{t as r}from"./add-flow-cvrMO_aV.mjs";var i=e({meta:{name:`add`,description:`Link a package from the Knarr store into this project`},args:{package:{type:`positional`,description:`Package name to add`,required:!0},from:{type:`string`,description:`Path to package source (will publish first)`},build:{type:`string`,description:`Build command to run before publishing --from`},"skip-build":{type:`boolean`,description:`Skip build detection before publishing --from`,default:!1},yes:{type:`boolean`,alias:`y`,description:`Auto-accept prompts (install missing deps, etc.)`,default:!1}},async run({args:e}){n(),await r({packageArg:e.package,from:e.from,build:e.build,skipBuild:e[`skip-build`],yes:e.yes,timer:new t})}});export{i as default};
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e}from"./shell-RQ7Hf1kp.mjs";import{t}from"./hints-Hz3V4h3A.mjs";import{t as n}from"./console-CIiXr7ge.mjs";import{n as r,t as i}from"./store-DjPdOKqg.mjs";import{t as a}from"./publisher-CvXTbkLP.mjs";import{i as o,n as s,r as c,t as l}from"./injector-nt40JxVt.mjs";import{d as u,h as d,n as f,o as p}from"./tracker-B3Fqx94J.mjs";import{M as m,N as h,P as g,c as _,v}from"./fs-CPnWm9CR.mjs";import{t as y}from"./package-manager-DJ8CE0zL.mjs";import{t as b}from"./build-detect-BTHh2OBm.mjs";import{n as x}from"./bundler-detect-Dq-QAbQj.mjs";import{i as S,o as C}from"./init-helpers-CYYWQm-P.mjs";import{t as w}from"./nextjs-config-dUw2J6B9.mjs";import{t as T}from"./timer-DqgB175x.mjs";import{t as E}from"./output-BxR2v-jn.mjs";import{t as D}from"./errors-BlOfexcH.mjs";import{i as O,n as k,r as A}from"./logger-9C6B9Na8.mjs";import{i as j,r as M}from"./dry-run-BkdMYSIx.mjs";import{o as N}from"./json-DbSkpxtr.mjs";import{readFile as P}from"node:fs/promises";import{basename as F,join as I,resolve as L}from"node:path";async function addPackageToConsumer(e){let s=e.timer??new T,m=L(`.`),{name:b,version:x}=parsePackageArg(e.packageArg),w,O=null,A=!1,j=!1;if(validatePackageNameArg(b,e.packageArg),x)try{h(x)}catch{D(`Invalid package version "${x}" in "${e.packageArg}".`),process.exit(1)}let N=(await y(m)).resolve(),P=N.packageManager;if(N.nodeModulesCompatible||(n.error(N.incompatibilityReason),process.exit(1)),e.from){let t=L(e.from);w=t;let r=await maybeBuildSource(t,{build:e.build,skipBuild:e.skipBuild,yes:e.yes??!1});O=r.buildCmd,A=r.ran,j=r.skipped,n.info(`Publishing from ${t}...`),await a(t)}let F=x?await r(b,x):await i(b);if(!F){let e=x?`@${x}`:``;D(`Package "${b}${e}" not found in store. Run 'knarr publish' in the package directory first, or use --from <path>.`),process.exit(1)}await _(v(m))||(await S(m,P),n.success(`Auto-initialized knarr (consumer mode)`)),n.info(`Detected package manager: ${P}`);let I=await p(m,b);I&&(I.version===F.version?n.info(`Updating ${b}@${F.version} (already linked)`):n.info(`Updating ${b}: ${I.version} -> ${F.version}`));let R=I?I.backupExists:await l(m,b,P);!I&&R&&n.info(`Backed up existing ${b} installation`),await g(m,b,F.version),await configureBundler(m,b,N),await handleMissingDeps(F,m,N,e.yes??!1);let z=await c(F,m,P);n.success(`Linked ${b}@${F.version} -> node_modules/${b} (${z.copied} files copied, ${z.skipped} unchanged)`),z.binLinks>0&&n.info(`Created ${z.binLinks} bin link(s)`);let B={version:F.version,contentHash:F.meta.contentHash,linkedAt:(/* @__PURE__ */ new Date()).toISOString(),sourcePath:F.meta.sourcePath,backupExists:R,packageManager:P,buildId:F.meta.buildId??``};await f(m,b,B),await u(b,m).catch(d),await C(m),await o(m,b)||n.info(`${b} isn't in package.json, so adding or removing other packages can prune it. Run \`knarr restore\` afterwards, or add it to dependencies.`);let V=w?[`cd ${w} && knarr dev`]:[];w&&n.info(`Next: ${t(w,process.cwd(),await workspaceRootFor(w))}`),n.info(`Done in ${s.elapsed()}`);let H={package:b,version:F.version,copied:z.copied,skipped:z.skipped,binLinks:z.binLinks,elapsed:s.elapsedMs(),buildCmd:O,buildRan:A,buildSkipped:j,nextSteps:V};return e.emitOutput!==!1&&E(H),k()&&M(),H}async function readPackageNameFromSource(e){let t=L(e);await _(t)||(D(`Source path not found: ${t}`),process.exit(1));let n=I(t,`package.json`);await _(n)||(D(`No package.json found at ${n}. Pass a package directory to 'knarr use'.`),process.exit(1));let r;try{r=N(await P(n,`utf-8`))}catch(e){D(`Could not read package.json at ${n}: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}r&&typeof r==`object`&&typeof r.name==`string`||(D(`package.json at ${n} must include a package name for 'knarr use'.`),process.exit(1));let i=r.name.trim();return validatePackageNameArg(i,i),i}function parsePackageArg(e){if(e.startsWith(`@`)){let t=e.indexOf(`/`);if(t>0){let n=e.indexOf(`@`,t);if(n>t)return{name:e.slice(0,n),version:e.slice(n+1)}}return{name:e,version:null}}let t=e.lastIndexOf(`@`);return t>0?{name:e.slice(0,t),version:e.slice(t+1)}:{name:e,version:null}}function validatePackageNameArg(e,t){try{m(e)}catch{D(`Invalid package name "${t}". Use format: package-name or @scope/package-name.`),process.exit(1)}}async function maybeBuildSource(e,t){if(t.skipBuild)return t.build&&n.warn(`--skip-build was provided; ignoring --build`),{buildCmd:null,ran:!1,skipped:!0};let r=t.build,i=!!r;if(!r){let t=(await y(e)).resolve().packageManager;r=await b(e,t)??void 0}if(!r)return{buildCmd:null,ran:!1,skipped:!1};if(!i&&!t.yes&&!A()){let e=await n.prompt(`Run detected build command before publishing? (${r})`,{type:`confirm`,initial:!0});if(!e||typeof e==`symbol`)return n.info(`Skipping build before publish`),{buildCmd:r,ran:!1,skipped:!0}}else if(!i&&A()&&!t.yes)return O(`[add] Detected build command but skipping in json mode: ${r}`),{buildCmd:r,ran:!1,skipped:!0};return n.info(k()?`[dry-run] Would run build command: ${r}`:`Running build command: ${r}`),await runShellCommand(r,e)||(D(`Build command failed: ${r}`),await explainBuildFailure(e),process.exit(1)),{buildCmd:r,ran:!0,skipped:!1}}async function workspaceRootFor(e){let{findWorkspacePackageRoot:t,findWorkspacePackages:n}=await import(`./workspace-DBxNrowu.mjs`),r=await t(e);if(!r)return null;let i=await n(r),a=L(e);return i.some(e=>L(e)===a)?r:null}async function explainBuildFailure(e){if(!await _(I(e,`node_modules`))){let t=(await y(e)).resolve().packageManager;n.info(`Suggestion: ${e} has no node_modules. Run \`${t} install\` there, then retry.`)}n.info(`Suggestion: if the package is already built, re-run with --skip-build.`)}async function handleMissingDeps(e,t,r,i){let a=r.packageManager,o=await s(e,t,a);if(o.length!==0){if(A())O(`[add] Missing transitive deps (json mode): ${o.join(`, `)}`);else if(i){let e=r.installCommand(o),t=r.formatCommand(e);n.info(k()?`[dry-run] Would install missing dependencies: ${o.join(`, `)}`:`Installing missing dependencies: ${o.join(`, `)}`);let i=await r.run(e);i&&!k()?n.success(`Installed missing dependencies`):i||n.warn(`Install failed. Run manually: ${t}`)}else if(await n.prompt(`Install ${o.length} missing dependencies? (${o.join(`, `)})`,{type:`confirm`,initial:!0})){let e=r.installCommand(o),t=r.formatCommand(e),i=await r.run(e);i&&!k()?n.success(`Installed missing dependencies`):i||n.warn(`Install failed. Run manually: ${t}`)}else{let e=r.installCommand(o);n.warn(`Missing transitive dependencies: ${o.join(`, `)}\n Run: ${r.formatCommand(e)}`)}}}async function configureBundler(e,t,r){let i=await x(e);if(i.type===`next`&&i.configFile){let e=await w(i.configFile,t);e.modified?n.success(`Added ${t} to transpilePackages in ${F(i.configFile)}`):e.error&&n.info(`Add to next.config manually: transpilePackages: ['${t}']`)}else if(i.type===`vite`&&i.configFile){let{addKnarrVitePlugin:e}=await import(`./vite-config-BRlYc4ni.mjs`),t=await e(i.configFile);if(t.modified){n.success(`Added knarr plugin to ${F(i.configFile)}`);let e=r.installCommand([`knarr`],{dev:!0}),t=r.formatCommand(e);n.info(k()?`[dry-run] Would install knarr as devDependency`:`Installing knarr as devDependency...`);let a=await r.run(e);a&&!k()?n.success(`Installed knarr`):a||n.warn(`Install failed. Run manually: ${t}`)}else t.error&&n.info(`Add manually:
4
+ import knarr from "knarr/vite"
5
+ plugins: [knarr()]`)}let{findTailwindCss:a,addTailwindSource:o}=await import(`./tailwind-source-D1cUiG-t.mjs`),s=await a(e);if(s){let r=await o(s,t,e);r.modified?n.success(`Added @source for ${t} to ${F(s)}`):r.error&&n.info(`Add to your CSS manually: @source "../node_modules/${t}";`)}}function runShellCommand(t,n){return k()?(j({type:`command-skip`,path:n,detail:t}),Promise.resolve(!0)):new Promise(r=>{let i=e(t,{cwd:n,stdio:`inherit`});i.on(`close`,e=>r(e===0)),i.on(`error`,()=>r(!1))})}export{readPackageNameFromSource as n,addPackageToConsumer as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-CIiXr7ge.mjs";import{n as t,r as n,t as r}from"./workspace-CdLSxPFS.mjs";import{n as i,t as a}from"./topo-sort-yd4jxr_E.mjs";import{t as o}from"./push-engine-BpNr8qXR.mjs";import{t as s}from"./timer-DqgB175x.mjs";import{i as c}from"./logger-9C6B9Na8.mjs";async function doPushAll(l,u={}){let d=new s,f=await t(l),p=n(f);if(p.packages.length===0){e.warn(`No publishable workspace packages found`);return}let m=f.packages.length-p.packages.length;m>0&&e.info(`Skipping ${m} private workspace package(s)`);let h;try{h=i(p.adjacency)}catch(t){throw t instanceof a&&e.error(`Cannot push: ${t.message}`),t}let g=new Map(p.packages.map(e=>[e.name,e.dir]));e.info(`Pushing ${h.length} packages in dependency order`),c(`[batch-push] Order: ${h.join(` → `)}`);let _=r(p.adjacency),v=new Set(u.skipPackages??[]);for(let e of[...v])markTransitiveDependentsBlocked(e,_,v);let y=0,b=0,x=0;for(let t of h){let n=g.get(t);if(n){if(v.has(t))c(`[batch-push] Skipping ${t}: dependency build/push failed`),x++;else try{(await o(n,u)).failedConsumers>0?(b++,markTransitiveDependentsBlocked(t,_,v)):y++}catch(n){e.warn(`Failed to push ${t}: ${n instanceof Error?n.message:String(n)}`),b++,markTransitiveDependentsBlocked(t,_,v)}}}let S=[b>0?`${b} failed`:null,x>0?`${x} skipped`:null].filter(e=>e!==null),C=`Pushed ${y}/${h.length} packages in ${d.elapsed()}`+(S.length>0?` (${S.join(`, `)})`:``);if(b>0)throw e.warn(C),Error(`Failed to push ${b} workspace package(s)`);x>0?e.warn(C):e.success(C)}function markTransitiveDependentsBlocked(e,t,n){for(let r of t.get(e)??[])n.has(r)||(n.add(r),markTransitiveDependentsBlocked(r,t,n))}export{doPushAll as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{c as e,u as t}from"./json-DbSkpxtr.mjs";import{join as n}from"node:path";async function detectBuildCommand(r,i){let a=i===`npm`||i===`bun`?`${i} run `:`${i} `;try{let i=t(await e(n(r,`package.json`)),`scripts`);for(let e of[`build`,`compile`,`bundle`,`tsc`])if(i[e])return`${a}${e}`}catch{}return null}export{detectBuildCommand as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{c as e}from"./fs-CPnWm9CR.mjs";import{join as t}from"node:path";const n=[[`vite`,[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]],[`next`,[`next.config.js`,`next.config.ts`,`next.config.mjs`]],[`webpack`,[`webpack.config.js`,`webpack.config.ts`]],[`turbo`,[`turbo.json`]],[`rollup`,[`rollup.config.js`,`rollup.config.ts`,`rollup.config.mjs`]]];async function detectBundler(r){for(let[i,a]of n)for(let n of a){let a=t(r,n);if(await e(a))return{type:i,configFile:a}}return{type:null,configFile:null}}async function detectAllBundlers(r){let i=n.flatMap(([n,i])=>i.map(async i=>({type:n,configFile:t(r,i),found:await e(t(r,i))}))),a=await Promise.all(i),o=/* @__PURE__ */ new Set,s=[];for(let{type:e,configFile:t,found:n}of a)n&&!o.has(e)&&(o.add(e),s.push({type:e,configFile:t}));return s}export{detectBundler as n,detectAllBundlers as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{t as r}from"./preflight-MzNjLXiy.mjs";import{n as i,t as a}from"./output-BxR2v-jn.mjs";import{resolve as o}from"node:path";var s=e({meta:{name:`check`,description:`Validate package configuration (exports, types, entry points)`},args:{dir:{type:`positional`,description:`Package directory (default: current directory)`,required:!1}},async run({args:e}){i();let s=o(e.dir||`.`),c=await r(s);if(c.length===0){n.success(`All pre-flight checks passed`),a({issues:[],passed:!0});return}let l=c.filter(e=>e.severity===`error`),u=c.filter(e=>e.severity===`warn`);n.info(`Found ${c.length} issue(s):\n`);for(let e of l)n.log(` ${t.red(`ERROR`)} ${t.dim(`[${e.code}]`)} ${e.message}`);for(let e of u)n.log(` ${t.yellow(`WARN`)} ${t.dim(`[${e.code}]`)} ${e.message}`);l.length>0?n.error(`\n${l.length} error(s), ${u.length} warning(s)`):n.warn(`\n${u.length} warning(s)`),a({issues:c,passed:l.length===0})}});export{s as default};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{type as e}from"node:os";import{EventEmitter as t}from"node:events";import{realpathSync as n,watch as r}from"node:fs";import{lstat as i,open as a,readdir as o,readlink as s,realpath as c,stat as l}from"node:fs/promises";import*as u from"node:path";import{join as d,resolve as f,sep as p}from"node:path";import{Readable as m}from"node:stream";const h={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},g={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:h.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(g);const _=`READDIRP_RECURSIVE_ERROR`,v=/* @__PURE__ */ new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,_]),y=[h.DIR_TYPE,h.EVERYTHING_TYPE,h.FILE_DIR_TYPE,h.FILE_TYPE],b=/* @__PURE__ */ new Set([h.DIR_TYPE,h.EVERYTHING_TYPE,h.FILE_DIR_TYPE]),x=/* @__PURE__ */ new Set([h.EVERYTHING_TYPE,h.FILE_DIR_TYPE,h.FILE_TYPE]),isNormalFlowError=e=>v.has(e.code),S=process.platform===`win32`,emptyFn=e=>!0,normalizeFilter=e=>{if(e===void 0)return emptyFn;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return emptyFn};var ReaddirpStream=class extends m{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??g.highWaterMark});let t={...g,...e},n=t.root??g.root,r=t.type??g.type;this._fileFilter=normalizeFilter(t.fileFilter),this._directoryFilter=normalizeFilter(t.directoryFilter);let a=t.lstat?i:l;this._stat=S?e=>a(e,{bigint:!0}):a,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:g.depth,this._wantsDir=b.has(r),this._wantsFile=x.has(r),this._wantsEverything=r===h.EVERYTHING_TYPE,this._root=f(n),this._relStart=this._root.endsWith(p)?this._root.length:this._root.length+1,this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent};let o={path:this._root,depth:1};o.pending=this._exploreDir(this._root,1),this.parents=[o],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=this._isDirent?a:await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=this._getEntryType(t);typeof n!=`string`&&(n=await n),n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push({path:t.fullPath,depth:i+1}),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}let t=e.pending??this._exploreDir(e.path,e.depth),n=this.parents[this.parents.length-1];if(n&&!n.pending&&(n.pending=this._exploreDir(n.path,n.depth)),this.parent=await t,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await o(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}_formatEntry(e,t){let n=this._isDirent?e.name:e,r=d(t,n),i={path:r.slice(this._relStart),fullPath:r,basename:n};return this._isDirent?(i.dirent=e,i):this._stat(r).then(e=>(i.stats=e,i),e=>{this._onError(e)})}_onError(e){isNormalFlowError(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return``;let t=e[this._statsProp];return t.isFile()?`file`:t.isDirectory()?`directory`:t.isSymbolicLink()?this._getSymlinkEntryType(e):``}async _getSymlinkEntryType(e){let t=e.fullPath;try{let e=await c(t),n=await i(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t[n]===p){let n=/* @__PURE__ */ Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=_,this._onError(n),``}return`directory`}}catch(e){this._onError(e)}return``}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function readdirp(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=h.FILE_DIR_TYPE),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!y.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${y.join(`, `)}`);let r={...t,root:e};return n&&(r.type=n),new ReaddirpStream(r)}const C=process.platform,w=C===`win32`,T=C===`darwin`,E=C===`linux`,D=e()===`OS400`;function errorCode(e){return e?.code}function classifyError(e){let t=errorCode(e);return t===`ENOENT`||t===`ENOTDIR`?`missing`:t===`EPERM`||t===`EACCES`?`permission`:t===`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`?`recursive-unsupported`:`other`}function isMissingError(e){return classifyError(e)===`missing`}function isPermissionError(e){return classifyError(e)===`permission`}function isRecursiveWatchUnsupported(e){return classifyError(e)===`recursive-unsupported`}const O=Object.freeze({now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>{e&&clearTimeout(e)}}),k={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},A=/\\/g,j=/\/\//g;function normalizePath(e){if(typeof e!=`string`)throw TypeError(`string expected`);let t=e.replace(A,`/`),n=t.startsWith(`//`),r=u.normalize(t).replace(A,`/`).replace(j,`/`);return n&&!r.startsWith(`//`)&&(r=`/${r}`),r}function statIdentity(e){if(typeof e.mtimeMs!=`bigint`)return e;let t=e,n=t.mtimeNs/1000000000n,r=t.mtimeNs%1000000000n,i=Number(n)*1e3+Number(r)/1e6;return{size:Number(t.size),mtimeMs:i,ino:Number(t.ino)}}function logicalPathKey(e){let t=u.resolve(e);return w||!t.includes(`\\`)?t.replace(A,`/`):normalizePath(t)}function isInsideRelativePath(e){return e!==`..`&&!e.startsWith(`..${u.sep}`)&&!u.isAbsolute(e)}function isSameOrInside(e,t){let n=u.relative(e,t);return n===``||isInsideRelativePath(n)}function isStrictlyInside(e,t){let n=u.relative(e,t);return n!==``&&isInsideRelativePath(n)}function isMatcherObject(e){return typeof e==`object`&&!!e&&!(e instanceof RegExp)}function cloneOwnedMatcher(e){return e instanceof RegExp?new RegExp(e.source,e.flags):isMatcherObject(e)?Object.freeze({...e}):e}function compileMatcher(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>(e.lastIndex=0,e.test(t)):isMatcherObject(e)?t=>e.path===t||!!(e.recursive&&isStrictlyInside(e.path,t)):()=>!1}function compileMatchers(e){let t=e.map(compileMatcher);return(e,n)=>{if(t.length===0)return!1;let r=normalizePath(e);return t.some(e=>e(r,n))}}function normalizeMatcher(e,t=process.cwd()){return typeof e==`string`?normalizePath(u.isAbsolute(e)?e:u.join(t,e)):isMatcherObject(e)?{path:normalizePath(u.isAbsolute(e.path)?e.path:u.join(t,e.path)),recursive:e.recursive}:e}const M=/^\.[/\\]/;var N=class WatchHelper{watchPath;followSymlinks;recursiveRoot;recursiveDisabled;observationTrigger;realpathAncestry;pathGeneration;context;constructor(e,t,n){this.context=n,this.watchPath=e.replace(M,``),this.followSymlinks=t,this.realpathAncestry=/* @__PURE__ */ new Set,this.pathGeneration=n.capturePathGeneration()}fork(e){let t=new WatchHelper(e,this.followSymlinks,this.context);return t.recursiveRoot=this.recursiveRoot,t.recursiveDisabled=this.recursiveDisabled,t.observationTrigger=this.observationTrigger,t.realpathAncestry=new Set(this.realpathAncestry),t.pathGeneration=this.pathGeneration,t}withObservation(e){let t=Object.create(this);return t.observationTrigger=e,t}filterPath(e){return e.stats?.isSymbolicLink()?this.filterDir(e):this.context.isntIgnored(u.join(this.watchPath,e.path),e.stats)}filterDir(e){return this.context.isntIgnored(u.join(this.watchPath,e.path),e.stats)}};let P=0;function allocateSharedResourceGeneration(){return++P}function attachSharedSubscriber(e,t){return!e.closed&&(e.subscribers.add(t),!0)}function detachSharedSubscriber(e,t){if(!e.closed&&e.subscribers.delete(t))return e.subscribers.size>0?`remaining`:`last`}function invalidateSharedResource(e){if(e.closed)return;e.closed=!0;let t=[...e.subscribers];return e.subscribers.clear(),t}function reconfigureWatcherPersistence(e){[...e.subscribers].some(e=>e.persistent)?e.watcher.ref():e.watcher.unref()}function invalidateWatcherResource(e,t){let n=invalidateSharedResource(e);if(n)return t.get(e.resource)===e&&t.delete(e.resource),e.watcher.close(),n}function attachWatcherSubscriber(e,t){attachSharedSubscriber(e,t),reconfigureWatcherPersistence(e)}function createWatcherSubscription(e,t,n){let r=!1;return{resource:e.resource,close:()=>{if(r)return;r=!0;let i=detachSharedSubscriber(e,t);i===`remaining`?reconfigureWatcherPersistence(e):i===`last`&&n.get(e.resource)===e&&invalidateWatcherResource(e,n)}}}function selectBackend(e){let t=e.backend===`native-recursive`||e.backend===`auto`&&(T||w),n=e.backend===`polling`?`polling`:t&&e.depth===void 0?`native-recursive-preferred`:`native-per-directory`;return Object.freeze({kind:n,polling:n===`polling`,recursive:n===`native-recursive-preferred`,perDirectory:n===`native-per-directory`})}const F=k;function backendNow(){return performance.now()}function toNativeWatchPath(e){let t=u.normalize(e);if(!w)return t;try{return n.native(t)}catch{return t}}function projectNativeRelativePath(e,t){if(!w||t===null||!u.isAbsolute(t))return t;let n=u.normalize(u.toNamespacedPath(e)),r=u.normalize(u.toNamespacedPath(t)),i=u.relative(n,r);return isSameOrInside(n,r)?i||null:t}const I=/* @__PURE__ */ new Map;function systemNativeWatchFactory(e,t,n){return r(e,t,n)}let L=systemNativeWatchFactory;const R=/* @__PURE__ */ new Map;let z=!1;function systemRecursiveWatchFactory(e,t,n){return r(e,t,n)}let B=systemRecursiveWatchFactory;function failRecursiveResource(e,t){let n=invalidateWatcherResource(e,R);n&&n.forEach(e=>e.failure(t))}function subscribeRecursiveNative(e,t,n,r){if(z)return{kind:`unsupported`};let i=u.resolve(e),a={...n,watchedPath:e,persistent:t},o=R.get(i);if(!o){let n,r,a=toNativeWatchPath(e);try{n=B(a,{persistent:t,recursive:!0},(e,t)=>{let n=r;if(!n||n.closed||R.get(i)!==n)return;let o={kind:`native`,resource:i,rawEvent:e,relativePath:projectNativeRelativePath(a,t),sequence:++n.sequence,observedAt:backendNow()};n.subscribers.forEach(n=>{n.rawEmitter(e,t,{watchedPath:n.watchedPath}),n.publish(o)})})}catch(e){return isRecursiveWatchUnsupported(e)?(z=!0,{kind:`unsupported`}):{kind:`failed`,error:e}}r=o={resource:i,generation:allocateSharedResourceGeneration(),subscribers:/* @__PURE__ */ new Set,closed:!1,watcher:n,sequence:0},R.set(i,o),n.on(F.ERROR,e=>failRecursiveResource(o,e))}attachWatcherSubscriber(o,a);let s=createWatcherSubscription(o,a,R);return r.aborted&&s.close(),{kind:`subscribed`,subscription:s}}function createFsWatchInstance(e,t,n,r){try{return L(e,{persistent:t.persistent},n)}catch(e){r(e);return}}function publishNativeTrigger(e,t,n,r,i=n){if(e.closed||I.get(e.resource)!==e)return;let a={kind:`native`,resource:e.resource,rawEvent:t,relativePath:n,sequence:++e.sequence,observedAt:backendNow()};e.subscribers.forEach(e=>{r&&e.rawEmitter(t,i,{watchedPath:e.watchedPath}),e.publish(a)})}function broadcastNativeError(e,t){e.closed||I.get(e.resource)!==e||e.subscribers.forEach(e=>e.errHandler(t))}function closeFailedNativeResource(e,t){invalidateWatcherResource(e,I)?.forEach(e=>e.failure?.(t))}async function handleNativeError(e,t,n){if(w&&n.code===`EPERM`)try{await(await a(e,`r`)).close(),broadcastNativeError(t,n)}catch{publishNativeTrigger(t,`rename`,null,!1)}else broadcastNativeError(t,n);closeFailedNativeResource(t,n)}async function retireIfSelfRemoved(e,t){try{await i(u.join(t,u.basename(t)));return}catch(e){if(!isMissingError(e))return}try{if(!(await l(t)).isDirectory())return}catch{return}e.closed||I.get(e.resource)!==e||closeFailedNativeResource(e,/* @__PURE__ */ Error(`Watched directory was replaced: ${t}`))}function createNativeContainer(e,t,n,r,i){let a,o=createFsWatchInstance(t,r,(e,n)=>{let r=projectNativeRelativePath(t,n);publishNativeTrigger(a,e,r,!0,n),E&&e===`rename`&&n===u.basename(t)&&retireIfSelfRemoved(a,t)},i.errHandler);if(o)return a={resource:n,generation:allocateSharedResourceGeneration(),subscribers:/* @__PURE__ */ new Set([i]),closed:!1,watcher:o,sequence:0},I.set(n,a),o.on(F.ERROR,t=>{handleNativeError(e,a,t)}),a}function setFsWatchListener(e,t,n,r,i){let a=t,o={...r,watchedPath:e,persistent:n.persistent??!0},s=I.get(a);if(s)attachWatcherSubscriber(s,o);else if(s=createNativeContainer(e,toNativeWatchPath(e),a,n,o),!s)return;let c=createWatcherSubscription(s,o,I);if(i.aborted)c.close();else return c}const V=Object.freeze({missing:!0}),H=/* @__PURE__ */ new Map;function isMissingObservation(e){return`missing`in e}function observationsDiffer(e,t){let n=isMissingObservation(e),r=isMissingObservation(t);if(n||r)return n!==r;let i=!w&&e.ino!==0&&t.ino!==0&&e.ino!==t.ino;return e.size!==t.size||e.mtimeMs!==t.mtimeMs||i}function setTimerPersistence(e){e.timer&&(e.persistent?e.timer.ref():e.timer.unref())}function schedulePoll(e,t=e.interval){e.closed||e.subscribers.size===0||(e.timer=e.scheduler.setTimeout(()=>{e.timer=void 0;let t=pollResource(e);e.currentPoll=t,t.then(()=>{e.currentPoll===t&&(e.currentPoll=void 0)},()=>{e.currentPoll===t&&(e.currentPoll=void 0)})},t),setTimerPersistence(e))}async function pollResource(e){if(e.closed||e.running||e.subscribers.size===0)return;e.running=!0;let t=e.scheduler.now(),n;try{n=await l(e.resource)}catch(t){isMissingError(t)?n=V:e.subscribers.forEach(e=>e.errHandler(t))}if(!e.closed&&n){let t=e.previous;e.previous=n;let r=e.scheduler.now(),i=t&&observationsDiffer(t,n),a=e.directoryReplayAt!==void 0&&r>=e.directoryReplayAt;if(!isMissingObservation(n)&&n.isDirectory()?i?e.directoryReplayAt=r+1e3:a&&(e.directoryReplayAt=void 0):e.directoryReplayAt=void 0,t&&(i||a)){let r={kind:`poll`,resource:e.resource,current:n,previous:t,sequence:++e.sequence,observedAt:e.scheduler.now()};e.subscribers.forEach(i=>{i.rawEmitter(F.CHANGE,e.resource,{current:n,previous:t}),i.publish(r)})}}if(e.running=!1,!e.closed&&e.subscribers.size>0){let n=e.scheduler.now()-t;schedulePoll(e,Math.max(0,e.interval-n))}}function reconfigurePollResource(e){if(e.closed||e.subscribers.size===0)return;let t=Math.min(...[...e.subscribers].map(e=>e.interval)),n=[...e.subscribers].some(e=>e.persistent),r=e.interval!==t;e.interval=t,e.persistent=n,e.timer&&r?(e.scheduler.clearTimeout(e.timer),e.timer=void 0,schedulePoll(e)):e.timer?setTimerPersistence(e):e.running||schedulePoll(e)}function setPollingListener(e,t,n,r,i,a,o){let s=t,c={watchedPath:e,...n,...i},l=H.get(s);l||(l=/* @__PURE__ */ new Map,H.set(s,l));let u=l.get(r);u?!u.previous&&a&&(u.previous=a):(u={resource:s,generation:allocateSharedResourceGeneration(),scheduler:r,subscribers:/* @__PURE__ */ new Set,interval:n.interval,persistent:n.persistent,previous:a,running:!1,closed:!1,sequence:0},l.set(r,u)),u.subscribers.add(c),reconfigurePollResource(u);let d=!1,f,p={resource:s,close:()=>f||(f=(async()=>{if(d)return;if(d=!0,u.subscribers.delete(c),u.subscribers.size>0){reconfigurePollResource(u);return}if(u.closed)return;u.closed=!0,u.timer&&u.scheduler.clearTimeout(u.timer),u.timer=void 0;let e=H.get(s);e?.get(r)===u&&(e.delete(r),e.size===0&&H.delete(s)),u.currentPoll&&await Promise.allSettled([u.currentPoll])})(),f)};if(o.aborted)p.close();else return p}var LifecycleScope=class{state=`OPEN`;generation=0;abortController=new AbortController;tasks=/* @__PURE__ */ new Set;closers=/* @__PURE__ */ new Map;onTaskSettled;onTaskError;constructor(e,t){this.onTaskSettled=e,this.onTaskError=t}isActive(e){return this.state===`OPEN`&&this.generation===e}track(e){let t=Promise.resolve(e).finally(()=>{this.tasks.delete(t),this.onTaskSettled()});return this.tasks.add(t),t.catch(this.onTaskError),t}addCloser(e,t){let n=this.closers.get(e);n?n.push(t):this.closers.set(e,[t])}takeClosers(e){let t=this.closers.get(e)??[];return this.closers.delete(e),t}beginClose(){if(this.state!==`OPEN`)return[];this.state=`CLOSING`,this.generation+=1,this.abortController.abort();let e=[];return this.closers.forEach(t=>{t.forEach(t=>{try{e.push(Promise.resolve(t()))}catch(t){e.push(Promise.reject(t))}})}),this.closers.clear(),e}async drain(){for(;this.tasks.size>0;)await Promise.allSettled([...this.tasks])}finishClose(){this.state=`CLOSED`}};function IGNORE_RECONCILIATION_ERROR(){}function resolveRecursiveCandidate(e,t){if(u.isAbsolute(t))return;let n=u.resolve(e);if(isSameOrInside(n,u.resolve(n,t)))return u.join(e,t)}var ReconciliationQueue=class{queues=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;lifecycle;constructor(e){this.lifecycle=e}enqueue(e,t,n=e){let r=logicalPathKey(e),i=n===!1?void 0:`${r}\0${logicalPathKey(n)}`,a=i?this.pending.get(i):void 0;if(a)return a.work=t,a.replay=!0,a.promise;let o=this.lifecycle.generation,s={promise:Promise.resolve(),work:t,replay:!1},c=(this.queues.get(r)??Promise.resolve()).catch(IGNORE_RECONCILIATION_ERROR).then(async()=>{do{let e=s.work;if(s.replay=!1,!this.lifecycle.isActive(o))return;await e()}while(s.replay)}).finally(()=>{this.queues.get(r)===c&&this.queues.delete(r),i&&this.pending.get(i)===s&&this.pending.delete(i)});this.queues.set(r,c);let l=this.lifecycle.track(c);return s.promise=l,i&&this.pending.set(i,s),l}forgetPending(e){for(let t of this.pending.keys()){let[n,r]=t.split(`\0`,2);e(n,r)&&this.pending.delete(t)}}clear(){this.queues.clear(),this.pending.clear()}};const U=Object.freeze({size:0,mtimeMs:0,ino:0,kind:`other`,initialRecursive:!0});function statKind(e){return e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function sameStatFact(e,t){let n=statIdentity(t);return e?.size===n.size&&e.mtimeMs===n.mtimeMs&&e.ino===n.ino&&e.kind===statKind(t)}function withinWindow(e,t,n){return e?.observedAt!==void 0&&t.observedAt>=e.observedAt&&t.observedAt-e.observedAt<=n}var DirEntry=class{path;items=/* @__PURE__ */ new Set;constructor(e){this.path=e}add(e){e!==`.`&&e!==`..`&&e!==``&&this.items.add(e)}remove(e){return this.items.delete(e)&&this.items.size===0}has(e){return this.items.has(e)}getChildren(){return[...this.items]}dispose(){this.items.clear(),this.path=``}},TreeState=class{watched=/* @__PURE__ */ new Map;observed=/* @__PURE__ */ new Map;symlinkPaths=/* @__PURE__ */ new Map;recursiveRoots=/* @__PURE__ */ new Set;observesNative;constructor(e){this.observesNative=e}getDirectory(e){let t=u.resolve(e),n=logicalPathKey(t),r=this.watched.get(n);return r||(r=new DirEntry(t),this.watched.set(n,r)),r}peekDirectory(e){return this.watched.get(logicalPathKey(u.resolve(e)))}recordObserved(e,t,n,r,i=!1,a=!1){if(!this.observesNative()||!r&&!i&&!a)return;let{size:o,mtimeMs:s,ino:c}=statIdentity(t);this.observed.set(logicalPathKey(e),{size:o,mtimeMs:s,ino:c,kind:statKind(t),transition:n,rawEvent:r?.rawEvent,relativePath:r?.relativePath,observedAt:r?.observedAt,initialRecursive:i})}consumeInitialCreate(e,t,n,r){if(this.observed.get(logicalPathKey(e))?.initialRecursive&&n.rawEvent===`rename`)return this.recordObserved(e,t,`add`,n),r?t.isDirectory()?k.ADD_DIR:k.ADD:!1}markInitialCreate(e){let t=logicalPathKey(e),n=this.observed.get(t);n?n.initialRecursive=!0:this.observed.set(t,{...U})}clearInitialCreate(e){let t=this.observed.get(logicalPathKey(e));t&&(t.initialRecursive=!1)}clearInitialCreates(e){let t=logicalPathKey(e);for(let[e,n]of this.observed)isSameOrInside(t,e)&&n.initialRecursive&&(n.initialRecursive=!1)}replacedSinceObserved(e,t){let n=this.observed.get(logicalPathKey(e)),{ino:r}=statIdentity(t);return n?.kind===`directory`&&t.isDirectory()&&n.ino!==0&&r!==0&&n.ino!==r}changedSinceObserved(e,t){let n=this.observed.get(logicalPathKey(e));return n!==void 0&&n.kind===statKind(t)&&!sameStatFact(n,t)}isDuplicateObservation(e,t,n){let r=this.observed.get(logicalPathKey(e)),i=sameStatFact(r,t),a=i&&r?.transition===`add`&&r?.relativePath===n.relativePath&&r.rawEvent===`rename`&&n.rawEvent===`change`&&withinWindow(r,n,25),o=i&&t.isFile()&&!r?.initialRecursive&&(r?.transition===`add`||n.relativePath===null),s=i&&r?.transition===`change`&&r.relativePath===n.relativePath&&withinWindow(r,n,10)&&r.rawEvent===n.rawEvent,c=o||a||s,l=s?void 0:o?r?.transition:`change`;return this.recordObserved(e,t,l,n),c}dispose(){this.watched.forEach(e=>e.dispose()),this.watched.clear(),this.observed.clear(),this.symlinkPaths.clear(),this.recursiveRoots.clear()}};function isEmptyFile(e){return e!==void 0&&e.isFile()&&statIdentity(e).size===0}function sameChangeStats(e,t){if(e===void 0||t===void 0)return!1;let n=statIdentity(e),r=statIdentity(t);return n.size===r.size&&n.mtimeMs===r.mtimeMs&&n.ino===r.ino}var EventPolicy=class{pendingWrites=/* @__PURE__ */ new Map;pendingUnlinks=/* @__PURE__ */ new Map;pendingChanges=/* @__PURE__ */ new Map;heldAdds=/* @__PURE__ */ new Map;throttled=/* @__PURE__ */ new Map;context;constructor(e){this.context=e}presentPath(e){return w&&(e=u.normalize(e)),this.context.options.cwd?u.relative(this.context.options.cwd,e):e}dropHeldAdd(e){let t=this.heldAdds.get(e);t&&this.context.scheduler.clearTimeout(t.timer),this.heldAdds.delete(e)}dropPendingChange(e){let t=this.pendingChanges.get(e);t?.held&&this.context.scheduler.clearTimeout(t.held.timer),this.pendingChanges.delete(e)}setTimeout(e,t){let n=this.context.scheduler.setTimeout(e,t);return this.context.options.persistent||n.unref(),n}async emit(e,t,n){if(this.context.isClosed())return;let{options:r,scheduler:i}=this.context,a=t,o=logicalPathKey(t),s=this.context.lifecycle.generation,c=this.context.capturePathGeneration();t=this.presentPath(t);let d=[t];n!=null&&d.push(n);let f=this.heldAdds.get(o);if(f){if(e===k.CHANGE){f.path=a,n&&(f.stats=n),isEmptyFile(n)||f.release();return}f.release()}(e===k.UNLINK||e===k.UNLINK_DIR)&&(this.dropPendingChange(o),this.throttled.get(k.CHANGE)?.get(o)?.clear(!1));let p=r.awaitWriteFinish,m=p?this.pendingWrites.get(o):void 0;if(m)m.lastChange=i.now();else{if(r.atomic){if(e===k.UNLINK){let t=this.pendingUnlinks.get(o);t&&i.clearTimeout(t.timer);let n=[e,...d],a=this.setTimeout(()=>{let e=this.pendingUnlinks.get(o);if(!e||e.timer!==a||(this.pendingUnlinks.delete(o),this.context.isClosed()))return;let[t,...n]=e.event;this.context.publish(t,n)},typeof r.atomic==`number`?r.atomic:100);this.pendingUnlinks.set(o,{event:n,timer:a});return}let t=this.pendingUnlinks.get(o);e===k.ADD&&t&&(e=k.CHANGE,i.clearTimeout(t.timer),this.pendingUnlinks.delete(o))}if(p&&(e===k.ADD||e===k.CHANGE)&&this.context.isReady()){let awfEmit=(t,n)=>{this.context.isClosed()||(t?(e=k.ERROR,d[0]=t,this.context.publish(e,d)):n&&(d.length>1?d[1]=n:d.push(n),this.context.publish(e,d)))};this.awaitWriteFinish(t,p.stabilityThreshold,e,awfEmit,o)}else if(e===k.ADD&&isEmptyFile(n)&&this.context.isReady()){let e={path:a,stats:n,release:()=>{if(this.context.scheduler.clearTimeout(e.timer),this.heldAdds.get(o)!==e||(this.heldAdds.delete(o),this.context.isClosed()||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c)))return;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(k.ADD,t)}};e.timer=this.setTimeout(e.release,10),this.heldAdds.set(o,e)}else{if(e===k.CHANGE){if(!this.throttle(k.CHANGE,a,50,e=>{let t=this.pendingChanges.get(o);this.dropPendingChange(o),e>0&&t?.replay&&this.context.lifecycle.isActive(s)&&this.context.isPathGenerationActive(o,c)&&this.emit(k.CHANGE,t.path,t.stats)})){let e=this.pendingChanges.get(o);e&&!sameChangeStats(e.stats,n)&&(e.path=a,e.stats=n,e.replay=!0,e.held&&!isEmptyFile(n)&&e.held.release());return}let e={path:a,stats:n,replay:!1};if(this.pendingChanges.set(o,e),isEmptyFile(n)){let release=()=>{if(e.held&&this.context.scheduler.clearTimeout(e.held.timer),e.held=void 0,this.pendingChanges.get(o)!==e||this.context.isClosed()||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c))return;e.replay=!1;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(k.CHANGE,t)};e.held={timer:this.setTimeout(release,10),release};return}}if(r.alwaysStat&&n===void 0&&(e===k.ADD||e===k.ADD_DIR||e===k.CHANGE)){let e=r.cwd?u.join(r.cwd,t):t;try{n=await l(e)}catch(e){this.context.handleError(e)}if(!n||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c))return;d.push(n)}this.context.publish(e,d)}}}throttle(e,t,n,r){let i=this.throttled.get(e);i||(i=/* @__PURE__ */ new Map,this.throttled.set(e,i));let a=e===`readdir`?t:logicalPathKey(t),o=i.get(a);if(o)return o.count+=1,!1;let s,clear=(e=!0)=>{let t=i.get(a),n=t?.count??0;return i.delete(a),this.context.scheduler.clearTimeout(s),t&&this.context.scheduler.clearTimeout(t.timeoutObject),e&&r&&r(n),n};s=this.setTimeout(clear,n);let c={timeoutObject:s,clear,count:0};return i.set(a,c),c}awaitWriteFinish(e,t,n,r,i){let a=this.context.options.awaitWriteFinish;if(typeof a!=`object`)return;let o=a.pollInterval,s,c=e;this.context.options.cwd&&!u.isAbsolute(e)&&(c=u.join(this.context.options.cwd,e));let d=i??logicalPathKey(c);if(this.pendingWrites.has(d))return;let f=this.context.lifecycle.generation,p={lastChange:this.context.scheduler.now(),cancelWait:()=>(this.pendingWrites.get(d)===p&&this.pendingWrites.delete(d),this.context.scheduler.clearTimeout(s),n)},isCurrent=()=>this.context.lifecycle.isActive(f)&&this.pendingWrites.get(d)===p,inspect=e=>{let n=(async()=>{let n;try{n=await l(c)}catch(e){if(!isCurrent())return;isMissingError(e)?(this.context.remove(u.dirname(c),u.basename(c)),this.pendingWrites.get(d)===p&&p.cancelWait()):(this.pendingWrites.delete(d),r(e));return}if(!isCurrent())return;let i=this.context.scheduler.now();e&&n.size!==e.size&&(p.lastChange=i),i-p.lastChange>=t?(this.pendingWrites.delete(d),r(void 0,n)):s=this.setTimeout(()=>inspect(n),o)})();this.context.lifecycle.track(n)};this.pendingWrites.set(d,p),s=this.setTimeout(inspect,o)}cancelPath(e){let t=logicalPathKey(e),n=this.pendingUnlinks.get(t);n&&(this.context.scheduler.clearTimeout(n.timer),this.pendingUnlinks.delete(t)),this.pendingWrites.get(t)?.cancelWait(),this.dropPendingChange(t),this.dropHeldAdd(t),[`watch`,`add`,`remove`,`change`].forEach(e=>{this.throttled.get(e)?.get(t)?.clear(!1)});let r=this.throttled.get(`readdir`);r?.get(t)?.clear(!1),r?.get(`${logicalPathKey(u.dirname(t))}\0${u.basename(t)}`)?.clear(!1)}cancelWhere(e){[.../* @__PURE__ */ new Set([...this.pendingUnlinks.keys(),...this.pendingWrites.keys(),...this.pendingChanges.keys(),...this.heldAdds.keys()])].filter(e).forEach(e=>this.cancelPath(e)),this.throttled.forEach((t,n)=>{[...t.keys()].filter(t=>e(n===`readdir`?t.split(`\0`,1)[0]:t)).forEach(e=>t.get(e)?.clear(!1))})}close(){this.pendingWrites.forEach(e=>e.cancelWait()),this.pendingUnlinks.forEach(({timer:e})=>this.context.scheduler.clearTimeout(e)),this.pendingUnlinks.clear(),this.pendingChanges.forEach(({held:e})=>this.context.scheduler.clearTimeout(e?.timer)),this.pendingChanges.clear(),this.heldAdds.forEach(({timer:e})=>this.context.scheduler.clearTimeout(e)),this.heldAdds.clear(),this.throttled.forEach(e=>{e.forEach(e=>e.clear(!1))}),this.throttled.clear()}};const W=k,G=1024,K=Object.freeze({});function recoveryTrigger(e){return{kind:`native`,resource:e,rawEvent:W.CHANGE,relativePath:null,sequence:2**53-1,observedAt:backendNow()}}function sameMappedFileSnapshot(e,t){return e===!1||t===!1?e===t:e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ctimeMs===t.ctimeMs&&e.ino===t.ino&&e.mode===t.mode}var ReplayBuffer=class{entries=[];overflow;limit;constructor(e){this.limit=e}get overflowed(){return this.overflow!==void 0}push(e){this.entries.length<this.limit&&!this.overflowed?this.entries.push(e):this.overflow=e}clear(){this.entries.length=0,this.overflow=void 0}};function consumeDirectoryStream(e,t){let n=[];return e.on(`data`,e=>{let r;try{r=t(e)}catch(e){r=Promise.reject(e)}r&&n.push(Promise.resolve(r))}),new Promise(t=>{e.once(`end`,()=>t({complete:!0})),e.once(`close`,()=>t({complete:!1})),e.once(W.ERROR,e=>t({complete:!1,error:e}))}).then(async({complete:e,error:t})=>{let r=(await Promise.allSettled(n)).filter(e=>e.status===`rejected`).map(e=>e.reason);return{complete:e&&r.length===0,error:t,failures:r}})}const q=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(` `));function isBinaryPath(e){return q.has(u.extname(e).slice(1).toLowerCase())}var ObservationEngine=class{fsw;reportError;constructor(e){this.fsw=e,this.reportError=t=>e.handleError(t)}subscribePath(e,t,n,r=!1,i=e){let a=this.fsw.options,o=u.basename(e),s=u.resolve(e),c={persistent:a.persistent},l=this.fsw.lifecycle.generation,d=!0,trackedListener=(e,n,r)=>{if(d&&this.fsw.lifecycle.isActive(l))return t(e,n,r)},publish=t=>{this.reconcileBackendTrigger(e,r,t,e=>trackedListener(e,t.kind===`poll`&&!isMissingObservation(t.current)?t.current:void 0,t),()=>d&&this.fsw.lifecycle.isActive(l),!0,i)},f,p=0,subscribeNative=()=>setFsWatchListener(e,s,c,{publish:e=>{p=0,publish(e)},errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e),failure:()=>{d&&this.fsw.lifecycle.isActive(l)&&(f=p++<3?subscribeNative():void 0,publish(recoveryTrigger(s)))}},this.fsw.lifecycle.abortController.signal);if(f=a.backendCapabilities.polling?setPollingListener(e,s,{interval:a.pollingInterval!==a.pollingBinaryInterval&&isBinaryPath(o)?a.pollingBinaryInterval:a.pollingInterval,persistent:a.persistent},this.fsw.scheduler,{publish,errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e)},n,this.fsw.lifecycle.abortController.signal):subscribeNative(),f)return()=>{if(d)return d=!1,f?.close()}}subscribeMappedFile(e,t,n,r,i=T){if(this.fsw.options.backendCapabilities.polling)return;let a=u.dirname(t),o=logicalPathKey(t),s=u.dirname(e),c=this.fsw.lifecycle.generation,l=!0,d=i,f=!1,p,m,h,isActive=()=>l&&this.fsw.lifecycle.isActive(c)&&this.isHelperActive(n,e),matchesTarget=e=>{if(e===null)return!0;let t=logicalPathKey(u.isAbsolute(e)?e:u.resolve(a,e));return w?t.toLowerCase()===o.toLowerCase():t===o},retireExact=()=>{d&&(d=!1,h&&h.close())},publish=(i,o)=>{if(o.kind!==`native`||!matchesTarget(o.relativePath)||!isActive())return;let c=i===`directory`&&f;i===`directory`?(f=!1,retireExact()):m&&(f=!0,retireExact()),this.reconcileBackendTrigger(a,!0,o,async()=>{if(c&&p!==void 0){let e=await this.mappedFileSnapshot(t);if(e!==void 0&&sameMappedFileSnapshot(p,e))return}await this.reconcileNativeTrigger(s,n,o,e,r-1,K),i===`exact`&&(p=await this.mappedFileSnapshot(t))},isActive,!1,e)},g=0,handlers=t=>({publish:e=>{t===`directory`&&(g=0),publish(t,e)},errHandler:this.reportError,rawEmitter:(n,r)=>{(t===`directory`||d)&&matchesTarget(r)&&isActive()&&this.fsw.emitRaw(n,r,{watchedPath:e})},failure:()=>{t===`exact`?(h=void 0,d=!1):(m=void 0,isActive()&&(g++<3&&(m=subscribe(t)),publish(t,recoveryTrigger(u.resolve(a)))))}}),subscribe=e=>{let n=e===`directory`?a:t;return setFsWatchListener(n,u.resolve(n),{persistent:this.fsw.options.persistent},handlers(e),this.fsw.lifecycle.abortController.signal)};if(m=subscribe(`directory`),h=i?subscribe(`exact`):void 0,h||(d=!1),m||h)return async()=>{if(!l)return;l=!1;let e=[m,h].filter(e=>e!==void 0);await Promise.allSettled(e.map(e=>e.close()))}}async mappedFileSnapshot(e){try{return await i(e)}catch(e){if(isMissingError(e))return!1;this.reportError(e);return}}watchSymlinkDeletion(e,t=!1){if(!T&&!t||this.fsw.options.backendCapabilities.polling)return;let n=this.fsw,r=n.lifecycle.generation,a=u.dirname(e),o=u.basename(e),s=!0,c,schedule=()=>{c=n.scheduler.setTimeout(()=>{c=void 0,(async()=>{try{await i(e)}catch(e){if(!s||!n.lifecycle.isActive(r))return;if(isMissingError(e)){s=!1,n.removePath(a,o);return}this.reportError(e)}s&&n.lifecycle.isActive(r)&&schedule()})()},n.options.pollingInterval),n.options.persistent||c.unref()};return schedule(),()=>{s&&(s=!1,n.scheduler.clearTimeout(c),c=void 0)}}reconcileBackendTrigger(e,t,n,r,i=()=>!0,a=!0,o=e){let s=e;if(t&&n.kind===`native`&&n.relativePath!==null){let t=resolveRecursiveCandidate(e,n.relativePath);if(!t)return this.reportError(/* @__PURE__ */ Error(`Watcher reported a path outside its root: ${n.relativePath}`)),Promise.resolve();s=t}if(!i()||this.fsw.isUnwatched(s))return Promise.resolve();let c=logicalPathKey(o),l=logicalPathKey(s);return this.fsw.reconciliation.enqueue(c,async()=>{i()&&!this.fsw.isUnwatched(l)&&await r(s)},a?l:!1)}handleFile(e,t,n,r=!0,a,o=!1,s=!1){if(this.fsw.closed)return;let c=u.dirname(e),d=u.basename(e),f=this.fsw.tree.getDirectory(c),p=t;if(f.has(d))return;let m=this.fsw.capturePathGeneration(),isActive=()=>this.fsw.isPathGenerationActive(e,m),listener=async(t,n)=>{if(!n||n.mtimeMs===0)try{let t=p.isSymbolicLink()&&!this.fsw.options.followSymlinks?await i(e):await l(e);if(!isActive())return;let n=t.atimeMs,r=t.mtimeMs;(!n||n<=r||r!==p.mtimeMs)&&this.fsw.emitEvent(W.CHANGE,e,t),this.fsw.tree.recordObserved(e,t,`change`),p=t}catch(e){if(!isActive())return;isMissingError(e)?this.fsw.removePath(c,d):this.reportError(e)}else if(f.has(d)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==p.mtimeMs)&&this.fsw.emitEvent(W.CHANGE,e,n),this.fsw.tree.recordObserved(e,n,`change`),p=n}},h=r&&this.fsw.options.backendCapabilities.polling?this.subscribePath(e,listener,t):void 0;return f.add(d),this.fsw.tree.recordObserved(e,t,`add`,a,o,s),!(n&&this.fsw.options.ignoreInitial)&&!this.fsw.isIgnored(e,t)&&this.fsw.emitEvent(W.ADD,e,t),h}async handleSymlink(e,t,n,r,i,a){if(this.fsw.closed||a&&!this.isHelperActive(a,n))return;let o=logicalPathKey(e.fullPath),c=this.fsw.tree.getDirectory(t);if(!this.fsw.options.followSymlinks){let t;try{t=await s(n)}catch(e){return isMissingError(e)||this.reportError(e),!0}return this.fsw.closed||a&&!this.isHelperActive(a,n)||(c.has(r)?this.fsw.tree.symlinkPaths.get(o)!==t&&(this.fsw.tree.symlinkPaths.set(o,t),this.fsw.emitEvent(W.CHANGE,n,e.stats)):(c.add(r),this.fsw.tree.symlinkPaths.set(o,t),this.fsw.tree.recordObserved(n,e.stats,`add`,a?.observationTrigger,i&&!!a?.recursiveRoot),i&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(W.ADD,n,e.stats))),!0}if(this.fsw.tree.symlinkPaths.has(o))return!0;this.fsw.tree.symlinkPaths.set(o,!0)}readDirectory(e,t,n,r,a,o){if(!this.isHelperActive(n,e))return;e=u.join(e,``);let s=logicalPathKey(e),c=this.fsw.tree.getDirectory(n.watchPath),d=/* @__PURE__ */ new Set,f=this.fsw.createScanStream(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(f)return consumeDirectoryStream(f,i=>{if(!this.isHelperActive(n,e))return;let s=i.stats;if(!s)return;let l=i.path,f=u.join(e,l);if(!this.isHelperActive(n,f))return;d.add(l);let p=l===r||!r&&!c.has(l);if(r===void 0&&!s.isSymbolicLink()&&!s.isDirectory()){if(!p)return;f=u.join(a,u.relative(a,f));let e=this.handleFile(f,s,t,!n.recursiveRoot,n.observationTrigger,t&&!!n.recursiveRoot);e&&this.fsw.addPathCloser(f,e)}else return(async()=>{s.isSymbolicLink()&&await this.handleSymlink(i,e,f,l,t,n)||this.isHelperActive(n,f)&&p&&(f=u.join(a,u.relative(a,f)),await this.addPathOnce(f,t,n,o+1))})()}).then(async({complete:t,error:a,failures:f})=>{if(f.forEach(this.reportError),a){if(isMissingError(a)&&this.isHelperActive(n,e)){let t=r?u.join(e,r):e,a=!1,d=!1;try{let e=r?await i(t):await l(t);d=!r&&!e.isDirectory()}catch(e){isMissingError(e)?a=!0:this.reportError(e)}r?a&&c.has(r)&&this.fsw.removePath(e,r):(a||d)&&this.fsw.tree.watched.has(s)&&(this.fsw.removePath(u.dirname(e),u.basename(e),!0),d&&await this.addPathOnce(e,!1,n,o))}else this.reportError(a)}t&&this.isHelperActive(n,e)&&await Promise.all(c.getChildren().filter(e=>!d.has(e)).map(t=>this.removeIfMissing(n,e,t,c)))})}async removeIfMissing(e,t,n,r){let a=u.join(t,n);if(this.isHelperActive(e,a)){try{await i(a);return}catch(e){if(!isMissingError(e))return}this.isHelperActive(e,a)&&r.has(n)&&this.fsw.removePath(t,n)}}scanRecursiveTree(e,t,n,r,i){if(!this.isHelperActive(n,e))return;let a=this.fsw,o=a.options.depth,s=o===void 0?void 0:o-r,c=a.createScanStream(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>!e.stats?.isSymbolicLink()&&n.filterDir(e),depth:s});if(c)return consumeDirectoryStream(c,o=>{if(!this.isHelperActive(n,e))return;let s=o.stats;if(!s)return;let c=u.join(e,o.path);if(!this.isHelperActive(n,c))return;let l=u.dirname(c),d=u.basename(c);if(i&&(i.seen.add(logicalPathKey(c)),s.isDirectory()&&i.directories.push(c)),s.isSymbolicLink())return(async()=>{if(await this.handleSymlink(o,l,c,d,t,n)||!this.isHelperActive(n,c))return;let e=r+o.path.split(/[/\\]/).length;await this.addPathOnce(c,t,n,e)})();let f=a.tree.getDirectory(l);if(f.has(d)){i&&s.isFile()&&a.tree.changedSinceObserved(c,s)&&(a.tree.recordObserved(c,s,`change`,void 0,!1,!0),a.emitEvent(W.CHANGE,c,s));return}f.add(d);let p=s.isDirectory();p&&a.tree.getDirectory(c),a.tree.recordObserved(c,s,`add`,n.observationTrigger,t),t&&a.options.ignoreInitial||a.emitEvent(p?W.ADD_DIR:W.ADD,c,s)}).then(e=>{e.error&&this.reportError(e.error),e.failures.forEach(this.reportError),i&&(i.complete=e.complete)})}async rescanRecursiveTree(e,t,n){let r={seen:/* @__PURE__ */ new Set,directories:[e],complete:!1};if(await this.scanRecursiveTree(e,!1,t,n,r),!r.complete||!this.isHelperActive(t,e))return;let i=[];for(let e of r.directories)for(let t of this.fsw.tree.peekDirectory(e)?.getChildren()??[]){let n=u.join(e,t);r.seen.has(logicalPathKey(n))||i.push(n)}i.sort((e,t)=>e.length-t.length);for(let e of i){let n=this.fsw.tree.peekDirectory(u.dirname(e));n?.has(u.basename(e))&&await this.removeIfMissing(t,u.dirname(e),u.basename(e),n)}}isHelperActive(e,t=e.watchPath){return this.fsw.isPathGenerationActive(t,e.pathGeneration)}candidateDepth(e,t){let n=u.relative(e,t);return n?n.split(u.sep).length:0}candidateIgnored(e,t,n){let r=u.relative(e,t),i=e;if(this.fsw.isIgnored(i))return!0;if(r){let e=r.split(u.sep);for(let t=0;t<e.length-1;t++)if(i=u.join(i,e[t]),this.fsw.isIgnored(i))return!0}return this.fsw.isIgnored(t,n)}async highestMissingPath(e,t){let n=t,r=u.dirname(t);for(;;){try{return await i(r),n}catch(e){if(!isMissingError(e))return this.reportError(e),n}if(n=r,r===e)return n;let t=u.dirname(r);if(t===r)return n;r=t}}async reconcileNativeTrigger(e,t,n,r,a=0,o){let l=this.fsw;if(!this.isHelperActive(t,e))return;let d,helper=()=>d??=t.withObservation(n),f=r??(n.relativePath===null?e:resolveRecursiveCandidate(e,n.relativePath));if(!f){this.reportError(/* @__PURE__ */ Error(`Native watcher reported a path outside its root: ${n.relativePath}`));return}let p=a+this.candidateDepth(e,f),m=l.options.depth;if(m!==void 0&&p>m+1||this.candidateIgnored(e,f))return;let h;try{h=await i(f)}catch(t){if(!isMissingError(t)){if(this.reportError(t),o)return;let n=f===e?e:u.dirname(f),r=Math.max(0,a+this.candidateDepth(e,n));await this.readDirectory(n,!1,helper().fork(n),void 0,n,r);return}if(l.closed)return;let n=f===e?e:await this.highestMissingPath(e,f);if(l.closed)return;if(n===e){l.removePath(u.dirname(e),u.basename(e),!0),o?.onRootMissing?.();return}let r=u.dirname(n),i=u.basename(n);l.tree.getDirectory(r).has(i)?l.removePath(r,i):o||await this.readDirectory(r,!1,helper().fork(r),void 0,r,Math.max(0,a+this.candidateDepth(e,r)));return}if(!this.isHelperActive(t,f)||this.candidateIgnored(e,f,h))return;if(!h.isDirectory()&&!(h.isSymbolicLink()&&l.options.followSymlinks)){let e=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(e!==void 0){e&&l.emitEvent(e,f,h);return}}if(f===e){if(!h.isDirectory())return;t.recursiveRoot===e?await this.rescanRecursiveTree(e,helper(),a):await this.readDirectory(e,!1,helper(),void 0,e,a);return}let g=u.dirname(f),_=u.basename(f),v=l.tree.getDirectory(g),y=v.has(_);if(h.isSymbolicLink()){if(!l.options.followSymlinks){let e=!0;try{e=await s(f)}catch{}y||v.add(_),l.tree.symlinkPaths.set(logicalPathKey(f),e),y&&l.tree.isDuplicateObservation(f,h,n)||l.emitEvent(y?W.CHANGE:W.ADD,f,h),y||l.tree.recordObserved(f,h,`add`,n);return}let e=logicalPathKey(f),r=l.tree.symlinkPaths.get(e),i;try{i=await c(f)}catch(e){if(!isMissingError(e)){this.reportError(e);return}}if(y&&typeof r==`string`&&(i===void 0||logicalPathKey(r)!==logicalPathKey(i))){let n=l.tree.observed.get(e)?.kind;if(l.removePath(g,_,n===`directory`),!i||!this.isHelperActive(t,f))return;let r=helper().fork(f);r.recursiveRoot=void 0,await this.addPathOnce(f,!1,r,p);return}let a=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(a!==void 0){if(a){l.closePath(f,!0);let e=helper().fork(f);e.recursiveRoot=void 0,await this.addPathOnce(f,!1,e,p)}return}if(y)l.emitEvent(W.CHANGE,f,h);else{let e=helper().fork(f);e.recursiveRoot=void 0,await this.addPathOnce(f,!1,e,p)}}else if(h.isDirectory()){let e=helper().fork(f),t=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(t!==void 0){t&&(l.closePath(f,!0),await this.addPathOnce(f,!1,e,p));return}y?l.tree.replacedSinceObserved(f,h)?(l.removePath(g,_,!0),await this.addPathOnce(f,!1,e,p)):(m===void 0||p<=m)&&await this.readDirectory(f,!1,e,void 0,f,p):await this.addPathOnce(f,!1,e,p)}else y?l.tree.isDuplicateObservation(f,h,n)||l.emitEvent(W.CHANGE,f,h):await this.addPathOnce(f,!1,helper(),p)}watchRootParent(e,t){if(!this.fsw.options.backendCapabilities.perDirectory||!w)return;let n=u.dirname(e);if(u.resolve(n)===u.resolve(e))return;let r=u.normalize(u.toNamespacedPath(u.resolve(n))).toLowerCase(),a=u.basename(e).toLowerCase(),o=this.fsw.lifecycle.generation,s=!0,matchesRoot=e=>{if(e===null)return!0;let t=u.isAbsolute(e)?u.resolve(e):u.resolve(n,e);return u.normalize(u.toNamespacedPath(u.dirname(t))).toLowerCase()===r&&u.basename(t).toLowerCase()===a},isActive=()=>s&&this.fsw.lifecycle.isActive(o)&&this.isHelperActive(t,e),publish=r=>{r.kind===`native`&&matchesRoot(r.relativePath)&&isActive()&&this.reconcileBackendTrigger(e,!1,r,async()=>{let r;try{r=await i(e)}catch(t){isMissingError(t)?this.fsw.removePath(n,u.basename(e),!0):this.reportError(t);return}isActive()&&(r.isDirectory()?await this.readDirectory(e,!1,t,void 0,e,0):(this.fsw.removePath(n,u.basename(e),!0),await this.addPathOnce(e,!1,t,0)))},isActive)},c=setFsWatchListener(n,u.resolve(n),{persistent:this.fsw.options.persistent},{publish,errHandler:this.reportError,rawEmitter:(e,t,n)=>{matchesRoot(t)&&this.fsw.emitRaw(e,t,n)}},this.fsw.lifecycle.abortController.signal);if(c)return()=>{if(s)return s=!1,c.close()}}async watchRecursiveDirectory(e,t,n,r){let a=this.fsw,o=a.lifecycle.generation,s=logicalPathKey(e),c=new ReplayBuffer(G),l=[],d=`scanning`,f,p=!1,m,h,scopeActive=(t=e)=>a.lifecycle.isActive(o)&&a.isPathGenerationActive(t,r.pathGeneration),acceptsTrigger=(t=e)=>d!==`recovering`&&d!==`closed`&&scopeActive(t),establishFallback=async t=>{if(!scopeActive())return;r.recursiveRoot=void 0,r.recursiveDisabled=!0;let o;try{o=await i(e)}catch(n){isMissingError(n)?a.removePath(u.dirname(e),u.basename(e),!0):this.reportError(n),this.reportError(t);return}let s=await this.handleDirectory(e,o,!1,n,void 0,r);scopeActive()?(s&&l.push(s),await this.subscribeTrackedDirectories(e,r,n),this.reportError(t)):s&&await s()},handleFailure=t=>{if(!acceptsTrigger())return;let n=d!==`live`;d=`recovering`,a.tree.recursiveRoots.delete(s),f=t,p=!0,n||(m=a.reconciliation.enqueue(e,()=>establishFallback(t),!1))},processTrigger=t=>{if(!acceptsTrigger())return;if(d!==`live`){c.push(t);return}let n=t.relativePath===null?e:resolveRecursiveCandidate(e,t.relativePath)??e;this.reconcileBackendTrigger(e,!0,t,()=>acceptsTrigger()?this.reconcileNativeTrigger(e,r,t):void 0,()=>acceptsTrigger(n))},g=subscribeRecursiveNative(e,a.options.persistent,{publish:processTrigger,failure:handleFailure,rawEmitter:(...e)=>a.emitRaw(...e)},a.lifecycle.abortController.signal);if(g.kind===`unsupported`)return!1;if(g.kind===`failed`)throw g.error;h=g.subscription,a.tree.recursiveRoots.add(s),r.recursiveRoot=e;let close=async()=>{d!==`closed`&&(d=`closed`,a.tree.recursiveRoots.delete(s),c.clear(),await h?.close(),m&&await Promise.allSettled([m]),await Promise.allSettled(l.map(e=>e())))};try{if(await this.scanRecursiveTree(e,t,r,n),!p){d=`replaying`;let t=0;for(;acceptsTrigger();){if(c.overflowed){c.clear(),t=0;let n={kind:`native`,resource:h.resource,rawEvent:W.CHANGE,relativePath:null,sequence:2**53-1,observedAt:backendNow()};await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,r,n),()=>acceptsTrigger(),!1);continue}if(t>=c.entries.length)break;let n=c.entries[t++];if(n.rawEvent===`rename`&&n.relativePath!==null){let t=resolveRecursiveCandidate(e,n.relativePath);t&&t!==e&&a.tree.getDirectory(u.dirname(t)).has(u.basename(t))&&a.tree.markInitialCreate(t)}await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,r,n),()=>acceptsTrigger(),!1)}d!==`recovering`&&(d=`live`)}p&&(c.clear(),await establishFallback(f)),c.clear(),a.tree.clearInitialCreates(e)}catch(e){throw await close(),e}if(!scopeActive())await close();else return close}async subscribeTrackedDirectories(e,t,n){let r=this.fsw,i=u.resolve(e),needsSubscription=e=>{let n=logicalPathKey(e);return this.isHelperActive(t,e)&&!r.lifecycle.closers.has(n)&&!r.tree.symlinkPaths.has(n)&&(r.tree.peekDirectory(u.dirname(e))?.has(u.basename(e))??!1)},a=[...r.tree.watched.values()].filter(e=>isStrictlyInside(i,e.path)).map(t=>u.join(e,u.relative(i,t.path))).filter(needsSubscription).sort((e,t)=>e.length-t.length),o=0,subscribeNext=async()=>{for(;o<a.length;){let r=a[o++];needsSubscription(r)&&await this.addPathOnce(r,!1,t,n+this.candidateDepth(e,r))}},s=Math.min(16,a.length);await Promise.all(Array.from({length:s},subscribeNext))}async handleDirectory(e,t,n,r,a,o){if(!this.isHelperActive(o,e))return;if(a)this.fsw.tree.getDirectory(e);else{let r=this.fsw.tree.getDirectory(u.dirname(e)),i=r.has(u.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&this.fsw.emitEvent(W.ADD_DIR,e,t),r.add(u.basename(e)),this.fsw.tree.getDirectory(e),this.fsw.tree.recordObserved(e,t,i?void 0:`add`,o.observationTrigger,n&&!!o.recursiveRoot,!0)}let closer,s=this.fsw.options.depth;if(s==null||r<=s){if(this.fsw.options.backendCapabilities.recursive&&r===0&&!a&&!o.recursiveRoot&&!o.recursiveDisabled){let t=await this.watchRecursiveDirectory(e,n,r,o);if(t!==!1)return t}if(o.recursiveRoot){a||await this.scanRecursiveTree(e,n,o,r);return}let s=new ReplayBuffer(G),c=/* @__PURE__ */ new Set,d=!a,f=!0,p=T&&!a,m=a?u.join(e,a):void 0,rewatchTarget=()=>{m&&f&&this.isHelperActive(o,m)&&this.fsw.rewatchMissingPath(m)},removeObserved=e=>{a?(this.fsw.tree.getDirectory(e).has(a)&&this.fsw.removePath(e,a),rewatchTarget()):this.fsw.removePath(u.dirname(e),u.basename(e),!0)},observeDirectory=async(t,n,s)=>{if(f&&this.isHelperActive(o,t)){if(this.fsw.options.backendCapabilities.polling&&!n)removeObserved(t);else{if(s.kind===`native`){let e;try{let n=await i(t);e=n.isSymbolicLink()&&this.fsw.options.followSymlinks?await l(t):n}catch(e){isMissingError(e)?removeObserved(t):this.reportError(e);return}if(!e.isDirectory()){removeObserved(t),a||await this.addPathOnce(t,!1,o,r);return}}await this.readDirectory(t,!1,o,a,e,r)}}},reconcile=(t,n,i)=>{if(f&&this.isHelperActive(o,t)){if(d)s.push({path:t,stats:n,trigger:i});else return i.kind===`native`&&!a?p?(p=!1,(async()=>{await this.reconcileNativeTrigger(e,o,i,t,r),await observeDirectory(e,void 0,i)})()):this.reconcileNativeTrigger(e,o,i,t,r):i.kind===`native`&&a&&(t===e||(w?u.basename(t).toLowerCase()===a.toLowerCase():u.basename(t)===a))?this.reconcileNativeTrigger(e,o,i,m,r,{onRootMissing:rewatchTarget}):observeDirectory(e,n,i)}},h=r===0&&!a?this.watchRootParent(e,o):void 0;if(closer=this.subscribePath(e,reconcile,t.isDirectory()?t:void 0,!0,a?u.join(e,a):e),a&&m&&closer){let t=recoveryTrigger(u.resolve(e));await this.fsw.reconciliation.enqueue(m,async()=>{this.fsw.tree.getDirectory(e).has(a)||await reconcile(m,void 0,t)},m)}if(!a){await this.readDirectory(e,n,o,a,e,r);let t=0;for(;!this.fsw.closed;){if(s.overflow){let n=s.overflow;s.clear(),t=0,await observeDirectory(e,n.stats,n.trigger);continue}if(t>=s.entries.length)break;let n=s.entries[t++];n.trigger.kind===`native`&&n.trigger.rawEvent===`rename`&&n.path!==e&&this.fsw.tree.getDirectory(u.dirname(n.path)).has(u.basename(n.path))&&(this.fsw.tree.markInitialCreate(n.path),c.add(n.path)),await this.reconcileBackendTrigger(e,!0,n.trigger,()=>n.trigger.kind===`native`&&!a?this.reconcileNativeTrigger(e,o,n.trigger,n.path,r):observeDirectory(e,n.stats,n.trigger),()=>f&&this.isHelperActive(o,n.path),!1)}s.clear(),c.forEach(e=>this.fsw.tree.clearInitialCreate(e)),d=!1}if(!this.isHelperActive(o,e)){f=!1,closer&&await closer(),h&&await h();return}if(closer||h){let e=[closer,h].filter(e=>e!==void 0);closer=async()=>{f&&(f=!1,s.clear(),await Promise.allSettled(e.map(e=>e())))}}}return closer}async addRoot(e,t,n,r){let i=e,a=r,o=this.fsw.lifecycle.generation;for(;this.fsw.lifecycle.isActive(o);){if(await this.addPathOnce(i,t,void 0,0,a,n)===`complete`)return;let e=u.dirname(i);if(e===i)return;a=u.basename(i),i=e}}async addPathOnce(e,t,n,r,a,o){if(this.fsw.isIgnored(e)||this.fsw.closed)return`complete`;let d=n?n.fork(e):this.fsw.createHelper(e);if(!n&&o!==void 0&&(d.pathGeneration=o),!this.isHelperActive(d))return`complete`;try{let o=await i(d.watchPath);if(!this.isHelperActive(d)||this.fsw.isIgnored(d.watchPath,o))return`complete`;let f=this.fsw.options.followSymlinks,p=o.isSymbolicLink(),m=p&&f?await l(d.watchPath):o,h=p&&f?await c(e):void 0,closer;if(m.isDirectory()){let n=logicalPathKey(e),i=f?await c(e):e,o=h??e,s=logicalPathKey(i);if(!this.isHelperActive(d))return`complete`;if(p&&d.realpathAncestry.has(s))return this.fsw.tree.getDirectory(u.dirname(d.watchPath)).add(u.basename(d.watchPath)),this.fsw.tree.getDirectory(d.watchPath),this.fsw.tree.symlinkPaths.set(n,o),this.fsw.tree.recordObserved(d.watchPath,m,`add`,d.observationTrigger,t&&!!d.recursiveRoot),t&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(W.ADD_DIR,d.watchPath,m),`complete`;if(d.realpathAncestry.add(s),d.recursiveRoot&&p&&(d.recursiveRoot=void 0),p&&(d.recursiveDisabled=!0),closer=await this.handleDirectory(d.watchPath,m,t,r,a,d),!this.isHelperActive(d))return closer&&await closer(),`complete`;if(a&&!closer)return`watch-parent`;p&&this.fsw.tree.symlinkPaths.set(n,o)}else if(p&&!f){let i=await s(e),a=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!n,o=this.handleFile(d.watchPath,m,t,!d.recursiveRoot,d.observationTrigger,t&&!!d.recursiveRoot,a);if(d.recursiveRoot)return this.fsw.tree.symlinkPaths.set(logicalPathKey(e),i),`complete`;let c=u.dirname(d.watchPath),f=await l(c),p=this.fsw.createHelper(c);p.pathGeneration=d.pathGeneration;let h=await this.handleDirectory(c,f,t,r,u.basename(d.watchPath),p),g=this.watchSymlinkDeletion(d.watchPath);if(!this.isHelperActive(d))return o&&await o(),h&&await h(),g&&g(),`complete`;closer=async()=>{await Promise.allSettled([o,h,g].filter(e=>e!==void 0).map(e=>e()))},this.fsw.tree.symlinkPaths.set(logicalPathKey(e),i)}else{h&&this.fsw.tree.symlinkPaths.set(logicalPathKey(e),h);let i=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!n,a=this.handleFile(d.watchPath,m,t,!d.recursiveRoot,d.observationTrigger,t&&!!d.recursiveRoot,i),o=h??(i?d.watchPath:void 0),s=o?this.subscribeMappedFile(d.watchPath,o,d,r,T&&m.isFile()):void 0,c;if(i&&h){let e=u.dirname(d.watchPath),n=await l(e),i=this.fsw.createHelper(e);i.pathGeneration=d.pathGeneration,c=await this.handleDirectory(e,n,t,r,u.basename(d.watchPath),i)}let f=[a,s,c].filter(e=>e!==void 0);closer=f.length===0?void 0:async()=>{await Promise.allSettled(f.map(e=>e()))}}return this.isHelperActive(d)?(closer&&this.fsw.addPathCloser(a?u.join(e,a):e,closer),`complete`):(closer&&await closer(),`complete`)}catch(e){return this.isHelperActive(d)?(this.fsw.handleError(e),`watch-parent`):`complete`}}};const J=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Y=/* @__PURE__ */ new Set([`auto`,`native`,`native-recursive`,`polling`]),X=Object.freeze({stabilityThreshold:2e3,pollInterval:100});function*ancestorKeys(e){let t=u.resolve(e);for(let e=u.dirname(t);e!==t;e=u.dirname(e))yield logicalPathKey(e),t=e}function arrify(e){return Array.isArray(e)?e:[e]}function unifyPaths(e){let t=arrify(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(normalizePath)}function getAbsolutePath(e,t){return u.isAbsolute(e)?e:u.join(t,e)}function validatePositiveFinite(e,t){if(!Number.isFinite(t)||t<=0)throw TypeError(`${e} must be a finite number greater than zero`)}function validateNonNegativeFinite(e,t){if(!Number.isFinite(t)||t<0)throw TypeError(`${e} must be a finite non-negative number`)}function validateOptions(e){if(validatePositiveFinite(`pollingInterval`,e.pollingInterval),validatePositiveFinite(`pollingBinaryInterval`,e.pollingBinaryInterval),typeof e.atomic==`number`)validateNonNegativeFinite(`atomic`,e.atomic);else if(typeof e.atomic!=`boolean`)throw TypeError(`atomic must be a boolean or finite non-negative number`);if(e.depth!==void 0&&(!Number.isSafeInteger(e.depth)||e.depth<0))throw TypeError(`depth must be a non-negative safe integer`);e.awaitWriteFinish&&(validatePositiveFinite(`awaitWriteFinish.pollInterval`,e.awaitWriteFinish.pollInterval),validateNonNegativeFinite(`awaitWriteFinish.stabilityThreshold`,e.awaitWriteFinish.stabilityThreshold))}var FSWatcher=class extends t{options;lifecycle;tree;reconciliation;events;scheduler;handler;readyEmitted;streams;get closed(){return this.lifecycle!==void 0&&this.lifecycle.state!==`OPEN`}#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e={},t=O){if(super(),e.backend!==void 0&&!Y.has(e.backend))throw TypeError(`backend must be auto, native, native-recursive, or polling`);this.#e=/* @__PURE__ */ new Set,this.streams=/* @__PURE__ */ new Set,this.#t=/* @__PURE__ */ new Map,this.#n=0,this.#r=/* @__PURE__ */ new Map,this.#o=/* @__PURE__ */ new Map,this.#s=/* @__PURE__ */ new Set,this.#c=/* @__PURE__ */ new Map,this.readyEmitted=!1,this.#u=!1,this.#d=!1,this.scheduler=t;let n=e.awaitWriteFinish,r={...e,persistent:e.persistent??!0,ignoreInitial:e.ignoreInitial??!1,ignorePermissionErrors:e.ignorePermissionErrors??!1,pollingInterval:e.pollingInterval??e.interval??100,pollingBinaryInterval:e.pollingBinaryInterval??e.binaryInterval??300,interval:100,binaryInterval:300,followSymlinks:e.followSymlinks??!0,backend:e.backend??`auto`,usePolling:e.usePolling??!1,depth:e.depth===1/0?void 0:e.depth,backendStrategy:`native-per-directory`,backendCapabilities:void 0,atomic:e.atomic??!0,ignored:Object.freeze(e.ignored?arrify(e.ignored).map(cloneOwnedMatcher):[]),awaitWriteFinish:n===!0?X:typeof n==`object`&&Object.freeze({...X,...n})};(e.usePolling===!0||D)&&(r.backend=`polling`);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e!==`false`&&e!==`0`&&(e===`true`||e===`1`||e)?r.backend=`polling`:r.backend===`polling`&&(r.backend=`auto`)}let a=process.env.CHOKIDAR_INTERVAL;a!==void 0&&(r.pollingInterval=Number(a)),r.interval=r.pollingInterval,r.binaryInterval=r.pollingBinaryInterval,r.usePolling=r.backend===`polling`,r.backendCapabilities=selectBackend(r),r.backendStrategy=r.backendCapabilities.kind,e.atomic===void 0&&(r.atomic=!r.usePolling),validateOptions(r),this.options=r,this.lifecycle=new LifecycleScope(()=>{this.#u&&this.queueReady()},e=>{this.closed||this.handleError(e instanceof Error?e:Error(String(e)))}),this.tree=new TreeState(()=>!this.options.backendCapabilities.polling),this.reconciliation=new ReconciliationQueue(this.lifecycle),this.events=new EventPolicy({options:this.options,scheduler:this.scheduler,lifecycle:this.lifecycle,isClosed:()=>this.closed,capturePathGeneration:()=>this.capturePathGeneration(),isPathGenerationActive:(e,t)=>this.isPathGenerationActive(e,t),isReady:()=>this.readyEmitted,remove:(e,t)=>this.removePath(e,t),handleError:e=>this.handleError(e),publish:(e,t)=>this.emitWithAll(e,t)}),this.handler=new ObservationEngine(this),Object.freeze(r)}addIgnoredPath(e){if(e=this.ignoredMatcher(e),isMatcherObject(e)){for(let t of this.#e)if(isMatcherObject(t)&&t.path===e.path&&t.recursive===e.recursive)return}this.#e.add(e),this.#l=void 0}removeIgnoredPath(e){if(e=this.ignoredMatcher(e),this.#e.delete(e),typeof e==`string`)for(let t of this.#e)isMatcherObject(t)&&t.path===e&&this.#e.delete(t);this.#l=void 0}ignoredMatcher(e){return typeof e==`string`?logicalPathKey(e):isMatcherObject(e)?{path:logicalPathKey(e.path),recursive:e.recursive}:e}capturePathGeneration(){return this.#n}invalidatePath(e){this.#r.set(logicalPathKey(e),++this.#n)}isPathGenerationActive(e,t){if(this.lifecycle.state!==`OPEN`)return!1;if(this.#r.size===0)return!0;let n=logicalPathKey(e);for(let[e,r]of this.#r)if(!(r<=t)&&isSameOrInside(e,n))return!1;return!0}queueReady(){this.closed||this.readyEmitted||(this.#u=!0,this.lifecycle.tasks.size>0||this.#d||(this.#d=!0,process.nextTick(()=>{this.#d=!1,this.closed||this.readyEmitted||this.lifecycle.tasks.size>0||(this.#u=!1,this.readyEmitted=!0,this.emit(k.READY))})))}add(e){if(this.closed)throw Error(`Cannot add paths after FSWatcher.close() has been called`);let{cwd:t}=this.options,n=unifyPaths(e);t&&(n=n.map(e=>getAbsolutePath(e,t))),n.forEach(e=>{this.removeIgnoredPath(e),this.addRootAncestors(e)}),this.readyEmitted||(this.#u=!0);let r=Promise.all(n.map(async e=>{let t=logicalPathKey(e);if(this.lifecycle.closers.has(t)||this.#t.has(t))return;let n=Symbol(t),r=this.capturePathGeneration();this.#t.set(t,n);try{await this.handler.addRoot(e,!0,r)}finally{this.#t.get(t)===n&&this.#t.delete(t)}}));return this.lifecycle.track(r),this.readyEmitted||this.queueReady(),this}unwatch(e){if(this.closed)return this;let t=unifyPaths(e),{cwd:n}=this.options;return n&&(t=t.map(e=>getAbsolutePath(e,n))),t.forEach(e=>{let t=logicalPathKey(e),n=this.tree.watched.has(t);this.invalidatePath(t),this.removeRootAncestors(t),this.#t.delete(t),this.events.cancelPath(t),this.closePath(t,n),this.addIgnoredPath(t),n&&this.addIgnoredPath({path:t,recursive:!0}),this.#l=void 0}),this}close(){if(this.#i)return this.#i;let e=this.lifecycle.beginClose();return this.removeAllListeners(),this.events.close(),this.#t.clear(),this.#s.clear(),this.#c.clear(),this.streams.forEach(e=>e.destroy()),this.#a=void 0,this.#l=void 0,this.readyEmitted=!1,this.tree.dispose(),this.#r.clear(),this.streams.clear(),this.reconciliation.clear(),this.#o.clear(),this.#i=(async()=>{let t=await Promise.allSettled(e);await this.lifecycle.drain(),this.lifecycle.finishClose();let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason})(),this.#i}getWatched(){let e=Object.create(null);return this.tree.watched.forEach(t=>{let n=t.path,r=(this.options.cwd?u.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitRaw(...e){this.closed||this.emit(k.RAW,...e)}emitWithAll(e,t){this.emit(e,...t),e!==k.ERROR&&this.emit(k.ALL,e,...t)}async emitEvent(e,t,n){this.closed||await this.events.emit(e,t,n)}handleError(e){if(this.closed)return;let t=e instanceof Error?e:Error(String(e));isMissingError(t)||this.options.ignorePermissionErrors&&isPermissionError(t)||this.emit(k.ERROR,t)}isIgnored(e,t){if(this.options.atomic&&J.test(e))return!0;if(!this.#a){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(t=>normalizeMatcher(t,e)),n=compileMatchers(t),r=t.filter(e=>typeof e==`string`||isMatcherObject(e)),i=compileMatchers(r);this.#a=(e,t)=>{if(n(e,t))return!0;if(w||r.length===0)return!1;let a=u.resolve(e),o;if(t?.isDirectory())o=this.realDirectory(a);else{let e=this.realDirectory(u.dirname(a));e!==void 0&&(o=u.join(e,u.basename(a)))}return o!==void 0&&o!==a&&i(o,t)}}return this.#a(e,t)&&!this.isRootAncestor(e,t)?!0:this.#e.size!==0&&(this.#l||=compileMatchers([...this.#e]),this.#l(logicalPathKey(e),t))}isRootAncestor(e,t){return!t?.isFile()&&this.#c.has(logicalPathKey(e))}addRootAncestors(e){let t=logicalPathKey(e);if(!this.#s.has(t)){this.#s.add(t);for(let t of ancestorKeys(e))this.#c.set(t,(this.#c.get(t)??0)+1)}}removeRootAncestors(e){if(this.#s.delete(logicalPathKey(e)))for(let t of ancestorKeys(e)){let e=(this.#c.get(t)??1)-1;e>0?this.#c.set(t,e):this.#c.delete(t)}}realDirectory(e){let t=logicalPathKey(e);if(this.#o.has(t))return this.#o.get(t);let r;try{r=n.native(e)}catch{}return this.#o.set(t,r),r}isUnwatched(e){return this.#e.size!==0&&(this.#l||=compileMatchers([...this.#e]),this.#l(logicalPathKey(e)))}createHelper(e){return new N(e,this.options.followSymlinks,{capturePathGeneration:()=>this.capturePathGeneration(),isntIgnored:(e,t)=>!this.isIgnored(e,t)})}removeTreeItem(e,t){let n=this.tree.peekDirectory(e);if(!n?.remove(t))return;let r=n.path,i=this.lifecycle.generation;this.lifecycle.track((async()=>{try{await o(r)}catch(e){isMissingError(e)&&this.lifecycle.isActive(i)&&this.removePath(u.dirname(r),u.basename(r))}})())}removePath(e,t,n){let r=u.join(e,t),i=logicalPathKey(r);n??=this.tree.watched.has(i);let a=this.tree.peekDirectory(r)?.getChildren()??[];for(let e of a)this.removePath(r,e);let o=this.tree.peekDirectory(e)?.has(t)??!1,s=this.lifecycle.closers.has(i);this.removeTreeItem(e,t),this.tree.symlinkPaths.has(i)&&this.tree.symlinkPaths.delete(i);let c=this.events.pendingWrites.get(i),l=!1;this.options.awaitWriteFinish&&c&&(l=c.cancelWait()===k.ADD),this.tree.watched.delete(i),this.tree.observed.delete(i);let d=n?k.UNLINK_DIR:k.UNLINK;o&&!l&&!this.isIgnored(r)&&this.emitEvent(d,r),this.closePath(r),(o||s)&&this.#s.has(i)&&this.rewatchMissingPath(r)}rewatchMissingPath(e){this.closed||this.isUnwatched(e)||(this.closePath(e),this.lifecycle.track(this.handler.addRoot(e,!1,this.capturePathGeneration())))}closePath(e,t=!1){let n=logicalPathKey(e),contains=e=>e===n?!0:t?isStrictlyInside(n,e):!1;if([...this.lifecycle.closers.keys()].filter(contains).forEach(e=>this.closeFile(e)),this.#o.delete(n)||t){let e=n.endsWith(`/`)?n:`${n}/`;for(let t of this.#o.keys())t.startsWith(e)&&this.#o.delete(t)}if(t){for(let[e,t]of this.tree.watched)contains(e)&&(t.dispose(),this.tree.watched.delete(e));for(let e of this.tree.observed.keys())contains(e)&&this.tree.observed.delete(e);for(let e of this.tree.symlinkPaths.keys())contains(e)&&this.tree.symlinkPaths.delete(e);this.events.cancelWhere(contains),this.reconciliation.forgetPending((e,t)=>contains(e)||contains(t));for(let e of this.#t.keys())contains(e)&&this.#t.delete(e)}let r=u.dirname(n);this.removeTreeItem(r,u.basename(n))}closeFile(e){let t=logicalPathKey(e),n=this.lifecycle.takeClosers(t);n.length!==0&&n.forEach(e=>{try{let t=e();t instanceof Promise&&this.lifecycle.track(t)}catch(e){this.lifecycle.track(Promise.reject(e))}})}addPathCloser(e,t){if(!t)return;if(this.closed||this.isUnwatched(e)){try{let e=t();e instanceof Promise&&this.lifecycle.track(e)}catch(e){this.lifecycle.track(Promise.reject(e))}return}let n=logicalPathKey(e);this.lifecycle.addCloser(n,t)}createScanStream(e,t){if(this.closed)return;let n=readdirp(e,{type:k.ALL,alwaysStat:!0,lstat:!0,depth:0,...t});this.streams.add(n);let finalize=()=>this.streams.delete(n);return n.once(`close`,finalize),n.once(`end`,finalize),n.once(k.ERROR,finalize),n}};function watch(e,t={}){let n=new FSWatcher(t);return n.add(e),n}export{watch};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./console-CIiXr7ge.mjs";import{c as n,l as r,r as i}from"./tracker-B3Fqx94J.mjs";import{a,r as o,s}from"./store-DjPdOKqg.mjs";import{D as c,E as l,a as u,c as d,f}from"./fs-CPnWm9CR.mjs";import{t as p}from"./format-DRqD29u-.mjs";import{i as m,n as h}from"./logger-9C6B9Na8.mjs";import{r as g}from"./dry-run-BkdMYSIx.mjs";import{n as _,t as v}from"./output-BxR2v-jn.mjs";import{t as y}from"./timer-DqgB175x.mjs";import{readdir as b}from"node:fs/promises";import{join as x}from"node:path";const S=3e5;var C=e({meta:{name:`clean`,description:`Remove unreferenced store entries and stale consumer registrations`},args:{yes:{type:`boolean`,alias:`y`,description:`Skip confirmation prompts`,default:!1}},async run({args:e}){_();let C=new y;t.start(`Checking consumer registrations...`);let{removedConsumers:w,removedPackages:T}=await i();w>0&&t.success(`Removed ${w} stale consumer registration(s) across ${T} package(s)`);let E=await r(),D=/* @__PURE__ */ new Set,O=[...new Set(Object.values(E).flat())],k=await Promise.all(O.map(async e=>{let{state:t,reliable:r}=await n(e);return{path:e,state:t,reliable:r}}));for(let{state:e,reliable:t}of k)if(t)for(let[t,n]of Object.entries(e.links))D.add(`${t}@${n.version}`);let A=/* @__PURE__ */ new Set,j=k.filter(e=>!e.reliable);if(j.length>0){t.warn(`${j.length} consumer(s) have corrupt state; their store entries will be preserved`);let e=new Set(j.map(e=>c(e.path)));for(let[t,n]of Object.entries(E))n.some(t=>e.has(t))&&A.add(t);m(`[clean] Protected packages (corrupt state): ${[...A].join(`, `)}`)}m(`[clean] Referenced entries: ${[...D].join(`, `)||`(none)`}`);let M=await o(),N=[];for(let e of M){let t=`${e.name}@${e.version}`;if(!D.has(t)){if(A.has(e.name)){m(`[clean] Preserving ${t} (consumer state unreadable)`);continue}let n=Date.now()-new Date(e.meta.publishedAt).getTime();if(n<S){m(`[clean] Skipping recently published entry: ${t} (${Math.round(n/1e3)}s old)`);continue}N.push(e)}}let P=[],F=l();if(await d(F)){let e=await b(F,{withFileTypes:!0});for(let t of e){let e=t.isDirectory()?a(t.name):null;if(e===null)continue;let n=Date.now()-e;n<S?m(`[clean] Skipping recent temp directory: ${t.name} (${Math.round(n/1e3)}s old)`):P.push(t.name)}}if(N.length+P.length>0&&!e.yes){let e=[];N.length>0&&e.push(`${N.length} unreferenced store entry(ies)`),P.length>0&&e.push(`${P.length} orphaned temp directory(ies)`);let n=await t.prompt(`Remove ${e.join(` and `)}?`,{type:`confirm`});if(!n||typeof n==`symbol`){t.info(`Cancelled`);return}}let I=0,L=await Promise.all(N.map(e=>u(e.packageDir))),R=await Promise.all(P.map(e=>u(x(F,e)))),z=0;for(let[e,t]of N.entries())m(`[clean] Removing unreferenced store entry: ${t.name}@${t.version}`),await s(t.name,t.version),I+=L[e]??0,z++;z>0&&t.success(`Removed ${z} unreferenced store entry(ies)`);let B=0;for(let[e,t]of P.entries())m(`[clean] Removing orphaned directory: ${t}`),await f(x(F,t)),I+=R[e]??0,B++;B>0&&t.success(`Removed ${B} orphaned temp directory(ies)`),w===0&&z===0&&B===0&&t.info(`Store is clean; no stale entries or registrations found`);let V=I>0?` (reclaimed ${p(I)})`:``;t.info(`Clean complete in ${C.elapsed()}${V}`),v({removedConsumers:w,removedPackages:T,removedEntries:z,removedOrphans:B,reclaimedBytes:I,elapsed:C.elapsedMs()}),h()&&g()}});export{C as default};
package/dist/cli.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import {createRequire}from'node:module';import {a as a$4}from'./chunk-NGPAGRK4.mjs';import {a as a$3}from'./chunk-SPHWZS5P.mjs';import {a as a$1,b as b$1}from'./chunk-OQDZJP55.mjs';import {c,a as a$2}from'./chunk-L7O2RSTN.mjs';import {availableParallelism}from'os';globalThis.require=createRequire(import.meta.url);
3
- var a=c(a$1(),1);var _=`
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e,t}from"./dist-CFkjiIqD.mjs";import{t as n}from"./logger-9C6B9Na8.mjs";import{n as r,t as i}from"./console-CIiXr7ge.mjs";import{availableParallelism as a}from"node:os";function showBanner(){console.log(r.yellow(`
4
4
  _ __
5
5
  | |/ /_ __ __ _ _ __ _ __
6
6
  | ' /| '_ \\ / _\` | '__| '__|
7
7
  | . \\| | | | (_| | | | |
8
8
  |_|\\_\\_| |_|\\__,_|_| |_|
9
- `;function n(){console.log(a.default.yellow(_)),console.log(a.default.cyan(" Local npm package development without symlinks")),console.log(a.default.dim(` Copies built files into consumer node_modules with incremental sync
10
- `));}a$2(n,"showBanner");process.env.UV_THREADPOOL_SIZE??=String(Math.max(availableParallelism(),8));a$3();var l=process.argv.slice(2),b=["init","publish","add","use","remove","push","dev","restore","list","status","update","clean","gc","doctor","explain","migrate","reset","rollback","check"],u=l.some(e=>!e.startsWith("-")&&b.includes(e)),v=l.includes("--help")||l.includes("-h")||l.includes("--version");if(!u&&!v&&process.stdin.isTTY){n();let e=await g();e&&process.argv.splice(2,0,e);}else u||n();async function g(){try{let{readConsumerStateSafe:p}=await import('./tracker-QAKEXYUJ.mjs'),{resolve:c}=await import('path'),{state:d}=await p(c(".")),i=Object.keys(d.links).length;i>0&&b$1.info(`${i} package(s) linked in this project`);}catch{}return await b$1.prompt("What would you like to do?",{type:"select",options:[{label:"init - Set up knarr in this project",value:"init"},{label:"publish - Publish package to the knarr store",value:"publish"},{label:"add - Link a package from the store",value:"add"},{label:"use - Link a local package path",value:"use"},{label:"push - Publish and push to all consumers",value:"push"},{label:"dev - Watch, rebuild, and push continuously",value:"dev"},{label:"list - Show linked packages",value:"list"},{label:"status - Show project status",value:"status"},{label:"explain - Explain linked package state",value:"explain"},{label:"help - Show help",value:"--help"}]})||null}a$2(g,"showInteractiveMenu");var k={meta:{name:"knarr",version:"0.1.3",description:"Local npm package development - copies built files into consumer node_modules"},args:{verbose:{type:"boolean",alias:"v",description:"Enable verbose debug logging",default:false},"dry-run":{type:"boolean",description:"Preview changes without writing files",default:false},json:{type:"boolean",description:"Output machine-readable JSON",default:false}},subCommands:{init:a$2(()=>import('./init-SNG5LBZK.mjs').then(e=>e.default),"init"),publish:a$2(()=>import('./publish-2IH7IQV4.mjs').then(e=>e.default),"publish"),add:a$2(()=>import('./add-LQ6WMCGD.mjs').then(e=>e.default),"add"),use:a$2(()=>import('./use-4Z5KXRVR.mjs').then(e=>e.default),"use"),remove:a$2(()=>import('./remove-MVQOIN2I.mjs').then(e=>e.default),"remove"),push:a$2(()=>import('./push-W3TM2QYK.mjs').then(e=>e.default),"push"),dev:a$2(()=>import('./dev-WU5KB5PJ.mjs').then(e=>e.default),"dev"),restore:a$2(()=>import('./restore-TWOOF2BN.mjs').then(e=>e.default),"restore"),list:a$2(()=>import('./list-4PTHMIQ4.mjs').then(e=>e.default),"list"),status:a$2(()=>import('./status-3ZXM3CRH.mjs').then(e=>e.default),"status"),explain:a$2(()=>import('./explain-LZLNIMVZ.mjs').then(e=>e.default),"explain"),update:a$2(()=>import('./update-TGGCUOOO.mjs').then(e=>e.default),"update"),clean:a$2(()=>import('./clean-EJIYYQZM.mjs').then(e=>e.default),"clean"),gc:a$2(()=>import('./clean-EJIYYQZM.mjs').then(e=>e.default),"gc"),doctor:a$2(()=>import('./doctor-W2G34POC.mjs').then(e=>e.default),"doctor"),migrate:a$2(()=>import('./migrate-USY26Y5R.mjs').then(e=>e.default),"migrate"),reset:a$2(()=>import('./reset-BTOJ54MJ.mjs').then(e=>e.default),"reset"),rollback:a$2(()=>import('./rollback-CFYSE5YG.mjs').then(e=>e.default),"rollback"),check:a$2(()=>import('./check-7CJHAF6Y.mjs').then(e=>e.default),"check")}};a$4(k);
9
+ `)),console.log(r.cyan(` Local npm package development without symlinks`)),console.log(r.dim(` Copies built files into consumer node_modules with incremental sync
10
+ `))}process.env.UV_THREADPOOL_SIZE??=String(Math.max(a(),8)),n();const o=process.argv.slice(2),s=[`init`,`publish`,`add`,`use`,`remove`,`push`,`dev`,`restore`,`list`,`status`,`update`,`clean`,`gc`,`doctor`,`explain`,`migrate`,`reset`,`rollback`,`check`],c=o.some(e=>!e.startsWith(`-`)&&s.includes(e)),l=o.includes(`--help`)||o.includes(`-h`)||o.includes(`--version`);if(!c&&!l&&process.stdin.isTTY){showBanner();let e=await showInteractiveMenu();e&&process.argv.splice(2,0,e)}else c||showBanner();async function showInteractiveMenu(){try{let{readConsumerStateSafe:e}=await import(`./tracker-89eW0ArT.mjs`),{resolve:t}=await import(`node:path`),{state:n}=await e(t(`.`)),r=Object.keys(n.links).length;r>0&&i.info(`${r} package(s) linked in this project`)}catch{}return await i.prompt(`What would you like to do?`,{type:`select`,options:[{label:`init - Set up knarr in this project`,value:`init`},{label:`publish - Publish package to the knarr store`,value:`publish`},{label:`add - Link a package from the store`,value:`add`},{label:`use - Link a local package path`,value:`use`},{label:`push - Publish and push to all consumers`,value:`push`},{label:`dev - Watch, rebuild, and push continuously`,value:`dev`},{label:`list - Show linked packages`,value:`list`},{label:`status - Show project status`,value:`status`},{label:`explain - Explain linked package state`,value:`explain`},{label:`help - Show help`,value:`--help`}]})||null}const u=t({meta:{name:`knarr`,version:`0.3.0`,description:`Local npm package development - copies built files into consumer node_modules`},args:{verbose:{type:`boolean`,alias:`v`,description:`Enable verbose debug logging`,default:!1},"dry-run":{type:`boolean`,description:`Preview changes without writing files`,default:!1},json:{type:`boolean`,description:`Output machine-readable JSON`,default:!1}},subCommands:{init:()=>import(`./init-TN84d5jM.mjs`).then(e=>e.default),publish:()=>import(`./publish-C7ZUvHkE.mjs`).then(e=>e.default),add:()=>import(`./add-B_xzUp5y.mjs`).then(e=>e.default),use:()=>import(`./use-CCx6J0mc.mjs`).then(e=>e.default),remove:()=>import(`./remove-DkOgVQMZ.mjs`).then(e=>e.default),push:()=>import(`./push-B5KrkILW.mjs`).then(e=>e.default),dev:()=>import(`./dev-kqgY9NjI.mjs`).then(e=>e.default),restore:()=>import(`./restore-Bx2V59SL.mjs`).then(e=>e.default),list:()=>import(`./list-9hWJjw19.mjs`).then(e=>e.default),status:()=>import(`./status-Rnvw6dG2.mjs`).then(e=>e.default),explain:()=>import(`./explain-9Y4SZHjC.mjs`).then(e=>e.default),update:()=>import(`./update-CAKFICZu.mjs`).then(e=>e.default),clean:()=>import(`./clean-CyDDqbBD.mjs`).then(e=>e.default),gc:()=>import(`./clean-CyDDqbBD.mjs`).then(e=>e.default),doctor:()=>import(`./doctor-D-S1P0UG.mjs`).then(e=>e.default),migrate:()=>import(`./migrate-Co4qcFt6.mjs`).then(e=>e.default),reset:()=>import(`./reset-ClGouUb5.mjs`).then(e=>e.default),rollback:()=>import(`./rollback-RPjHZWtG.mjs`).then(e=>e.default),check:()=>import(`./check-CbVdpTsw.mjs`).then(e=>e.default)}});e(u);export{};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e}from"./logger-9C6B9Na8.mjs";import{t}from"./fs-CPnWm9CR.mjs";import{i as n,n as r,s as i}from"./json-DbSkpxtr.mjs";import{readFile as a}from"node:fs/promises";import{join as o}from"node:path";function finiteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}async function loadKnarrConfig(t){try{let r=await a(o(t,`package.json`),`utf-8`),s=n(i(r,`package.json`),`knarr`);if(!s)return{};let c={};typeof s.buildCmd==`string`&&(c.buildCmd=s.buildCmd);let l=s.watchPatterns;Array.isArray(l)&&(c.watchPatterns=l.filter(e=>typeof e==`string`));let u=finiteNumber(s.debounce);u!==void 0&&(c.debounce=u);let d=finiteNumber(s.cooldown);d!==void 0&&(c.cooldown=d);let f=finiteNumber(s.historyLimit);return f!==void 0&&(c.historyLimit=Math.max(0,Math.floor(f))),typeof s.notify==`boolean`&&(c.notify=s.notify),e(`[config] Loaded knarr config from package.json: ${JSON.stringify(c)}`),c}catch{return{}}}async function setKnarrBuildCmdIfMissing(e,o){if(!o)return!1;let s=await a(e,`utf-8`),c=i(s,e),l=n(c,`knarr`);return l&&typeof l.buildCmd==`string`?!1:(c.knarr={...l,buildCmd:o},await t(e,JSON.stringify(c,null,r(s))+`
4
+ `),!0)}export{setKnarrBuildCmdIfMissing as n,loadKnarrConfig as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{styleText as e}from"node:util";import{createInterface as t}from"node:readline/promises";import{stdin as n,stdout as r}from"node:process";function style(t){return n=>e(t,String(n))}const i={bold:style(`bold`),dim:style(`dim`),cyan:style(`cyan`),green:style(`green`),red:style(`red`),yellow:style(`yellow`)};let a=3;async function prompt(e,a){if(!n.isTTY)return answerNonInteractive(e,a);let o=t({input:n,output:r});try{if(a.type===`confirm`){let t=a.initial===!1?`y/N`:`Y/n`,n=(await o.question(`${i.cyan(`?`)} ${e} ${i.dim(`(${t})`)} `)).trim().toLowerCase();return n===``?a.initial!==!1:n===`y`||n===`yes`}if(a.type===`text`){let t=a.default?i.dim(` (${a.default})`):``;return(await o.question(`${i.cyan(`?`)} ${e}${t} `)).trim()||a.default||``}console.log(`${i.cyan(`?`)} ${e}`);for(let[e,t]of a.options.entries())console.log(` ${i.cyan(`${e+1}.`)} ${t.label}`);let t=await o.question(`${i.dim(`Enter number:`)} `),n=a.options[parseInt(t,10)-1]??a.options[0];if(!n)throw Error(`No options to choose from for "${e}"`);return n.value}finally{o.close()}}function answerNonInteractive(e,t){if(t.type===`confirm`&&t.initial!==void 0)return console.error(`${i.cyan(`i`)} ${e} ${i.dim(`-> ${t.initial?`yes`:`no`} (no interactive terminal, using default)`)}`),t.initial;if(t.type===`text`)return t.default??``;console.error(`${i.red(`x`)} Cannot ask "${e}": no interactive terminal (stdin is not a TTY).`),console.error(`${i.cyan(`i`)} ${i.dim(`Suggestion:`)} ${t.type===`confirm`?`Re-run with --yes to confirm.`:t.nonInteractiveHint??`Pass the choice as a flag (see --help).`}`),process.exit(1)}const o={get level(){return a},set level(e){a=e},info(e,...t){a>=3&&console.log(i.cyan(`i`),e,...t)},success(e,...t){a>=3&&console.log(i.green(`OK`),e,...t)},warn(e,...t){a>=2&&console.warn(i.yellow(`!`),e,...t)},error(e,...t){a>=1&&console.error(i.red(`x`),e,...t)},start(e,...t){a>=3&&console.log(i.cyan(`...`),e,...t)},debug(e,...t){a>=4&&console.debug(i.dim(`D`),e,...t)},log(e,...t){a>=3&&console.log(e,...t)},prompt};export{i as n,o as t};