giget 1.2.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -19,3 +19,166 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ ---
24
+
25
+ Third party bundled dependencies
26
+
27
+ - https://github.com/isaacs/node-tar
28
+ - https://github.com/isaacs/fs-minipass
29
+
30
+ """
31
+ The ISC License
32
+
33
+ Copyright (c) Isaac Z. Schlueter and Contributors
34
+
35
+ Permission to use, copy, modify, and/or distribute this software for any
36
+ purpose with or without fee is hereby granted, provided that the above
37
+ copyright notice and this permission notice appear in all copies.
38
+
39
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
40
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
41
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
42
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
43
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
44
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
45
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
46
+ """"
47
+
48
+ - https://github.com/isaacs/minipass
49
+
50
+ """
51
+ The ISC License
52
+
53
+ Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors
54
+
55
+ Permission to use, copy, modify, and/or distribute this software for any
56
+ purpose with or without fee is hereby granted, provided that the above
57
+ copyright notice and this permission notice appear in all copies.
58
+
59
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
60
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
61
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
62
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
63
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
64
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
65
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
66
+ """
67
+
68
+ - https://github.com/isaacs/minizlib
69
+
70
+ """
71
+ Minizlib was created by Isaac Z. Schlueter.
72
+ It is a derivative work of the Node.js project.
73
+
74
+ """
75
+ Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
76
+ Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
77
+ Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.
78
+
79
+ Permission is hereby granted, free of charge, to any person obtaining a
80
+ copy of this software and associated documentation files (the "Software"),
81
+ to deal in the Software without restriction, including without limitation
82
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
83
+ and/or sell copies of the Software, and to permit persons to whom the
84
+ Software is furnished to do so, subject to the following conditions:
85
+
86
+ The above copyright notice and this permission notice shall be included in
87
+ all copies or substantial portions of the Software.
88
+
89
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
90
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
91
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
92
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
93
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
94
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
95
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
96
+ """
97
+
98
+ - https://github.com/isaacs/node-mkdirp
99
+
100
+ """
101
+ Copyright (c) 2011-2023 James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)
102
+
103
+ This project is free software released under the MIT license:
104
+
105
+ Permission is hereby granted, free of charge, to any person obtaining a copy
106
+ of this software and associated documentation files (the "Software"), to deal
107
+ in the Software without restriction, including without limitation the rights
108
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
109
+ copies of the Software, and to permit persons to whom the Software is
110
+ furnished to do so, subject to the following conditions:
111
+
112
+ The above copyright notice and this permission notice shall be included in
113
+ all copies or substantial portions of the Software.
114
+
115
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
116
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
117
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
118
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
119
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
120
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
121
+ THE SOFTWARE.
122
+ """
123
+
124
+ - https://github.com/isaacs/yallist/blob/main/LICENSE.md
125
+ - https://github.com/isaacs/chownr/blob/main/LICENSE.md
126
+
127
+ """
128
+
129
+ # Blue Oak Model License
130
+
131
+ Version 1.0.0
132
+
133
+ ## Purpose
134
+
135
+ This license gives everyone as much permission to work with
136
+ this software as possible, while protecting contributors
137
+ from liability.
138
+
139
+ ## Acceptance
140
+
141
+ In order to receive this license, you must agree to its
142
+ rules. The rules of this license are both obligations
143
+ under that agreement and conditions to your license.
144
+ You must not do anything with this software that triggers
145
+ a rule that you cannot or will not follow.
146
+
147
+ ## Copyright
148
+
149
+ Each contributor licenses you to do everything with this
150
+ software that would otherwise infringe that contributor's
151
+ copyright in it.
152
+
153
+ ## Notices
154
+
155
+ You must ensure that everyone who gets a copy of
156
+ any part of this software from you, with or without
157
+ changes, also gets the text of this license or a link to
158
+ <https://blueoakcouncil.org/license/1.0.0>.
159
+
160
+ ## Excuse
161
+
162
+ If anyone notifies you in writing that you have not
163
+ complied with [Notices](#notices), you can keep your
164
+ license by taking all practical steps to comply within 30
165
+ days after the notice. If you do not do so, your license
166
+ ends immediately.
167
+
168
+ ## Patent
169
+
170
+ Each contributor licenses you to do everything with this
171
+ software that would otherwise infringe any patent claims
172
+ they can license or become able to license.
173
+
174
+ ## Reliability
175
+
176
+ No contributor can revoke this license.
177
+
178
+ ## No Liability
179
+
180
+ **_As far as the law allows, this software comes as is,
181
+ without any warranty or condition, and no contributor
182
+ will be liable to anyone for any damages related to this
183
+ software or this license, under any kind of legal claim._**
184
+ """
package/README.md CHANGED
@@ -8,6 +8,8 @@
8
8
 
9
9
  ## Features
10
10
 
11
+ ✨ Zero dependency
12
+
11
13
  ✨ Support popular git providers (GitHub, GitLab, Bitbucket, Sourcehut) out of the box.
12
14
 
13
15
  ✨ Built-in and custom [template registry](#template-registry).
@@ -24,8 +26,6 @@
24
26
 
25
27
  ✨ Optionally install dependencies after clone using [unjs/nypm](https://github.com/unjs/nypm)
26
28
 
27
- ✨ HTTP proxy support and native fetch via [unjs/node-fetch-native](https://github.com/unjs/node-fetch-native)
28
-
29
29
  ## Usage (CLI)
30
30
 
31
31
  ```bash
@@ -216,14 +216,14 @@ If your project depends on a private GitHub repository, you need to add the acce
216
216
  GIGET_AUTH: ${{ secrets.GIGET_AUTH }}
217
217
  ```
218
218
 
219
-
220
219
  ## Related projects
221
220
 
222
221
  Giget wouldn't be possible without inspiration from former projects. In comparison, giget does not depend on any local command which increases stability and performance and supports custom template providers, auth, and many more features out of the box.
223
222
 
224
- - https://github.com/samsonjs/gitter
225
- - https://github.com/tiged/tiged
226
- - https://github.com/Rich-Harris/degit
223
+ - [tiged/tiged](https://github.com/tiged/tiged) (maintained fork of degit)
224
+ - [nrjdalal/gitpick](https://github.com/nrjdalal/gitpick) (alternative approach)
225
+ - [Rich-Harris/degit](https://github.com/Rich-Harris/degit) (last updated - 2021)
226
+ - [samsonjs/gitter](https://github.com/samsonjs/gitter) (archived/updated - 2012)
227
227
 
228
228
  ## 💻 Development
229
229
 
@@ -0,0 +1,271 @@
1
+ import { t as extract } from "./libs/tar.mjs";
2
+ import { a as resolve, i as relative, n as basename, r as dirname, t as installDependencies } from "./libs/nypm.mjs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { createWriteStream, existsSync, readdirSync, renameSync } from "node:fs";
5
+ import { pipeline } from "node:stream";
6
+ import { spawnSync } from "node:child_process";
7
+ import { homedir, tmpdir } from "node:os";
8
+ import { promisify } from "node:util";
9
+
10
+ //#region src/_utils.ts
11
+ async function download(url, filePath, options = {}) {
12
+ const infoPath = filePath + ".json";
13
+ const info = JSON.parse(await readFile(infoPath, "utf8").catch(() => "{}"));
14
+ const etag = (await sendFetch(url, {
15
+ method: "HEAD",
16
+ headers: options.headers
17
+ }).catch(() => void 0))?.headers.get("etag");
18
+ if (info.etag === etag && existsSync(filePath)) return;
19
+ if (typeof etag === "string") info.etag = etag;
20
+ const response = await sendFetch(url, { headers: options.headers });
21
+ if (response.status >= 400) throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);
22
+ const stream = createWriteStream(filePath);
23
+ await promisify(pipeline)(response.body, stream);
24
+ await writeFile(infoPath, JSON.stringify(info), "utf8");
25
+ }
26
+ const inputRegex = /^(?<repo>[\w.-]+\/[\w.-]+)(?<subdir>[^#]+)?(?<ref>#[\w./@-]+)?/;
27
+ function parseGitURI(input) {
28
+ const m = input.match(inputRegex)?.groups || {};
29
+ return {
30
+ repo: m.repo || "",
31
+ subdir: m.subdir || "/",
32
+ ref: m.ref ? m.ref.slice(1) : "main"
33
+ };
34
+ }
35
+ function debug(...args) {
36
+ if (process.env.DEBUG) console.debug("[giget]", ...args);
37
+ }
38
+ async function sendFetch(url, options = {}) {
39
+ if (options.headers?.["sec-fetch-mode"]) options.mode = options.headers["sec-fetch-mode"];
40
+ const res = await fetch(url, {
41
+ ...options,
42
+ headers: normalizeHeaders(options.headers)
43
+ }).catch((error) => {
44
+ throw new Error(`Failed to download ${url}: ${error}`, { cause: error });
45
+ });
46
+ if (options.validateStatus && res.status >= 400) throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`);
47
+ return res;
48
+ }
49
+ function cacheDirectory() {
50
+ const cacheDir = process.env.XDG_CACHE_HOME ? resolve(process.env.XDG_CACHE_HOME, "giget") : resolve(homedir(), ".cache/giget");
51
+ if (process.platform === "win32") {
52
+ const windowsCacheDir = resolve(tmpdir(), "giget");
53
+ if (!existsSync(windowsCacheDir) && existsSync(cacheDir)) try {
54
+ renameSync(cacheDir, windowsCacheDir);
55
+ } catch {}
56
+ return windowsCacheDir;
57
+ }
58
+ return cacheDir;
59
+ }
60
+ function normalizeHeaders(headers = {}) {
61
+ const normalized = {};
62
+ for (const [key, value] of Object.entries(headers)) {
63
+ if (!value) continue;
64
+ normalized[key.toLowerCase()] = value;
65
+ }
66
+ return normalized;
67
+ }
68
+ function currentShell() {
69
+ if (process.env.SHELL) return process.env.SHELL;
70
+ if (process.platform === "win32") return "cmd.exe";
71
+ return "/bin/bash";
72
+ }
73
+ function startShell(cwd) {
74
+ cwd = resolve(cwd);
75
+ const shell = currentShell();
76
+ console.info(`(experimental) Opening shell in ${relative(process.cwd(), cwd)}...`);
77
+ spawnSync(shell, [], {
78
+ cwd,
79
+ shell: true,
80
+ stdio: "inherit"
81
+ });
82
+ }
83
+
84
+ //#endregion
85
+ //#region src/providers.ts
86
+ const http = async (input, options) => {
87
+ if (input.endsWith(".json")) return await _httpJSON(input, options);
88
+ const url = new URL(input);
89
+ let name = basename(url.pathname);
90
+ try {
91
+ const head = await sendFetch(url.href, {
92
+ method: "HEAD",
93
+ validateStatus: true,
94
+ headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
95
+ });
96
+ if ((head.headers.get("content-type") || "").includes("application/json")) return await _httpJSON(input, options);
97
+ const filename = head.headers.get("content-disposition")?.match(/filename="?(.+)"?/)?.[1];
98
+ if (filename) name = filename.split(".")[0];
99
+ } catch (error) {
100
+ debug(`Failed to fetch HEAD for ${url.href}:`, error);
101
+ }
102
+ return {
103
+ name: `${name}-${url.href.slice(0, 8)}`,
104
+ version: "",
105
+ subdir: "",
106
+ tar: url.href,
107
+ defaultDir: name,
108
+ headers: { Authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
109
+ };
110
+ };
111
+ const _httpJSON = async (input, options) => {
112
+ const info = await (await sendFetch(input, {
113
+ validateStatus: true,
114
+ headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
115
+ })).json();
116
+ if (!info.tar || !info.name) throw new Error(`Invalid template info from ${input}. name or tar fields are missing!`);
117
+ return info;
118
+ };
119
+ const github = (input, options) => {
120
+ const parsed = parseGitURI(input);
121
+ const githubAPIURL = process.env.GIGET_GITHUB_URL || "https://api.github.com";
122
+ return {
123
+ name: parsed.repo.replace("/", "-"),
124
+ version: parsed.ref,
125
+ subdir: parsed.subdir,
126
+ headers: {
127
+ Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
128
+ Accept: "application/vnd.github+json",
129
+ "X-GitHub-Api-Version": "2022-11-28"
130
+ },
131
+ url: `${githubAPIURL.replace("api.github.com", "github.com")}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
132
+ tar: `${githubAPIURL}/repos/${parsed.repo}/tarball/${parsed.ref}`
133
+ };
134
+ };
135
+ const gitlab = (input, options) => {
136
+ const parsed = parseGitURI(input);
137
+ const gitlab = process.env.GIGET_GITLAB_URL || "https://gitlab.com";
138
+ return {
139
+ name: parsed.repo.replace("/", "-"),
140
+ version: parsed.ref,
141
+ subdir: parsed.subdir,
142
+ headers: {
143
+ authorization: options.auth ? `Bearer ${options.auth}` : void 0,
144
+ "sec-fetch-mode": "same-origin"
145
+ },
146
+ url: `${gitlab}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
147
+ tar: `${gitlab}/${parsed.repo}/-/archive/${parsed.ref}.tar.gz`
148
+ };
149
+ };
150
+ const bitbucket = (input, options) => {
151
+ const parsed = parseGitURI(input);
152
+ return {
153
+ name: parsed.repo.replace("/", "-"),
154
+ version: parsed.ref,
155
+ subdir: parsed.subdir,
156
+ headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 },
157
+ url: `https://bitbucket.com/${parsed.repo}/src/${parsed.ref}${parsed.subdir}`,
158
+ tar: `https://bitbucket.org/${parsed.repo}/get/${parsed.ref}.tar.gz`
159
+ };
160
+ };
161
+ const sourcehut = (input, options) => {
162
+ const parsed = parseGitURI(input);
163
+ return {
164
+ name: parsed.repo.replace("/", "-"),
165
+ version: parsed.ref,
166
+ subdir: parsed.subdir,
167
+ headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 },
168
+ url: `https://git.sr.ht/~${parsed.repo}/tree/${parsed.ref}/item${parsed.subdir}`,
169
+ tar: `https://git.sr.ht/~${parsed.repo}/archive/${parsed.ref}.tar.gz`
170
+ };
171
+ };
172
+ const providers = {
173
+ http,
174
+ https: http,
175
+ github,
176
+ gh: github,
177
+ gitlab,
178
+ bitbucket,
179
+ sourcehut
180
+ };
181
+
182
+ //#endregion
183
+ //#region src/registry.ts
184
+ const DEFAULT_REGISTRY = "https://raw.githubusercontent.com/unjs/giget/main/templates";
185
+ const registryProvider = (registryEndpoint = DEFAULT_REGISTRY, options = {}) => {
186
+ return (async (input) => {
187
+ const start = Date.now();
188
+ const registryURL = `${registryEndpoint}/${input}.json`;
189
+ const result = await sendFetch(registryURL, { headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 } });
190
+ if (result.status >= 400) throw new Error(`Failed to download ${input} template info from ${registryURL}: ${result.status} ${result.statusText}`);
191
+ const info = await result.json();
192
+ if (!info.tar || !info.name) throw new Error(`Invalid template info from ${registryURL}. name or tar fields are missing!`);
193
+ debug(`Fetched ${input} template info from ${registryURL} in ${Date.now() - start}ms`);
194
+ return info;
195
+ });
196
+ };
197
+
198
+ //#endregion
199
+ //#region src/giget.ts
200
+ const sourceProtoRe = /^([\w-.]+):/;
201
+ async function downloadTemplate(input, options = {}) {
202
+ options.registry = process.env.GIGET_REGISTRY ?? options.registry;
203
+ options.auth = process.env.GIGET_AUTH ?? options.auth;
204
+ const registry = options.registry === false ? void 0 : registryProvider(options.registry, { auth: options.auth });
205
+ let providerName = options.provider || (registry ? "registry" : "github");
206
+ let source = input;
207
+ const sourceProviderMatch = input.match(sourceProtoRe);
208
+ if (sourceProviderMatch) {
209
+ providerName = sourceProviderMatch[1];
210
+ source = input.slice(sourceProviderMatch[0].length);
211
+ if (providerName === "http" || providerName === "https") source = input;
212
+ }
213
+ const provider = options.providers?.[providerName] || providers[providerName] || registry;
214
+ if (!provider) throw new Error(`Unsupported provider: ${providerName}`);
215
+ const template = await Promise.resolve().then(() => provider(source, { auth: options.auth })).catch((error) => {
216
+ throw new Error(`Failed to download template from ${providerName}: ${error.message}`);
217
+ });
218
+ if (!template) throw new Error(`Failed to resolve template from ${providerName}`);
219
+ template.name = (template.name || "template").replace(/[^\da-z-]/gi, "-");
220
+ template.defaultDir = (template.defaultDir || template.name).replace(/[^\da-z-]/gi, "-");
221
+ const tarPath = resolve(resolve(cacheDirectory(), providerName, template.name), (template.version || template.name) + ".tar.gz");
222
+ if (options.preferOffline && existsSync(tarPath)) options.offline = true;
223
+ if (!options.offline) {
224
+ await mkdir(dirname(tarPath), { recursive: true });
225
+ const s$1 = Date.now();
226
+ await download(template.tar, tarPath, { headers: {
227
+ Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
228
+ ...normalizeHeaders(template.headers)
229
+ } }).catch((error) => {
230
+ if (!existsSync(tarPath)) throw error;
231
+ debug("Download error. Using cached version:", error);
232
+ options.offline = true;
233
+ });
234
+ debug(`Downloaded ${template.tar} to ${tarPath} in ${Date.now() - s$1}ms`);
235
+ }
236
+ if (!existsSync(tarPath)) throw new Error(`Tarball not found: ${tarPath} (offline: ${options.offline})`);
237
+ const extractPath = resolve(resolve(options.cwd || "."), options.dir || template.defaultDir);
238
+ if (options.forceClean) await rm(extractPath, {
239
+ recursive: true,
240
+ force: true
241
+ });
242
+ if (!options.force && existsSync(extractPath) && readdirSync(extractPath).length > 0) throw new Error(`Destination ${extractPath} already exists.`);
243
+ await mkdir(extractPath, { recursive: true });
244
+ const s = Date.now();
245
+ const subdir = template.subdir?.replace(/^\//, "") || "";
246
+ await extract({
247
+ file: tarPath,
248
+ cwd: extractPath,
249
+ onReadEntry(entry) {
250
+ entry.path = entry.path.split("/").splice(1).join("/");
251
+ if (subdir) if (entry.path.startsWith(subdir + "/")) entry.path = entry.path.slice(subdir.length);
252
+ else entry.path = "";
253
+ }
254
+ });
255
+ debug(`Extracted to ${extractPath} in ${Date.now() - s}ms`);
256
+ if (options.install) {
257
+ debug("Installing dependencies...");
258
+ await installDependencies({
259
+ cwd: extractPath,
260
+ silent: options.silent
261
+ });
262
+ }
263
+ return {
264
+ ...template,
265
+ source,
266
+ dir: extractPath
267
+ };
268
+ }
269
+
270
+ //#endregion
271
+ export { registryProvider as n, startShell as r, downloadTemplate as t };
@@ -0,0 +1 @@
1
+ import EE from"events";import fs from"fs";import{EventEmitter as EventEmitter$1}from"node:events";import Stream from"node:stream";import{StringDecoder}from"node:string_decoder";const proc=typeof process==`object`&&process?process:{stdout:null,stderr:null},isStream=_=>!!_&&typeof _==`object`&&(_ instanceof Minipass||_ instanceof Stream||isReadable(_)||isWritable(_)),isReadable=_=>!!_&&typeof _==`object`&&_ instanceof EventEmitter$1&&typeof _.pipe==`function`&&_.pipe!==Stream.Writable.prototype.pipe,isWritable=_=>!!_&&typeof _==`object`&&_ instanceof EventEmitter$1&&typeof _.write==`function`&&typeof _.end==`function`,EOF=Symbol(`EOF`),MAYBE_EMIT_END=Symbol(`maybeEmitEnd`),EMITTED_END=Symbol(`emittedEnd`),EMITTING_END=Symbol(`emittingEnd`),EMITTED_ERROR=Symbol(`emittedError`),CLOSED=Symbol(`closed`),READ=Symbol(`read`),FLUSH=Symbol(`flush`),FLUSHCHUNK=Symbol(`flushChunk`),ENCODING=Symbol(`encoding`),DECODER=Symbol(`decoder`),FLOWING=Symbol(`flowing`),PAUSED=Symbol(`paused`),RESUME=Symbol(`resume`),BUFFER=Symbol(`buffer`),PIPES=Symbol(`pipes`),BUFFERLENGTH=Symbol(`bufferLength`),BUFFERPUSH=Symbol(`bufferPush`),BUFFERSHIFT=Symbol(`bufferShift`),OBJECTMODE=Symbol(`objectMode`),DESTROYED=Symbol(`destroyed`),ERROR=Symbol(`error`),EMITDATA=Symbol(`emitData`),EMITEND=Symbol(`emitEnd`),EMITEND2=Symbol(`emitEnd2`),ASYNC=Symbol(`async`),ABORT=Symbol(`abort`),ABORTED=Symbol(`aborted`),SIGNAL=Symbol(`signal`),DATALISTENERS=Symbol(`dataListeners`),DISCARDED=Symbol(`discarded`),defer=_=>Promise.resolve().then(_),nodefer=_=>_(),isEndish=_=>_===`end`||_===`finish`||_===`prefinish`,isArrayBufferLike=_=>_ instanceof ArrayBuffer||!!_&&typeof _==`object`&&_.constructor&&_.constructor.name===`ArrayBuffer`&&_.byteLength>=0,isArrayBufferView=_=>!Buffer.isBuffer(_)&&ArrayBuffer.isView(_);var Pipe=class{src;dest;opts;ondrain;constructor(_,K,q){this.src=_,this.dest=K,this.opts=q,this.ondrain=()=>_[RESUME](),this.dest.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(_){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},PipeProxyErrors=class extends Pipe{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(_,K,q){super(_,K,q),this.proxyErrors=_=>K.emit(`error`,_),_.on(`error`,this.proxyErrors)}};const isObjectModeOptions=_=>!!_.objectMode,isEncodingOptions=_=>!_.objectMode&&!!_.encoding&&_.encoding!==`buffer`;var Minipass=class extends EventEmitter$1{[FLOWING]=!1;[PAUSED]=!1;[PIPES]=[];[BUFFER]=[];[OBJECTMODE];[ENCODING];[ASYNC];[DECODER];[EOF]=!1;[EMITTED_END]=!1;[EMITTING_END]=!1;[CLOSED]=!1;[EMITTED_ERROR]=null;[BUFFERLENGTH]=0;[DESTROYED]=!1;[SIGNAL];[ABORTED]=!1;[DATALISTENERS]=0;[DISCARDED]=!1;writable=!0;readable=!0;constructor(..._){let K=_[0]||{};if(super(),K.objectMode&&typeof K.encoding==`string`)throw TypeError(`Encoding and objectMode may not be used together`);isObjectModeOptions(K)?(this[OBJECTMODE]=!0,this[ENCODING]=null):isEncodingOptions(K)?(this[ENCODING]=K.encoding,this[OBJECTMODE]=!1):(this[OBJECTMODE]=!1,this[ENCODING]=null),this[ASYNC]=!!K.async,this[DECODER]=this[ENCODING]?new StringDecoder(this[ENCODING]):null,K&&K.debugExposeBuffer===!0&&Object.defineProperty(this,`buffer`,{get:()=>this[BUFFER]}),K&&K.debugExposePipes===!0&&Object.defineProperty(this,`pipes`,{get:()=>this[PIPES]});let{signal:q}=K;q&&(this[SIGNAL]=q,q.aborted?this[ABORT]():q.addEventListener(`abort`,()=>this[ABORT]()))}get bufferLength(){return this[BUFFERLENGTH]}get encoding(){return this[ENCODING]}set encoding(_){throw Error(`Encoding must be set at instantiation time`)}setEncoding(_){throw Error(`Encoding must be set at instantiation time`)}get objectMode(){return this[OBJECTMODE]}set objectMode(_){throw Error(`objectMode must be set at instantiation time`)}get async(){return this[ASYNC]}set async(_){this[ASYNC]=this[ASYNC]||!!_}[ABORT](){this[ABORTED]=!0,this.emit(`abort`,this[SIGNAL]?.reason),this.destroy(this[SIGNAL]?.reason)}get aborted(){return this[ABORTED]}set aborted(_){}write(_,K,q){if(this[ABORTED])return!1;if(this[EOF])throw Error(`write after end`);if(this[DESTROYED])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof K==`function`&&(q=K,K=`utf8`),K||=`utf8`;let J=this[ASYNC]?defer:nodefer;if(!this[OBJECTMODE]&&!Buffer.isBuffer(_)){if(isArrayBufferView(_))_=Buffer.from(_.buffer,_.byteOffset,_.byteLength);else if(isArrayBufferLike(_))_=Buffer.from(_);else if(typeof _!=`string`)throw Error(`Non-contiguous data written to non-objectMode stream`)}return this[OBJECTMODE]?(this[FLOWING]&&this[BUFFERLENGTH]!==0&&this[FLUSH](!0),this[FLOWING]?this.emit(`data`,_):this[BUFFERPUSH](_),this[BUFFERLENGTH]!==0&&this.emit(`readable`),q&&J(q),this[FLOWING]):_.length?(typeof _==`string`&&!(K===this[ENCODING]&&!this[DECODER]?.lastNeed)&&(_=Buffer.from(_,K)),Buffer.isBuffer(_)&&this[ENCODING]&&(_=this[DECODER].write(_)),this[FLOWING]&&this[BUFFERLENGTH]!==0&&this[FLUSH](!0),this[FLOWING]?this.emit(`data`,_):this[BUFFERPUSH](_),this[BUFFERLENGTH]!==0&&this.emit(`readable`),q&&J(q),this[FLOWING]):(this[BUFFERLENGTH]!==0&&this.emit(`readable`),q&&J(q),this[FLOWING])}read(_){if(this[DESTROYED])return null;if(this[DISCARDED]=!1,this[BUFFERLENGTH]===0||_===0||_&&_>this[BUFFERLENGTH])return this[MAYBE_EMIT_END](),null;this[OBJECTMODE]&&(_=null),this[BUFFER].length>1&&!this[OBJECTMODE]&&(this[BUFFER]=[this[ENCODING]?this[BUFFER].join(``):Buffer.concat(this[BUFFER],this[BUFFERLENGTH])]);let K=this[READ](_||null,this[BUFFER][0]);return this[MAYBE_EMIT_END](),K}[READ](_,K){if(this[OBJECTMODE])this[BUFFERSHIFT]();else{let q=K;_===q.length||_===null?this[BUFFERSHIFT]():typeof q==`string`?(this[BUFFER][0]=q.slice(_),K=q.slice(0,_),this[BUFFERLENGTH]-=_):(this[BUFFER][0]=q.subarray(_),K=q.subarray(0,_),this[BUFFERLENGTH]-=_)}return this.emit(`data`,K),!this[BUFFER].length&&!this[EOF]&&this.emit(`drain`),K}end(_,K,q){return typeof _==`function`&&(q=_,_=void 0),typeof K==`function`&&(q=K,K=`utf8`),_!==void 0&&this.write(_,K),q&&this.once(`end`,q),this[EOF]=!0,this.writable=!1,(this[FLOWING]||!this[PAUSED])&&this[MAYBE_EMIT_END](),this}[RESUME](){this[DESTROYED]||(!this[DATALISTENERS]&&!this[PIPES].length&&(this[DISCARDED]=!0),this[PAUSED]=!1,this[FLOWING]=!0,this.emit(`resume`),this[BUFFER].length?this[FLUSH]():this[EOF]?this[MAYBE_EMIT_END]():this.emit(`drain`))}resume(){return this[RESUME]()}pause(){this[FLOWING]=!1,this[PAUSED]=!0,this[DISCARDED]=!1}get destroyed(){return this[DESTROYED]}get flowing(){return this[FLOWING]}get paused(){return this[PAUSED]}[BUFFERPUSH](_){this[OBJECTMODE]?this[BUFFERLENGTH]+=1:this[BUFFERLENGTH]+=_.length,this[BUFFER].push(_)}[BUFFERSHIFT](){return this[OBJECTMODE]?--this[BUFFERLENGTH]:this[BUFFERLENGTH]-=this[BUFFER][0].length,this[BUFFER].shift()}[FLUSH](_=!1){do;while(this[FLUSHCHUNK](this[BUFFERSHIFT]())&&this[BUFFER].length);!_&&!this[BUFFER].length&&!this[EOF]&&this.emit(`drain`)}[FLUSHCHUNK](_){return this.emit(`data`,_),this[FLOWING]}pipe(_,K){if(this[DESTROYED])return _;this[DISCARDED]=!1;let q=this[EMITTED_END];return K||={},_===proc.stdout||_===proc.stderr?K.end=!1:K.end=K.end!==!1,K.proxyErrors=!!K.proxyErrors,q?K.end&&_.end():(this[PIPES].push(K.proxyErrors?new PipeProxyErrors(this,_,K):new Pipe(this,_,K)),this[ASYNC]?defer(()=>this[RESUME]()):this[RESUME]()),_}unpipe(_){let K=this[PIPES].find(K=>K.dest===_);K&&(this[PIPES].length===1?(this[FLOWING]&&this[DATALISTENERS]===0&&(this[FLOWING]=!1),this[PIPES]=[]):this[PIPES].splice(this[PIPES].indexOf(K),1),K.unpipe())}addListener(_,K){return this.on(_,K)}on(_,K){let q=super.on(_,K);if(_===`data`)this[DISCARDED]=!1,this[DATALISTENERS]++,!this[PIPES].length&&!this[FLOWING]&&this[RESUME]();else if(_===`readable`&&this[BUFFERLENGTH]!==0)super.emit(`readable`);else if(isEndish(_)&&this[EMITTED_END])super.emit(_),this.removeAllListeners(_);else if(_===`error`&&this[EMITTED_ERROR]){let _=K;this[ASYNC]?defer(()=>_.call(this,this[EMITTED_ERROR])):_.call(this,this[EMITTED_ERROR])}return q}removeListener(_,K){return this.off(_,K)}off(_,K){let q=super.off(_,K);return _===`data`&&(this[DATALISTENERS]=this.listeners(`data`).length,this[DATALISTENERS]===0&&!this[DISCARDED]&&!this[PIPES].length&&(this[FLOWING]=!1)),q}removeAllListeners(_){let K=super.removeAllListeners(_);return(_===`data`||_===void 0)&&(this[DATALISTENERS]=0,!this[DISCARDED]&&!this[PIPES].length&&(this[FLOWING]=!1)),K}get emittedEnd(){return this[EMITTED_END]}[MAYBE_EMIT_END](){!this[EMITTING_END]&&!this[EMITTED_END]&&!this[DESTROYED]&&this[BUFFER].length===0&&this[EOF]&&(this[EMITTING_END]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[CLOSED]&&this.emit(`close`),this[EMITTING_END]=!1)}emit(_,...K){let q=K[0];if(_!==`error`&&_!==`close`&&_!==DESTROYED&&this[DESTROYED])return!1;if(_===`data`)return!this[OBJECTMODE]&&!q?!1:this[ASYNC]?(defer(()=>this[EMITDATA](q)),!0):this[EMITDATA](q);if(_===`end`)return this[EMITEND]();if(_===`close`){if(this[CLOSED]=!0,!this[EMITTED_END]&&!this[DESTROYED])return!1;let _=super.emit(`close`);return this.removeAllListeners(`close`),_}else if(_===`error`){this[EMITTED_ERROR]=q,super.emit(ERROR,q);let _=!this[SIGNAL]||this.listeners(`error`).length?super.emit(`error`,q):!1;return this[MAYBE_EMIT_END](),_}else if(_===`resume`){let _=super.emit(`resume`);return this[MAYBE_EMIT_END](),_}else if(_===`finish`||_===`prefinish`){let K=super.emit(_);return this.removeAllListeners(_),K}let J=super.emit(_,...K);return this[MAYBE_EMIT_END](),J}[EMITDATA](_){for(let K of this[PIPES])K.dest.write(_)===!1&&this.pause();let K=this[DISCARDED]?!1:super.emit(`data`,_);return this[MAYBE_EMIT_END](),K}[EMITEND](){return this[EMITTED_END]?!1:(this[EMITTED_END]=!0,this.readable=!1,this[ASYNC]?(defer(()=>this[EMITEND2]()),!0):this[EMITEND2]())}[EMITEND2](){if(this[DECODER]){let _=this[DECODER].end();if(_){for(let K of this[PIPES])K.dest.write(_);this[DISCARDED]||super.emit(`data`,_)}}for(let _ of this[PIPES])_.end();let _=super.emit(`end`);return this.removeAllListeners(`end`),_}async collect(){let _=Object.assign([],{dataLength:0});this[OBJECTMODE]||(_.dataLength=0);let K=this.promise();return this.on(`data`,K=>{_.push(K),this[OBJECTMODE]||(_.dataLength+=K.length)}),await K,_}async concat(){if(this[OBJECTMODE])throw Error(`cannot concat in objectMode`);let _=await this.collect();return this[ENCODING]?_.join(``):Buffer.concat(_,_.dataLength)}async promise(){return new Promise((_,K)=>{this.on(DESTROYED,()=>K(Error(`stream destroyed`))),this.on(`error`,_=>K(_)),this.on(`end`,()=>_())})}[Symbol.asyncIterator](){this[DISCARDED]=!1;let _=!1,K=async()=>(this.pause(),_=!0,{value:void 0,done:!0});return{next:()=>{if(_)return K();let q=this.read();if(q!==null)return Promise.resolve({done:!1,value:q});if(this[EOF])return K();let J,Y,X=_=>{this.off(`data`,Z),this.off(`end`,Q),this.off(DESTROYED,$),K(),Y(_)},Z=_=>{this.off(`error`,X),this.off(`end`,Q),this.off(DESTROYED,$),this.pause(),J({value:_,done:!!this[EOF]})},Q=()=>{this.off(`error`,X),this.off(`data`,Z),this.off(DESTROYED,$),K(),J({done:!0,value:void 0})},$=()=>X(Error(`stream destroyed`));return new Promise((_,K)=>{Y=K,J=_,this.once(DESTROYED,$),this.once(`error`,X),this.once(`end`,Q),this.once(`data`,Z)})},throw:K,return:K,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[DISCARDED]=!1;let _=!1,K=()=>(this.pause(),this.off(ERROR,K),this.off(DESTROYED,K),this.off(`end`,K),_=!0,{done:!0,value:void 0});return this.once(`end`,K),this.once(ERROR,K),this.once(DESTROYED,K),{next:()=>{if(_)return K();let q=this.read();return q===null?K():{done:!1,value:q}},throw:K,return:K,[Symbol.iterator](){return this}}}destroy(_){if(this[DESTROYED])return _?this.emit(`error`,_):this.emit(DESTROYED),this;this[DESTROYED]=!0,this[DISCARDED]=!0,this[BUFFER].length=0,this[BUFFERLENGTH]=0;let K=this;return typeof K.close==`function`&&!this[CLOSED]&&K.close(),_?this.emit(`error`,_):this.emit(DESTROYED),this}static get isStream(){return isStream}};const writev=fs.writev,_autoClose=Symbol(`_autoClose`),_close=Symbol(`_close`),_ended=Symbol(`_ended`),_fd=Symbol(`_fd`),_finished=Symbol(`_finished`),_flags=Symbol(`_flags`),_flush=Symbol(`_flush`),_handleChunk=Symbol(`_handleChunk`),_makeBuf=Symbol(`_makeBuf`),_mode=Symbol(`_mode`),_needDrain=Symbol(`_needDrain`),_onerror=Symbol(`_onerror`),_onopen=Symbol(`_onopen`),_onread=Symbol(`_onread`),_onwrite=Symbol(`_onwrite`),_open=Symbol(`_open`),_path=Symbol(`_path`),_pos=Symbol(`_pos`),_queue=Symbol(`_queue`),_read=Symbol(`_read`),_readSize=Symbol(`_readSize`),_reading=Symbol(`_reading`),_remain=Symbol(`_remain`),_size=Symbol(`_size`),_write=Symbol(`_write`),_writing=Symbol(`_writing`),_defaultFlag=Symbol(`_defaultFlag`),_errored=Symbol(`_errored`);var ReadStream=class extends Minipass{[_errored]=!1;[_fd];[_path];[_readSize];[_reading]=!1;[_size];[_remain];[_autoClose];constructor(_,K){if(K||={},super(K),this.readable=!0,this.writable=!1,typeof _!=`string`)throw TypeError(`path must be a string`);this[_errored]=!1,this[_fd]=typeof K.fd==`number`?K.fd:void 0,this[_path]=_,this[_readSize]=K.readSize||16*1024*1024,this[_reading]=!1,this[_size]=typeof K.size==`number`?K.size:1/0,this[_remain]=this[_size],this[_autoClose]=typeof K.autoClose==`boolean`?K.autoClose:!0,typeof this[_fd]==`number`?this[_read]():this[_open]()}get fd(){return this[_fd]}get path(){return this[_path]}write(){throw TypeError(`this is a readable stream`)}end(){throw TypeError(`this is a readable stream`)}[_open](){fs.open(this[_path],`r`,(_,K)=>this[_onopen](_,K))}[_onopen](_,K){_?this[_onerror](_):(this[_fd]=K,this.emit(`open`,K),this[_read]())}[_makeBuf](){return Buffer.allocUnsafe(Math.min(this[_readSize],this[_remain]))}[_read](){if(!this[_reading]){this[_reading]=!0;let _=this[_makeBuf]();if(_.length===0)return process.nextTick(()=>this[_onread](null,0,_));fs.read(this[_fd],_,0,_.length,null,(_,K,q)=>this[_onread](_,K,q))}}[_onread](_,K,q){this[_reading]=!1,_?this[_onerror](_):this[_handleChunk](K,q)&&this[_read]()}[_close](){if(this[_autoClose]&&typeof this[_fd]==`number`){let _=this[_fd];this[_fd]=void 0,fs.close(_,_=>_?this.emit(`error`,_):this.emit(`close`))}}[_onerror](_){this[_reading]=!0,this[_close](),this.emit(`error`,_)}[_handleChunk](_,K){let q=!1;return this[_remain]-=_,_>0&&(q=super.write(_<K.length?K.subarray(0,_):K)),(_===0||this[_remain]<=0)&&(q=!1,this[_close](),super.end()),q}emit(_,...K){switch(_){case`prefinish`:case`finish`:return!1;case`drain`:return typeof this[_fd]==`number`&&this[_read](),!1;case`error`:return this[_errored]?!1:(this[_errored]=!0,super.emit(_,...K));default:return super.emit(_,...K)}}},ReadStreamSync=class extends ReadStream{[_open](){let _=!0;try{this[_onopen](null,fs.openSync(this[_path],`r`)),_=!1}finally{_&&this[_close]()}}[_read](){let _=!0;try{if(!this[_reading]){this[_reading]=!0;do{let _=this[_makeBuf](),q=_.length===0?0:fs.readSync(this[_fd],_,0,_.length,null);if(!this[_handleChunk](q,_))break}while(!0);this[_reading]=!1}_=!1}finally{_&&this[_close]()}}[_close](){if(this[_autoClose]&&typeof this[_fd]==`number`){let _=this[_fd];this[_fd]=void 0,fs.closeSync(_),this.emit(`close`)}}},WriteStream=class extends EE{readable=!1;writable=!0;[_errored]=!1;[_writing]=!1;[_ended]=!1;[_queue]=[];[_needDrain]=!1;[_path];[_mode];[_autoClose];[_fd];[_defaultFlag];[_flags];[_finished]=!1;[_pos];constructor(_,K){K||={},super(K),this[_path]=_,this[_fd]=typeof K.fd==`number`?K.fd:void 0,this[_mode]=K.mode===void 0?438:K.mode,this[_pos]=typeof K.start==`number`?K.start:void 0,this[_autoClose]=typeof K.autoClose==`boolean`?K.autoClose:!0;let q=this[_pos]===void 0?`w`:`r+`;this[_defaultFlag]=K.flags===void 0,this[_flags]=K.flags===void 0?q:K.flags,this[_fd]===void 0&&this[_open]()}emit(_,...K){if(_===`error`){if(this[_errored])return!1;this[_errored]=!0}return super.emit(_,...K)}get fd(){return this[_fd]}get path(){return this[_path]}[_onerror](_){this[_close](),this[_writing]=!0,this.emit(`error`,_)}[_open](){fs.open(this[_path],this[_flags],this[_mode],(_,K)=>this[_onopen](_,K))}[_onopen](_,K){this[_defaultFlag]&&this[_flags]===`r+`&&_&&_.code===`ENOENT`?(this[_flags]=`w`,this[_open]()):_?this[_onerror](_):(this[_fd]=K,this.emit(`open`,K),this[_writing]||this[_flush]())}end(_,K){return _&&this.write(_,K),this[_ended]=!0,!this[_writing]&&!this[_queue].length&&typeof this[_fd]==`number`&&this[_onwrite](null,0),this}write(_,K){return typeof _==`string`&&(_=Buffer.from(_,K)),this[_ended]?(this.emit(`error`,Error(`write() after end()`)),!1):this[_fd]===void 0||this[_writing]||this[_queue].length?(this[_queue].push(_),this[_needDrain]=!0,!1):(this[_writing]=!0,this[_write](_),!0)}[_write](_){fs.write(this[_fd],_,0,_.length,this[_pos],(_,K)=>this[_onwrite](_,K))}[_onwrite](_,K){_?this[_onerror](_):(this[_pos]!==void 0&&typeof K==`number`&&(this[_pos]+=K),this[_queue].length?this[_flush]():(this[_writing]=!1,this[_ended]&&!this[_finished]?(this[_finished]=!0,this[_close](),this.emit(`finish`)):this[_needDrain]&&(this[_needDrain]=!1,this.emit(`drain`))))}[_flush](){if(this[_queue].length===0)this[_ended]&&this[_onwrite](null,0);else if(this[_queue].length===1)this[_write](this[_queue].pop());else{let _=this[_queue];this[_queue]=[],writev(this[_fd],_,this[_pos],(_,K)=>this[_onwrite](_,K))}}[_close](){if(this[_autoClose]&&typeof this[_fd]==`number`){let _=this[_fd];this[_fd]=void 0,fs.close(_,_=>_?this.emit(`error`,_):this.emit(`close`))}}},WriteStreamSync=class extends WriteStream{[_open](){let _;if(this[_defaultFlag]&&this[_flags]===`r+`)try{_=fs.openSync(this[_path],this[_flags],this[_mode])}catch(_){if(_?.code===`ENOENT`)return this[_flags]=`w`,this[_open]();throw _}else _=fs.openSync(this[_path],this[_flags],this[_mode]);this[_onopen](null,_)}[_close](){if(this[_autoClose]&&typeof this[_fd]==`number`){let _=this[_fd];this[_fd]=void 0,fs.closeSync(_),this.emit(`close`)}}[_write](_){let q=!0;try{this[_onwrite](null,fs.writeSync(this[_fd],_,0,_.length,this[_pos])),q=!1}finally{if(q)try{this[_close]()}catch{}}}};export{Minipass as a,WriteStreamSync as i,ReadStreamSync as n,WriteStream as r,ReadStream as t};
@@ -0,0 +1 @@
1
+ import fs from"node:fs";import path from"node:path";const lchownSync=(t,n,r)=>{try{return fs.lchownSync(t,n,r)}catch(e){if(e?.code!==`ENOENT`)throw e}},chown=(t,n,r,i)=>{fs.lchown(t,n,r,e=>{i(e&&e?.code!==`ENOENT`?e:null)})},chownrKid=(e,n,i,o,s)=>{n.isDirectory()?chownr(path.resolve(e,n.name),i,o,a=>{if(a)return s(a);chown(path.resolve(e,n.name),i,o,s)}):chown(path.resolve(e,n.name),i,o,s)},chownr=(t,n,a,o)=>{fs.readdir(t,{withFileTypes:!0},(e,s)=>{if(e){if(e.code===`ENOENT`)return o();if(e.code!==`ENOTDIR`&&e.code!==`ENOTSUP`)return o(e)}if(e||!s.length)return chown(t,n,a,o);let c=s.length,l=null,u=e=>{if(!l){if(e)return o(l=e);if(--c===0)return chown(t,n,a,o)}};for(let e of s)chownrKid(t,e,n,a,u)})},chownrKidSync=(e,r,i,a)=>{r.isDirectory()&&chownrSync(path.resolve(e,r.name),i,a),lchownSync(path.resolve(e,r.name),i,a)},chownrSync=(t,r,i)=>{let a;try{a=fs.readdirSync(t,{withFileTypes:!0})}catch(e){let a=e;if(a?.code===`ENOENT`)return;if(a?.code===`ENOTDIR`||a?.code===`ENOTSUP`)return lchownSync(t,r,i);throw a}for(let e of a)chownrKidSync(t,e,r,i);return lchownSync(t,r,i)};export{chownrSync as n,chownr as t};
@@ -0,0 +1,5 @@
1
+ import{parseArgs}from"node:util";const NUMBER_CHAR_RE=/\d/,STR_SPLITTERS=[`-`,`_`,`/`,`.`];function isUppercase(e=``){if(!NUMBER_CHAR_RE.test(e))return e!==e.toLowerCase()}function splitByCase(e,h){let v=h??STR_SPLITTERS,y=[];if(!e||typeof e!=`string`)return y;let b=``,x,S;for(let h of e){let e=v.includes(h);if(e===!0){y.push(b),b=``,x=void 0;continue}let g=isUppercase(h);if(S===!1){if(x===!1&&g===!0){y.push(b),b=h,x=g;continue}if(x===!0&&g===!1&&b.length>1){let e=b.at(-1);y.push(b.slice(0,Math.max(0,b.length-1))),b=e+h,x=g;continue}}b+=h,x=g,S=e}return y.push(b),y}function upperFirst(e){return e?e[0].toUpperCase()+e.slice(1):``}function lowerFirst(e){return e?e[0].toLowerCase()+e.slice(1):``}function pascalCase(e,h){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>upperFirst(h?.normalize?e.toLowerCase():e)).join(``):``}function camelCase(e,h){return lowerFirst(pascalCase(e||``,h))}function kebabCase(e,h){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>e.toLowerCase()).join(h??`-`):``}function toArray(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function formatLineColumns(e,h=``){let g=[];for(let h of e)for(let[e,_]of h.entries())g[e]=Math.max(g[e]||0,_.length);return e.map(e=>e.map((e,_)=>h+e[_===0?`padStart`:`padEnd`](g[_])).join(` `)).join(`
2
+ `)}function resolveValue(e){return typeof e==`function`?e():e}var CLIError=class extends Error{code;constructor(e,h){super(e),this.name=`CLIError`,this.code=h}};function parseRawArgs(h=[],g={}){let _=new Set(g.boolean||[]),v=new Set(g.string||[]),y=g.alias||{},b=g.default||{},x=new Map,S=new Map;for(let[e,h]of Object.entries(y)){let g=h;for(let h of g)x.set(e,h),S.has(h)||S.set(h,[]),S.get(h).push(e),x.set(h,e),S.has(e)||S.set(e,[]),S.get(e).push(h)}let C={};function w(e){if(_.has(e))return`boolean`;let h=S.get(e)||[];for(let e of h)if(_.has(e))return`boolean`;return`string`}let T=new Set([..._,...v,...Object.keys(y),...Object.values(y).flat(),...Object.keys(b)]);for(let e of T)C[e]||(C[e]={type:w(e),default:b[e]});for(let[e,h]of x.entries())e.length===1&&C[h]&&!C[h].short&&(C[h].short=e);let E=[],D={};for(let e=0;e<h.length;e++){let g=h[e];if(g===`--`){E.push(...h.slice(e));break}if(g.startsWith(`--no-`)){let e=g.slice(5);D[e]=!0;continue}E.push(g)}let O;try{O=parseArgs({args:E,options:Object.keys(C).length>0?C:void 0,allowPositionals:!0,strict:!1})}catch{O={values:{},positionals:E}}let k={_:[]};k._=O.positionals;for(let[e,h]of Object.entries(O.values))k[e]=h;for(let[e]of Object.entries(D))k[e]=!1;for(let[e,h]of x.entries())k[e]!==void 0&&k[h]===void 0&&(k[h]=k[e]),k[h]!==void 0&&k[e]===void 0&&(k[e]=k[h]);return k}const noColor=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),_c=(e,h=39)=>g=>noColor?g:`\u001B[${e}m${g}\u001B[${h}m`,bold=_c(1,22),cyan=_c(36),gray=_c(90),underline=_c(4,24);function parseArgs$1(e,h){let g={boolean:[],string:[],alias:{},default:{}},_=resolveArgs(h);for(let e of _){if(e.type===`positional`)continue;e.type===`string`||e.type===`enum`?g.string.push(e.name):e.type===`boolean`&&g.boolean.push(e.name),e.default!==void 0&&(g.default[e.name]=e.default),e.alias&&(g.alias[e.name]=e.alias);let h=camelCase(e.name),_=kebabCase(e.name);if(h!==e.name||_!==e.name){let v=toArray(g.alias[e.name]||[]);h!==e.name&&!v.includes(h)&&v.push(h),_!==e.name&&!v.includes(_)&&v.push(_),v.length>0&&(g.alias[e.name]=v)}}let v=parseRawArgs(e,g),[...y]=v._,b=new Proxy(v,{get(e,h){return e[h]??e[camelCase(h)]??e[kebabCase(h)]}});for(let[,e]of _.entries())if(e.type===`positional`){let h=y.shift();if(h!==void 0)b[e.name]=h;else if(e.default===void 0&&e.required!==!1)throw new CLIError(`Missing required positional argument: ${e.name.toUpperCase()}`,`EARG`);else b[e.name]=e.default}else if(e.type===`enum`){let h=b[e.name],g=e.options||[];if(h!==void 0&&g.length>0&&!g.includes(h))throw new CLIError(`Invalid value for argument: ${cyan(`--${e.name}`)} (${cyan(h)}). Expected one of: ${g.map(e=>cyan(e)).join(`, `)}.`,`EARG`)}else if(e.required&&b[e.name]===void 0)throw new CLIError(`Missing required argument: --${e.name}`,`EARG`);return b}function resolveArgs(e){let h=[];for(let[g,_]of Object.entries(e||{}))h.push({..._,name:g,alias:toArray(_.alias)});return h}function defineCommand(e){return e}async function runCommand(e,h){let g=await resolveValue(e.args||{}),_=parseArgs$1(h.rawArgs,g),v={rawArgs:h.rawArgs,args:_,data:h.data,cmd:e};typeof e.setup==`function`&&await e.setup(v);let y;try{let g=await resolveValue(e.subCommands);if(g&&Object.keys(g).length>0){let _=h.rawArgs.findIndex(e=>!e.startsWith(`-`)),v=h.rawArgs[_];if(v){if(!g[v])throw new CLIError(`Unknown command ${cyan(v)}`,`E_UNKNOWN_COMMAND`);let e=await resolveValue(g[v]);e&&await runCommand(e,{rawArgs:h.rawArgs.slice(_+1)})}else if(!e.run)throw new CLIError(`No command specified.`,`E_NO_COMMAND`)}typeof e.run==`function`&&(y=await e.run(v))}finally{typeof e.cleanup==`function`&&await e.cleanup(v)}return{result:y}}async function resolveSubCommand(e,h,g){let _=await resolveValue(e.subCommands);if(_&&Object.keys(_).length>0){let g=h.findIndex(e=>!e.startsWith(`-`)),v=h[g],y=await resolveValue(_[v]);if(y)return resolveSubCommand(y,h.slice(g+1),e)}return[e,g]}async function showUsage(e,h){try{console.log(await renderUsage(e,h)+`
3
+ `)}catch(e){console.error(e)}}const negativePrefixRe=/^no[-A-Z]/;async function renderUsage(e,h){let g=await resolveValue(e.meta||{}),_=resolveArgs(await resolveValue(e.args||{})),v=await resolveValue(h?.meta||{}),y=`${v.name?`${v.name} `:``}`+(g.name||process.argv[1]),b=[],x=[],S=[],C=[];for(let e of _)if(e.type===`positional`){let h=e.name.toUpperCase(),g=e.required!==!1&&e.default===void 0,_=e.default?`="${e.default}"`:``;x.push([cyan(h+_),e.description||``,e.valueHint?`<${e.valueHint}>`:``]),C.push(g?`<${h}>`:`[${h}]`)}else{let h=e.required===!0&&e.default===void 0,g=[...(e.alias||[]).map(e=>`-${e}`),`--${e.name}`].join(`, `)+(e.type===`string`&&(e.valueHint||e.default)?`=${e.valueHint?`<${e.valueHint}>`:`"${e.default||``}"`}`:``)+(e.type===`enum`&&e.options?`=<${e.options.join(`|`)}>`:``);if(b.push([cyan(g+(h?` (required)`:``)),e.description||``]),e.type===`boolean`&&(e.default===!0||e.negativeDescription)&&!negativePrefixRe.test(e.name)){let g=[...(e.alias||[]).map(e=>`--no-${e}`),`--no-${e.name}`].join(`, `);b.push([cyan(g+(h?` (required)`:``)),e.negativeDescription||``])}h&&C.push(g)}if(e.subCommands){let h=[],g=await resolveValue(e.subCommands);for(let[e,_]of Object.entries(g)){let g=await resolveValue((await resolveValue(_))?.meta);g?.hidden||(S.push([cyan(e),g?.description||``]),h.push(e))}C.push(h.join(`|`))}let w=[],D=g.version||v.version;w.push(gray(`${g.description} (${y+(D?` v${D}`:``)})`),``);let O=b.length>0||x.length>0;return w.push(`${underline(bold(`USAGE`))} ${cyan(`${y}${O?` [OPTIONS]`:``} ${C.join(` `)}`)}`,``),x.length>0&&(w.push(underline(bold(`ARGUMENTS`)),``),w.push(formatLineColumns(x,` `)),w.push(``)),b.length>0&&(w.push(underline(bold(`OPTIONS`)),``),w.push(formatLineColumns(b,` `)),w.push(``)),S.length>0&&(w.push(underline(bold(`COMMANDS`)),``),w.push(formatLineColumns(S,` `)),w.push(``,`Use ${cyan(`${y} <command> --help`)} for more information about a command.`)),w.filter(e=>typeof e==`string`).join(`
4
+ `)}async function runMain(e,h={}){let g=h.rawArgs||process.argv.slice(2),_=h.showUsage||showUsage;try{if(g.includes(`--help`)||g.includes(`-h`))await _(...await resolveSubCommand(e,g)),process.exit(0);else if(g.length===1&&g[0]===`--version`){let h=typeof e.meta==`function`?await e.meta():await e.meta;if(!h?.version)throw new CLIError(`No version specified`,`E_NO_VERSION`);console.log(h.version)}else await runCommand(e,{rawArgs:g})}catch(h){h instanceof CLIError?(await _(...await resolveSubCommand(e,g)),console.error(h.message)):console.error(h,`
5
+ `),process.exit(1)}}export{runMain as n,defineCommand as t};
@@ -0,0 +1 @@
1
+ import{a as Minipass}from"./@isaacs/fs-minipass.mjs";import assert from"assert";import{Buffer}from"buffer";import*as realZlib$1 from"zlib";import realZlib from"zlib";const realZlibConstants=realZlib.constants||{ZLIB_VERNUM:4736},constants=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},realZlibConstants)),OriginalBufferConcat=Buffer.concat,desc=Object.getOwnPropertyDescriptor(Buffer,`concat`),noop=e=>e,passthroughBufferConcat=desc?.writable===!0||desc?.set!==void 0?e=>{Buffer.concat=e?noop:OriginalBufferConcat}:e=>{},_superWrite=Symbol(`_superWrite`);var ZlibError=class extends Error{code;errno;constructor(e,h){super(`zlib: `+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||=`ZLIB_ERROR`,this.message=`zlib: `+e.message,Error.captureStackTrace(this,h??this.constructor)}get name(){return`ZlibError`}};const _flushFlag=Symbol(`flushFlag`);var ZlibBase=class extends Minipass{#sawError=!1;#ended=!1;#flushFlag;#finishFlushFlag;#fullFlushFlag;#handle;#onError;get sawError(){return this.#sawError}get handle(){return this.#handle}get flushFlag(){return this.#flushFlag}constructor(e,h){if(!e||typeof e!=`object`)throw TypeError(`invalid options for ZlibBase constructor`);if(super(e),this.#flushFlag=e.flush??0,this.#finishFlushFlag=e.finishFlush??0,this.#fullFlushFlag=e.fullFlushFlag??0,typeof realZlib$1[h]!=`function`)throw TypeError(`Compression method not supported: `+h);try{this.#handle=new realZlib$1[h](e)}catch(e){throw new ZlibError(e,this.constructor)}this.#onError=e=>{this.#sawError||(this.#sawError=!0,this.close(),this.emit(`error`,e))},this.#handle?.on(`error`,e=>this.#onError(new ZlibError(e))),this.once(`end`,()=>this.close)}close(){this.#handle&&(this.#handle.close(),this.#handle=void 0,this.emit(`close`))}reset(){if(!this.#sawError)return assert(this.#handle,`zlib binding closed`),this.#handle.reset?.()}flush(e){this.ended||(typeof e!=`number`&&(e=this.#fullFlushFlag),this.write(Object.assign(Buffer.alloc(0),{[_flushFlag]:e})))}end(e,h,g){return typeof e==`function`&&(g=e,h=void 0,e=void 0),typeof h==`function`&&(g=h,h=void 0),e&&(h?this.write(e,h):this.write(e)),this.flush(this.#finishFlushFlag),this.#ended=!0,super.end(g)}get ended(){return this.#ended}[_superWrite](e){return super.write(e)}write(e,_,v){if(typeof _==`function`&&(v=_,_=`utf8`),typeof e==`string`&&(e=Buffer.from(e,_)),this.#sawError)return;assert(this.#handle,`zlib binding closed`);let y=this.#handle._handle,b=y.close;y.close=()=>{};let x=this.#handle.close;this.#handle.close=()=>{},passthroughBufferConcat(!0);let S;try{let h=typeof e[_flushFlag]==`number`?e[_flushFlag]:this.#flushFlag;S=this.#handle._processChunk(e,h),passthroughBufferConcat(!1)}catch(e){passthroughBufferConcat(!1),this.#onError(new ZlibError(e,this.write))}finally{this.#handle&&(this.#handle._handle=y,y.close=b,this.#handle.close=x,this.#handle.removeAllListeners(`error`))}this.#handle&&this.#handle.on(`error`,e=>this.#onError(new ZlibError(e,this.write)));let C;if(S)if(Array.isArray(S)&&S.length>0){let e=S[0];C=this[_superWrite](Buffer.from(e));for(let e=1;e<S.length;e++)C=this[_superWrite](S[e])}else C=this[_superWrite](Buffer.from(S));return v&&v(),C}},Zlib=class extends ZlibBase{#level;#strategy;constructor(e,h){e||={},e.flush=e.flush||constants.Z_NO_FLUSH,e.finishFlush=e.finishFlush||constants.Z_FINISH,e.fullFlushFlag=constants.Z_FULL_FLUSH,super(e,h),this.#level=e.level,this.#strategy=e.strategy}params(e,g){if(!this.sawError){if(!this.handle)throw Error(`cannot switch params when binding is closed`);if(!this.handle.params)throw Error(`not supported in this implementation`);if(this.#level!==e||this.#strategy!==g){this.flush(constants.Z_SYNC_FLUSH),assert(this.handle,`zlib binding closed`);let _=this.handle.flush;this.handle.flush=(e,h)=>{typeof e==`function`&&(h=e,e=this.flushFlag),this.flush(e),h?.()};try{this.handle.params(e,g)}finally{this.handle.flush=_}this.handle&&(this.#level=e,this.#strategy=g)}}}},Gzip=class extends Zlib{#portable;constructor(e){super(e,`Gzip`),this.#portable=e&&!!e.portable}[_superWrite](e){return this.#portable?(this.#portable=!1,e[9]=255,super[_superWrite](e)):super[_superWrite](e)}},Unzip=class extends Zlib{constructor(e){super(e,`Unzip`)}},Brotli=class extends ZlibBase{constructor(e,h){e||={},e.flush=e.flush||constants.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||constants.BROTLI_OPERATION_FINISH,e.fullFlushFlag=constants.BROTLI_OPERATION_FLUSH,super(e,h)}},BrotliCompress=class extends Brotli{constructor(e){super(e,`BrotliCompress`)}},BrotliDecompress=class extends Brotli{constructor(e){super(e,`BrotliDecompress`)}},Zstd=class extends ZlibBase{constructor(e,h){e||={},e.flush=e.flush||constants.ZSTD_e_continue,e.finishFlush=e.finishFlush||constants.ZSTD_e_end,e.fullFlushFlag=constants.ZSTD_e_flush,super(e,h)}},ZstdCompress=class extends Zstd{constructor(e){super(e,`ZstdCompress`)}},ZstdDecompress=class extends Zstd{constructor(e){super(e,`ZstdDecompress`)}};export{ZstdCompress as a,Unzip as i,BrotliDecompress as n,ZstdDecompress as o,Gzip as r,BrotliCompress as t};
@@ -0,0 +1,2 @@
1
+ import"node:module";import{readFile}from"node:fs/promises";import{existsSync}from"node:fs";import{PassThrough}from"node:stream";import{delimiter,dirname,join,normalize,resolve}from"node:path";import{createRequire}from"module";import{spawn}from"node:child_process";import{cwd}from"node:process";import c from"node:readline";const _DRIVE_LETTER_START_RE=/^[A-Za-z]:\//;function normalizeWindowsPath(e=``){return e&&e.replace(/\\/g,`/`).replace(_DRIVE_LETTER_START_RE,e=>e.toUpperCase())}const _UNC_REGEX=/^[/\\]{2}/,_IS_ABSOLUTE_RE=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,_DRIVE_LETTER_RE=/^[A-Za-z]:$/,_ROOT_FOLDER_RE=/^\/([A-Za-z]:)?$/,normalize$1=function(e){if(e.length===0)return`.`;e=normalizeWindowsPath(e);let r=e.match(_UNC_REGEX),i=isAbsolute(e),a=e[e.length-1]===`/`;return e=normalizeString(e,!i),e.length===0?i?`/`:a?`./`:`.`:(a&&(e+=`/`),_DRIVE_LETTER_RE.test(e)&&(e+=`/`),r?i?`//${e}`:`//./${e}`:i&&!isAbsolute(e)?`/${e}`:e)},join$1=function(...e){let r=``;for(let i of e)if(i)if(r.length>0){let e=r[r.length-1]===`/`,a=i[0]===`/`;e&&a?r+=i.slice(1):r+=e||a?i:`/${i}`}else r+=i;return normalize$1(r)};function cwd$1(){return typeof process<`u`&&typeof process.cwd==`function`?process.cwd().replace(/\\/g,`/`):`/`}const resolve$1=function(...e){e=e.map(e=>normalizeWindowsPath(e));let r=``,i=!1;for(let a=e.length-1;a>=-1&&!i;a--){let o=a>=0?e[a]:cwd$1();!o||o.length===0||(r=`${o}/${r}`,i=isAbsolute(o))}return r=normalizeString(r,!i),i&&!isAbsolute(r)?`/${r}`:r.length>0?r:`.`};function normalizeString(e,r){let i=``,a=0,o=-1,s=0,L=null;for(let J=0;J<=e.length;++J){if(J<e.length)L=e[J];else if(L===`/`)break;else L=`/`;if(L===`/`){if(!(o===J-1||s===1))if(s===2){if(i.length<2||a!==2||i[i.length-1]!==`.`||i[i.length-2]!==`.`){if(i.length>2){let e=i.lastIndexOf(`/`);e===-1?(i=``,a=0):(i=i.slice(0,e),a=i.length-1-i.lastIndexOf(`/`)),o=J,s=0;continue}else if(i.length>0){i=``,a=0,o=J,s=0;continue}}r&&(i+=i.length>0?`/..`:`..`,a=2)}else i.length>0?i+=`/${e.slice(o+1,J)}`:i=e.slice(o+1,J),a=J-o-1;o=J,s=0}else L===`.`&&s!==-1?++s:s=-1}return i}const isAbsolute=function(e){return _IS_ABSOLUTE_RE.test(e)},relative=function(e,r){let i=resolve$1(e).replace(_ROOT_FOLDER_RE,`$1`).split(`/`),a=resolve$1(r).replace(_ROOT_FOLDER_RE,`$1`).split(`/`);if(a[0][1]===`:`&&i[0][1]===`:`&&i[0]!==a[0])return a.join(`/`);let o=[...i];for(let e of o){if(a[0]!==e)break;i.shift(),a.shift()}return[...i.map(()=>`..`),...a].join(`/`)},dirname$1=function(e){let r=normalizeWindowsPath(e).replace(/\/$/,``).split(`/`).slice(0,-1);return r.length===1&&_DRIVE_LETTER_RE.test(r[0])&&(r[0]+=`/`),r.join(`/`)||(isAbsolute(e)?`/`:`.`)},basename$1=function(e,r){let i=normalizeWindowsPath(e).split(`/`),a=``;for(let e=i.length-1;e>=0;e--){let r=i[e];if(r){a=r;break}}return r&&a.endsWith(r)?a.slice(0,-r.length):a};var l=Object.create,u=Object.defineProperty,d=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,p=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty,h=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),g=(e,r,i,a)=>{if(r&&typeof r==`object`||typeof r==`function`)for(var o=f(r),s=0,L=o.length,J;s<L;s++)J=o[s],!m.call(e,J)&&J!==i&&u(e,J,{get:(e=>r[e]).bind(null,J),enumerable:!(a=d(r,J))||a.enumerable});return e},_=(e,r,i)=>(i=e==null?{}:l(p(e)),g(r||!e||!e.__esModule?u(i,`default`,{value:e,enumerable:!0}):i,e)),v=createRequire(import.meta.url);const y=/^path$/i,b={key:`PATH`,value:``};function x(e){for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r)||!y.test(r))continue;let i=e[r];return i?{key:r,value:i}:b}return b}function S(e,r){let i=r.value.split(delimiter),s=e,L;do i.push(resolve(s,`node_modules`,`.bin`)),L=s,s=dirname(s);while(s!==L);return{key:r.key,value:i.join(delimiter)}}function C(e,r){let i={...process.env,...r},a=S(e,x(i));return i[a.key]=a.value,i}const w=e=>{let r=e.length,a=new PassThrough,o=()=>{--r===0&&a.emit(`end`)};for(let r of e)r.pipe(a,{end:!1}),r.on(`end`,o);return a};var T=h((e,r)=>{r.exports=s,s.sync=L;var i=v(`fs`);function a(e,r){var i=r.pathExt===void 0?process.env.PATHEXT:r.pathExt;if(!i||(i=i.split(`;`),i.indexOf(``)!==-1))return!0;for(var a=0;a<i.length;a++){var o=i[a].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function o(e,r,i){return!e.isSymbolicLink()&&!e.isFile()?!1:a(r,i)}function s(e,r,a){i.stat(e,function(i,s){a(i,i?!1:o(s,e,r))})}function L(e,r){return o(i.statSync(e),e,r)}}),E=h((e,r)=>{r.exports=a,a.sync=o;var i=v(`fs`);function a(e,r,a){i.stat(e,function(e,i){a(e,e?!1:s(i,r))})}function o(e,r){return s(i.statSync(e),r)}function s(e,r){return e.isFile()&&L(e,r)}function L(e,r){var i=e.mode,a=e.uid,o=e.gid,s=r.uid===void 0?process.getuid&&process.getuid():r.uid,L=r.gid===void 0?process.getgid&&process.getgid():r.gid,J=64,Y=8,X=1,Z=J|Y;return i&X||i&Y&&o===L||i&J&&a===s||i&Z&&s===0}}),D=h((e,r)=>{v(`fs`);var i=process.platform===`win32`||global.TESTING_WINDOWS?T():E();r.exports=a,a.sync=o;function a(e,r,o){if(typeof r==`function`&&(o=r,r={}),!o){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(i,o){a(e,r||{},function(e,r){e?o(e):i(r)})})}i(e,r||{},function(e,i){e&&(e.code===`EACCES`||r&&r.ignoreErrors)&&(e=null,i=!1),o(e,i)})}function o(e,r){try{return i.sync(e,r||{})}catch(e){if(r&&r.ignoreErrors||e.code===`EACCES`)return!1;throw e}}}),O=h((e,r)=>{let i=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,a=v(`path`),o=i?`;`:`:`,s=D(),L=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),J=(e,r)=>{let a=r.colon||o,s=e.match(/\//)||i&&e.match(/\\/)?[``]:[...i?[process.cwd()]:[],...(r.path||process.env.PATH||``).split(a)],L=i?r.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,J=i?L.split(a):[``];return i&&e.indexOf(`.`)!==-1&&J[0]!==``&&J.unshift(``),{pathEnv:s,pathExt:J,pathExtExe:L}},Y=(e,r,i)=>{typeof r==`function`&&(i=r,r={}),r||={};let{pathEnv:o,pathExt:Y,pathExtExe:X}=J(e,r),Z=[],Q=i=>new Promise((s,J)=>{if(i===o.length)return r.all&&Z.length?s(Z):J(L(e));let Y=o[i],X=/^".*"$/.test(Y)?Y.slice(1,-1):Y,Q=a.join(X,e);s($(!X&&/^\.[\\\/]/.test(e)?e.slice(0,2)+Q:Q,i,0))}),$=(e,i,a)=>new Promise((o,L)=>{if(a===Y.length)return o(Q(i+1));let J=Y[a];s(e+J,{pathExt:X},(s,L)=>{if(!s&&L)if(r.all)Z.push(e+J);else return o(e+J);return o($(e,i,a+1))})});return i?Q(0).then(e=>i(null,e),i):Q(0)};r.exports=Y,Y.sync=(e,r)=>{r||={};let{pathEnv:i,pathExt:o,pathExtExe:Y}=J(e,r),X=[];for(let L=0;L<i.length;L++){let J=i[L],Z=/^".*"$/.test(J)?J.slice(1,-1):J,Q=a.join(Z,e),$=!Z&&/^\.[\\\/]/.test(e)?e.slice(0,2)+Q:Q;for(let e=0;e<o.length;e++){let i=$+o[e];try{if(s.sync(i,{pathExt:Y}))if(r.all)X.push(i);else return i}catch{}}}if(r.all&&X.length)return X;if(r.nothrow)return null;throw L(e)}}),k=h((e,r)=>{let i=(e={})=>{let r=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(r).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};r.exports=i,r.exports.default=i}),A=h((e,r)=>{let i=v(`path`),a=O(),o=k();function s(e,r){let s=e.options.env||process.env,L=process.cwd(),J=e.options.cwd!=null,Y=J&&process.chdir!==void 0&&!process.chdir.disabled;if(Y)try{process.chdir(e.options.cwd)}catch{}let X;try{X=a.sync(e.command,{path:s[o({env:s})],pathExt:r?i.delimiter:void 0})}catch{}finally{Y&&process.chdir(L)}return X&&=i.resolve(J?e.options.cwd:``,X),X}function L(e){return s(e)||s(e,!0)}r.exports=L}),j=h((e,r)=>{let i=/([()\][%!^"`<>&|;, *?])/g;function a(e){return e=e.replace(i,`^$1`),e}function o(e,r){return e=`${e}`,e=e.replace(/(\\*)"/g,`$1$1\\"`),e=e.replace(/(\\*)$/,`$1$1`),e=`"${e}"`,e=e.replace(i,`^$1`),r&&(e=e.replace(i,`^$1`)),e}r.exports.command=a,r.exports.argument=o}),M=h((e,r)=>{r.exports=/^#!(.*)/}),N=h((e,r)=>{let i=M();r.exports=(e=``)=>{let r=e.match(i);if(!r)return null;let[a,o]=r[0].replace(/#! ?/,``).split(` `),s=a.split(`/`).pop();return s===`env`?o:o?`${s} ${o}`:s}}),P=h((e,r)=>{let i=v(`fs`),a=N();function o(e){let r=Buffer.alloc(150),o;try{o=i.openSync(e,`r`),i.readSync(o,r,0,150,0),i.closeSync(o)}catch{}return a(r.toString())}r.exports=o}),F=h((e,r)=>{let i=v(`path`),a=A(),o=j(),s=P(),L=process.platform===`win32`,J=/\.(?:com|exe)$/i,Y=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function X(e){e.file=a(e);let r=e.file&&s(e.file);return r?(e.args.unshift(e.file),e.command=r,a(e)):e.file}function Z(e){if(!L)return e;let r=X(e),a=!J.test(r);if(e.options.forceShell||a){let a=Y.test(r);e.command=i.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,a)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function Q(e,r,i){r&&!Array.isArray(r)&&(i=r,r=null),r=r?r.slice(0):[],i=Object.assign({},i);let a={command:e,args:r,options:i,file:void 0,original:{command:e,args:r}};return i.shell?a:Z(a)}r.exports=Q}),I=h((e,r)=>{let i=process.platform===`win32`;function a(e,r){return Object.assign(Error(`${r} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${r} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,r){if(!i)return;let a=e.emit;e.emit=function(i,o){if(i===`exit`){let i=s(o,r,`spawn`);if(i)return a.call(e,`error`,i)}return a.apply(e,arguments)}}function s(e,r){return i&&e===1&&!r.file?a(r.original,`spawn`):null}function L(e,r){return i&&e===1&&!r.file?a(r.original,`spawnSync`):null}r.exports={hookChildProcess:o,verifyENOENT:s,verifyENOENTSync:L,notFoundError:a}}),R=_(h((e,r)=>{let i=v(`child_process`),a=F(),o=I();function s(e,r,s){let L=a(e,r,s),J=i.spawn(L.command,L.args,L.options);return o.hookChildProcess(J,L),J}function L(e,r,s){let L=a(e,r,s),J=i.spawnSync(L.command,L.args,L.options);return J.error=J.error||o.verifyENOENTSync(J.status,L),J}r.exports=s,r.exports.spawn=s,r.exports.sync=L,r.exports._parse=a,r.exports._enoent=o})(),1),z=class extends Error{result;output;get exitCode(){if(this.result.exitCode!==null)return this.result.exitCode}constructor(e,r){super(`Process exited with non-zero status (${e.exitCode})`),this.result=e,this.output=r}};const B={timeout:void 0,persist:!1},V={windowsHide:!0};function H(e,r){return{command:normalize(e),args:r??[]}}function U(e){let r=new AbortController;for(let i of e){if(i.aborted)return r.abort(),i;i.addEventListener(`abort`,()=>{r.abort(i.reason)},{signal:r.signal})}return r.signal}async function W(e){let r=``;for await(let i of e)r+=i.toString();return r}var G=class{_process;_aborted=!1;_options;_command;_args;_resolveClose;_processClosed;_thrownError;get process(){return this._process}get pid(){return this._process?.pid}get exitCode(){if(this._process&&this._process.exitCode!==null)return this._process.exitCode}constructor(e,r,i){this._options={...B,...i},this._command=e,this._args=r??[],this._processClosed=new Promise(e=>{this._resolveClose=e})}kill(e){return this._process?.kill(e)===!0}get aborted(){return this._aborted}get killed(){return this._process?.killed===!0}pipe(e,r,i){return q(e,r,{...i,stdin:this})}async*[Symbol.asyncIterator](){let e=this._process;if(!e)return;let r=[];this._streamErr&&r.push(this._streamErr),this._streamOut&&r.push(this._streamOut);let i=w(r),a=c.createInterface({input:i});for await(let e of a)yield e.toString();if(await this._processClosed,e.removeAllListeners(),this._thrownError)throw this._thrownError;if(this._options?.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new z(this)}async _waitForOutput(){let e=this._process;if(!e)throw Error(`No process was started`);let[r,i]=await Promise.all([this._streamOut?W(this._streamOut):``,this._streamErr?W(this._streamErr):``]);if(await this._processClosed,this._options?.stdin&&await this._options.stdin,e.removeAllListeners(),this._thrownError)throw this._thrownError;let a={stderr:i,stdout:r,exitCode:this.exitCode};if(this._options.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new z(this,a);return a}then(e,r){return this._waitForOutput().then(e,r)}_streamOut;_streamErr;spawn(){let e=cwd(),r=this._options,i={...V,...r.nodeOptions},a=[];this._resetState(),r.timeout!==void 0&&a.push(AbortSignal.timeout(r.timeout)),r.signal!==void 0&&a.push(r.signal),r.persist===!0&&(i.detached=!0),a.length>0&&(i.signal=U(a)),i.env=C(e,i.env);let{command:o,args:s}=H(this._command,this._args),L=(0,R._parse)(o,s,i),J=spawn(L.command,L.args,L.options);if(J.stderr&&(this._streamErr=J.stderr),J.stdout&&(this._streamOut=J.stdout),this._process=J,J.once(`error`,this._onError),J.once(`close`,this._onClose),r.stdin!==void 0&&J.stdin&&r.stdin.process){let{stdout:e}=r.stdin.process;e&&e.pipe(J.stdin)}}_resetState(){this._aborted=!1,this._processClosed=new Promise(e=>{this._resolveClose=e}),this._thrownError=void 0}_onError=e=>{if(e.name===`AbortError`&&(!(e.cause instanceof Error)||e.cause.name!==`TimeoutError`)){this._aborted=!0;return}this._thrownError=e};_onClose=()=>{this._resolveClose&&this._resolveClose()}};const K=(e,r,i)=>{let a=new G(e,r,i);return a.spawn(),a},q=K;async function findup(e,r,i={}){let a=normalize$1(e).split(`/`);for(;a.length>0;){let e=await r(a.join(`/`)||`/`);if(e||!i.includeParentDirs)return e;a.pop()}}function cached(e){let r;return()=>(r===void 0&&(r=e().then(e=>(r=e,r))),r)}const hasCorepack=cached(async()=>{if(globalThis.process?.versions?.webcontainer)return!1;try{let{exitCode:e}=await K(`corepack`,[`--version`]);return e===0}catch{return!1}});async function executeCommand(e,r,i={}){let a=e!==`npm`&&e!==`bun`&&e!==`deno`&&i.corepack!==!1&&await hasCorepack()?[`corepack`,[e,...r]]:[e,r],{exitCode:o,stdout:s,stderr:L}=await K(a[0],a[1],{nodeOptions:{cwd:resolve$1(i.cwd||process.cwd()),env:i.env,stdio:i.silent?`pipe`:`inherit`}});if(o!==0)throw Error(`\`${a.flat().join(` `)}\` failed.${i.silent?[``,s,L].join(`
2
+ `):``}`)}async function resolveOperationOptions(e={}){let r=e.cwd||process.cwd(),i={...process.env,...e.env},a=(typeof e.packageManager==`string`?packageManagers.find(r=>r.name===e.packageManager):e.packageManager)||await detectPackageManager(e.cwd||process.cwd());if(!a)throw Error(`No package manager auto-detected.`);return{cwd:r,env:i,silent:e.silent??!1,packageManager:a,dev:e.dev??!1,workspace:e.workspace,global:e.global??!1,dry:e.dry??!1,corepack:e.corepack??!0}}function parsePackageManagerField(e){let[r,i]=(e||``).split(`@`),[a,o]=i?.split(`+`)||[];if(r&&r!==`-`&&/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(r))return{name:r,version:a,buildMeta:o};let s=(r||``).replace(/\W+/g,``);return{name:s,version:a,buildMeta:o,warnings:[`Abnormal characters found in \`packageManager\` field, sanitizing from \`${r}\` to \`${s}\``]}}const packageManagers=[{name:`npm`,command:`npm`,lockFile:`package-lock.json`},{name:`pnpm`,command:`pnpm`,lockFile:`pnpm-lock.yaml`,files:[`pnpm-workspace.yaml`]},{name:`bun`,command:`bun`,lockFile:[`bun.lockb`,`bun.lock`]},{name:`yarn`,command:`yarn`,lockFile:`yarn.lock`,files:[`.yarnrc.yml`]},{name:`deno`,command:`deno`,lockFile:`deno.lock`,files:[`deno.json`]}];async function detectPackageManager(i,a={}){let o=await findup(resolve$1(i||`.`),async i=>{if(!a.ignorePackageJSON){let a=join$1(i,`package.json`);if(existsSync(a)){let r=JSON.parse(await readFile(a,`utf8`));if(r?.packageManager){let{name:e,version:i=`0.0.0`,buildMeta:a,warnings:o}=parsePackageManagerField(r.packageManager);if(e){let r=i.split(`.`)[0],s=packageManagers.find(i=>i.name===e&&i.majorVersion===r)||packageManagers.find(r=>r.name===e);return{name:e,command:e,version:i,majorVersion:r,buildMeta:a,warnings:o,files:s?.files,lockFile:s?.lockFile}}}}if(existsSync(join$1(i,`deno.json`)))return packageManagers.find(e=>e.name===`deno`)}if(!a.ignoreLockFile){for(let e of packageManagers)if([e.lockFile,e.files].flat().filter(Boolean).some(e=>existsSync(resolve$1(i,e))))return{...e}}},{includeParentDirs:a.includeParentDirs??!0});if(!o&&!a.ignoreArgv){let e=process.argv[1];if(e){for(let r of packageManagers)if(RegExp(`[/\\\\]\\.?${r.command}`).test(e))return r}}return o}async function installDependencies(e={}){let r=await resolveOperationOptions(e),i=e.frozenLockFile?{npm:[`ci`],yarn:[`install`,`--immutable`],bun:[`install`,`--frozen-lockfile`],pnpm:[`install`,`--frozen-lockfile`],deno:[`install`,`--frozen`]}[r.packageManager.name]:[`install`];return e.ignoreWorkspace&&r.packageManager.name===`pnpm`&&i.push(`--ignore-workspace`),r.dry||await executeCommand(r.packageManager.command,i,{cwd:r.cwd,silent:r.silent,corepack:r.corepack}),{exec:{command:r.packageManager.command,args:i}}}export{resolve$1 as a,relative as i,basename$1 as n,dirname$1 as r,installDependencies as t};