knarr 0.2.0 → 0.3.1

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 (144) hide show
  1. package/README.md +65 -106
  2. package/dist/add-CyrFHzUe.mjs +1 -0
  3. package/dist/add-flow-BjjRSNWm.mjs +3 -0
  4. package/dist/batch-push-Cee2SPW3.mjs +1 -0
  5. package/dist/build-detect-Bo1fe8OV.mjs +1 -0
  6. package/dist/bundler-detect-BaShXORS.mjs +1 -0
  7. package/dist/check-ChNlHxR5.mjs +1 -0
  8. package/dist/chokidar-DoHpObCq.mjs +1 -0
  9. package/dist/clean-oNr4nUNk.mjs +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.mjs +3 -4
  12. package/dist/config-D0TqqAAJ.mjs +2 -0
  13. package/dist/console-C8XtlRyM.mjs +1 -0
  14. package/dist/dev-vA8K5egW.mjs +1 -0
  15. package/dist/dist-jMqCJR3W.mjs +5 -0
  16. package/dist/doctor-ITFcIVoj.mjs +4 -0
  17. package/dist/dry-run-DPoN8bZo.mjs +1 -0
  18. package/dist/errors-DRugrv36.mjs +1 -0
  19. package/dist/explain-xtY13-Ex.mjs +1 -0
  20. package/dist/format-IsfSiyGV.mjs +1 -0
  21. package/dist/fs-Ce7wcxvx.mjs +1 -0
  22. package/dist/fs-DusqxRQR.mjs +1 -0
  23. package/dist/hints-BKo_2axg.mjs +1 -0
  24. package/dist/history-540r0BHF.mjs +1 -0
  25. package/dist/history-B3E1DMFO.mjs +1 -0
  26. package/dist/index.d.ts +17 -14
  27. package/dist/index.mjs +1 -3559
  28. package/dist/init-KBwXbX7j.mjs +2 -0
  29. package/dist/init-helpers-DGSTVbNx.mjs +13 -0
  30. package/dist/injector-BMOi1uN3.mjs +1 -0
  31. package/dist/json-1jsvqdBb.mjs +1 -0
  32. package/dist/list-BkniWIlD.mjs +1 -0
  33. package/dist/logger-Oo2Slehd.mjs +1 -0
  34. package/dist/migrate-DM80YXOF.mjs +3 -0
  35. package/dist/nextjs-config-BlbmHmCb.mjs +1 -0
  36. package/dist/nextjs-config-m83qz9Qp.mjs +2 -0
  37. package/dist/output-B7NC4xgj.mjs +1 -0
  38. package/dist/package-manager-Cs9kCsjJ.mjs +11 -0
  39. package/dist/paths-B5sEvS_7.mjs +1 -0
  40. package/dist/picomatch-DEttMFSR.mjs +1 -0
  41. package/dist/preflight-C_Zr3uyO.mjs +1 -0
  42. package/dist/preflight-fF8g1t6F.mjs +1 -0
  43. package/dist/publish-PaTRQ5Ga.mjs +1 -0
  44. package/dist/publisher-oHVy3LA2.mjs +2 -0
  45. package/dist/push-DX9dRKDw.mjs +1 -0
  46. package/dist/push-engine-ByiNZr52.mjs +1 -0
  47. package/dist/remove-BEBkMPak.mjs +1 -0
  48. package/dist/remove-DxezmGfU.mjs +1 -0
  49. package/dist/reset-B9Xcepo1.mjs +1 -0
  50. package/dist/restore-B8aEJn3N.mjs +1 -0
  51. package/dist/rollback-pqomySb-.mjs +1 -0
  52. package/dist/shell-DQfdqK0J.mjs +1 -0
  53. package/dist/status-2-lE-2hH.mjs +1 -0
  54. package/dist/store-CAzxNmpU.mjs +1 -0
  55. package/dist/tailwind-source-Ho_nKVtd.mjs +3 -0
  56. package/dist/timer-BZNWRS3O.mjs +1 -0
  57. package/dist/topo-sort-CNCKE3Ap.mjs +1 -0
  58. package/dist/topo-sort-I086ZoiN.mjs +1 -0
  59. package/dist/tracker-OhIA445x.mjs +1 -0
  60. package/dist/tracker-nsfA6PWa.mjs +1 -0
  61. package/dist/update-CjAl0ZO9.mjs +1 -0
  62. package/dist/use-BCXyvJf2.mjs +1 -0
  63. package/dist/vite-config-B6bZDoGe.mjs +1 -0
  64. package/dist/vite-config-D_iXaoHh.mjs +10 -0
  65. package/dist/vite-plugin.mjs +1 -210
  66. package/dist/watch-orchestrator-DGe9gBjj.mjs +1 -0
  67. package/dist/watch-orchestrator-DkuwJOEb.mjs +1 -0
  68. package/dist/watcher-DN6vT6nw.mjs +1 -0
  69. package/dist/watcher-LcNLwOgA.mjs +1 -0
  70. package/dist/webpack-plugin.mjs +1 -145
  71. package/dist/workspace-7rWwh6jI.mjs +1 -0
  72. package/dist/workspace-CSQVbAw4.mjs +1 -0
  73. package/package.json +6 -8
  74. package/dist/add-Clbi3vJ2.mjs +0 -3
  75. package/dist/add-flow-DdDziP5M.mjs +0 -5
  76. package/dist/batch-push-pVkjhRbp.mjs +0 -3
  77. package/dist/bell-BJuCym_5.mjs +0 -11
  78. package/dist/bell-CIzHg0kw.mjs +0 -3
  79. package/dist/bell-UNNirKkz.mjs +0 -3
  80. package/dist/build-detect-mSo9jKXK.mjs +0 -3
  81. package/dist/bundler-detect-Cx8_R2hT.mjs +0 -3
  82. package/dist/check-Boh8WU_W.mjs +0 -3
  83. package/dist/chokidar-BkIWf7Ix.mjs +0 -3
  84. package/dist/clean-DHh6fpmR.mjs +0 -3
  85. package/dist/config-CQpgsGyL.mjs +0 -4
  86. package/dist/console-BxhMcj-D.mjs +0 -81
  87. package/dist/console-X31Y_QS5.mjs +0 -3
  88. package/dist/dev-DeOwxr_7.mjs +0 -3
  89. package/dist/dist-CFkjiIqD.mjs +0 -7
  90. package/dist/doctor-XEdsr84Q.mjs +0 -6
  91. package/dist/dry-run-BxVjpNqJ.mjs +0 -3
  92. package/dist/errors-CV7G61Hr.mjs +0 -3
  93. package/dist/explain-BBv3U-D3.mjs +0 -3
  94. package/dist/format-DRqD29u-.mjs +0 -3
  95. package/dist/fs-BjaNhdzt.mjs +0 -683
  96. package/dist/fs-Cf1JTFyh.mjs +0 -3
  97. package/dist/fs-DUcoWJ1g.mjs +0 -3
  98. package/dist/hints-Hz3V4h3A.mjs +0 -3
  99. package/dist/history-BZS2YUIt.mjs +0 -3
  100. package/dist/history-C5ehozRy.mjs +0 -3
  101. package/dist/init-Dwf-EIG3.mjs +0 -4
  102. package/dist/init-helpers-BfDosqvf.mjs +0 -15
  103. package/dist/injector-XwK_LBUh.mjs +0 -3
  104. package/dist/json-C6XtcMC4.mjs +0 -46
  105. package/dist/json-CWzEb9Rt.mjs +0 -3
  106. package/dist/list-DcREV9JM.mjs +0 -3
  107. package/dist/logger-DlikgOlh.mjs +0 -3
  108. package/dist/migrate-DW5KQeDq.mjs +0 -5
  109. package/dist/nextjs-config-BfHv8mBE.mjs +0 -3
  110. package/dist/nextjs-config-CA4N_9VY.mjs +0 -4
  111. package/dist/output-BxyRer_F.mjs +0 -3
  112. package/dist/package-manager-DBBQ0XtZ.mjs +0 -13
  113. package/dist/picomatch-B0_Pxgms.mjs +0 -3
  114. package/dist/preflight-B17VQJs0.mjs +0 -3
  115. package/dist/preflight-B8ypfoKV.mjs +0 -3
  116. package/dist/publish-BLk5_qx1.mjs +0 -3
  117. package/dist/publisher-Br4Od-iL.mjs +0 -4
  118. package/dist/push-C6UFcNGO.mjs +0 -3
  119. package/dist/push-engine-D3rfg2Tj.mjs +0 -3
  120. package/dist/remove-Bz9dNgDM.mjs +0 -3
  121. package/dist/remove-DMj6k2PK.mjs +0 -3
  122. package/dist/reset--AuvAPTc.mjs +0 -3
  123. package/dist/restore-CIBe2F1d.mjs +0 -3
  124. package/dist/rollback-CFLIncnW.mjs +0 -3
  125. package/dist/rolldown-runtime-BZbIAPMk.mjs +0 -3
  126. package/dist/rolldown-runtime-D3KUYPsf.mjs +0 -12
  127. package/dist/shell-RQ7Hf1kp.mjs +0 -3
  128. package/dist/status-Dy-e_RtI.mjs +0 -3
  129. package/dist/store-BNeGfW_b.mjs +0 -3
  130. package/dist/tailwind-source-Cgva0Hte.mjs +0 -5
  131. package/dist/timer-DqgB175x.mjs +0 -3
  132. package/dist/topo-sort-DOCpHjT7.mjs +0 -3
  133. package/dist/topo-sort-yd4jxr_E.mjs +0 -3
  134. package/dist/tracker-DXSo5wXO.mjs +0 -3
  135. package/dist/tracker-DofCXLTP.mjs +0 -3
  136. package/dist/update-Dacjzw4f.mjs +0 -3
  137. package/dist/use-BSCV4IQ5.mjs +0 -3
  138. package/dist/vite-config-CbYEhn5K.mjs +0 -3
  139. package/dist/vite-config-DqxvL5TW.mjs +0 -12
  140. package/dist/watch-orchestrator-CghvwrNS.mjs +0 -3
  141. package/dist/watcher-Bw_qcI0M.mjs +0 -3
  142. package/dist/workspace-D4vhzpO4.mjs +0 -3
  143. package/dist/workspace-DVY5o1g8.mjs +0 -3
  144. package/dist/xxhash-wasm-D_QjdUuv.mjs +0 -3
package/README.md CHANGED
@@ -1,13 +1,13 @@
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>
@@ -16,151 +16,110 @@
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), [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 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{t}from"./timer-BZNWRS3O.mjs";import{n}from"./output-B7NC4xgj.mjs";import{t as r}from"./add-flow-BjjRSNWm.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,3 @@
1
+ import{n as e}from"./shell-DQfdqK0J.mjs";import{t}from"./hints-BKo_2axg.mjs";import{t as n}from"./console-C8XtlRyM.mjs";import{n as r,t as i}from"./store-CAzxNmpU.mjs";import{t as a}from"./publisher-oHVy3LA2.mjs";import{i as o,n as s,r as c,t as l}from"./injector-BMOi1uN3.mjs";import{d as u,h as d,n as f,o as p}from"./tracker-nsfA6PWa.mjs";import{c as m}from"./fs-DusqxRQR.mjs";import{t as h}from"./package-manager-Cs9kCsjJ.mjs";import{t as g}from"./build-detect-Bo1fe8OV.mjs";import{n as _}from"./bundler-detect-BaShXORS.mjs";import{i as v,o as y}from"./init-helpers-DGSTVbNx.mjs";import{t as b}from"./nextjs-config-m83qz9Qp.mjs";import{b as x,i as S,v as C,y as w}from"./paths-B5sEvS_7.mjs";import{t as T}from"./timer-BZNWRS3O.mjs";import{t as E}from"./output-B7NC4xgj.mjs";import{t as D}from"./errors-DRugrv36.mjs";import{i as O,n as k,r as A}from"./logger-Oo2Slehd.mjs";import{i as j,r as M}from"./dry-run-DPoN8bZo.mjs";import{o as N}from"./json-1jsvqdBb.mjs";import{readFile as P}from"node:fs/promises";import{basename as F,join as I,resolve as L}from"node:path";async function R(e){let s=e.timer??new T,g=L(`.`),{name:_,version:b}=B(e.packageArg),C,O=null,A=!1,j=!1;if(V(_,e.packageArg),b)try{w(b)}catch{D(`Invalid package version "${b}" in "${e.packageArg}".`),process.exit(1)}let N=(await h(g)).resolve(),P=N.packageManager;if(N.nodeModulesCompatible||(n.error(N.incompatibilityReason),process.exit(1)),e.from){let t=L(e.from);C=t;let r=await H(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=b?await r(_,b):await i(_);if(!F){let e=b?`@${b}`:``;D(`Package "${_}${e}" not found in store. Run 'knarr publish' in the package directory first, or use --from <path>.`),process.exit(1)}await m(S(g))||(await v(g,P),n.success(`Auto-initialized knarr (consumer mode)`)),n.info(`Detected package manager: ${P}`);let I=await p(g,_);I&&(I.version===F.version?n.info(`Updating ${_}@${F.version} (already linked)`):n.info(`Updating ${_}: ${I.version} -> ${F.version}`));let R=I?I.backupExists:await l(g,_,P);!I&&R&&n.info(`Backed up existing ${_} installation`),await x(g,_,F.version),await K(g,_,N),await G(F,g,N,e.yes??!1);let z=await c(F,g,P);n.success(`Linked ${_}@${F.version} -> node_modules/${_} (${z.copied} files copied, ${z.skipped} unchanged)`),z.binLinks>0&&n.info(`Created ${z.binLinks} bin link(s)`);let W={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(g,_,W),await u(_,g).catch(d),await y(g),await o(g,_)||n.info(`${_} isn't in package.json, so adding or removing other packages can prune it. Run \`knarr restore\` afterwards, or add it to dependencies.`);let q=C?[`cd ${C} && knarr dev`]:[];C&&n.info(`Next: ${t(C,process.cwd(),await U(C))}`),n.info(`Done in ${s.elapsed()}`);let J={package:_,version:F.version,copied:z.copied,skipped:z.skipped,binLinks:z.binLinks,elapsed:s.elapsedMs(),buildCmd:O,buildRan:A,buildSkipped:j,nextSteps:q};return e.emitOutput!==!1&&E(J),k()&&M(),J}async function z(e){let t=L(e);await m(t)||(D(`Source path not found: ${t}`),process.exit(1));let n=I(t,`package.json`);await m(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 V(i,i),i}function B(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 V(e,t){try{C(e)}catch{D(`Invalid package name "${t}". Use format: package-name or @scope/package-name.`),process.exit(1)}}async function H(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 h(e)).resolve().packageManager;r=await g(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 q(r,e)||(D(`Build command failed: ${r}`),await W(e),process.exit(1)),{buildCmd:r,ran:!0,skipped:!1}}async function U(e){let{findWorkspacePackageRoot:t,findWorkspacePackages:n}=await import(`./workspace-CSQVbAw4.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 W(e){if(!await m(I(e,`node_modules`))){let t=(await h(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 G(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 K(e,t,r){let i=await _(e);if(i.type===`next`&&i.configFile){let e=await b(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-B6bZDoGe.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:
2
+ import knarr from "knarr/vite"
3
+ plugins: [knarr()]`)}let{findTailwindCss:a,addTailwindSource:o}=await import(`./tailwind-source-Ho_nKVtd.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 q(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{z as n,R as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./console-C8XtlRyM.mjs";import{n as t,r as n,t as r}from"./workspace-7rWwh6jI.mjs";import{n as i,t as a}from"./topo-sort-I086ZoiN.mjs";import{t as o}from"./push-engine-ByiNZr52.mjs";import{t as s}from"./timer-BZNWRS3O.mjs";import{i as c}from"./logger-Oo2Slehd.mjs";async function l(l,d={}){let f=new s,p=await t(l),m=n(p);if(m.packages.length===0){e.warn(`No publishable workspace packages found`);return}let h=p.packages.length-m.packages.length;h>0&&e.info(`Skipping ${h} private workspace package(s)`);let g;try{g=i(m.adjacency)}catch(t){throw t instanceof a&&e.error(`Cannot push: ${t.message}`),t}let _=new Map(m.packages.map(e=>[e.name,e.dir]));e.info(`Pushing ${g.length} packages in dependency order`),c(`[batch-push] Order: ${g.join(` → `)}`);let v=r(m.adjacency),y=new Set(d.skipPackages??[]);for(let e of[...y])u(e,v,y);let b=0,x=0,S=0;for(let t of g){let n=_.get(t);if(n){if(y.has(t))c(`[batch-push] Skipping ${t}: dependency build/push failed`),S++;else try{(await o(n,d)).failedConsumers>0?(x++,u(t,v,y)):b++}catch(n){e.warn(`Failed to push ${t}: ${n instanceof Error?n.message:String(n)}`),x++,u(t,v,y)}}}let C=[x>0?`${x} failed`:null,S>0?`${S} skipped`:null].filter(e=>e!==null),w=`Pushed ${b}/${g.length} packages in ${f.elapsed()}`+(C.length>0?` (${C.join(`, `)})`:``);if(x>0)throw e.warn(w),Error(`Failed to push ${x} workspace package(s)`);S>0?e.warn(w):e.success(w)}function u(e,t,n){for(let r of t.get(e)??[])n.has(r)||(n.add(r),u(r,t,n))}export{l as t};
@@ -0,0 +1 @@
1
+ import{c as e,u as t}from"./json-1jsvqdBb.mjs";import{join as n}from"node:path";async function r(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{r as t};
@@ -0,0 +1 @@
1
+ import{c as e}from"./fs-DusqxRQR.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 r(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 i(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{r as n,i as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{n as t,t as n}from"./console-C8XtlRyM.mjs";import{t as r}from"./preflight-fF8g1t6F.mjs";import{n as i,t as a}from"./output-B7NC4xgj.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 @@
1
+ import{type as e}from"node:os";import{lstat as t,open as n,readdir as r,readlink as i,realpath as a,stat as o}from"node:fs/promises";import*as s from"node:path";import{join as c,resolve as l,sep as u}from"node:path";import{realpathSync as d,watch as f}from"node:fs";import{EventEmitter as p}from"node:events";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]),ee=/* @__PURE__ */ new Set([h.EVERYTHING_TYPE,h.FILE_DIR_TYPE,h.FILE_TYPE]),x=e=>v.has(e.code),te=process.platform===`win32`,ne=e=>!0,re=e=>{if(e===void 0)return ne;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 ne};var ie=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 n={...g,...e},r=n.root??g.root,i=n.type??g.type;this._fileFilter=re(n.fileFilter),this._directoryFilter=re(n.directoryFilter);let a=n.lstat?t:o;this._stat=te?e=>a(e,{bigint:!0}):a,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:g.depth,this._wantsDir=b.has(i),this._wantsFile=ee.has(i),this._wantsEverything=i===h.EVERYTHING_TYPE,this._root=l(r),this._relStart=this._root.endsWith(u)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent};let s={path:this._root,depth:1};s.pending=this._exploreDir(this._root,1),this.parents=[s],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 r(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=c(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){x(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 n=e.fullPath;try{let e=await a(n),r=await t(e);if(r.isFile())return`file`;if(r.isDirectory()){let t=e.length;if(n.startsWith(e)&&n[t]===u){let t=/* @__PURE__ */ Error(`Circular symlink detected: "${n}" points to "${e}"`);return t.code=_,this._onError(t),``}return`directory`}}catch(e){this._onError(e)}return``}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function ae(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 ie(r)}const S=process.platform,C=S===`win32`,w=S===`darwin`,oe=S===`linux`,se=e()===`OS400`;function ce(e){return e?.code}function T(e){let t=ce(e);return t===`ENOENT`||t===`ENOTDIR`?`missing`:t===`EPERM`||t===`EACCES`?`permission`:t===`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`?`recursive-unsupported`:`other`}function E(e){return T(e)===`missing`}function le(e){return T(e)===`permission`}function ue(e){return T(e)===`recursive-unsupported`}const de=Object.freeze({now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>{e&&clearTimeout(e)}}),D={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},O=/\\/g,fe=/\/\//g;function k(e){if(typeof e!=`string`)throw TypeError(`string expected`);let t=e.replace(O,`/`),n=t.startsWith(`//`),r=s.normalize(t).replace(O,`/`).replace(fe,`/`);return n&&!r.startsWith(`//`)&&(r=`/${r}`),r}function A(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 j(e){let t=s.resolve(e);return C||!t.includes(`\\`)?t.replace(O,`/`):k(t)}function pe(e){return e!==`..`&&!e.startsWith(`..${s.sep}`)&&!s.isAbsolute(e)}function M(e,t){let n=s.relative(e,t);return n===``||pe(n)}function N(e,t){let n=s.relative(e,t);return n!==``&&pe(n)}function P(e){return typeof e==`object`&&!!e&&!(e instanceof RegExp)}function me(e){return e instanceof RegExp?new RegExp(e.source,e.flags):P(e)?Object.freeze({...e}):e}function he(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>(e.lastIndex=0,e.test(t)):P(e)?t=>e.path===t||!!(e.recursive&&N(e.path,t)):()=>!1}function F(e){let t=e.map(he);return(e,n)=>{if(t.length===0)return!1;let r=k(e);return t.some(e=>e(r,n))}}function ge(e,t=process.cwd()){return typeof e==`string`?k(s.isAbsolute(e)?e:s.join(t,e)):P(e)?{path:k(s.isAbsolute(e.path)?e.path:s.join(t,e.path)),recursive:e.recursive}:e}const _e=/^\.[/\\]/;var ve=class e{watchPath;followSymlinks;recursiveRoot;recursiveDisabled;observationTrigger;realpathAncestry;pathGeneration;context;constructor(e,t,n){this.context=n,this.watchPath=e.replace(_e,``),this.followSymlinks=t,this.realpathAncestry=/* @__PURE__ */ new Set,this.pathGeneration=n.capturePathGeneration()}fork(t){let n=new e(t,this.followSymlinks,this.context);return n.recursiveRoot=this.recursiveRoot,n.recursiveDisabled=this.recursiveDisabled,n.observationTrigger=this.observationTrigger,n.realpathAncestry=new Set(this.realpathAncestry),n.pathGeneration=this.pathGeneration,n}withObservation(e){let t=Object.create(this);return t.observationTrigger=e,t}filterPath(e){return e.stats?.isSymbolicLink()?this.filterDir(e):this.context.isntIgnored(s.join(this.watchPath,e.path),e.stats)}filterDir(e){return this.context.isntIgnored(s.join(this.watchPath,e.path),e.stats)}};let ye=0;function I(){return++ye}function be(e,t){return!e.closed&&(e.subscribers.add(t),!0)}function xe(e,t){if(!e.closed&&e.subscribers.delete(t))return e.subscribers.size>0?`remaining`:`last`}function Se(e){if(e.closed)return;e.closed=!0;let t=[...e.subscribers];return e.subscribers.clear(),t}function Ce(e){[...e.subscribers].some(e=>e.persistent)?e.watcher.ref():e.watcher.unref()}function L(e,t){let n=Se(e);if(n)return t.get(e.resource)===e&&t.delete(e.resource),e.watcher.close(),n}function we(e,t){be(e,t),Ce(e)}function Te(e,t,n){let r=!1;return{resource:e.resource,close:()=>{if(r)return;r=!0;let i=xe(e,t);i===`remaining`?Ce(e):i===`last`&&n.get(e.resource)===e&&L(e,n)}}}function Ee(e){let t=e.backend===`native-recursive`||e.backend===`auto`&&(w||C),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 R=D;function z(){return performance.now()}function De(e){let t=s.normalize(e);if(!C)return t;try{return d.native(t)}catch{return t}}function Oe(e,t){if(!C||t===null||!s.isAbsolute(t))return t;let n=s.normalize(s.toNamespacedPath(e)),r=s.normalize(s.toNamespacedPath(t)),i=s.relative(n,r);return M(n,r)?i||null:t}const B=/* @__PURE__ */ new Map;function ke(e,t,n){return f(e,t,n)}let Ae=ke;const V=/* @__PURE__ */ new Map;let je=!1;function Me(e,t,n){return f(e,t,n)}let Ne=Me;function Pe(e,t){let n=L(e,V);n&&n.forEach(e=>e.failure(t))}function Fe(e,t,n,r){if(je)return{kind:`unsupported`};let i=s.resolve(e),a={...n,watchedPath:e,persistent:t},o=V.get(i);if(!o){let n,r,a=De(e);try{n=Ne(a,{persistent:t,recursive:!0},(e,t)=>{let n=r;if(!n||n.closed||V.get(i)!==n)return;let o={kind:`native`,resource:i,rawEvent:e,relativePath:Oe(a,t),sequence:++n.sequence,observedAt:z()};n.subscribers.forEach(n=>{n.rawEmitter(e,t,{watchedPath:n.watchedPath}),n.publish(o)})})}catch(e){return ue(e)?(je=!0,{kind:`unsupported`}):{kind:`failed`,error:e}}r=o={resource:i,generation:I(),subscribers:/* @__PURE__ */ new Set,closed:!1,watcher:n,sequence:0},V.set(i,o),n.on(R.ERROR,e=>Pe(o,e))}we(o,a);let c=Te(o,a,V);return r.aborted&&c.close(),{kind:`subscribed`,subscription:c}}function Ie(e,t,n,r){try{return Ae(e,{persistent:t.persistent},n)}catch(e){r(e);return}}function Le(e,t,n,r,i=n){if(e.closed||B.get(e.resource)!==e)return;let a={kind:`native`,resource:e.resource,rawEvent:t,relativePath:n,sequence:++e.sequence,observedAt:z()};e.subscribers.forEach(e=>{r&&e.rawEmitter(t,i,{watchedPath:e.watchedPath}),e.publish(a)})}function Re(e,t){e.closed||B.get(e.resource)!==e||e.subscribers.forEach(e=>e.errHandler(t))}function ze(e,t){L(e,B)?.forEach(e=>e.failure?.(t))}async function Be(e,t,r){if(C&&r.code===`EPERM`)try{await(await n(e,`r`)).close(),Re(t,r)}catch{Le(t,`rename`,null,!1)}else Re(t,r);ze(t,r)}async function Ve(e,n){try{await t(s.join(n,s.basename(n)));return}catch(e){if(!E(e))return}try{if(!(await o(n)).isDirectory())return}catch{return}e.closed||B.get(e.resource)!==e||ze(e,/* @__PURE__ */ Error(`Watched directory was replaced: ${n}`))}function He(e,t,n,r,i){let a,o=Ie(t,r,(e,n)=>{let r=Oe(t,n);Le(a,e,r,!0,n),oe&&e===`rename`&&n===s.basename(t)&&Ve(a,t)},i.errHandler);if(o)return a={resource:n,generation:I(),subscribers:/* @__PURE__ */ new Set([i]),closed:!1,watcher:o,sequence:0},B.set(n,a),o.on(R.ERROR,t=>{Be(e,a,t)}),a}function H(e,t,n,r,i){let a=t,o={...r,watchedPath:e,persistent:n.persistent??!0},s=B.get(a);if(s)we(s,o);else if(s=He(e,De(e),a,n,o),!s)return;let c=Te(s,o,B);if(i.aborted)c.close();else return c}const Ue=Object.freeze({missing:!0}),U=/* @__PURE__ */ new Map;function W(e){return`missing`in e}function We(e,t){let n=W(e),r=W(t);if(n||r)return n!==r;let i=!C&&e.ino!==0&&t.ino!==0&&e.ino!==t.ino;return e.size!==t.size||e.mtimeMs!==t.mtimeMs||i}function Ge(e){e.timer&&(e.persistent?e.timer.ref():e.timer.unref())}function G(e,t=e.interval){e.closed||e.subscribers.size===0||(e.timer=e.scheduler.setTimeout(()=>{e.timer=void 0;let t=Ke(e);e.currentPoll=t,t.then(()=>{e.currentPoll===t&&(e.currentPoll=void 0)},()=>{e.currentPoll===t&&(e.currentPoll=void 0)})},t),Ge(e))}async function Ke(e){if(e.closed||e.running||e.subscribers.size===0)return;e.running=!0;let t=e.scheduler.now(),n;try{n=await o(e.resource)}catch(t){E(t)?n=Ue: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&&We(t,n),a=e.directoryReplayAt!==void 0&&r>=e.directoryReplayAt;if(!W(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(R.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;G(e,Math.max(0,e.interval-n))}}function qe(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,G(e)):e.timer?Ge(e):e.running||G(e)}function Je(e,t,n,r,i,a,o){let s=t,c={watchedPath:e,...n,...i},l=U.get(s);l||(l=/* @__PURE__ */ new Map,U.set(s,l));let u=l.get(r);u?!u.previous&&a&&(u.previous=a):(u={resource:s,generation:I(),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),qe(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){qe(u);return}if(u.closed)return;u.closed=!0,u.timer&&u.scheduler.clearTimeout(u.timer),u.timer=void 0;let e=U.get(s);e?.get(r)===u&&(e.delete(r),e.size===0&&U.delete(s)),u.currentPoll&&await Promise.allSettled([u.currentPoll])})(),f)};if(o.aborted)p.close();else return p}var Ye=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 Xe(){}function K(e,t){if(s.isAbsolute(t))return;let n=s.resolve(e);if(M(n,s.resolve(n,t)))return s.join(e,t)}var Ze=class{queues=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;lifecycle;constructor(e){this.lifecycle=e}enqueue(e,t,n=e){let r=j(e),i=n===!1?void 0:`${r}\0${j(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(Xe).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 Qe=Object.freeze({size:0,mtimeMs:0,ino:0,kind:`other`,initialRecursive:!0});function q(e){return e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function $e(e,t){let n=A(t);return e?.size===n.size&&e.mtimeMs===n.mtimeMs&&e.ino===n.ino&&e.kind===q(t)}function et(e,t,n){return e?.observedAt!==void 0&&t.observedAt>=e.observedAt&&t.observedAt-e.observedAt<=n}var tt=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=``}},nt=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=s.resolve(e),n=j(t),r=this.watched.get(n);return r||(r=new tt(t),this.watched.set(n,r)),r}peekDirectory(e){return this.watched.get(j(s.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}=A(t);this.observed.set(j(e),{size:o,mtimeMs:s,ino:c,kind:q(t),transition:n,rawEvent:r?.rawEvent,relativePath:r?.relativePath,observedAt:r?.observedAt,initialRecursive:i})}consumeInitialCreate(e,t,n,r){if(this.observed.get(j(e))?.initialRecursive&&n.rawEvent===`rename`)return this.recordObserved(e,t,`add`,n),r?t.isDirectory()?D.ADD_DIR:D.ADD:!1}markInitialCreate(e){let t=j(e),n=this.observed.get(t);n?n.initialRecursive=!0:this.observed.set(t,{...Qe})}clearInitialCreate(e){let t=this.observed.get(j(e));t&&(t.initialRecursive=!1)}clearInitialCreates(e){let t=j(e);for(let[e,n]of this.observed)M(t,e)&&n.initialRecursive&&(n.initialRecursive=!1)}replacedSinceObserved(e,t){let n=this.observed.get(j(e)),{ino:r}=A(t);return n?.kind===`directory`&&t.isDirectory()&&n.ino!==0&&r!==0&&n.ino!==r}changedSinceObserved(e,t){let n=this.observed.get(j(e));return n!==void 0&&n.kind===q(t)&&!$e(n,t)}isDuplicateObservation(e,t,n){let r=this.observed.get(j(e)),i=$e(r,t),a=i&&r?.transition===`add`&&r?.relativePath===n.relativePath&&r.rawEvent===`rename`&&n.rawEvent===`change`&&et(r,n,25),o=i&&t.isFile()&&!r?.initialRecursive&&(r?.transition===`add`||n.relativePath===null),s=i&&r?.transition===`change`&&r.relativePath===n.relativePath&&et(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 J(e){return e!==void 0&&e.isFile()&&A(e).size===0}function rt(e,t){if(e===void 0||t===void 0)return!1;let n=A(e),r=A(t);return n.size===r.size&&n.mtimeMs===r.mtimeMs&&n.ino===r.ino}var it=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 C&&(e=s.normalize(e)),this.context.options.cwd?s.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,c=j(t),l=this.context.lifecycle.generation,u=this.context.capturePathGeneration();t=this.presentPath(t);let d=[t];n!=null&&d.push(n);let f=this.heldAdds.get(c);if(f){if(e===D.CHANGE){f.path=a,n&&(f.stats=n),J(n)||f.release();return}f.release()}(e===D.UNLINK||e===D.UNLINK_DIR)&&(this.dropPendingChange(c),this.throttled.get(D.CHANGE)?.get(c)?.clear(!1));let p=r.awaitWriteFinish,m=p?this.pendingWrites.get(c):void 0;if(m)m.lastChange=i.now();else{if(r.atomic){if(e===D.UNLINK){let t=this.pendingUnlinks.get(c);t&&i.clearTimeout(t.timer);let n=[e,...d],a=this.setTimeout(()=>{let e=this.pendingUnlinks.get(c);if(!e||e.timer!==a||(this.pendingUnlinks.delete(c),this.context.isClosed()))return;let[t,...n]=e.event;this.context.publish(t,n)},typeof r.atomic==`number`?r.atomic:100);this.pendingUnlinks.set(c,{event:n,timer:a});return}let t=this.pendingUnlinks.get(c);e===D.ADD&&t&&(e=D.CHANGE,i.clearTimeout(t.timer),this.pendingUnlinks.delete(c))}if(p&&(e===D.ADD||e===D.CHANGE)&&this.context.isReady())this.awaitWriteFinish(t,p.stabilityThreshold,e,(t,n)=>{this.context.isClosed()||(t?(e=D.ERROR,d[0]=t,this.context.publish(e,d)):n&&(d.length>1?d[1]=n:d.push(n),this.context.publish(e,d)))},c);else if(e===D.ADD&&J(n)&&this.context.isReady()){let e={path:a,stats:n,release:()=>{if(this.context.scheduler.clearTimeout(e.timer),this.heldAdds.get(c)!==e||(this.heldAdds.delete(c),this.context.isClosed()||!this.context.lifecycle.isActive(l)||!this.context.isPathGenerationActive(c,u)))return;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(D.ADD,t)}};e.timer=this.setTimeout(e.release,10),this.heldAdds.set(c,e)}else{if(e===D.CHANGE){if(!this.throttle(D.CHANGE,a,50,e=>{let t=this.pendingChanges.get(c);this.dropPendingChange(c),e>0&&t?.replay&&this.context.lifecycle.isActive(l)&&this.context.isPathGenerationActive(c,u)&&this.emit(D.CHANGE,t.path,t.stats)})){let e=this.pendingChanges.get(c);e&&!rt(e.stats,n)&&(e.path=a,e.stats=n,e.replay=!0,e.held&&!J(n)&&e.held.release());return}let e={path:a,stats:n,replay:!1};if(this.pendingChanges.set(c,e),J(n)){let t=()=>{if(e.held&&this.context.scheduler.clearTimeout(e.held.timer),e.held=void 0,this.pendingChanges.get(c)!==e||this.context.isClosed()||!this.context.lifecycle.isActive(l)||!this.context.isPathGenerationActive(c,u))return;e.replay=!1;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(D.CHANGE,t)};e.held={timer:this.setTimeout(t,10),release:t};return}}if(r.alwaysStat&&n===void 0&&(e===D.ADD||e===D.ADD_DIR||e===D.CHANGE)){let e=r.cwd?s.join(r.cwd,t):t;try{n=await o(e)}catch(e){this.context.handleError(e)}if(!n||!this.context.lifecycle.isActive(l)||!this.context.isPathGenerationActive(c,u))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:j(t),o=i.get(a);if(o)return o.count+=1,!1;let s,c=(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(c,n);let l={timeoutObject:s,clear:c,count:0};return i.set(a,l),l}awaitWriteFinish(e,t,n,r,i){let a=this.context.options.awaitWriteFinish;if(typeof a!=`object`)return;let c=a.pollInterval,l,u=e;this.context.options.cwd&&!s.isAbsolute(e)&&(u=s.join(this.context.options.cwd,e));let d=i??j(u);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(l),n)},m=()=>this.context.lifecycle.isActive(f)&&this.pendingWrites.get(d)===p,h=e=>{let n=(async()=>{let n;try{n=await o(u)}catch(e){if(!m())return;E(e)?(this.context.remove(s.dirname(u),s.basename(u)),this.pendingWrites.get(d)===p&&p.cancelWait()):(this.pendingWrites.delete(d),r(e));return}if(!m())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)):l=this.setTimeout(()=>h(n),c)})();this.context.lifecycle.track(n)};this.pendingWrites.set(d,p),l=this.setTimeout(h,c)}cancelPath(e){let t=j(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(`${j(s.dirname(t))}\0${s.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 Y=D,at=1024,ot=Object.freeze({});function X(e){return{kind:`native`,resource:e,rawEvent:Y.CHANGE,relativePath:null,sequence:2**53-1,observedAt:z()}}function st(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 ct=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 lt(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(Y.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 ut=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 dt(e){return ut.has(s.extname(e).slice(1).toLowerCase())}var ft=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=s.basename(e),c=s.resolve(e),l={persistent:a.persistent},u=this.fsw.lifecycle.generation,d=!0,f=(e,n,r)=>{if(d&&this.fsw.lifecycle.isActive(u))return t(e,n,r)},p=t=>{this.reconcileBackendTrigger(e,r,t,e=>f(e,t.kind===`poll`&&!W(t.current)?t.current:void 0,t),()=>d&&this.fsw.lifecycle.isActive(u),!0,i)},m,h=0,g=()=>H(e,c,l,{publish:e=>{h=0,p(e)},errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e),failure:()=>{d&&this.fsw.lifecycle.isActive(u)&&(m=h++<3?g():void 0,p(X(c)))}},this.fsw.lifecycle.abortController.signal);if(m=a.backendCapabilities.polling?Je(e,c,{interval:a.pollingInterval!==a.pollingBinaryInterval&&dt(o)?a.pollingBinaryInterval:a.pollingInterval,persistent:a.persistent},this.fsw.scheduler,{publish:p,errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e)},n,this.fsw.lifecycle.abortController.signal):g(),m)return()=>{if(d)return d=!1,m?.close()}}subscribeMappedFile(e,t,n,r,i=w){if(this.fsw.options.backendCapabilities.polling)return;let a=s.dirname(t),o=j(t),c=s.dirname(e),l=this.fsw.lifecycle.generation,u=!0,d=i,f=!1,p,m,h,g=()=>u&&this.fsw.lifecycle.isActive(l)&&this.isHelperActive(n,e),_=e=>{if(e===null)return!0;let t=j(s.isAbsolute(e)?e:s.resolve(a,e));return C?t.toLowerCase()===o.toLowerCase():t===o},v=()=>{d&&(d=!1,h&&h.close())},y=(i,o)=>{if(o.kind!==`native`||!_(o.relativePath)||!g())return;let s=i===`directory`&&f;i===`directory`?(f=!1,v()):m&&(f=!0,v()),this.reconcileBackendTrigger(a,!0,o,async()=>{if(s&&p!==void 0){let e=await this.mappedFileSnapshot(t);if(e!==void 0&&st(p,e))return}await this.reconcileNativeTrigger(c,n,o,e,r-1,ot),i===`exact`&&(p=await this.mappedFileSnapshot(t))},g,!1,e)},b=0,ee=t=>({publish:e=>{t===`directory`&&(b=0),y(t,e)},errHandler:this.reportError,rawEmitter:(n,r)=>{(t===`directory`||d)&&_(r)&&g()&&this.fsw.emitRaw(n,r,{watchedPath:e})},failure:()=>{t===`exact`?(h=void 0,d=!1):(m=void 0,g()&&(b++<3&&(m=x(t)),y(t,X(s.resolve(a)))))}}),x=e=>{let n=e===`directory`?a:t;return H(n,s.resolve(n),{persistent:this.fsw.options.persistent},ee(e),this.fsw.lifecycle.abortController.signal)};if(m=x(`directory`),h=i?x(`exact`):void 0,h||(d=!1),m||h)return async()=>{if(!u)return;u=!1;let e=[m,h].filter(e=>e!==void 0);await Promise.allSettled(e.map(e=>e.close()))}}async mappedFileSnapshot(e){try{return await t(e)}catch(e){if(E(e))return!1;this.reportError(e);return}}watchSymlinkDeletion(e,n=!1){if(!w&&!n||this.fsw.options.backendCapabilities.polling)return;let r=this.fsw,i=r.lifecycle.generation,a=s.dirname(e),o=s.basename(e),c=!0,l,u=()=>{l=r.scheduler.setTimeout(()=>{l=void 0,(async()=>{try{await t(e)}catch(e){if(!c||!r.lifecycle.isActive(i))return;if(E(e)){c=!1,r.removePath(a,o);return}this.reportError(e)}c&&r.lifecycle.isActive(i)&&u()})()},r.options.pollingInterval),r.options.persistent||l.unref()};return u(),()=>{c&&(c=!1,r.scheduler.clearTimeout(l),l=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=K(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=j(o),l=j(s);return this.fsw.reconciliation.enqueue(c,async()=>{i()&&!this.fsw.isUnwatched(l)&&await r(s)},a?l:!1)}handleFile(e,n,r,i=!0,a,c=!1,l=!1){if(this.fsw.closed)return;let u=s.dirname(e),d=s.basename(e),f=this.fsw.tree.getDirectory(u),p=n;if(f.has(d))return;let m=this.fsw.capturePathGeneration(),h=()=>this.fsw.isPathGenerationActive(e,m),g=i&&this.fsw.options.backendCapabilities.polling?this.subscribePath(e,async(n,r)=>{if(!r||r.mtimeMs===0)try{let n=p.isSymbolicLink()&&!this.fsw.options.followSymlinks?await t(e):await o(e);if(!h())return;let r=n.atimeMs,i=n.mtimeMs;(!r||r<=i||i!==p.mtimeMs)&&this.fsw.emitEvent(Y.CHANGE,e,n),this.fsw.tree.recordObserved(e,n,`change`),p=n}catch(e){if(!h())return;E(e)?this.fsw.removePath(u,d):this.reportError(e)}else if(f.has(d)){let t=r.atimeMs,n=r.mtimeMs;(!t||t<=n||n!==p.mtimeMs)&&this.fsw.emitEvent(Y.CHANGE,e,r),this.fsw.tree.recordObserved(e,r,`change`),p=r}},n):void 0;return f.add(d),this.fsw.tree.recordObserved(e,n,`add`,a,c,l),!(r&&this.fsw.options.ignoreInitial)&&!this.fsw.isIgnored(e,n)&&this.fsw.emitEvent(Y.ADD,e,n),g}async handleSymlink(e,t,n,r,a,o){if(this.fsw.closed||o&&!this.isHelperActive(o,n))return;let s=j(e.fullPath),c=this.fsw.tree.getDirectory(t);if(!this.fsw.options.followSymlinks){let t;try{t=await i(n)}catch(e){return E(e)||this.reportError(e),!0}return this.fsw.closed||o&&!this.isHelperActive(o,n)||(c.has(r)?this.fsw.tree.symlinkPaths.get(s)!==t&&(this.fsw.tree.symlinkPaths.set(s,t),this.fsw.emitEvent(Y.CHANGE,n,e.stats)):(c.add(r),this.fsw.tree.symlinkPaths.set(s,t),this.fsw.tree.recordObserved(n,e.stats,`add`,o?.observationTrigger,a&&!!o?.recursiveRoot),a&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(Y.ADD,n,e.stats))),!0}if(this.fsw.tree.symlinkPaths.has(s))return!0;this.fsw.tree.symlinkPaths.set(s,!0)}readDirectory(e,n,r,i,a,c){if(!this.isHelperActive(r,e))return;e=s.join(e,``);let l=j(e),u=this.fsw.tree.getDirectory(r.watchPath),d=/* @__PURE__ */ new Set,f=this.fsw.createScanStream(e,{fileFilter:e=>r.filterPath(e),directoryFilter:e=>r.filterDir(e)});if(f)return lt(f,t=>{if(!this.isHelperActive(r,e))return;let o=t.stats;if(!o)return;let l=t.path,f=s.join(e,l);if(!this.isHelperActive(r,f))return;d.add(l);let p=l===i||!i&&!u.has(l);if(i===void 0&&!o.isSymbolicLink()&&!o.isDirectory()){if(!p)return;f=s.join(a,s.relative(a,f));let e=this.handleFile(f,o,n,!r.recursiveRoot,r.observationTrigger,n&&!!r.recursiveRoot);e&&this.fsw.addPathCloser(f,e)}else return(async()=>{o.isSymbolicLink()&&await this.handleSymlink(t,e,f,l,n,r)||this.isHelperActive(r,f)&&p&&(f=s.join(a,s.relative(a,f)),await this.addPathOnce(f,n,r,c+1))})()}).then(async({complete:n,error:a,failures:f})=>{if(f.forEach(this.reportError),a){if(E(a)&&this.isHelperActive(r,e)){let n=i?s.join(e,i):e,a=!1,d=!1;try{let e=i?await t(n):await o(n);d=!i&&!e.isDirectory()}catch(e){E(e)?a=!0:this.reportError(e)}i?a&&u.has(i)&&this.fsw.removePath(e,i):(a||d)&&this.fsw.tree.watched.has(l)&&(this.fsw.removePath(s.dirname(e),s.basename(e),!0),d&&await this.addPathOnce(e,!1,r,c))}else this.reportError(a)}n&&this.isHelperActive(r,e)&&await Promise.all(u.getChildren().filter(e=>!d.has(e)).map(t=>this.removeIfMissing(r,e,t,u)))})}async removeIfMissing(e,n,r,i){let a=s.join(n,r);if(this.isHelperActive(e,a)){try{await t(a);return}catch(e){if(!E(e))return}this.isHelperActive(e,a)&&i.has(r)&&this.fsw.removePath(n,r)}}scanRecursiveTree(e,t,n,r,i){if(!this.isHelperActive(n,e))return;let a=this.fsw,o=a.options.depth,c=o===void 0?void 0:o-r,l=a.createScanStream(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>!e.stats?.isSymbolicLink()&&n.filterDir(e),depth:c});if(l)return lt(l,o=>{if(!this.isHelperActive(n,e))return;let c=o.stats;if(!c)return;let l=s.join(e,o.path);if(!this.isHelperActive(n,l))return;let u=s.dirname(l),d=s.basename(l);if(i&&(i.seen.add(j(l)),c.isDirectory()&&i.directories.push(l)),c.isSymbolicLink())return(async()=>{if(await this.handleSymlink(o,u,l,d,t,n)||!this.isHelperActive(n,l))return;let e=r+o.path.split(/[/\\]/).length;await this.addPathOnce(l,t,n,e)})();let f=a.tree.getDirectory(u);if(f.has(d)){i&&c.isFile()&&a.tree.changedSinceObserved(l,c)&&(a.tree.recordObserved(l,c,`change`,void 0,!1,!0),a.emitEvent(Y.CHANGE,l,c));return}f.add(d);let p=c.isDirectory();p&&a.tree.getDirectory(l),a.tree.recordObserved(l,c,`add`,n.observationTrigger,t),t&&a.options.ignoreInitial||a.emitEvent(p?Y.ADD_DIR:Y.ADD,l,c)}).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=s.join(e,t);r.seen.has(j(n))||i.push(n)}i.sort((e,t)=>e.length-t.length);for(let e of i){let n=this.fsw.tree.peekDirectory(s.dirname(e));n?.has(s.basename(e))&&await this.removeIfMissing(t,s.dirname(e),s.basename(e),n)}}isHelperActive(e,t=e.watchPath){return this.fsw.isPathGenerationActive(t,e.pathGeneration)}candidateDepth(e,t){let n=s.relative(e,t);return n?n.split(s.sep).length:0}candidateIgnored(e,t,n){let r=s.relative(e,t),i=e;if(this.fsw.isIgnored(i))return!0;if(r){let e=r.split(s.sep);for(let t=0;t<e.length-1;t++)if(i=s.join(i,e[t]),this.fsw.isIgnored(i))return!0}return this.fsw.isIgnored(t,n)}async highestMissingPath(e,n){let r=n,i=s.dirname(n);for(;;){try{return await t(i),r}catch(e){if(!E(e))return this.reportError(e),r}if(r=i,i===e)return r;let n=s.dirname(i);if(n===i)return r;i=n}}async reconcileNativeTrigger(e,n,r,o,c=0,l){let u=this.fsw;if(!this.isHelperActive(n,e))return;let d,f=()=>d??=n.withObservation(r),p=o??(r.relativePath===null?e:K(e,r.relativePath));if(!p){this.reportError(/* @__PURE__ */ Error(`Native watcher reported a path outside its root: ${r.relativePath}`));return}let m=c+this.candidateDepth(e,p),h=u.options.depth;if(h!==void 0&&m>h+1||this.candidateIgnored(e,p))return;let g;try{g=await t(p)}catch(t){if(!E(t)){if(this.reportError(t),l)return;let n=p===e?e:s.dirname(p),r=Math.max(0,c+this.candidateDepth(e,n));await this.readDirectory(n,!1,f().fork(n),void 0,n,r);return}if(u.closed)return;let n=p===e?e:await this.highestMissingPath(e,p);if(u.closed)return;if(n===e){u.removePath(s.dirname(e),s.basename(e),!0),l?.onRootMissing?.();return}let r=s.dirname(n),i=s.basename(n);u.tree.getDirectory(r).has(i)?u.removePath(r,i):l||await this.readDirectory(r,!1,f().fork(r),void 0,r,Math.max(0,c+this.candidateDepth(e,r)));return}if(!this.isHelperActive(n,p)||this.candidateIgnored(e,p,g))return;if(!g.isDirectory()&&!(g.isSymbolicLink()&&u.options.followSymlinks)){let e=u.tree.consumeInitialCreate(p,g,r,u.options.ignoreInitial);if(e!==void 0){e&&u.emitEvent(e,p,g);return}}if(p===e){if(!g.isDirectory())return;n.recursiveRoot===e?await this.rescanRecursiveTree(e,f(),c):await this.readDirectory(e,!1,f(),void 0,e,c);return}let _=s.dirname(p),v=s.basename(p),y=u.tree.getDirectory(_),b=y.has(v);if(g.isSymbolicLink()){if(!u.options.followSymlinks){let e=!0;try{e=await i(p)}catch{}b||y.add(v),u.tree.symlinkPaths.set(j(p),e),b&&u.tree.isDuplicateObservation(p,g,r)||u.emitEvent(b?Y.CHANGE:Y.ADD,p,g),b||u.tree.recordObserved(p,g,`add`,r);return}let e=j(p),t=u.tree.symlinkPaths.get(e),o;try{o=await a(p)}catch(e){if(!E(e)){this.reportError(e);return}}if(b&&typeof t==`string`&&(o===void 0||j(t)!==j(o))){let t=u.tree.observed.get(e)?.kind;if(u.removePath(_,v,t===`directory`),!o||!this.isHelperActive(n,p))return;let r=f().fork(p);r.recursiveRoot=void 0,await this.addPathOnce(p,!1,r,m);return}let s=u.tree.consumeInitialCreate(p,g,r,u.options.ignoreInitial);if(s!==void 0){if(s){u.closePath(p,!0);let e=f().fork(p);e.recursiveRoot=void 0,await this.addPathOnce(p,!1,e,m)}return}if(b)u.emitEvent(Y.CHANGE,p,g);else{let e=f().fork(p);e.recursiveRoot=void 0,await this.addPathOnce(p,!1,e,m)}}else if(g.isDirectory()){let e=f().fork(p),t=u.tree.consumeInitialCreate(p,g,r,u.options.ignoreInitial);if(t!==void 0){t&&(u.closePath(p,!0),await this.addPathOnce(p,!1,e,m));return}b?u.tree.replacedSinceObserved(p,g)?(u.removePath(_,v,!0),await this.addPathOnce(p,!1,e,m)):(h===void 0||m<=h)&&await this.readDirectory(p,!1,e,void 0,p,m):await this.addPathOnce(p,!1,e,m)}else b?u.tree.isDuplicateObservation(p,g,r)||u.emitEvent(Y.CHANGE,p,g):await this.addPathOnce(p,!1,f(),m)}watchRootParent(e,n){if(!this.fsw.options.backendCapabilities.perDirectory||!C)return;let r=s.dirname(e);if(s.resolve(r)===s.resolve(e))return;let i=s.normalize(s.toNamespacedPath(s.resolve(r))).toLowerCase(),a=s.basename(e).toLowerCase(),o=this.fsw.lifecycle.generation,c=!0,l=e=>{if(e===null)return!0;let t=s.isAbsolute(e)?s.resolve(e):s.resolve(r,e);return s.normalize(s.toNamespacedPath(s.dirname(t))).toLowerCase()===i&&s.basename(t).toLowerCase()===a},u=()=>c&&this.fsw.lifecycle.isActive(o)&&this.isHelperActive(n,e),d=H(r,s.resolve(r),{persistent:this.fsw.options.persistent},{publish:i=>{i.kind===`native`&&l(i.relativePath)&&u()&&this.reconcileBackendTrigger(e,!1,i,async()=>{let i;try{i=await t(e)}catch(t){E(t)?this.fsw.removePath(r,s.basename(e),!0):this.reportError(t);return}u()&&(i.isDirectory()?await this.readDirectory(e,!1,n,void 0,e,0):(this.fsw.removePath(r,s.basename(e),!0),await this.addPathOnce(e,!1,n,0)))},u)},errHandler:this.reportError,rawEmitter:(e,t,n)=>{l(t)&&this.fsw.emitRaw(e,t,n)}},this.fsw.lifecycle.abortController.signal);if(d)return()=>{if(c)return c=!1,d.close()}}async watchRecursiveDirectory(e,n,r,i){let a=this.fsw,o=a.lifecycle.generation,c=j(e),l=new ct(at),u=[],d=`scanning`,f,p=!1,m,h,g=(t=e)=>a.lifecycle.isActive(o)&&a.isPathGenerationActive(t,i.pathGeneration),_=(t=e)=>d!==`recovering`&&d!==`closed`&&g(t),v=async n=>{if(!g())return;i.recursiveRoot=void 0,i.recursiveDisabled=!0;let o;try{o=await t(e)}catch(t){E(t)?a.removePath(s.dirname(e),s.basename(e),!0):this.reportError(t),this.reportError(n);return}let c=await this.handleDirectory(e,o,!1,r,void 0,i);g()?(c&&u.push(c),await this.subscribeTrackedDirectories(e,i,r),this.reportError(n)):c&&await c()},y=Fe(e,a.options.persistent,{publish:t=>{if(!_())return;if(d!==`live`){l.push(t);return}let n=t.relativePath===null?e:K(e,t.relativePath)??e;this.reconcileBackendTrigger(e,!0,t,()=>_()?this.reconcileNativeTrigger(e,i,t):void 0,()=>_(n))},failure:t=>{if(!_())return;let n=d!==`live`;d=`recovering`,a.tree.recursiveRoots.delete(c),f=t,p=!0,n||(m=a.reconciliation.enqueue(e,()=>v(t),!1))},rawEmitter:(...e)=>a.emitRaw(...e)},a.lifecycle.abortController.signal);if(y.kind===`unsupported`)return!1;if(y.kind===`failed`)throw y.error;h=y.subscription,a.tree.recursiveRoots.add(c),i.recursiveRoot=e;let b=async()=>{d!==`closed`&&(d=`closed`,a.tree.recursiveRoots.delete(c),l.clear(),await h?.close(),m&&await Promise.allSettled([m]),await Promise.allSettled(u.map(e=>e())))};try{if(await this.scanRecursiveTree(e,n,i,r),!p){d=`replaying`;let t=0;for(;_();){if(l.overflowed){l.clear(),t=0;let n={kind:`native`,resource:h.resource,rawEvent:Y.CHANGE,relativePath:null,sequence:2**53-1,observedAt:z()};await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,i,n),()=>_(),!1);continue}if(t>=l.entries.length)break;let n=l.entries[t++];if(n.rawEvent===`rename`&&n.relativePath!==null){let t=K(e,n.relativePath);t&&t!==e&&a.tree.getDirectory(s.dirname(t)).has(s.basename(t))&&a.tree.markInitialCreate(t)}await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,i,n),()=>_(),!1)}d!==`recovering`&&(d=`live`)}p&&(l.clear(),await v(f)),l.clear(),a.tree.clearInitialCreates(e)}catch(e){throw await b(),e}if(!g())await b();else return b}async subscribeTrackedDirectories(e,t,n){let r=this.fsw,i=s.resolve(e),a=e=>{let n=j(e);return this.isHelperActive(t,e)&&!r.lifecycle.closers.has(n)&&!r.tree.symlinkPaths.has(n)&&(r.tree.peekDirectory(s.dirname(e))?.has(s.basename(e))??!1)},o=[...r.tree.watched.values()].filter(e=>N(i,e.path)).map(t=>s.join(e,s.relative(i,t.path))).filter(a).sort((e,t)=>e.length-t.length),c=0,l=async()=>{for(;c<o.length;){let r=o[c++];a(r)&&await this.addPathOnce(r,!1,t,n+this.candidateDepth(e,r))}},u=Math.min(16,o.length);await Promise.all(Array.from({length:u},l))}async handleDirectory(e,n,r,i,a,c){if(!this.isHelperActive(c,e))return;if(a)this.fsw.tree.getDirectory(e);else{let t=this.fsw.tree.getDirectory(s.dirname(e)),i=t.has(s.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!i&&this.fsw.emitEvent(Y.ADD_DIR,e,n),t.add(s.basename(e)),this.fsw.tree.getDirectory(e),this.fsw.tree.recordObserved(e,n,i?void 0:`add`,c.observationTrigger,r&&!!c.recursiveRoot,!0)}let l,u=this.fsw.options.depth;if(u==null||i<=u){if(this.fsw.options.backendCapabilities.recursive&&i===0&&!a&&!c.recursiveRoot&&!c.recursiveDisabled){let t=await this.watchRecursiveDirectory(e,r,i,c);if(t!==!1)return t}if(c.recursiveRoot){a||await this.scanRecursiveTree(e,r,c,i);return}let u=new ct(at),d=/* @__PURE__ */ new Set,f=!a,p=!0,m=w&&!a,h=a?s.join(e,a):void 0,g=()=>{h&&p&&this.isHelperActive(c,h)&&this.fsw.rewatchMissingPath(h)},_=e=>{a?(this.fsw.tree.getDirectory(e).has(a)&&this.fsw.removePath(e,a),g()):this.fsw.removePath(s.dirname(e),s.basename(e),!0)},v=async(n,r,s)=>{if(p&&this.isHelperActive(c,n)){if(this.fsw.options.backendCapabilities.polling&&!r)_(n);else{if(s.kind===`native`){let e;try{let r=await t(n);e=r.isSymbolicLink()&&this.fsw.options.followSymlinks?await o(n):r}catch(e){E(e)?_(n):this.reportError(e);return}if(!e.isDirectory()){_(n),a||await this.addPathOnce(n,!1,c,i);return}}await this.readDirectory(n,!1,c,a,e,i)}}},y=(t,n,r)=>{if(p&&this.isHelperActive(c,t)){if(f)u.push({path:t,stats:n,trigger:r});else return r.kind===`native`&&!a?m?(m=!1,(async()=>{await this.reconcileNativeTrigger(e,c,r,t,i),await v(e,void 0,r)})()):this.reconcileNativeTrigger(e,c,r,t,i):r.kind===`native`&&a&&(t===e||(C?s.basename(t).toLowerCase()===a.toLowerCase():s.basename(t)===a))?this.reconcileNativeTrigger(e,c,r,h,i,{onRootMissing:g}):v(e,n,r)}},b=i===0&&!a?this.watchRootParent(e,c):void 0;if(l=this.subscribePath(e,y,n.isDirectory()?n:void 0,!0,a?s.join(e,a):e),a&&h&&l){let t=X(s.resolve(e));await this.fsw.reconciliation.enqueue(h,async()=>{this.fsw.tree.getDirectory(e).has(a)||await y(h,void 0,t)},h)}if(!a){await this.readDirectory(e,r,c,a,e,i);let t=0;for(;!this.fsw.closed;){if(u.overflow){let n=u.overflow;u.clear(),t=0,await v(e,n.stats,n.trigger);continue}if(t>=u.entries.length)break;let n=u.entries[t++];n.trigger.kind===`native`&&n.trigger.rawEvent===`rename`&&n.path!==e&&this.fsw.tree.getDirectory(s.dirname(n.path)).has(s.basename(n.path))&&(this.fsw.tree.markInitialCreate(n.path),d.add(n.path)),await this.reconcileBackendTrigger(e,!0,n.trigger,()=>n.trigger.kind===`native`&&!a?this.reconcileNativeTrigger(e,c,n.trigger,n.path,i):v(e,n.stats,n.trigger),()=>p&&this.isHelperActive(c,n.path),!1)}u.clear(),d.forEach(e=>this.fsw.tree.clearInitialCreate(e)),f=!1}if(!this.isHelperActive(c,e)){p=!1,l&&await l(),b&&await b();return}if(l||b){let e=[l,b].filter(e=>e!==void 0);l=async()=>{p&&(p=!1,u.clear(),await Promise.allSettled(e.map(e=>e())))}}}return l}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=s.dirname(i);if(e===i)return;a=s.basename(i),i=e}}async addPathOnce(e,n,r,c,l,u){if(this.fsw.isIgnored(e)||this.fsw.closed)return`complete`;let d=r?r.fork(e):this.fsw.createHelper(e);if(!r&&u!==void 0&&(d.pathGeneration=u),!this.isHelperActive(d))return`complete`;try{let u=await t(d.watchPath);if(!this.isHelperActive(d)||this.fsw.isIgnored(d.watchPath,u))return`complete`;let f=this.fsw.options.followSymlinks,p=u.isSymbolicLink(),m=p&&f?await o(d.watchPath):u,h=p&&f?await a(e):void 0,g;if(m.isDirectory()){let t=j(e),r=f?await a(e):e,i=h??e,o=j(r);if(!this.isHelperActive(d))return`complete`;if(p&&d.realpathAncestry.has(o))return this.fsw.tree.getDirectory(s.dirname(d.watchPath)).add(s.basename(d.watchPath)),this.fsw.tree.getDirectory(d.watchPath),this.fsw.tree.symlinkPaths.set(t,i),this.fsw.tree.recordObserved(d.watchPath,m,`add`,d.observationTrigger,n&&!!d.recursiveRoot),n&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(Y.ADD_DIR,d.watchPath,m),`complete`;if(d.realpathAncestry.add(o),d.recursiveRoot&&p&&(d.recursiveRoot=void 0),p&&(d.recursiveDisabled=!0),g=await this.handleDirectory(d.watchPath,m,n,c,l,d),!this.isHelperActive(d))return g&&await g(),`complete`;if(l&&!g)return`watch-parent`;p&&this.fsw.tree.symlinkPaths.set(t,i)}else if(p&&!f){let t=await i(e),a=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!r,l=this.handleFile(d.watchPath,m,n,!d.recursiveRoot,d.observationTrigger,n&&!!d.recursiveRoot,a);if(d.recursiveRoot)return this.fsw.tree.symlinkPaths.set(j(e),t),`complete`;let u=s.dirname(d.watchPath),f=await o(u),p=this.fsw.createHelper(u);p.pathGeneration=d.pathGeneration;let h=await this.handleDirectory(u,f,n,c,s.basename(d.watchPath),p),_=this.watchSymlinkDeletion(d.watchPath);if(!this.isHelperActive(d))return l&&await l(),h&&await h(),_&&_(),`complete`;g=async()=>{await Promise.allSettled([l,h,_].filter(e=>e!==void 0).map(e=>e()))},this.fsw.tree.symlinkPaths.set(j(e),t)}else{h&&this.fsw.tree.symlinkPaths.set(j(e),h);let t=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!r,i=this.handleFile(d.watchPath,m,n,!d.recursiveRoot,d.observationTrigger,n&&!!d.recursiveRoot,t),a=h??(t?d.watchPath:void 0),l=a?this.subscribeMappedFile(d.watchPath,a,d,c,w&&m.isFile()):void 0,u;if(t&&h){let e=s.dirname(d.watchPath),t=await o(e),r=this.fsw.createHelper(e);r.pathGeneration=d.pathGeneration,u=await this.handleDirectory(e,t,n,c,s.basename(d.watchPath),r)}let f=[i,l,u].filter(e=>e!==void 0);g=f.length===0?void 0:async()=>{await Promise.allSettled(f.map(e=>e()))}}return this.isHelperActive(d)?(g&&this.fsw.addPathCloser(l?s.join(e,l):e,g),`complete`):(g&&await g(),`complete`)}catch(e){return this.isHelperActive(d)?(this.fsw.handleError(e),`watch-parent`):`complete`}}};const pt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,mt=/* @__PURE__ */ new Set([`auto`,`native`,`native-recursive`,`polling`]),Z=Object.freeze({stabilityThreshold:2e3,pollInterval:100});function*ht(e){let t=s.resolve(e);for(let e=s.dirname(t);e!==t;e=s.dirname(e))yield j(e),t=e}function gt(e){return Array.isArray(e)?e:[e]}function _t(e){let t=gt(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(k)}function vt(e,t){return s.isAbsolute(e)?e:s.join(t,e)}function Q(e,t){if(!Number.isFinite(t)||t<=0)throw TypeError(`${e} must be a finite number greater than zero`)}function $(e,t){if(!Number.isFinite(t)||t<0)throw TypeError(`${e} must be a finite non-negative number`)}function yt(e){if(Q(`pollingInterval`,e.pollingInterval),Q(`pollingBinaryInterval`,e.pollingBinaryInterval),typeof e.atomic==`number`)$(`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&&(Q(`awaitWriteFinish.pollInterval`,e.awaitWriteFinish.pollInterval),$(`awaitWriteFinish.stabilityThreshold`,e.awaitWriteFinish.stabilityThreshold))}var bt=class extends p{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=de){if(super(),e.backend!==void 0&&!mt.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?gt(e.ignored).map(me):[]),awaitWriteFinish:n===!0?Z:typeof n==`object`&&Object.freeze({...Z,...n})};(e.usePolling===!0||se)&&(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=Ee(r),r.backendStrategy=r.backendCapabilities.kind,e.atomic===void 0&&(r.atomic=!r.usePolling),yt(r),this.options=r,this.lifecycle=new Ye(()=>{this.#u&&this.queueReady()},e=>{this.closed||this.handleError(e instanceof Error?e:Error(String(e)))}),this.tree=new nt(()=>!this.options.backendCapabilities.polling),this.reconciliation=new Ze(this.lifecycle),this.events=new it({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 ft(this),Object.freeze(r)}addIgnoredPath(e){if(e=this.ignoredMatcher(e),P(e)){for(let t of this.#e)if(P(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)P(t)&&t.path===e&&this.#e.delete(t);this.#l=void 0}ignoredMatcher(e){return typeof e==`string`?j(e):P(e)?{path:j(e.path),recursive:e.recursive}:e}capturePathGeneration(){return this.#n}invalidatePath(e){this.#r.set(j(e),++this.#n)}isPathGenerationActive(e,t){if(this.lifecycle.state!==`OPEN`)return!1;if(this.#r.size===0)return!0;let n=j(e);for(let[e,r]of this.#r)if(!(r<=t)&&M(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(D.READY))})))}add(e){if(this.closed)throw Error(`Cannot add paths after FSWatcher.close() has been called`);let{cwd:t}=this.options,n=_t(e);t&&(n=n.map(e=>vt(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=j(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=_t(e),{cwd:n}=this.options;return n&&(t=t.map(e=>vt(e,n))),t.forEach(e=>{let t=j(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?s.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitRaw(...e){this.closed||this.emit(D.RAW,...e)}emitWithAll(e,t){this.emit(e,...t),e!==D.ERROR&&this.emit(D.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));E(t)||this.options.ignorePermissionErrors&&le(t)||this.emit(D.ERROR,t)}isIgnored(e,t){if(this.options.atomic&&pt.test(e))return!0;if(!this.#a){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(t=>ge(t,e)),n=F(t),r=t.filter(e=>typeof e==`string`||P(e)),i=F(r);this.#a=(e,t)=>{if(n(e,t))return!0;if(C||r.length===0)return!1;let a=s.resolve(e),o;if(t?.isDirectory())o=this.realDirectory(a);else{let e=this.realDirectory(s.dirname(a));e!==void 0&&(o=s.join(e,s.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||=F([...this.#e]),this.#l(j(e),t))}isRootAncestor(e,t){return!t?.isFile()&&this.#c.has(j(e))}addRootAncestors(e){let t=j(e);if(!this.#s.has(t)){this.#s.add(t);for(let t of ht(e))this.#c.set(t,(this.#c.get(t)??0)+1)}}removeRootAncestors(e){if(this.#s.delete(j(e)))for(let t of ht(e)){let e=(this.#c.get(t)??1)-1;e>0?this.#c.set(t,e):this.#c.delete(t)}}realDirectory(e){let t=j(e);if(this.#o.has(t))return this.#o.get(t);let n;try{n=d.native(e)}catch{}return this.#o.set(t,n),n}isUnwatched(e){return this.#e.size!==0&&(this.#l||=F([...this.#e]),this.#l(j(e)))}createHelper(e){return new ve(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 i=n.path,a=this.lifecycle.generation;this.lifecycle.track((async()=>{try{await r(i)}catch(e){E(e)&&this.lifecycle.isActive(a)&&this.removePath(s.dirname(i),s.basename(i))}})())}removePath(e,t,n){let r=s.join(e,t),i=j(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,c=this.lifecycle.closers.has(i);this.removeTreeItem(e,t),this.tree.symlinkPaths.has(i)&&this.tree.symlinkPaths.delete(i);let l=this.events.pendingWrites.get(i),u=!1;this.options.awaitWriteFinish&&l&&(u=l.cancelWait()===D.ADD),this.tree.watched.delete(i),this.tree.observed.delete(i);let d=n?D.UNLINK_DIR:D.UNLINK;o&&!u&&!this.isIgnored(r)&&this.emitEvent(d,r),this.closePath(r),(o||c)&&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=j(e),r=e=>e===n?!0:t?N(n,e):!1;if([...this.lifecycle.closers.keys()].filter(r).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)r(e)&&(t.dispose(),this.tree.watched.delete(e));for(let e of this.tree.observed.keys())r(e)&&this.tree.observed.delete(e);for(let e of this.tree.symlinkPaths.keys())r(e)&&this.tree.symlinkPaths.delete(e);this.events.cancelWhere(r),this.reconciliation.forgetPending((e,t)=>r(e)||r(t));for(let e of this.#t.keys())r(e)&&this.#t.delete(e)}let i=s.dirname(n);this.removeTreeItem(i,s.basename(n))}closeFile(e){let t=j(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=j(e);this.lifecycle.addCloser(n,t)}createScanStream(e,t){if(this.closed)return;let n=ae(e,{type:D.ALL,alwaysStat:!0,lstat:!0,depth:0,...t});this.streams.add(n);let r=()=>this.streams.delete(n);return n.once(`close`,r),n.once(`end`,r),n.once(D.ERROR,r),n}};function xt(e,t={}){let n=new bt(t);return n.add(e),n}export{xt as watch};
@@ -0,0 +1 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{t}from"./console-C8XtlRyM.mjs";import{c as n,l as r,r as i}from"./tracker-nsfA6PWa.mjs";import{a,r as o,s}from"./store-CAzxNmpU.mjs";import{a as c,c as l,f as u}from"./fs-DusqxRQR.mjs";import{t as d}from"./format-IsfSiyGV.mjs";import{i as f,n as p}from"./logger-Oo2Slehd.mjs";import{r as m}from"./dry-run-DPoN8bZo.mjs";import{n as h,t as g}from"./output-B7NC4xgj.mjs";import{f as _,p as v}from"./paths-B5sEvS_7.mjs";import{t as y}from"./timer-BZNWRS3O.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}){h();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=>v(e.path)));for(let[t,n]of Object.entries(E))n.some(t=>e.has(t))&&A.add(t);f(`[clean] Protected packages (corrupt state): ${[...A].join(`, `)}`)}f(`[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)){f(`[clean] Preserving ${t} (consumer state unreadable)`);continue}let n=Date.now()-new Date(e.meta.publishedAt).getTime();if(n<S){f(`[clean] Skipping recently published entry: ${t} (${Math.round(n/1e3)}s old)`);continue}N.push(e)}}let P=[],F=_();if(await l(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?f(`[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=>c(e.packageDir))),R=await Promise.all(P.map(e=>c(x(F,e)))),z=0;for(let[e,t]of N.entries())f(`[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())f(`[clean] Removing orphaned directory: ${t}`),await u(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 ${d(I)})`:``;t.info(`Clean complete in ${C.elapsed()}${V}`),g({removedConsumers:w,removedPackages:T,removedEntries:z,removedOrphans:B,reclaimedBytes:I,elapsed:C.elapsedMs()}),p()&&m()}});export{C as default};
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.mjs CHANGED
@@ -1,10 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import{r as e}from"./rolldown-runtime-BZbIAPMk.mjs";import{n as t,t as n}from"./dist-CFkjiIqD.mjs";import{t as r}from"./logger-DlikgOlh.mjs";import{n as i,t as a}from"./console-X31Y_QS5.mjs";import{availableParallelism as o}from"node:os";var s=/* @__PURE__ */ e(i(),1);function showBanner(){console.log(s.default.yellow(`
2
+ import{n as e,t}from"./dist-jMqCJR3W.mjs";import{t as n}from"./logger-Oo2Slehd.mjs";import{n as r,t as i}from"./console-C8XtlRyM.mjs";import{availableParallelism as a}from"node:os";function o(){console.log(r.yellow(`
4
3
  _ __
5
4
  | |/ /_ __ __ _ _ __ _ __
6
5
  | ' /| '_ \\ / _\` | '__| '__|
7
6
  | . \\| | | | (_| | | | |
8
7
  |_|\\_\\_| |_|\\__,_|_| |_|
9
- `)),console.log(s.default.cyan(` Local npm package development without symlinks`)),console.log(s.default.dim(` Copies built files into consumer node_modules with incremental sync
10
- `))}process.env.UV_THREADPOOL_SIZE??=String(Math.max(o(),8)),r();const c=process.argv.slice(2),l=[`init`,`publish`,`add`,`use`,`remove`,`push`,`dev`,`restore`,`list`,`status`,`update`,`clean`,`gc`,`doctor`,`explain`,`migrate`,`reset`,`rollback`,`check`],u=c.some(e=>!e.startsWith(`-`)&&l.includes(e)),d=c.includes(`--help`)||c.includes(`-h`)||c.includes(`--version`);if(!u&&!d&&process.stdin.isTTY){showBanner();let e=await showInteractiveMenu();e&&process.argv.splice(2,0,e)}else u||showBanner();async function showInteractiveMenu(){try{let{readConsumerStateSafe:e}=await import(`./tracker-DXSo5wXO.mjs`),{resolve:t}=await import(`node:path`),{state:n}=await e(t(`.`)),r=Object.keys(n.links).length;r>0&&a.info(`${r} package(s) linked in this project`)}catch{}return await a.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 f=n({meta:{name:`knarr`,version:`0.2.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-Dwf-EIG3.mjs`).then(e=>e.default),publish:()=>import(`./publish-BLk5_qx1.mjs`).then(e=>e.default),add:()=>import(`./add-Clbi3vJ2.mjs`).then(e=>e.default),use:()=>import(`./use-BSCV4IQ5.mjs`).then(e=>e.default),remove:()=>import(`./remove-Bz9dNgDM.mjs`).then(e=>e.default),push:()=>import(`./push-C6UFcNGO.mjs`).then(e=>e.default),dev:()=>import(`./dev-DeOwxr_7.mjs`).then(e=>e.default),restore:()=>import(`./restore-CIBe2F1d.mjs`).then(e=>e.default),list:()=>import(`./list-DcREV9JM.mjs`).then(e=>e.default),status:()=>import(`./status-Dy-e_RtI.mjs`).then(e=>e.default),explain:()=>import(`./explain-BBv3U-D3.mjs`).then(e=>e.default),update:()=>import(`./update-Dacjzw4f.mjs`).then(e=>e.default),clean:()=>import(`./clean-DHh6fpmR.mjs`).then(e=>e.default),gc:()=>import(`./clean-DHh6fpmR.mjs`).then(e=>e.default),doctor:()=>import(`./doctor-XEdsr84Q.mjs`).then(e=>e.default),migrate:()=>import(`./migrate-DW5KQeDq.mjs`).then(e=>e.default),reset:()=>import(`./reset--AuvAPTc.mjs`).then(e=>e.default),rollback:()=>import(`./rollback-CFLIncnW.mjs`).then(e=>e.default),check:()=>import(`./check-Boh8WU_W.mjs`).then(e=>e.default)}});t(f);export{};
8
+ `)),console.log(r.cyan(` Local npm package development without symlinks`)),console.log(r.dim(` Copies built files into consumer node_modules with incremental sync
9
+ `))}process.env.UV_THREADPOOL_SIZE??=String(Math.max(a(),8)),n();const s=process.argv.slice(2),c=[`init`,`publish`,`add`,`use`,`remove`,`push`,`dev`,`restore`,`list`,`status`,`update`,`clean`,`gc`,`doctor`,`explain`,`migrate`,`reset`,`rollback`,`check`],l=s.some(e=>!e.startsWith(`-`)&&c.includes(e)),u=s.includes(`--help`)||s.includes(`-h`)||s.includes(`--version`);if(!l&&!u&&process.stdin.isTTY){o();let e=await d();e&&process.argv.splice(2,0,e)}else l||o();async function d(){try{let{readConsumerStateSafe:e}=await import(`./tracker-OhIA445x.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 f=t({meta:{name:`knarr`,version:`0.3.1`,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-KBwXbX7j.mjs`).then(e=>e.default),publish:()=>import(`./publish-PaTRQ5Ga.mjs`).then(e=>e.default),add:()=>import(`./add-CyrFHzUe.mjs`).then(e=>e.default),use:()=>import(`./use-BCXyvJf2.mjs`).then(e=>e.default),remove:()=>import(`./remove-DxezmGfU.mjs`).then(e=>e.default),push:()=>import(`./push-DX9dRKDw.mjs`).then(e=>e.default),dev:()=>import(`./dev-vA8K5egW.mjs`).then(e=>e.default),restore:()=>import(`./restore-B8aEJn3N.mjs`).then(e=>e.default),list:()=>import(`./list-BkniWIlD.mjs`).then(e=>e.default),status:()=>import(`./status-2-lE-2hH.mjs`).then(e=>e.default),explain:()=>import(`./explain-xtY13-Ex.mjs`).then(e=>e.default),update:()=>import(`./update-CjAl0ZO9.mjs`).then(e=>e.default),clean:()=>import(`./clean-oNr4nUNk.mjs`).then(e=>e.default),gc:()=>import(`./clean-oNr4nUNk.mjs`).then(e=>e.default),doctor:()=>import(`./doctor-ITFcIVoj.mjs`).then(e=>e.default),migrate:()=>import(`./migrate-DM80YXOF.mjs`).then(e=>e.default),reset:()=>import(`./reset-B9Xcepo1.mjs`).then(e=>e.default),rollback:()=>import(`./rollback-pqomySb-.mjs`).then(e=>e.default),check:()=>import(`./check-ChNlHxR5.mjs`).then(e=>e.default)}});e(f);export{};
@@ -0,0 +1,2 @@
1
+ import{i as e}from"./logger-Oo2Slehd.mjs";import{t}from"./fs-DusqxRQR.mjs";import{i as n,n as r,s as i}from"./json-1jsvqdBb.mjs";import{readFile as a}from"node:fs/promises";import{join as o}from"node:path";function s(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}async function c(t){try{let r=await a(o(t,`package.json`),`utf-8`),c=n(i(r,`package.json`),`knarr`);if(!c)return{};let l={};typeof c.buildCmd==`string`&&(l.buildCmd=c.buildCmd);let u=c.watchPatterns;Array.isArray(u)&&(l.watchPatterns=u.filter(e=>typeof e==`string`));let d=s(c.debounce);d!==void 0&&(l.debounce=d);let f=s(c.cooldown);f!==void 0&&(l.cooldown=f);let p=s(c.historyLimit);return p!==void 0&&(l.historyLimit=Math.max(0,Math.floor(p))),typeof c.notify==`boolean`&&(l.notify=c.notify),e(`[config] Loaded knarr config from package.json: ${JSON.stringify(l)}`),l}catch{return{}}}async function l(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))+`
2
+ `),!0)}export{l as n,c as t};
@@ -0,0 +1 @@
1
+ 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 i(t){return n=>e(t,String(n))}const a={bold:i(`bold`),dim:i(`dim`),cyan:i(`cyan`),green:i(`green`),red:i(`red`),yellow:i(`yellow`)};let o=3;async function s(e,i){if(!n.isTTY)return c(e,i);let o=t({input:n,output:r});try{if(i.type===`confirm`){let t=i.initial===!1?`y/N`:`Y/n`,n=(await o.question(`${a.cyan(`?`)} ${e} ${a.dim(`(${t})`)} `)).trim().toLowerCase();return n===``?i.initial!==!1:n===`y`||n===`yes`}if(i.type===`text`){let t=i.default?a.dim(` (${i.default})`):``;return(await o.question(`${a.cyan(`?`)} ${e}${t} `)).trim()||i.default||``}console.log(`${a.cyan(`?`)} ${e}`);for(let[e,t]of i.options.entries())console.log(` ${a.cyan(`${e+1}.`)} ${t.label}`);let t=await o.question(`${a.dim(`Enter number:`)} `),n=i.options[parseInt(t,10)-1]??i.options[0];if(!n)throw Error(`No options to choose from for "${e}"`);return n.value}finally{o.close()}}function c(e,t){if(t.type===`confirm`&&t.initial!==void 0)return console.error(`${a.cyan(`i`)} ${e} ${a.dim(`-> ${t.initial?`yes`:`no`} (no interactive terminal, using default)`)}`),t.initial;if(t.type===`text`)return t.default??``;console.error(`${a.red(`x`)} Cannot ask "${e}": no interactive terminal (stdin is not a TTY).`),console.error(`${a.cyan(`i`)} ${a.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 l={get level(){return o},set level(e){o=e},info(e,...t){o>=3&&console.log(a.cyan(`i`),e,...t)},success(e,...t){o>=3&&console.log(a.green(`OK`),e,...t)},warn(e,...t){o>=2&&console.warn(a.yellow(`!`),e,...t)},error(e,...t){o>=1&&console.error(a.red(`x`),e,...t)},start(e,...t){o>=3&&console.log(a.cyan(`...`),e,...t)},debug(e,...t){o>=4&&console.debug(a.dim(`D`),e,...t)},log(e,...t){o>=3&&console.log(e,...t)},prompt:s};export{a as n,l as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{n as t}from"./output-B7NC4xgj.mjs";import{a as n,i as r,o as i,s as a,t as o}from"./push-engine-ByiNZr52.mjs";import{t as s}from"./batch-push-Cee2SPW3.mjs";import{t as c}from"./config-D0TqqAAJ.mjs";import{n as l}from"./logger-Oo2Slehd.mjs";import{r as u}from"./dry-run-DPoN8bZo.mjs";import{resolve as d}from"node:path";var f=e({meta:{name:`dev`,description:`Watch, rebuild, and push to all consumers. Auto-detects build command.`},args:{all:{type:`boolean`,description:`Watch all workspace packages in dependency order`,default:!1},build:{type:`string`,description:`Override build command (default: auto-detect from package.json)`},"skip-build":{type:`boolean`,description:`Watch output dirs directly, skip build command detection`,default:!1},debounce:{type:`string`,description:`Debounce delay in ms (default: 500)`},cooldown:{type:`string`,description:`Minimum time between builds in ms (default: 500)`},"no-scripts":{type:`boolean`,description:`Skip prepack/postpack lifecycle hooks`,default:!1},force:{type:`boolean`,alias:`f`,description:`Force copy all files, bypassing hash comparison`,default:!1},notify:{type:`boolean`,description:`Ring terminal bell on push completion`,default:!1},"no-cascade":{type:`boolean`,description:`Disable cascading rebuilds in --all mode`,default:!1}},async run({args:e}){t();let f=d(`.`),p=await c(f),m={runScripts:!e[`no-scripts`],force:e.force,historyLimit:p.historyLimit};if(e.all){let t=await n(f,e),r=/* @__PURE__ */ new Set([...t.failedPackages,...t.skippedPackages]);if(t.canPush&&await s(f,{...m,skipPackages:r}),l()){u();return}await i(f,e,m)}else{let t=()=>o(f,m);if(await r(f,e,p)&&await t(),l()){u();return}await a(f,e,t)}}});export{f as default};
@@ -0,0 +1,5 @@
1
+ import{parseArgs as e}from"node:util";const t=/\d/,n=[`-`,`_`,`/`,`.`];function r(e=``){if(!t.test(e))return e!==e.toLowerCase()}function i(e,t){let i=t??n,a=[];if(!e||typeof e!=`string`)return a;let o=``,s,c;for(let t of e){let e=i.includes(t);if(e===!0){a.push(o),o=``,s=void 0;continue}let n=r(t);if(c===!1){if(s===!1&&n===!0){a.push(o),o=t,s=n;continue}if(s===!0&&n===!1&&o.length>1){let e=o.at(-1);a.push(o.slice(0,Math.max(0,o.length-1))),o=e+t,s=n;continue}}o+=t,s=n,c=e}return a.push(o),a}function a(e){return e?e[0].toUpperCase()+e.slice(1):``}function o(e){return e?e[0].toLowerCase()+e.slice(1):``}function s(e,t){return e?(Array.isArray(e)?e:i(e)).map(e=>a(t?.normalize?e.toLowerCase():e)).join(``):``}function c(e,t){return o(s(e||``,t))}function l(e,t){return e?(Array.isArray(e)?e:i(e)).map(e=>e.toLowerCase()).join(t??`-`):``}function u(e){return l(e||``,`_`)}function d(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function f(e,t=``){let n=[];for(let t of e)for(let[e,r]of t.entries())n[e]=Math.max(n[e]||0,r.length);return e.map(e=>e.map((e,r)=>t+e[r===0?`padStart`:`padEnd`](n[r])).join(` `)).join(`
2
+ `)}function p(e){return typeof e==`function`?e():e}var m=class extends Error{code;constructor(e,t){super(e),this.name=`CLIError`,this.code=t}};function h(t=[],n={}){let r=new Set(n.boolean||[]),i=new Set(n.string||[]),a=n.alias||{},o=n.default||{},s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(a)){let n=t;for(let t of n)s.set(e,t),c.has(t)||c.set(t,[]),c.get(t).push(e),s.set(t,e),c.has(e)||c.set(e,[]),c.get(e).push(t)}let l={};function u(e){if(r.has(e))return`boolean`;let t=c.get(e)||[];for(let e of t)if(r.has(e))return`boolean`;return`string`}function d(e){if(i.has(e))return!0;let t=c.get(e)||[];for(let e of t)if(i.has(e))return!0;return!1}let f=/* @__PURE__ */ new Set([...r,...i,...Object.keys(a),...Object.values(a).flat(),...Object.keys(o)]);for(let e of f)l[e]||(l[e]={type:u(e),default:o[e]});for(let[e,t]of s.entries())e.length===1&&l[t]&&!l[t].short&&(l[t].short=e);let p=[],m={};for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){p.push(...t.slice(e));break}if(n.startsWith(`--no-`)){let e=n.slice(5);m[e]=!0}else p.push(n)}let h;try{h=e({args:p,options:Object.keys(l).length>0?l:void 0,allowPositionals:!0,strict:!1})}catch{h={values:{},positionals:p}}let g={_:[]};g._=h.positionals;for(let[e,t]of Object.entries(h.values)){let n=t;u(e)===`boolean`&&typeof t==`string`?n=t!==`false`:d(e)&&typeof t==`boolean`&&(n=``),g[e]=n}for(let[e]of Object.entries(m)){g[e]=!1;let t=s.get(e);t&&(g[t]=!1);let n=c.get(e);if(n)for(let e of n)g[e]=!1}for(let[e,t]of s.entries())g[e]!==void 0&&g[t]===void 0&&(g[t]=g[e]),g[t]!==void 0&&g[e]===void 0&&(g[e]=g[t]),g[e]!==g[t]&&o[t]===g[t]&&(g[t]=g[e]);return g}const g=/* @__PURE__ */ (()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),_=(e,t=39)=>n=>g?n:`\u001B[${e}m${n}\u001B[${t}m`,v=/* @__PURE__ */ _(1,22),y=/* @__PURE__ */ _(36),b=/* @__PURE__ */ _(90),x=/* @__PURE__ */ _(4,24);function S(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=C(t);for(let e of r){if(e.type===`positional`)continue;e.type===`string`||e.type===`enum`?n.string.push(e.name):e.type===`boolean`&&n.boolean.push(e.name),e.default!==void 0&&(n.default[e.name]=e.default),e.alias&&(n.alias[e.name]=e.alias);let t=c(e.name),r=l(e.name);if(t!==e.name||r!==e.name){let i=d(n.alias[e.name]||[]);t!==e.name&&!i.includes(t)&&i.push(t),r!==e.name&&!i.includes(r)&&i.push(r),i.length>0&&(n.alias[e.name]=i)}}let i=h(e,n),[...a]=i._,o=new Proxy(i,{get(e,t){return e[t]??e[c(t)]??e[l(t)]}});for(let[,e]of r.entries())if(e.type===`positional`){let t=a.shift();if(t!==void 0)o[e.name]=t;else if(e.default===void 0&&e.required!==!1)throw new m(`Missing required positional argument: ${e.name.toUpperCase()}`,`EARG`);else o[e.name]=e.default}else if(e.type===`enum`){let t=o[e.name],n=e.options||[];if(t!==void 0&&n.length>0&&!n.includes(t))throw new m(`Invalid value for argument: ${y(`--${e.name}`)} (${y(t)}). Expected one of: ${n.map(e=>y(e)).join(`, `)}.`,`EARG`)}else if(e.required&&o[e.name]===void 0)throw new m(`Missing required argument: --${e.name}`,`EARG`);return o}function C(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:d(r.alias)});return t}async function w(e){return Promise.all(e.map(e=>p(e)))}function T(e){return e}async function E(e,t){let n=await p(e.args||{}),r=S(t.rawArgs,n),i={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},a=await w(e.plugins??[]),o,s;try{for(let e of a)await e.setup?.(i);typeof e.setup==`function`&&await e.setup(i);let r=await p(e.subCommands);if(r&&Object.keys(r).length>0){let i=k(t.rawArgs,n),a=t.rawArgs[i];if(a){let e=await O(r,a);if(!e)throw new m(`Unknown command ${y(a)}`,`E_UNKNOWN_COMMAND`);await E(e,{rawArgs:t.rawArgs.slice(i+1)})}else{let n=await p(e.default);if(n){if(e.run)throw new m(`Cannot specify both 'run' and 'default' on the same command.`,`E_DEFAULT_CONFLICT`);let i=await O(r,n);if(!i)throw new m(`Default sub command ${y(n)} not found in subCommands.`,`E_UNKNOWN_COMMAND`);await E(i,{rawArgs:t.rawArgs})}else if(!e.run)throw new m(`No command specified.`,`E_NO_COMMAND`)}}typeof e.run==`function`&&(o=await e.run(i))}catch(e){s=e}let c=[];if(typeof e.cleanup==`function`)try{await e.cleanup(i)}catch(e){c.push(e)}for(let e of[...a].reverse())try{await e.cleanup?.(i)}catch(e){c.push(e)}if(s)throw s;if(c.length===1)throw c[0];if(c.length>1)throw Error(`Multiple cleanup errors`,{cause:c});return{result:o}}async function D(e,t,n){let r=await p(e.subCommands);if(r&&Object.keys(r).length>0){let n=k(t,await p(e.args||{})),i=t[n],a=await O(r,i);if(a)return D(a,t.slice(n+1),e)}return[e,n]}async function O(e,t){if(t in e)return p(e[t]);for(let n of Object.values(e)){let e=await p(n),r=await p(e?.meta);if(r?.alias&&d(r.alias).includes(t))return e}}function k(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)return-1;if(r.startsWith(`-`))!r.includes(`=`)&&A(r,t)&&n++;else return n}return-1}function A(e,t){let n=e.replace(/^-{1,2}/,``),r=c(n);for(let[e,i]of Object.entries(t))if((i.type===`string`||i.type===`enum`)&&(r===c(e)||(Array.isArray(i.alias)?i.alias:i.alias?[i.alias]:[]).includes(n)))return!0;return!1}async function j(e,t){try{console.log(await N(e,t)+`
3
+ `)}catch(e){console.error(e)}}const M=/^no[-A-Z]/;async function N(e,t){let n=await p(e.meta||{}),r=C(await p(e.args||{})),i=await p(t?.meta||{}),a=`${i.name?`${i.name} `:``}`+(n.name||process.argv[1]),o=[],s=[],c=[],l=[];for(let e of r)if(e.type===`positional`){let t=e.name.toUpperCase(),n=e.required!==!1&&e.default===void 0;s.push([y(t+P(e)),F(e,n)]),l.push(n?`<${t}>`:`[${t}]`)}else{let t=e.required===!0&&e.default===void 0,n=[...(e.alias||[]).map(e=>`-${e}`),`--${e.name}`].join(`, `)+P(e);if(o.push([y(n),F(e,t)]),e.type===`boolean`&&(e.default===!0||e.negativeDescription)&&!M.test(e.name)){let n=[...(e.alias||[]).map(e=>`--no-${e}`),`--no-${e.name}`].join(`, `);o.push([y(n),[e.negativeDescription,t?b(`(Required)`):``].filter(Boolean).join(` `)])}t&&l.push(`--${e.name}`+P(e))}if(e.subCommands){let t=[],n=await p(e.subCommands);for(let[e,r]of Object.entries(n)){let n=await p((await p(r))?.meta);if(n?.hidden)continue;let i=d(n?.alias),a=[e,...i].join(`, `);c.push([y(a),n?.description||``]),t.push(e,...i)}l.push(t.join(`|`))}let u=[],m=n.version||i.version;u.push(b(`${n.description} (${a+(m?` v${m}`:``)})`),``);let h=o.length>0||s.length>0;return u.push(`${x(v(`USAGE`))} ${y(`${a}${h?` [OPTIONS]`:``} ${l.join(` `)}`)}`,``),s.length>0&&(u.push(x(v(`ARGUMENTS`)),``),u.push(f(s,` `)),u.push(``)),o.length>0&&(u.push(x(v(`OPTIONS`)),``),u.push(f(o,` `)),u.push(``)),c.length>0&&(u.push(x(v(`COMMANDS`)),``),u.push(f(c,` `)),u.push(``,`Use ${y(`${a} <command> --help`)} for more information about a command.`)),u.filter(e=>typeof e==`string`).join(`
4
+ `)}function P(e){let t=e.valueHint?`=<${e.valueHint}>`:``,n=t||`=<${u(e.name)}>`;return!e.type||e.type===`positional`||e.type===`boolean`?t:e.type===`enum`&&e.options?.length?`=<${e.options.join(`|`)}>`:n}function F(e,t){let n=t?b(`(Required)`):``,r=e.default===void 0?``:b(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(` `)}async function I(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||j;try{let t=await L(e);if(t.help.length>0&&n.some(e=>t.help.includes(e)))await r(...await D(e,n)),process.exit(0);else if(n.length===1&&t.version.includes(n[0])){let t=typeof e.meta==`function`?await e.meta():await e.meta;if(!t?.version)throw new m(`No version specified`,`E_NO_VERSION`);console.log(t.version)}else await E(e,{rawArgs:n})}catch(t){t instanceof m?(await r(...await D(e,n)),console.error(t.message)):console.error(t,`
5
+ `),process.exit(1)}}async function L(e){let t=await p(e.args||{}),n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;for(let[e,i]of Object.entries(t)){n.add(e);for(let e of d(i.alias))r.add(e)}return{help:R(`help`,`h`,n,r),version:R(`version`,`v`,n,r)}}function R(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}export{I as n,T as t};
@@ -0,0 +1,4 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{n as t,t as n}from"./console-C8XtlRyM.mjs";import{c as r,i,m as a,r as o,u as s}from"./tracker-nsfA6PWa.mjs";import{n as c,r as l}from"./store-CAzxNmpU.mjs";import{o as u}from"./injector-BMOi1uN3.mjs";import{c as d,u as f}from"./fs-DusqxRQR.mjs";import{a as ee,f as p,i as m,r as te}from"./paths-B5sEvS_7.mjs";import{t as h}from"./package-manager-Cs9kCsjJ.mjs";import{n as g}from"./bundler-detect-BaShXORS.mjs";import{a as ne,c as _,d as v,l as re,o as y,u as b}from"./init-helpers-DGSTVbNx.mjs";import{n as x,t as S}from"./output-B7NC4xgj.mjs";import{n as C,r as w}from"./logger-Oo2Slehd.mjs";import{r as T}from"./dry-run-DPoN8bZo.mjs";import{c as E,i as D,l as O}from"./json-1jsvqdBb.mjs";import{readFile as k,stat as A}from"node:fs/promises";import{basename as j,join as M,resolve as N}from"node:path";async function P(e,t={}){let n=[],f=C(),b=t.fix===!0,x=f?`Would `:``;async function S(e,t){let r={fixable:!1,fixed:!1,fixes:[],...e};if(b&&r.fixable&&t){let e=await t();e&&(r.fixed=!f,r.fixes.push(`${x}${e}`))}n.push(r)}let w=(await h(e)).resolve(),T=w.packageManager,k=!!w.nodeModulesCompatible,A="Yarn PnP has no node_modules tree for Knarr to manage. Set `nodeLinker: node-modules` or `nodeLinker: pnpm`, run `yarn install`, then re-run `knarr doctor --fix`.",N=p();await d(N)?await S({name:`Store directory`,status:`pass`,message:`${(await l()).length} entries in ${N}`}):await S({name:`Store directory`,status:`warn`,message:`Store not found at ${N}. Run 'knarr publish' to create it.`});let P=ee(),{registry:F,reliable:z}=await s();if(!z)await S({name:`Global registry`,status:`fail`,message:`${P} is corrupt or unreadable.`,unfixableReason:i()});else if(await d(P)){let e=Object.values(F).flat().length;await S({name:`Global registry`,status:`pass`,message:`${Object.keys(F).length} packages, ${e} consumer registrations`})}else await S({name:`Global registry`,status:`warn`,message:`No consumers registered yet. Use 'knarr add' to link packages.`});let V=await ie(F),H=V.missingDirectories+V.missingLinks;H>0&&await S({name:`Stale registry entries`,status:`warn`,message:`${H} stale consumer registration(s) found`+(V.unreadableConsumers>0?`; ${V.unreadableConsumers} unreadable state file(s) skipped`:``),fixable:!0},async()=>`remove ${(await o({removeMissingLinks:!0})).removedConsumers} stale consumer registration(s)`);let U=m(e),W=te(e),G=await L(W),K=await d(U),{state:q,reliable:J}=await r(e);if(G===`file`)await S({name:`Consumer state`,status:`fail`,message:`${W} exists but is not a directory.`,unfixableReason:`Move or delete ${W}, then run 'knarr init'.`}),J=!1;else if(K)J||await S({name:`Consumer state`,status:`fail`,message:`state.json is corrupt or unreadable. Delete .knarr/state.json and re-run 'knarr add' for each package.`,unfixableReason:`Corrupt state may contain links Knarr cannot safely reconstruct.`});else{let t={name:`Consumer state`,status:`warn`,message:`No .knarr/state.json found.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:A}};b&&t.fixable&&(await a(e,e=>{e.packageManager=T,e.role=`consumer`}),t.fixed=!f,t.fixes.push(`${x}create .knarr/state.json`),K=await d(U),{state:q,reliable:J}=await r(e)),n.push(t)}let Y=J?Object.entries(q.links):[];J&&K&&(Y.length>0?await S({name:`Consumer state`,status:`pass`,message:`${Y.length} linked package(s)`}):await S({name:`Consumer state`,status:`warn`,message:`No packages linked. Use 'knarr add' to link a package.`}));for(let[t,n]of Y){let r=await c(t,n.version);r?r.meta.contentHash===n.contentHash?await S({name:`Store: ${t}`,status:`pass`,message:`${t}@${n.version} in sync`}):await S({name:`Store: ${t}`,status:`warn`,message:`Store has newer content. Run 'knarr update' to sync.`}):await S({name:`Store: ${t}`,status:`fail`,message:`Store entry missing for ${t}@${n.version}. Re-publish it.`});let i;try{i=await u(e,t,n.packageManager,n.version,{warnOnFallback:!1})}catch(e){await S({name:`node_modules: ${t}`,status:`fail`,message:`Cannot resolve package target. ${e instanceof Error?e.message:String(e)}`});continue}if(!await d(i))await S({name:`node_modules: ${t}`,status:`fail`,message:`Missing from node_modules. Run 'knarr restore'.`});else try{let e=await E(M(i,`package.json`)),r=O(e,`name`),a=O(e,`version`);r&&r!==t?await S({name:`node_modules: ${t}`,status:`fail`,message:`node_modules target contains package "${r}". Run your package manager install, then 'knarr restore'.`}):a&&a!==n.version?await S({name:`node_modules: ${t}`,status:`warn`,message:`node_modules has v${a} but Knarr linked v${n.version}. Run 'knarr restore'.`}):await S({name:`node_modules: ${t}`,status:`pass`,message:`present`})}catch{await S({name:`node_modules: ${t}`,status:`pass`,message:`present`})}}await S({name:`Package manager`,status:`pass`,message:T}),w.yarnLinkerDiagnostic&&await S({name:`Yarn linker`,...w.yarnLinkerDiagnostic});let X=await g(e);if(X.type?await S({name:`Bundler`,status:`pass`,message:`${X.type}${X.configFile?` (${X.configFile})`:``}`}):await S({name:`Bundler`,status:`warn`,message:`No bundler config detected`}),X.type===`vite`&&X.configFile){let{addKnarrVitePlugin:e,hasKnarrVitePlugin:t}=await import(`./vite-config-B6bZDoGe.mjs`),r=await t(X.configFile);if(r.error)await S({name:`Vite integration`,status:`warn`,message:r.error});else if(r.configured)await S({name:`Vite integration`,status:`pass`,message:`Knarr plugin configured`});else{let t={name:`Vite integration`,status:`warn`,message:`Knarr Vite plugin is missing.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:A}};if(b&&t.fixable){let n=await e(X.configFile);n.modified?(t.fixed=!f,t.fixes.push(`${x}add Knarr Vite plugin to ${j(X.configFile)}`)):n.error&&(t.unfixableReason=n.error)}n.push(t)}}if(X.type===`next`&&X.configFile){let{addToTranspilePackages:e,hasTranspilePackage:t}=await import(`./nextjs-config-BlbmHmCb.mjs`);for(let[r]of Y){let i=await t(X.configFile,r);if(i.configured){await S({name:`Next.js integration: ${r}`,status:`pass`,message:`transpilePackages configured`});continue}let a={name:`Next.js integration: ${r}`,status:`warn`,message:`${r} is missing from transpilePackages.`,fixable:!i.error&&k,fixed:!1,fixes:[],...i.error?{unfixableReason:i.error}:k?{}:{unfixableReason:A}};if(b&&a.fixable){let t=await e(X.configFile,r);t.modified?(a.fixed=!f,a.fixes.push(`${x}add ${r} to transpilePackages in ${j(X.configFile)}`)):t.error&&(a.unfixableReason=t.error)}n.push(a)}}let Z=M(e,`.gitignore`);await I(Z)?await S({name:`.gitignore`,status:`pass`,message:`.knarr/ is ignored`}):await S({name:`.gitignore`,status:`warn`,message:`.knarr/ not in .gitignore.`,fixable:k,...k?{}:{unfixableReason:A}},async()=>await ne(Z)?`add .knarr/ to .gitignore`:null);let Q=M(e,`package.json`);if(await d(Q)){let t=await B(Q),n=t?D(t,`scripts`)?.postinstall:void 0;typeof n==`string`&&re(n)?await d(M(e,`.knarr`,`restore.cjs`))?await S({name:`Postinstall restore`,status:`pass`,message:`postinstall re-applies links via .knarr/restore.cjs`}):await S({name:`Postinstall restore`,status:`warn`,message:`.knarr/restore.cjs is missing, so installs won't re-apply links.`,fixable:k,...k?{}:{unfixableReason:A}},async()=>(await v(e),`write .knarr/restore.cjs`)):typeof n==`string`&&_(n)?await R(e,t,n)?await S({name:`Postinstall restore`,status:`pass`,message:`postinstall runs knarr restore`}):n.includes(`knarr restore --silent || node -e "process.exit(0)"`)?await S({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found, so installs silently drop links.`,fixable:k,...k?{}:{unfixableReason:A}},async()=>(await y(e),`upgrade postinstall restore hook (works without a global knarr)`)):await S({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found.`,unfixableReason:`Install knarr as a devDependency for reliable auto-restore, or ensure a global knarr binary is available during installs.`}):typeof n==`string`?await S({name:`Postinstall restore`,status:`warn`,message:`postinstall exists but does not run knarr restore.`,unfixableReason:`Existing postinstall scripts are not merged automatically.`}):await S({name:`Postinstall restore`,status:`warn`,message:`postinstall restore hook is missing.`,fixable:k,...k?{}:{unfixableReason:A}},async()=>(await y(e),`add postinstall restore hook to package.json`))}else await S({name:`Postinstall restore`,status:`warn`,message:`No package.json found.`});let[$=0,ae=0]=process.versions.node.split(`.`).map(e=>parseInt(e,10));return $>22||$===22&&ae>=22?await S({name:`Node.js version`,status:`pass`,message:`v${process.versions.node}`}):await S({name:`Node.js version`,status:`fail`,message:`v${process.versions.node}; Knarr requires Node.js >= 22.22`}),{results:n,failures:n.filter(e=>e.status===`fail`).length,warnings:n.filter(e=>e.status===`warn`).length,fixed:n.filter(e=>e.fixed).length,plannedFixes:f?n.reduce((e,t)=>e+t.fixes.length,0):0,dryRun:f}}var F=e({meta:{name:`doctor`,description:`Run diagnostic checks on your Knarr setup`},args:{fix:{type:`boolean`,description:`Apply safe automatic repairs`,default:!1}},async run({args:e}){x();let r=N(`.`);n.info(e.fix?`Running Knarr diagnostics with safe fixes...
2
+ `:`Running Knarr diagnostics...
3
+ `);let i=await P(r,{fix:e.fix}),a={pass:t.green(`PASS`),fail:t.red(`FAIL`),warn:t.yellow(`WARN`)};for(let e of i.results){n.log(` ${a[e.status]} ${e.name}: ${t.dim(e.message)}`);for(let r of e.fixes)n.log(` ${t.cyan(C()?`PLAN`:`FIX`)} ${t.dim(r)}`);e.unfixableReason&&n.log(` ${t.yellow(`!`)} ${t.dim(e.unfixableReason)}`)}n.log(``),i.plannedFixes>0?n.info(`${i.plannedFixes} fix(es) would be applied`):i.fixed>0&&n.success(`Applied ${i.fixed} fix(es)`),i.failures>0?n.error(`${i.failures} issue(s) found that need attention`):i.warnings>0?n.warn(`${i.warnings} warning(s), but no critical issues`):n.success(`All checks passed!`),S(i),e.fix&&C()&&!w()&&T()}});async function ie(e){let t=0,n=0,i=0;for(let[a,o]of Object.entries(e))for(let e of o){if(!await d(e)){t++;continue}let{state:o,reliable:s}=await r(e);s?o.links[a]||n++:i++}return{missingDirectories:t,missingLinks:n,unreadableConsumers:i}}async function I(e){try{return(await k(e,`utf-8`)).split(`
4
+ `).some(e=>{let t=e.trim();return t===`.knarr/`||t===`.knarr`||t===`/.knarr/`||t===`/.knarr`})}catch{return!1}}async function L(e){try{return(await A(e)).isDirectory()?`dir`:`file`}catch(e){return f(e)&&e.code===`ENOENT`?`missing`:`file`}}async function R(e,t,n){return b(n)||z(t)?!0:await d(M(e,`node_modules`,`.bin`,`knarr`))||await d(M(e,`node_modules`,`.bin`,`knarr.cmd`))}function z(e){return e?[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`].some(t=>D(e,t)?.knarr!==void 0):!1}async function B(e){try{return await E(e)}catch{return null}}export{F as default};
@@ -0,0 +1 @@
1
+ import{r as e}from"./logger-Oo2Slehd.mjs";import{t}from"./console-C8XtlRyM.mjs";import{homedir as n}from"node:os";import{isAbsolute as r,relative as i,sep as a}from"node:path";function o(e,t=process.cwd(),o=n()){let s=t=>{let n=i(t,e);return n!==``&&!n.startsWith(`..`)&&!r(n)?n:n===``?`.`:null},c=s(t);if(c!==null)return c;let l=s(o);return l===null?e:l===`.`?`~`:`~${a}${l}`}const s=[];let c=!1;function l(e){s.push(e)}function u(){return[...s]}function d(){c=!0}function f(){if(s.length===0){t.info(`[dry-run] No mutations would be performed`);return}if(e()){if(c)return;console.log(JSON.stringify({dryRun:!0,mutations:s},null,2)),c=!0;return}let n=/* @__PURE__ */ new Map;for(let e of s){let t=n.get(e.type);t||(t=[],n.set(e.type,t)),t.push(e)}t.info(`\n[dry-run] ${s.length} mutation(s) would be performed:\n`);let r={copy:`Copy`,remove:`Remove`,move:`Move`,mkdir:`Create directory`,write:`Write file`,"bin-link":`Create bin link`,"bin-unlink":`Remove bin link`,"cache-invalidate":`Invalidate cache`,"lock-skip":`Skip lock`,"lifecycle-skip":`Skip lifecycle hook`,"command-skip":`Skip command`};for(let[e,i]of n){t.info(` ${r[e]} (${i.length}):`);for(let e of i.slice(0,20)){let n=e.dest?` → ${o(e.dest)}`:``,r=e.detail?` (${e.detail})`:``;t.info(` ${o(e.path)}${n}${r}`)}i.length>20&&t.info(` ... and ${i.length-20} more`)}}function p(){s.length=0,c=!1}export{p as a,l as i,d as n,f as r,u as t};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./console-C8XtlRyM.mjs";const n=[{pattern:/not found in store/i,message:`Run 'knarr publish' in the package directory first, or use --from <path>.`},{pattern:/is not linked/i,message:`Run 'knarr add <package>' to link it first.`},{pattern:/No package\.json/i,message:`Make sure you're in a valid package directory with a package.json.`},{pattern:/missing 'name'/i,message:`Add a 'name' field to your package.json.`},{pattern:/missing 'version'/i,message:`Add a 'version' field to your package.json.`},{pattern:/store entry missing/i,message:`Re-publish the package with 'knarr publish'.`},{pattern:/EACCES|EPERM/i,message:`Permission denied. Try running with elevated privileges or check file ownership.`},{pattern:/ENOSPC/i,message:`Disk is full. Free up some space and try again.`},{pattern:/No publishable files/i,message:`Check the 'files' field in package.json, or ensure the build output exists.`},{pattern:/private.*package/i,message:`Use --private flag to publish private packages.`},{pattern:/Failed to read store entry/i,message:`The store may be corrupted. Try 'knarr clean' then re-publish.`},{pattern:/Failed to acquire lock/i,message:`Another Knarr process may be running. Wait or delete stale .lk directories.`},{pattern:/not a directory/i,message:`Check that the path exists and is a directory.`},{pattern:/timed out/i,message:`Set KNARR_HOOK_TIMEOUT to a higher value (in ms) if your scripts need more time.`},{pattern:/state.*corrupt|corrupt.*state/i,message:`Delete .knarr/state.json and re-run 'knarr add' for each package.`},{pattern:/EBUSY/i,message:`A file is locked by another process (e.g. dev server). Stop the process and retry.`},{pattern:/Invalid package name/i,message:`Package names must be non-empty. Use format: package-name or @scope/package-name.`}];function r(r){t.error(r);for(let{pattern:i,message:a}of n)if(i.test(r)){t.info(`${e.dim(`Suggestion:`)} ${a}`);break}}export{r as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./dist-jMqCJR3W.mjs";import{n as t,t as n}from"./console-C8XtlRyM.mjs";import{n as r,t as i}from"./store-CAzxNmpU.mjs";import{o as a}from"./injector-BMOi1uN3.mjs";import{c as o,l as s}from"./tracker-nsfA6PWa.mjs";import{t as c}from"./package-manager-Cs9kCsjJ.mjs";import{c as l}from"./fs-DusqxRQR.mjs";import{n as u,p as d,s as f}from"./paths-B5sEvS_7.mjs";import{n as p,t as m}from"./output-B7NC4xgj.mjs";import{c as h,l as g}from"./json-1jsvqdBb.mjs";import{join as _,resolve as v}from"node:path";async function y(e,t){let{state:n,reliable:r}=await o(e),i=(await c(e)).resolve().packageManager;if(!r)return{consumerPath:e,stateReliable:!1,packages:t?[await x(e,t,null,i,!1)]:[]};let a=t?[[t,n.links[t]??null]]:Object.entries(n.links);return{consumerPath:e,stateReliable:!0,packages:await Promise.all(a.map(([t,n])=>x(e,t,n,i,!0)))}}var b=e({meta:{name:`explain`,description:`Explain linked package state and suggested recovery actions`},args:{package:{type:`positional`,description:`Package name to explain (default: all linked packages)`,required:!1}},async run({args:e}){p();let r=await y(v(`.`),e.package);if(!r.stateReliable)n.error(`Consumer state is corrupt or unreadable`),n.info(`Delete .knarr/state.json and re-run 'knarr add' for each package.`);else if(!r.packages[0])n.info(`No linked packages in this project`);else if(e.package)S(r.packages[0]);else{n.info(`Linked packages (${r.packages.length}):\n`);for(let e of r.packages){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`!`):t.red(`FAIL`),i=e.version?t.dim(`@${e.version}`):t.dim(`(not linked)`),a=e.buildId?t.dim(` [${e.buildId}]`):``;n.log(` ${r} ${t.cyan(e.name)} ${i}${a}`),n.log(` ${t.dim(e.summary)}`)}n.log(``),n.info(`Run ${t.cyan(`knarr explain <package>`)} for details.`)}m(r)}});async function x(e,t,n,c,p){let m=n?await r(t,n.version):await i(t),h=(await s())[t]??[],g=d(e),_=[];p||_.push(`consumer state is corrupt or unreadable`),n||_.push(`package is not linked in this project`);let v=n?.sourcePath??m?.meta.sourcePath??null,y=v?await l(v):null;v&&y===!1&&_.push(`source directory missing: ${v}`),m?n&&m.meta.contentHash!==n.contentHash&&_.push(`store has newer content than the current link`):_.push(n?`store entry missing for ${t}@${n.version}`:`package not found in store`);let b=f(e,t),x=n?await a(e,t,n.packageManager,n.version,{warnOnFallback:!1}):b,S=await l(x),E=S?await T(x):null;n&&!S?_.push(`package is missing from node_modules`):n&&E&&E!==n.version&&_.push(`node_modules has v${E} but link expects v${n.version}`);let D=n?u(e,t):null,O=D?await l(D):!1;n?.backupExists&&!O&&_.push(`backup is recorded but missing on disk`);let k=await Promise.all(h.map(async e=>{if(!await l(e))return{path:e,exists:!1,stateReliable:null,hasLink:null};let{state:n,reliable:r}=await o(e);return{path:e,exists:!0,stateReliable:r,hasLink:r?!!n.links[t]:null}}));return n&&!h.includes(g)&&_.push(`current project is not registered for pushes`),{name:t,status:_.some(e=>e.includes(`corrupt`)||e.includes(`missing from node_modules`)||e.includes(`store entry missing`)||e.includes(`not linked`))?`fail`:_.length>0?`warn`:`ok`,summary:C(t,n,_),suggestedAction:w(t,n,_,v),linked:!!n,version:n?.version??m?.version??null,buildId:n?.buildId||m?.meta.buildId||null,sourcePath:v,sourceExists:y,packageManager:n?.packageManager??c,store:{exists:!!m,path:m?.packageDir??null,contentHash:m?.meta.contentHash??null,matchesLink:n&&m?m.meta.contentHash===n.contentHash:null,publishedAt:m?.meta.publishedAt??null},nodeModules:{path:b,targetPath:x,exists:S,packageVersion:E},backup:{expected:n?.backupExists??!1,exists:O,path:D},consumers:k,issues:_}}function S(e){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`WARN`):t.red(`FAIL`);if(n.info(`${r} ${t.cyan(e.name)} ${t.dim(e.summary)}\n`),n.log(` Version: ${e.version??`(not linked)`}`),n.log(` Build ID: ${e.buildId??`(none)`}`),n.log(` Package manager: ${e.packageManager}`),n.log(` Source: ${e.sourcePath??`(unknown)`}${e.sourceExists===!1?` (missing)`:``}`),n.log(` Store: ${e.store.exists?e.store.path:`(missing)`}`),e.store.matchesLink!==null&&n.log(` Content hash: ${e.store.matchesLink?`matches link`:`differs from link`}`),n.log(` node_modules: ${e.nodeModules.targetPath}${e.nodeModules.exists?``:` (missing)`}`),n.log(` Backup: ${e.backup.expected?e.backup.exists?`present`:`missing`:`not recorded`}`),n.log(` Registered consumers: ${e.consumers.length}`),e.issues.length>0){n.log(``);for(let r of e.issues)n.log(` ${t.yellow(`!`)} ${r}`)}n.log(``),n.info(`Suggested action: ${e.suggestedAction}`)}function C(e,t,n){return t?n.length===0?`link, store, and node_modules are in sync`:n[0]??`link, store, and node_modules are in sync`:`${e} is not linked in this project`}function w(e,t,n,r){return n.some(e=>e.includes(`corrupt`))?`Delete .knarr/state.json and re-run 'knarr add' for each package.`:t?n.some(e=>e.includes(`store entry missing`))?r?`Run 'knarr publish' in ${r}, then 'knarr restore'.`:`Re-publish the package, then run 'knarr restore'.`:n.some(e=>e.includes(`newer content`))?`Run 'knarr update ${e}'.`:n.some(e=>e.includes(`node_modules`))?`Run 'knarr restore'.`:n.some(e=>e.includes(`not registered`))?`Run 'knarr add ${e}' again to refresh registration.`:n.some(e=>e.includes(`source directory`))?`Check the source path or re-run 'knarr use <path>'.`:`No action needed.`:`Run 'knarr add ${e}' or 'knarr use <path>'.`}async function T(e){try{let t=await h(_(e,`package.json`));return g(t,`version`)??null}catch{return null}}export{b as default};