@heybox/hb-sdk 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +63 -28
  2. package/dist/cli-chunks/browser-RAy8e8cV.cjs +635 -0
  3. package/dist/cli-chunks/create-D1j9UnM7.cjs +1376 -0
  4. package/dist/cli-chunks/deploy-CknDDoS_.cjs +3730 -0
  5. package/dist/cli-chunks/dev-BS9h09yG.cjs +955 -0
  6. package/dist/cli-chunks/doctor-WTl1HCW0.cjs +186 -0
  7. package/dist/cli-chunks/index-io4h3kr-.cjs +13348 -0
  8. package/dist/cli-chunks/index-yjJgBEBF.cjs +64023 -0
  9. package/dist/cli-chunks/login-B-A53Sta.cjs +193 -0
  10. package/dist/cli-chunks/session-CMBN3o9z.cjs +3040 -0
  11. package/dist/cli.cjs +19 -77707
  12. package/dist/devtools/mock-host/index.html +62 -2
  13. package/dist/devtools/mock-host/main.js +3246 -20
  14. package/dist/index.cjs.js +20 -0
  15. package/dist/index.esm.js +20 -0
  16. package/dist/miniapp-publish.cjs.js +2810 -4
  17. package/dist/miniapp-publish.esm.js +2809 -4
  18. package/dist/protocol.cjs.js +15 -0
  19. package/dist/protocol.esm.js +15 -1
  20. package/dist/templates/vue3-vite-ts/README.md.ejs +2 -2
  21. package/dist/vite.cjs.js +2814 -14
  22. package/dist/vite.esm.js +2814 -14
  23. package/package.json +6 -1
  24. package/skill/SKILL.md +19 -13
  25. package/skill/references/api-protocol.md +7 -2
  26. package/skill/references/api-root.md +24 -13
  27. package/skill/references/cli.md +335 -104
  28. package/skill/scripts/sync-references.mjs +17 -1
  29. package/skill/skill.json +4 -4
  30. package/types/index.d.ts +1 -1
  31. package/types/miniapp-manifest/schema.d.ts +2 -1
  32. package/types/miniapp-publish/index.d.ts +2 -1
  33. package/types/modules/viewport/index.d.ts +33 -0
  34. package/types/protocol/capabilities.d.ts +17 -2
  35. package/types/protocol.d.ts +2 -2
@@ -0,0 +1,3040 @@
1
+ 'use strict';
2
+
3
+ var path = require('node:path');
4
+ var index = require('./index-io4h3kr-.cjs');
5
+ var require$$0$2 = require('fs');
6
+ var require$$0 = require('constants');
7
+ var require$$0$1 = require('stream');
8
+ var require$$1 = require('util');
9
+ var require$$0$3 = require('assert');
10
+ var require$$1$1 = require('path');
11
+
12
+ const HEYBOX_API_BASE_URL = 'https://api.xiaoheihe.cn';
13
+ const HEYBOX_LOGIN_BASE_URL = 'https://login.xiaoheihe.cn';
14
+ const TRUSTED_HEYBOX_API_HOST_SUFFIXES = ['.xiaoheihe.cn', '.debugmode.cn'];
15
+ function resolveHeyboxApiBaseUrl(options = {}) {
16
+ const env = options.env;
17
+ const baseUrl = normalizeHeyboxOriginUrl(options.apiBaseUrl ?? env?.HB_SDK_API_BASE_URL ?? HEYBOX_API_BASE_URL, 'Heybox API baseUrl');
18
+ assertSafeHeyboxApiBaseUrl(baseUrl, {
19
+ allowUnsafeApiBaseUrl: options.allowUnsafeApiBaseUrl === true || isTruthyEnvFlag(env?.HB_SDK_ALLOW_UNSAFE_API_BASE_URL),
20
+ });
21
+ return baseUrl;
22
+ }
23
+ function resolveHeyboxLoginBaseUrl(options = {}) {
24
+ const env = options.env;
25
+ return normalizeHeyboxOriginUrl(options.loginBaseUrl ?? env?.HB_SDK_LOGIN_BASE_URL ?? HEYBOX_LOGIN_BASE_URL, 'Heybox login baseUrl');
26
+ }
27
+ function normalizeHeyboxOriginUrl(value, label) {
28
+ const raw = String(value ?? '').trim();
29
+ if (!raw) {
30
+ throw new Error(`${label} 不能为空`);
31
+ }
32
+ let url;
33
+ try {
34
+ url = new URL(raw);
35
+ }
36
+ catch {
37
+ throw new Error(`${label} 必须是合法的 http(s) origin:${raw}`);
38
+ }
39
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
40
+ throw new Error(`${label} 只支持 http(s) 协议:${raw}`);
41
+ }
42
+ if (url.username || url.password) {
43
+ throw new Error(`${label} 不允许包含用户名或密码:${raw}`);
44
+ }
45
+ const rawSuffix = raw.match(/^[a-z][a-z\d+.-]*:\/\/[^/?#]+(.*)$/i)?.[1] ?? '';
46
+ if ((rawSuffix && rawSuffix !== '/') || url.search || url.hash) {
47
+ throw new Error(`${label} 只支持 origin,不允许包含 path、query 或 hash:${raw}`);
48
+ }
49
+ return url.origin;
50
+ }
51
+ function assertSafeHeyboxApiBaseUrl(origin, options) {
52
+ if (options.allowUnsafeApiBaseUrl) {
53
+ return;
54
+ }
55
+ const url = new URL(origin);
56
+ if (url.protocol !== 'https:' || !isTrustedHeyboxApiHost(url.hostname)) {
57
+ throw new Error('Heybox API baseUrl 默认只允许 Heybox 受信 HTTPS origin;本地调试请显式使用 --allow-unsafe-api-base-url 或 HB_SDK_ALLOW_UNSAFE_API_BASE_URL=1');
58
+ }
59
+ }
60
+ function isTrustedHeyboxApiHost(hostname) {
61
+ return TRUSTED_HEYBOX_API_HOST_SUFFIXES.some((suffix) => hostname === suffix.slice(1) || hostname.endsWith(suffix));
62
+ }
63
+ function isTruthyEnvFlag(value) {
64
+ return ['1', 'true', 'yes', 'on'].includes(String(value ?? '')
65
+ .trim()
66
+ .toLowerCase());
67
+ }
68
+
69
+ var fs$1 = {};
70
+
71
+ var universalify = {};
72
+
73
+ var hasRequiredUniversalify;
74
+
75
+ function requireUniversalify () {
76
+ if (hasRequiredUniversalify) return universalify;
77
+ hasRequiredUniversalify = 1;
78
+
79
+ universalify.fromCallback = function (fn) {
80
+ return Object.defineProperty(function (...args) {
81
+ if (typeof args[args.length - 1] === 'function') fn.apply(this, args);
82
+ else {
83
+ return new Promise((resolve, reject) => {
84
+ args.push((err, res) => (err != null) ? reject(err) : resolve(res));
85
+ fn.apply(this, args);
86
+ })
87
+ }
88
+ }, 'name', { value: fn.name })
89
+ };
90
+
91
+ universalify.fromPromise = function (fn) {
92
+ return Object.defineProperty(function (...args) {
93
+ const cb = args[args.length - 1];
94
+ if (typeof cb !== 'function') return fn.apply(this, args)
95
+ else {
96
+ args.pop();
97
+ fn.apply(this, args).then(r => cb(null, r), cb);
98
+ }
99
+ }, 'name', { value: fn.name })
100
+ };
101
+ return universalify;
102
+ }
103
+
104
+ var polyfills;
105
+ var hasRequiredPolyfills;
106
+
107
+ function requirePolyfills () {
108
+ if (hasRequiredPolyfills) return polyfills;
109
+ hasRequiredPolyfills = 1;
110
+ var constants = require$$0;
111
+
112
+ var origCwd = process.cwd;
113
+ var cwd = null;
114
+
115
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
116
+
117
+ process.cwd = function() {
118
+ if (!cwd)
119
+ cwd = origCwd.call(process);
120
+ return cwd
121
+ };
122
+ try {
123
+ process.cwd();
124
+ } catch (er) {}
125
+
126
+ // This check is needed until node.js 12 is required
127
+ if (typeof process.chdir === 'function') {
128
+ var chdir = process.chdir;
129
+ process.chdir = function (d) {
130
+ cwd = null;
131
+ chdir.call(process, d);
132
+ };
133
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
134
+ }
135
+
136
+ polyfills = patch;
137
+
138
+ function patch (fs) {
139
+ // (re-)implement some things that are known busted or missing.
140
+
141
+ // lchmod, broken prior to 0.6.2
142
+ // back-port the fix here.
143
+ if (constants.hasOwnProperty('O_SYMLINK') &&
144
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
145
+ patchLchmod(fs);
146
+ }
147
+
148
+ // lutimes implementation, or no-op
149
+ if (!fs.lutimes) {
150
+ patchLutimes(fs);
151
+ }
152
+
153
+ // https://github.com/isaacs/node-graceful-fs/issues/4
154
+ // Chown should not fail on einval or eperm if non-root.
155
+ // It should not fail on enosys ever, as this just indicates
156
+ // that a fs doesn't support the intended operation.
157
+
158
+ fs.chown = chownFix(fs.chown);
159
+ fs.fchown = chownFix(fs.fchown);
160
+ fs.lchown = chownFix(fs.lchown);
161
+
162
+ fs.chmod = chmodFix(fs.chmod);
163
+ fs.fchmod = chmodFix(fs.fchmod);
164
+ fs.lchmod = chmodFix(fs.lchmod);
165
+
166
+ fs.chownSync = chownFixSync(fs.chownSync);
167
+ fs.fchownSync = chownFixSync(fs.fchownSync);
168
+ fs.lchownSync = chownFixSync(fs.lchownSync);
169
+
170
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
171
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
172
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
173
+
174
+ fs.stat = statFix(fs.stat);
175
+ fs.fstat = statFix(fs.fstat);
176
+ fs.lstat = statFix(fs.lstat);
177
+
178
+ fs.statSync = statFixSync(fs.statSync);
179
+ fs.fstatSync = statFixSync(fs.fstatSync);
180
+ fs.lstatSync = statFixSync(fs.lstatSync);
181
+
182
+ // if lchmod/lchown do not exist, then make them no-ops
183
+ if (fs.chmod && !fs.lchmod) {
184
+ fs.lchmod = function (path, mode, cb) {
185
+ if (cb) process.nextTick(cb);
186
+ };
187
+ fs.lchmodSync = function () {};
188
+ }
189
+ if (fs.chown && !fs.lchown) {
190
+ fs.lchown = function (path, uid, gid, cb) {
191
+ if (cb) process.nextTick(cb);
192
+ };
193
+ fs.lchownSync = function () {};
194
+ }
195
+
196
+ // on Windows, A/V software can lock the directory, causing this
197
+ // to fail with an EACCES or EPERM if the directory contains newly
198
+ // created files. Try again on failure, for up to 60 seconds.
199
+
200
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
201
+ // bit9, may lock files for up to a minute, causing npm package install
202
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
203
+ // CPU to a busy looping process, which can cause the program causing the lock
204
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
205
+ if (platform === "win32") {
206
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
207
+ : (function (fs$rename) {
208
+ function rename (from, to, cb) {
209
+ var start = Date.now();
210
+ var backoff = 0;
211
+ fs$rename(from, to, function CB (er) {
212
+ if (er
213
+ && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
214
+ && Date.now() - start < 60000) {
215
+ setTimeout(function() {
216
+ fs.stat(to, function (stater, st) {
217
+ if (stater && stater.code === "ENOENT")
218
+ fs$rename(from, to, CB);
219
+ else
220
+ cb(er);
221
+ });
222
+ }, backoff);
223
+ if (backoff < 100)
224
+ backoff += 10;
225
+ return;
226
+ }
227
+ if (cb) cb(er);
228
+ });
229
+ }
230
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
231
+ return rename
232
+ })(fs.rename);
233
+ }
234
+
235
+ // if read() returns EAGAIN, then just try it again.
236
+ fs.read = typeof fs.read !== 'function' ? fs.read
237
+ : (function (fs$read) {
238
+ function read (fd, buffer, offset, length, position, callback_) {
239
+ var callback;
240
+ if (callback_ && typeof callback_ === 'function') {
241
+ var eagCounter = 0;
242
+ callback = function (er, _, __) {
243
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
244
+ eagCounter ++;
245
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
246
+ }
247
+ callback_.apply(this, arguments);
248
+ };
249
+ }
250
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
251
+ }
252
+
253
+ // This ensures `util.promisify` works as it does for native `fs.read`.
254
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
255
+ return read
256
+ })(fs.read);
257
+
258
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
259
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
260
+ var eagCounter = 0;
261
+ while (true) {
262
+ try {
263
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
264
+ } catch (er) {
265
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
266
+ eagCounter ++;
267
+ continue
268
+ }
269
+ throw er
270
+ }
271
+ }
272
+ }})(fs.readSync);
273
+
274
+ function patchLchmod (fs) {
275
+ fs.lchmod = function (path, mode, callback) {
276
+ fs.open( path
277
+ , constants.O_WRONLY | constants.O_SYMLINK
278
+ , mode
279
+ , function (err, fd) {
280
+ if (err) {
281
+ if (callback) callback(err);
282
+ return
283
+ }
284
+ // prefer to return the chmod error, if one occurs,
285
+ // but still try to close, and report closing errors if they occur.
286
+ fs.fchmod(fd, mode, function (err) {
287
+ fs.close(fd, function(err2) {
288
+ if (callback) callback(err || err2);
289
+ });
290
+ });
291
+ });
292
+ };
293
+
294
+ fs.lchmodSync = function (path, mode) {
295
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
296
+
297
+ // prefer to return the chmod error, if one occurs,
298
+ // but still try to close, and report closing errors if they occur.
299
+ var threw = true;
300
+ var ret;
301
+ try {
302
+ ret = fs.fchmodSync(fd, mode);
303
+ threw = false;
304
+ } finally {
305
+ if (threw) {
306
+ try {
307
+ fs.closeSync(fd);
308
+ } catch (er) {}
309
+ } else {
310
+ fs.closeSync(fd);
311
+ }
312
+ }
313
+ return ret
314
+ };
315
+ }
316
+
317
+ function patchLutimes (fs) {
318
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
319
+ fs.lutimes = function (path, at, mt, cb) {
320
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
321
+ if (er) {
322
+ if (cb) cb(er);
323
+ return
324
+ }
325
+ fs.futimes(fd, at, mt, function (er) {
326
+ fs.close(fd, function (er2) {
327
+ if (cb) cb(er || er2);
328
+ });
329
+ });
330
+ });
331
+ };
332
+
333
+ fs.lutimesSync = function (path, at, mt) {
334
+ var fd = fs.openSync(path, constants.O_SYMLINK);
335
+ var ret;
336
+ var threw = true;
337
+ try {
338
+ ret = fs.futimesSync(fd, at, mt);
339
+ threw = false;
340
+ } finally {
341
+ if (threw) {
342
+ try {
343
+ fs.closeSync(fd);
344
+ } catch (er) {}
345
+ } else {
346
+ fs.closeSync(fd);
347
+ }
348
+ }
349
+ return ret
350
+ };
351
+
352
+ } else if (fs.futimes) {
353
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
354
+ fs.lutimesSync = function () {};
355
+ }
356
+ }
357
+
358
+ function chmodFix (orig) {
359
+ if (!orig) return orig
360
+ return function (target, mode, cb) {
361
+ return orig.call(fs, target, mode, function (er) {
362
+ if (chownErOk(er)) er = null;
363
+ if (cb) cb.apply(this, arguments);
364
+ })
365
+ }
366
+ }
367
+
368
+ function chmodFixSync (orig) {
369
+ if (!orig) return orig
370
+ return function (target, mode) {
371
+ try {
372
+ return orig.call(fs, target, mode)
373
+ } catch (er) {
374
+ if (!chownErOk(er)) throw er
375
+ }
376
+ }
377
+ }
378
+
379
+
380
+ function chownFix (orig) {
381
+ if (!orig) return orig
382
+ return function (target, uid, gid, cb) {
383
+ return orig.call(fs, target, uid, gid, function (er) {
384
+ if (chownErOk(er)) er = null;
385
+ if (cb) cb.apply(this, arguments);
386
+ })
387
+ }
388
+ }
389
+
390
+ function chownFixSync (orig) {
391
+ if (!orig) return orig
392
+ return function (target, uid, gid) {
393
+ try {
394
+ return orig.call(fs, target, uid, gid)
395
+ } catch (er) {
396
+ if (!chownErOk(er)) throw er
397
+ }
398
+ }
399
+ }
400
+
401
+ function statFix (orig) {
402
+ if (!orig) return orig
403
+ // Older versions of Node erroneously returned signed integers for
404
+ // uid + gid.
405
+ return function (target, options, cb) {
406
+ if (typeof options === 'function') {
407
+ cb = options;
408
+ options = null;
409
+ }
410
+ function callback (er, stats) {
411
+ if (stats) {
412
+ if (stats.uid < 0) stats.uid += 0x100000000;
413
+ if (stats.gid < 0) stats.gid += 0x100000000;
414
+ }
415
+ if (cb) cb.apply(this, arguments);
416
+ }
417
+ return options ? orig.call(fs, target, options, callback)
418
+ : orig.call(fs, target, callback)
419
+ }
420
+ }
421
+
422
+ function statFixSync (orig) {
423
+ if (!orig) return orig
424
+ // Older versions of Node erroneously returned signed integers for
425
+ // uid + gid.
426
+ return function (target, options) {
427
+ var stats = options ? orig.call(fs, target, options)
428
+ : orig.call(fs, target);
429
+ if (stats) {
430
+ if (stats.uid < 0) stats.uid += 0x100000000;
431
+ if (stats.gid < 0) stats.gid += 0x100000000;
432
+ }
433
+ return stats;
434
+ }
435
+ }
436
+
437
+ // ENOSYS means that the fs doesn't support the op. Just ignore
438
+ // that, because it doesn't matter.
439
+ //
440
+ // if there's no getuid, or if getuid() is something other
441
+ // than 0, and the error is EINVAL or EPERM, then just ignore
442
+ // it.
443
+ //
444
+ // This specific case is a silent failure in cp, install, tar,
445
+ // and most other unix tools that manage permissions.
446
+ //
447
+ // When running as root, or if other types of errors are
448
+ // encountered, then it's strict.
449
+ function chownErOk (er) {
450
+ if (!er)
451
+ return true
452
+
453
+ if (er.code === "ENOSYS")
454
+ return true
455
+
456
+ var nonroot = !process.getuid || process.getuid() !== 0;
457
+ if (nonroot) {
458
+ if (er.code === "EINVAL" || er.code === "EPERM")
459
+ return true
460
+ }
461
+
462
+ return false
463
+ }
464
+ }
465
+ return polyfills;
466
+ }
467
+
468
+ var legacyStreams;
469
+ var hasRequiredLegacyStreams;
470
+
471
+ function requireLegacyStreams () {
472
+ if (hasRequiredLegacyStreams) return legacyStreams;
473
+ hasRequiredLegacyStreams = 1;
474
+ var Stream = require$$0$1.Stream;
475
+
476
+ legacyStreams = legacy;
477
+
478
+ function legacy (fs) {
479
+ return {
480
+ ReadStream: ReadStream,
481
+ WriteStream: WriteStream
482
+ }
483
+
484
+ function ReadStream (path, options) {
485
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
486
+
487
+ Stream.call(this);
488
+
489
+ var self = this;
490
+
491
+ this.path = path;
492
+ this.fd = null;
493
+ this.readable = true;
494
+ this.paused = false;
495
+
496
+ this.flags = 'r';
497
+ this.mode = 438; /*=0666*/
498
+ this.bufferSize = 64 * 1024;
499
+
500
+ options = options || {};
501
+
502
+ // Mixin options into this
503
+ var keys = Object.keys(options);
504
+ for (var index = 0, length = keys.length; index < length; index++) {
505
+ var key = keys[index];
506
+ this[key] = options[key];
507
+ }
508
+
509
+ if (this.encoding) this.setEncoding(this.encoding);
510
+
511
+ if (this.start !== undefined) {
512
+ if ('number' !== typeof this.start) {
513
+ throw TypeError('start must be a Number');
514
+ }
515
+ if (this.end === undefined) {
516
+ this.end = Infinity;
517
+ } else if ('number' !== typeof this.end) {
518
+ throw TypeError('end must be a Number');
519
+ }
520
+
521
+ if (this.start > this.end) {
522
+ throw new Error('start must be <= end');
523
+ }
524
+
525
+ this.pos = this.start;
526
+ }
527
+
528
+ if (this.fd !== null) {
529
+ process.nextTick(function() {
530
+ self._read();
531
+ });
532
+ return;
533
+ }
534
+
535
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
536
+ if (err) {
537
+ self.emit('error', err);
538
+ self.readable = false;
539
+ return;
540
+ }
541
+
542
+ self.fd = fd;
543
+ self.emit('open', fd);
544
+ self._read();
545
+ });
546
+ }
547
+
548
+ function WriteStream (path, options) {
549
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
550
+
551
+ Stream.call(this);
552
+
553
+ this.path = path;
554
+ this.fd = null;
555
+ this.writable = true;
556
+
557
+ this.flags = 'w';
558
+ this.encoding = 'binary';
559
+ this.mode = 438; /*=0666*/
560
+ this.bytesWritten = 0;
561
+
562
+ options = options || {};
563
+
564
+ // Mixin options into this
565
+ var keys = Object.keys(options);
566
+ for (var index = 0, length = keys.length; index < length; index++) {
567
+ var key = keys[index];
568
+ this[key] = options[key];
569
+ }
570
+
571
+ if (this.start !== undefined) {
572
+ if ('number' !== typeof this.start) {
573
+ throw TypeError('start must be a Number');
574
+ }
575
+ if (this.start < 0) {
576
+ throw new Error('start must be >= zero');
577
+ }
578
+
579
+ this.pos = this.start;
580
+ }
581
+
582
+ this.busy = false;
583
+ this._queue = [];
584
+
585
+ if (this.fd === null) {
586
+ this._open = fs.open;
587
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
588
+ this.flush();
589
+ }
590
+ }
591
+ }
592
+ return legacyStreams;
593
+ }
594
+
595
+ var clone_1;
596
+ var hasRequiredClone;
597
+
598
+ function requireClone () {
599
+ if (hasRequiredClone) return clone_1;
600
+ hasRequiredClone = 1;
601
+
602
+ clone_1 = clone;
603
+
604
+ var getPrototypeOf = Object.getPrototypeOf || function (obj) {
605
+ return obj.__proto__
606
+ };
607
+
608
+ function clone (obj) {
609
+ if (obj === null || typeof obj !== 'object')
610
+ return obj
611
+
612
+ if (obj instanceof Object)
613
+ var copy = { __proto__: getPrototypeOf(obj) };
614
+ else
615
+ var copy = Object.create(null);
616
+
617
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
618
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
619
+ });
620
+
621
+ return copy
622
+ }
623
+ return clone_1;
624
+ }
625
+
626
+ var gracefulFs;
627
+ var hasRequiredGracefulFs;
628
+
629
+ function requireGracefulFs () {
630
+ if (hasRequiredGracefulFs) return gracefulFs;
631
+ hasRequiredGracefulFs = 1;
632
+ var fs = require$$0$2;
633
+ var polyfills = requirePolyfills();
634
+ var legacy = requireLegacyStreams();
635
+ var clone = requireClone();
636
+
637
+ var util = require$$1;
638
+
639
+ /* istanbul ignore next - node 0.x polyfill */
640
+ var gracefulQueue;
641
+ var previousSymbol;
642
+
643
+ /* istanbul ignore else - node 0.x polyfill */
644
+ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
645
+ gracefulQueue = Symbol.for('graceful-fs.queue');
646
+ // This is used in testing by future versions
647
+ previousSymbol = Symbol.for('graceful-fs.previous');
648
+ } else {
649
+ gracefulQueue = '___graceful-fs.queue';
650
+ previousSymbol = '___graceful-fs.previous';
651
+ }
652
+
653
+ function noop () {}
654
+
655
+ function publishQueue(context, queue) {
656
+ Object.defineProperty(context, gracefulQueue, {
657
+ get: function() {
658
+ return queue
659
+ }
660
+ });
661
+ }
662
+
663
+ var debug = noop;
664
+ if (util.debuglog)
665
+ debug = util.debuglog('gfs4');
666
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
667
+ debug = function() {
668
+ var m = util.format.apply(util, arguments);
669
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
670
+ console.error(m);
671
+ };
672
+
673
+ // Once time initialization
674
+ if (!fs[gracefulQueue]) {
675
+ // This queue can be shared by multiple loaded instances
676
+ var queue = index.commonjsGlobal[gracefulQueue] || [];
677
+ publishQueue(fs, queue);
678
+
679
+ // Patch fs.close/closeSync to shared queue version, because we need
680
+ // to retry() whenever a close happens *anywhere* in the program.
681
+ // This is essential when multiple graceful-fs instances are
682
+ // in play at the same time.
683
+ fs.close = (function (fs$close) {
684
+ function close (fd, cb) {
685
+ return fs$close.call(fs, fd, function (err) {
686
+ // This function uses the graceful-fs shared queue
687
+ if (!err) {
688
+ resetQueue();
689
+ }
690
+
691
+ if (typeof cb === 'function')
692
+ cb.apply(this, arguments);
693
+ })
694
+ }
695
+
696
+ Object.defineProperty(close, previousSymbol, {
697
+ value: fs$close
698
+ });
699
+ return close
700
+ })(fs.close);
701
+
702
+ fs.closeSync = (function (fs$closeSync) {
703
+ function closeSync (fd) {
704
+ // This function uses the graceful-fs shared queue
705
+ fs$closeSync.apply(fs, arguments);
706
+ resetQueue();
707
+ }
708
+
709
+ Object.defineProperty(closeSync, previousSymbol, {
710
+ value: fs$closeSync
711
+ });
712
+ return closeSync
713
+ })(fs.closeSync);
714
+
715
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
716
+ process.on('exit', function() {
717
+ debug(fs[gracefulQueue]);
718
+ require$$0$3.equal(fs[gracefulQueue].length, 0);
719
+ });
720
+ }
721
+ }
722
+
723
+ if (!index.commonjsGlobal[gracefulQueue]) {
724
+ publishQueue(index.commonjsGlobal, fs[gracefulQueue]);
725
+ }
726
+
727
+ gracefulFs = patch(clone(fs));
728
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
729
+ gracefulFs = patch(fs);
730
+ fs.__patched = true;
731
+ }
732
+
733
+ function patch (fs) {
734
+ // Everything that references the open() function needs to be in here
735
+ polyfills(fs);
736
+ fs.gracefulify = patch;
737
+
738
+ fs.createReadStream = createReadStream;
739
+ fs.createWriteStream = createWriteStream;
740
+ var fs$readFile = fs.readFile;
741
+ fs.readFile = readFile;
742
+ function readFile (path, options, cb) {
743
+ if (typeof options === 'function')
744
+ cb = options, options = null;
745
+
746
+ return go$readFile(path, options, cb)
747
+
748
+ function go$readFile (path, options, cb, startTime) {
749
+ return fs$readFile(path, options, function (err) {
750
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
751
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
752
+ else {
753
+ if (typeof cb === 'function')
754
+ cb.apply(this, arguments);
755
+ }
756
+ })
757
+ }
758
+ }
759
+
760
+ var fs$writeFile = fs.writeFile;
761
+ fs.writeFile = writeFile;
762
+ function writeFile (path, data, options, cb) {
763
+ if (typeof options === 'function')
764
+ cb = options, options = null;
765
+
766
+ return go$writeFile(path, data, options, cb)
767
+
768
+ function go$writeFile (path, data, options, cb, startTime) {
769
+ return fs$writeFile(path, data, options, function (err) {
770
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
771
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
772
+ else {
773
+ if (typeof cb === 'function')
774
+ cb.apply(this, arguments);
775
+ }
776
+ })
777
+ }
778
+ }
779
+
780
+ var fs$appendFile = fs.appendFile;
781
+ if (fs$appendFile)
782
+ fs.appendFile = appendFile;
783
+ function appendFile (path, data, options, cb) {
784
+ if (typeof options === 'function')
785
+ cb = options, options = null;
786
+
787
+ return go$appendFile(path, data, options, cb)
788
+
789
+ function go$appendFile (path, data, options, cb, startTime) {
790
+ return fs$appendFile(path, data, options, function (err) {
791
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
792
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
793
+ else {
794
+ if (typeof cb === 'function')
795
+ cb.apply(this, arguments);
796
+ }
797
+ })
798
+ }
799
+ }
800
+
801
+ var fs$copyFile = fs.copyFile;
802
+ if (fs$copyFile)
803
+ fs.copyFile = copyFile;
804
+ function copyFile (src, dest, flags, cb) {
805
+ if (typeof flags === 'function') {
806
+ cb = flags;
807
+ flags = 0;
808
+ }
809
+ return go$copyFile(src, dest, flags, cb)
810
+
811
+ function go$copyFile (src, dest, flags, cb, startTime) {
812
+ return fs$copyFile(src, dest, flags, function (err) {
813
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
814
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
815
+ else {
816
+ if (typeof cb === 'function')
817
+ cb.apply(this, arguments);
818
+ }
819
+ })
820
+ }
821
+ }
822
+
823
+ var fs$readdir = fs.readdir;
824
+ fs.readdir = readdir;
825
+ var noReaddirOptionVersions = /^v[0-5]\./;
826
+ function readdir (path, options, cb) {
827
+ if (typeof options === 'function')
828
+ cb = options, options = null;
829
+
830
+ var go$readdir = noReaddirOptionVersions.test(process.version)
831
+ ? function go$readdir (path, options, cb, startTime) {
832
+ return fs$readdir(path, fs$readdirCallback(
833
+ path, options, cb, startTime
834
+ ))
835
+ }
836
+ : function go$readdir (path, options, cb, startTime) {
837
+ return fs$readdir(path, options, fs$readdirCallback(
838
+ path, options, cb, startTime
839
+ ))
840
+ };
841
+
842
+ return go$readdir(path, options, cb)
843
+
844
+ function fs$readdirCallback (path, options, cb, startTime) {
845
+ return function (err, files) {
846
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
847
+ enqueue([
848
+ go$readdir,
849
+ [path, options, cb],
850
+ err,
851
+ startTime || Date.now(),
852
+ Date.now()
853
+ ]);
854
+ else {
855
+ if (files && files.sort)
856
+ files.sort();
857
+
858
+ if (typeof cb === 'function')
859
+ cb.call(this, err, files);
860
+ }
861
+ }
862
+ }
863
+ }
864
+
865
+ if (process.version.substr(0, 4) === 'v0.8') {
866
+ var legStreams = legacy(fs);
867
+ ReadStream = legStreams.ReadStream;
868
+ WriteStream = legStreams.WriteStream;
869
+ }
870
+
871
+ var fs$ReadStream = fs.ReadStream;
872
+ if (fs$ReadStream) {
873
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
874
+ ReadStream.prototype.open = ReadStream$open;
875
+ }
876
+
877
+ var fs$WriteStream = fs.WriteStream;
878
+ if (fs$WriteStream) {
879
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
880
+ WriteStream.prototype.open = WriteStream$open;
881
+ }
882
+
883
+ Object.defineProperty(fs, 'ReadStream', {
884
+ get: function () {
885
+ return ReadStream
886
+ },
887
+ set: function (val) {
888
+ ReadStream = val;
889
+ },
890
+ enumerable: true,
891
+ configurable: true
892
+ });
893
+ Object.defineProperty(fs, 'WriteStream', {
894
+ get: function () {
895
+ return WriteStream
896
+ },
897
+ set: function (val) {
898
+ WriteStream = val;
899
+ },
900
+ enumerable: true,
901
+ configurable: true
902
+ });
903
+
904
+ // legacy names
905
+ var FileReadStream = ReadStream;
906
+ Object.defineProperty(fs, 'FileReadStream', {
907
+ get: function () {
908
+ return FileReadStream
909
+ },
910
+ set: function (val) {
911
+ FileReadStream = val;
912
+ },
913
+ enumerable: true,
914
+ configurable: true
915
+ });
916
+ var FileWriteStream = WriteStream;
917
+ Object.defineProperty(fs, 'FileWriteStream', {
918
+ get: function () {
919
+ return FileWriteStream
920
+ },
921
+ set: function (val) {
922
+ FileWriteStream = val;
923
+ },
924
+ enumerable: true,
925
+ configurable: true
926
+ });
927
+
928
+ function ReadStream (path, options) {
929
+ if (this instanceof ReadStream)
930
+ return fs$ReadStream.apply(this, arguments), this
931
+ else
932
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
933
+ }
934
+
935
+ function ReadStream$open () {
936
+ var that = this;
937
+ open(that.path, that.flags, that.mode, function (err, fd) {
938
+ if (err) {
939
+ if (that.autoClose)
940
+ that.destroy();
941
+
942
+ that.emit('error', err);
943
+ } else {
944
+ that.fd = fd;
945
+ that.emit('open', fd);
946
+ that.read();
947
+ }
948
+ });
949
+ }
950
+
951
+ function WriteStream (path, options) {
952
+ if (this instanceof WriteStream)
953
+ return fs$WriteStream.apply(this, arguments), this
954
+ else
955
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
956
+ }
957
+
958
+ function WriteStream$open () {
959
+ var that = this;
960
+ open(that.path, that.flags, that.mode, function (err, fd) {
961
+ if (err) {
962
+ that.destroy();
963
+ that.emit('error', err);
964
+ } else {
965
+ that.fd = fd;
966
+ that.emit('open', fd);
967
+ }
968
+ });
969
+ }
970
+
971
+ function createReadStream (path, options) {
972
+ return new fs.ReadStream(path, options)
973
+ }
974
+
975
+ function createWriteStream (path, options) {
976
+ return new fs.WriteStream(path, options)
977
+ }
978
+
979
+ var fs$open = fs.open;
980
+ fs.open = open;
981
+ function open (path, flags, mode, cb) {
982
+ if (typeof mode === 'function')
983
+ cb = mode, mode = null;
984
+
985
+ return go$open(path, flags, mode, cb)
986
+
987
+ function go$open (path, flags, mode, cb, startTime) {
988
+ return fs$open(path, flags, mode, function (err, fd) {
989
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
990
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
991
+ else {
992
+ if (typeof cb === 'function')
993
+ cb.apply(this, arguments);
994
+ }
995
+ })
996
+ }
997
+ }
998
+
999
+ return fs
1000
+ }
1001
+
1002
+ function enqueue (elem) {
1003
+ debug('ENQUEUE', elem[0].name, elem[1]);
1004
+ fs[gracefulQueue].push(elem);
1005
+ retry();
1006
+ }
1007
+
1008
+ // keep track of the timeout between retry() calls
1009
+ var retryTimer;
1010
+
1011
+ // reset the startTime and lastTime to now
1012
+ // this resets the start of the 60 second overall timeout as well as the
1013
+ // delay between attempts so that we'll retry these jobs sooner
1014
+ function resetQueue () {
1015
+ var now = Date.now();
1016
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
1017
+ // entries that are only a length of 2 are from an older version, don't
1018
+ // bother modifying those since they'll be retried anyway.
1019
+ if (fs[gracefulQueue][i].length > 2) {
1020
+ fs[gracefulQueue][i][3] = now; // startTime
1021
+ fs[gracefulQueue][i][4] = now; // lastTime
1022
+ }
1023
+ }
1024
+ // call retry to make sure we're actively processing the queue
1025
+ retry();
1026
+ }
1027
+
1028
+ function retry () {
1029
+ // clear the timer and remove it to help prevent unintended concurrency
1030
+ clearTimeout(retryTimer);
1031
+ retryTimer = undefined;
1032
+
1033
+ if (fs[gracefulQueue].length === 0)
1034
+ return
1035
+
1036
+ var elem = fs[gracefulQueue].shift();
1037
+ var fn = elem[0];
1038
+ var args = elem[1];
1039
+ // these items may be unset if they were added by an older graceful-fs
1040
+ var err = elem[2];
1041
+ var startTime = elem[3];
1042
+ var lastTime = elem[4];
1043
+
1044
+ // if we don't have a startTime we have no way of knowing if we've waited
1045
+ // long enough, so go ahead and retry this item now
1046
+ if (startTime === undefined) {
1047
+ debug('RETRY', fn.name, args);
1048
+ fn.apply(null, args);
1049
+ } else if (Date.now() - startTime >= 60000) {
1050
+ // it's been more than 60 seconds total, bail now
1051
+ debug('TIMEOUT', fn.name, args);
1052
+ var cb = args.pop();
1053
+ if (typeof cb === 'function')
1054
+ cb.call(null, err);
1055
+ } else {
1056
+ // the amount of time between the last attempt and right now
1057
+ var sinceAttempt = Date.now() - lastTime;
1058
+ // the amount of time between when we first tried, and when we last tried
1059
+ // rounded up to at least 1
1060
+ var sinceStart = Math.max(lastTime - startTime, 1);
1061
+ // backoff. wait longer than the total time we've been retrying, but only
1062
+ // up to a maximum of 100ms
1063
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
1064
+ // it's been long enough since the last retry, do it again
1065
+ if (sinceAttempt >= desiredDelay) {
1066
+ debug('RETRY', fn.name, args);
1067
+ fn.apply(null, args.concat([startTime]));
1068
+ } else {
1069
+ // if we can't do this job yet, push it to the end of the queue
1070
+ // and let the next iteration check again
1071
+ fs[gracefulQueue].push(elem);
1072
+ }
1073
+ }
1074
+
1075
+ // schedule our next run if one isn't already scheduled
1076
+ if (retryTimer === undefined) {
1077
+ retryTimer = setTimeout(retry, 0);
1078
+ }
1079
+ }
1080
+ return gracefulFs;
1081
+ }
1082
+
1083
+ var hasRequiredFs;
1084
+
1085
+ function requireFs () {
1086
+ if (hasRequiredFs) return fs$1;
1087
+ hasRequiredFs = 1;
1088
+ (function (exports) {
1089
+ // This is adapted from https://github.com/normalize/mz
1090
+ // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
1091
+ const u = requireUniversalify().fromCallback;
1092
+ const fs = requireGracefulFs();
1093
+
1094
+ const api = [
1095
+ 'access',
1096
+ 'appendFile',
1097
+ 'chmod',
1098
+ 'chown',
1099
+ 'close',
1100
+ 'copyFile',
1101
+ 'cp',
1102
+ 'fchmod',
1103
+ 'fchown',
1104
+ 'fdatasync',
1105
+ 'fstat',
1106
+ 'fsync',
1107
+ 'ftruncate',
1108
+ 'futimes',
1109
+ 'glob',
1110
+ 'lchmod',
1111
+ 'lchown',
1112
+ 'lutimes',
1113
+ 'link',
1114
+ 'lstat',
1115
+ 'mkdir',
1116
+ 'mkdtemp',
1117
+ 'open',
1118
+ 'opendir',
1119
+ 'readdir',
1120
+ 'readFile',
1121
+ 'readlink',
1122
+ 'realpath',
1123
+ 'rename',
1124
+ 'rm',
1125
+ 'rmdir',
1126
+ 'stat',
1127
+ 'statfs',
1128
+ 'symlink',
1129
+ 'truncate',
1130
+ 'unlink',
1131
+ 'utimes',
1132
+ 'writeFile'
1133
+ ].filter(key => {
1134
+ // Some commands are not available on some systems. Ex:
1135
+ // fs.cp was added in Node.js v16.7.0
1136
+ // fs.statfs was added in Node v19.6.0, v18.15.0
1137
+ // fs.glob was added in Node.js v22.0.0
1138
+ // fs.lchown is not available on at least some Linux
1139
+ return typeof fs[key] === 'function'
1140
+ });
1141
+
1142
+ // Export cloned fs:
1143
+ Object.assign(exports, fs);
1144
+
1145
+ // Universalify async methods:
1146
+ api.forEach(method => {
1147
+ exports[method] = u(fs[method]);
1148
+ });
1149
+
1150
+ // We differ from mz/fs in that we still ship the old, broken, fs.exists()
1151
+ // since we are a drop-in replacement for the native module
1152
+ exports.exists = function (filename, callback) {
1153
+ if (typeof callback === 'function') {
1154
+ return fs.exists(filename, callback)
1155
+ }
1156
+ return new Promise(resolve => {
1157
+ return fs.exists(filename, resolve)
1158
+ })
1159
+ };
1160
+
1161
+ // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args
1162
+
1163
+ exports.read = function (fd, buffer, offset, length, position, callback) {
1164
+ if (typeof callback === 'function') {
1165
+ return fs.read(fd, buffer, offset, length, position, callback)
1166
+ }
1167
+ return new Promise((resolve, reject) => {
1168
+ fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
1169
+ if (err) return reject(err)
1170
+ resolve({ bytesRead, buffer });
1171
+ });
1172
+ })
1173
+ };
1174
+
1175
+ // Function signature can be
1176
+ // fs.write(fd, buffer[, offset[, length[, position]]], callback)
1177
+ // OR
1178
+ // fs.write(fd, string[, position[, encoding]], callback)
1179
+ // We need to handle both cases, so we use ...args
1180
+ exports.write = function (fd, buffer, ...args) {
1181
+ if (typeof args[args.length - 1] === 'function') {
1182
+ return fs.write(fd, buffer, ...args)
1183
+ }
1184
+
1185
+ return new Promise((resolve, reject) => {
1186
+ fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
1187
+ if (err) return reject(err)
1188
+ resolve({ bytesWritten, buffer });
1189
+ });
1190
+ })
1191
+ };
1192
+
1193
+ // Function signature is
1194
+ // s.readv(fd, buffers[, position], callback)
1195
+ // We need to handle the optional arg, so we use ...args
1196
+ exports.readv = function (fd, buffers, ...args) {
1197
+ if (typeof args[args.length - 1] === 'function') {
1198
+ return fs.readv(fd, buffers, ...args)
1199
+ }
1200
+
1201
+ return new Promise((resolve, reject) => {
1202
+ fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => {
1203
+ if (err) return reject(err)
1204
+ resolve({ bytesRead, buffers });
1205
+ });
1206
+ })
1207
+ };
1208
+
1209
+ // Function signature is
1210
+ // s.writev(fd, buffers[, position], callback)
1211
+ // We need to handle the optional arg, so we use ...args
1212
+ exports.writev = function (fd, buffers, ...args) {
1213
+ if (typeof args[args.length - 1] === 'function') {
1214
+ return fs.writev(fd, buffers, ...args)
1215
+ }
1216
+
1217
+ return new Promise((resolve, reject) => {
1218
+ fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
1219
+ if (err) return reject(err)
1220
+ resolve({ bytesWritten, buffers });
1221
+ });
1222
+ })
1223
+ };
1224
+
1225
+ // fs.realpath.native sometimes not available if fs is monkey-patched
1226
+ if (typeof fs.realpath.native === 'function') {
1227
+ exports.realpath.native = u(fs.realpath.native);
1228
+ } else {
1229
+ process.emitWarning(
1230
+ 'fs.realpath.native is not a function. Is fs being monkey-patched?',
1231
+ 'Warning', 'fs-extra-WARN0003'
1232
+ );
1233
+ }
1234
+ } (fs$1));
1235
+ return fs$1;
1236
+ }
1237
+
1238
+ var makeDir = {};
1239
+
1240
+ var utils$1 = {};
1241
+
1242
+ var hasRequiredUtils$1;
1243
+
1244
+ function requireUtils$1 () {
1245
+ if (hasRequiredUtils$1) return utils$1;
1246
+ hasRequiredUtils$1 = 1;
1247
+ const path = require$$1$1;
1248
+
1249
+ // https://github.com/nodejs/node/issues/8987
1250
+ // https://github.com/libuv/libuv/pull/1088
1251
+ utils$1.checkPath = function checkPath (pth) {
1252
+ if (process.platform === 'win32') {
1253
+ const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''));
1254
+
1255
+ if (pathHasInvalidWinCharacters) {
1256
+ const error = new Error(`Path contains invalid characters: ${pth}`);
1257
+ error.code = 'EINVAL';
1258
+ throw error
1259
+ }
1260
+ }
1261
+ };
1262
+ return utils$1;
1263
+ }
1264
+
1265
+ var hasRequiredMakeDir;
1266
+
1267
+ function requireMakeDir () {
1268
+ if (hasRequiredMakeDir) return makeDir;
1269
+ hasRequiredMakeDir = 1;
1270
+ const fs = /*@__PURE__*/ requireFs();
1271
+ const { checkPath } = /*@__PURE__*/ requireUtils$1();
1272
+
1273
+ const getMode = options => {
1274
+ const defaults = { mode: 0o777 };
1275
+ if (typeof options === 'number') return options
1276
+ return ({ ...defaults, ...options }).mode
1277
+ };
1278
+
1279
+ makeDir.makeDir = async (dir, options) => {
1280
+ checkPath(dir);
1281
+
1282
+ return fs.mkdir(dir, {
1283
+ mode: getMode(options),
1284
+ recursive: true
1285
+ })
1286
+ };
1287
+
1288
+ makeDir.makeDirSync = (dir, options) => {
1289
+ checkPath(dir);
1290
+
1291
+ return fs.mkdirSync(dir, {
1292
+ mode: getMode(options),
1293
+ recursive: true
1294
+ })
1295
+ };
1296
+ return makeDir;
1297
+ }
1298
+
1299
+ var mkdirs;
1300
+ var hasRequiredMkdirs;
1301
+
1302
+ function requireMkdirs () {
1303
+ if (hasRequiredMkdirs) return mkdirs;
1304
+ hasRequiredMkdirs = 1;
1305
+ const u = requireUniversalify().fromPromise;
1306
+ const { makeDir: _makeDir, makeDirSync } = /*@__PURE__*/ requireMakeDir();
1307
+ const makeDir = u(_makeDir);
1308
+
1309
+ mkdirs = {
1310
+ mkdirs: makeDir,
1311
+ mkdirsSync: makeDirSync,
1312
+ // alias
1313
+ mkdirp: makeDir,
1314
+ mkdirpSync: makeDirSync,
1315
+ ensureDir: makeDir,
1316
+ ensureDirSync: makeDirSync
1317
+ };
1318
+ return mkdirs;
1319
+ }
1320
+
1321
+ var pathExists_1;
1322
+ var hasRequiredPathExists;
1323
+
1324
+ function requirePathExists () {
1325
+ if (hasRequiredPathExists) return pathExists_1;
1326
+ hasRequiredPathExists = 1;
1327
+ const u = requireUniversalify().fromPromise;
1328
+ const fs = /*@__PURE__*/ requireFs();
1329
+
1330
+ function pathExists (path) {
1331
+ return fs.access(path).then(() => true).catch(() => false)
1332
+ }
1333
+
1334
+ pathExists_1 = {
1335
+ pathExists: u(pathExists),
1336
+ pathExistsSync: fs.existsSync
1337
+ };
1338
+ return pathExists_1;
1339
+ }
1340
+
1341
+ var utimes;
1342
+ var hasRequiredUtimes;
1343
+
1344
+ function requireUtimes () {
1345
+ if (hasRequiredUtimes) return utimes;
1346
+ hasRequiredUtimes = 1;
1347
+
1348
+ const fs = /*@__PURE__*/ requireFs();
1349
+ const u = requireUniversalify().fromPromise;
1350
+
1351
+ async function utimesMillis (path, atime, mtime) {
1352
+ const fd = await fs.open(path, 'r+');
1353
+
1354
+ let error = null;
1355
+
1356
+ try {
1357
+ await fs.futimes(fd, atime, mtime);
1358
+ } catch (futimesErr) {
1359
+ error = futimesErr;
1360
+ } finally {
1361
+ try {
1362
+ await fs.close(fd);
1363
+ } catch (closeErr) {
1364
+ if (!error) error = closeErr;
1365
+ }
1366
+ }
1367
+
1368
+ if (error) {
1369
+ throw error
1370
+ }
1371
+ }
1372
+
1373
+ function utimesMillisSync (path, atime, mtime) {
1374
+ const fd = fs.openSync(path, 'r+');
1375
+
1376
+ let error = null;
1377
+
1378
+ try {
1379
+ fs.futimesSync(fd, atime, mtime);
1380
+ } catch (futimesErr) {
1381
+ error = futimesErr;
1382
+ } finally {
1383
+ try {
1384
+ fs.closeSync(fd);
1385
+ } catch (closeErr) {
1386
+ if (!error) error = closeErr;
1387
+ }
1388
+ }
1389
+
1390
+ if (error) {
1391
+ throw error
1392
+ }
1393
+ }
1394
+
1395
+ utimes = {
1396
+ utimesMillis: u(utimesMillis),
1397
+ utimesMillisSync
1398
+ };
1399
+ return utimes;
1400
+ }
1401
+
1402
+ var stat;
1403
+ var hasRequiredStat;
1404
+
1405
+ function requireStat () {
1406
+ if (hasRequiredStat) return stat;
1407
+ hasRequiredStat = 1;
1408
+
1409
+ const fs = /*@__PURE__*/ requireFs();
1410
+ const path = require$$1$1;
1411
+ const u = requireUniversalify().fromPromise;
1412
+
1413
+ function getStats (src, dest, opts) {
1414
+ const statFunc = opts.dereference
1415
+ ? (file) => fs.stat(file, { bigint: true })
1416
+ : (file) => fs.lstat(file, { bigint: true });
1417
+ return Promise.all([
1418
+ statFunc(src),
1419
+ statFunc(dest).catch(err => {
1420
+ if (err.code === 'ENOENT') return null
1421
+ throw err
1422
+ })
1423
+ ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
1424
+ }
1425
+
1426
+ function getStatsSync (src, dest, opts) {
1427
+ let destStat;
1428
+ const statFunc = opts.dereference
1429
+ ? (file) => fs.statSync(file, { bigint: true })
1430
+ : (file) => fs.lstatSync(file, { bigint: true });
1431
+ const srcStat = statFunc(src);
1432
+ try {
1433
+ destStat = statFunc(dest);
1434
+ } catch (err) {
1435
+ if (err.code === 'ENOENT') return { srcStat, destStat: null }
1436
+ throw err
1437
+ }
1438
+ return { srcStat, destStat }
1439
+ }
1440
+
1441
+ async function checkPaths (src, dest, funcName, opts) {
1442
+ const { srcStat, destStat } = await getStats(src, dest, opts);
1443
+ if (destStat) {
1444
+ if (areIdentical(srcStat, destStat)) {
1445
+ const srcBaseName = path.basename(src);
1446
+ const destBaseName = path.basename(dest);
1447
+ if (funcName === 'move' &&
1448
+ srcBaseName !== destBaseName &&
1449
+ srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
1450
+ return { srcStat, destStat, isChangingCase: true }
1451
+ }
1452
+ throw new Error('Source and destination must not be the same.')
1453
+ }
1454
+ if (srcStat.isDirectory() && !destStat.isDirectory()) {
1455
+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
1456
+ }
1457
+ if (!srcStat.isDirectory() && destStat.isDirectory()) {
1458
+ throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
1459
+ }
1460
+ }
1461
+
1462
+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
1463
+ throw new Error(errMsg(src, dest, funcName))
1464
+ }
1465
+
1466
+ return { srcStat, destStat }
1467
+ }
1468
+
1469
+ function checkPathsSync (src, dest, funcName, opts) {
1470
+ const { srcStat, destStat } = getStatsSync(src, dest, opts);
1471
+
1472
+ if (destStat) {
1473
+ if (areIdentical(srcStat, destStat)) {
1474
+ const srcBaseName = path.basename(src);
1475
+ const destBaseName = path.basename(dest);
1476
+ if (funcName === 'move' &&
1477
+ srcBaseName !== destBaseName &&
1478
+ srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
1479
+ return { srcStat, destStat, isChangingCase: true }
1480
+ }
1481
+ throw new Error('Source and destination must not be the same.')
1482
+ }
1483
+ if (srcStat.isDirectory() && !destStat.isDirectory()) {
1484
+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
1485
+ }
1486
+ if (!srcStat.isDirectory() && destStat.isDirectory()) {
1487
+ throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
1488
+ }
1489
+ }
1490
+
1491
+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
1492
+ throw new Error(errMsg(src, dest, funcName))
1493
+ }
1494
+ return { srcStat, destStat }
1495
+ }
1496
+
1497
+ // recursively check if dest parent is a subdirectory of src.
1498
+ // It works for all file types including symlinks since it
1499
+ // checks the src and dest inodes. It starts from the deepest
1500
+ // parent and stops once it reaches the src parent or the root path.
1501
+ async function checkParentPaths (src, srcStat, dest, funcName) {
1502
+ const srcParent = path.resolve(path.dirname(src));
1503
+ const destParent = path.resolve(path.dirname(dest));
1504
+ if (destParent === srcParent || destParent === path.parse(destParent).root) return
1505
+
1506
+ let destStat;
1507
+ try {
1508
+ destStat = await fs.stat(destParent, { bigint: true });
1509
+ } catch (err) {
1510
+ if (err.code === 'ENOENT') return
1511
+ throw err
1512
+ }
1513
+
1514
+ if (areIdentical(srcStat, destStat)) {
1515
+ throw new Error(errMsg(src, dest, funcName))
1516
+ }
1517
+
1518
+ return checkParentPaths(src, srcStat, destParent, funcName)
1519
+ }
1520
+
1521
+ function checkParentPathsSync (src, srcStat, dest, funcName) {
1522
+ const srcParent = path.resolve(path.dirname(src));
1523
+ const destParent = path.resolve(path.dirname(dest));
1524
+ if (destParent === srcParent || destParent === path.parse(destParent).root) return
1525
+ let destStat;
1526
+ try {
1527
+ destStat = fs.statSync(destParent, { bigint: true });
1528
+ } catch (err) {
1529
+ if (err.code === 'ENOENT') return
1530
+ throw err
1531
+ }
1532
+ if (areIdentical(srcStat, destStat)) {
1533
+ throw new Error(errMsg(src, dest, funcName))
1534
+ }
1535
+ return checkParentPathsSync(src, srcStat, destParent, funcName)
1536
+ }
1537
+
1538
+ function areIdentical (srcStat, destStat) {
1539
+ // stat.dev can be 0n on windows when node version >= 22.x.x
1540
+ return destStat.ino !== undefined && destStat.dev !== undefined && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
1541
+ }
1542
+
1543
+ // return true if dest is a subdir of src, otherwise false.
1544
+ // It only checks the path strings.
1545
+ function isSrcSubdir (src, dest) {
1546
+ const srcArr = path.resolve(src).split(path.sep).filter(i => i);
1547
+ const destArr = path.resolve(dest).split(path.sep).filter(i => i);
1548
+ return srcArr.every((cur, i) => destArr[i] === cur)
1549
+ }
1550
+
1551
+ function errMsg (src, dest, funcName) {
1552
+ return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
1553
+ }
1554
+
1555
+ stat = {
1556
+ // checkPaths
1557
+ checkPaths: u(checkPaths),
1558
+ checkPathsSync,
1559
+ // checkParent
1560
+ checkParentPaths: u(checkParentPaths),
1561
+ checkParentPathsSync,
1562
+ // Misc
1563
+ isSrcSubdir,
1564
+ areIdentical
1565
+ };
1566
+ return stat;
1567
+ }
1568
+
1569
+ var async;
1570
+ var hasRequiredAsync;
1571
+
1572
+ function requireAsync () {
1573
+ if (hasRequiredAsync) return async;
1574
+ hasRequiredAsync = 1;
1575
+
1576
+ // https://github.com/jprichardson/node-fs-extra/issues/1056
1577
+ // Performing parallel operations on each item of an async iterator is
1578
+ // surprisingly hard; you need to have handlers in place to avoid getting an
1579
+ // UnhandledPromiseRejectionWarning.
1580
+ // NOTE: This function does not presently handle return values, only errors
1581
+ async function asyncIteratorConcurrentProcess (iterator, fn) {
1582
+ const promises = [];
1583
+ for await (const item of iterator) {
1584
+ promises.push(
1585
+ fn(item).then(
1586
+ () => null,
1587
+ (err) => err ?? new Error('unknown error')
1588
+ )
1589
+ );
1590
+ }
1591
+ await Promise.all(
1592
+ promises.map((promise) =>
1593
+ promise.then((possibleErr) => {
1594
+ if (possibleErr !== null) throw possibleErr
1595
+ })
1596
+ )
1597
+ );
1598
+ }
1599
+
1600
+ async = {
1601
+ asyncIteratorConcurrentProcess
1602
+ };
1603
+ return async;
1604
+ }
1605
+
1606
+ var copy_1;
1607
+ var hasRequiredCopy$1;
1608
+
1609
+ function requireCopy$1 () {
1610
+ if (hasRequiredCopy$1) return copy_1;
1611
+ hasRequiredCopy$1 = 1;
1612
+
1613
+ const fs = /*@__PURE__*/ requireFs();
1614
+ const path = require$$1$1;
1615
+ const { mkdirs } = /*@__PURE__*/ requireMkdirs();
1616
+ const { pathExists } = /*@__PURE__*/ requirePathExists();
1617
+ const { utimesMillis } = /*@__PURE__*/ requireUtimes();
1618
+ const stat = /*@__PURE__*/ requireStat();
1619
+ const { asyncIteratorConcurrentProcess } = /*@__PURE__*/ requireAsync();
1620
+
1621
+ async function copy (src, dest, opts = {}) {
1622
+ if (typeof opts === 'function') {
1623
+ opts = { filter: opts };
1624
+ }
1625
+
1626
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
1627
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
1628
+
1629
+ // Warn about using preserveTimestamps on 32-bit node
1630
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
1631
+ process.emitWarning(
1632
+ 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
1633
+ '\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
1634
+ 'Warning', 'fs-extra-WARN0001'
1635
+ );
1636
+ }
1637
+
1638
+ const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts);
1639
+
1640
+ await stat.checkParentPaths(src, srcStat, dest, 'copy');
1641
+
1642
+ const include = await runFilter(src, dest, opts);
1643
+
1644
+ if (!include) return
1645
+
1646
+ // check if the parent of dest exists, and create it if it doesn't exist
1647
+ const destParent = path.dirname(dest);
1648
+ const dirExists = await pathExists(destParent);
1649
+ if (!dirExists) {
1650
+ await mkdirs(destParent);
1651
+ }
1652
+
1653
+ await getStatsAndPerformCopy(destStat, src, dest, opts);
1654
+ }
1655
+
1656
+ async function runFilter (src, dest, opts) {
1657
+ if (!opts.filter) return true
1658
+ return opts.filter(src, dest)
1659
+ }
1660
+
1661
+ async function getStatsAndPerformCopy (destStat, src, dest, opts) {
1662
+ const statFn = opts.dereference ? fs.stat : fs.lstat;
1663
+ const srcStat = await statFn(src);
1664
+
1665
+ if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
1666
+
1667
+ if (
1668
+ srcStat.isFile() ||
1669
+ srcStat.isCharacterDevice() ||
1670
+ srcStat.isBlockDevice()
1671
+ ) return onFile(srcStat, destStat, src, dest, opts)
1672
+
1673
+ if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
1674
+ if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
1675
+ if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
1676
+ throw new Error(`Unknown file: ${src}`)
1677
+ }
1678
+
1679
+ async function onFile (srcStat, destStat, src, dest, opts) {
1680
+ if (!destStat) return copyFile(srcStat, src, dest, opts)
1681
+
1682
+ if (opts.overwrite) {
1683
+ await fs.unlink(dest);
1684
+ return copyFile(srcStat, src, dest, opts)
1685
+ }
1686
+ if (opts.errorOnExist) {
1687
+ throw new Error(`'${dest}' already exists`)
1688
+ }
1689
+ }
1690
+
1691
+ async function copyFile (srcStat, src, dest, opts) {
1692
+ await fs.copyFile(src, dest);
1693
+ if (opts.preserveTimestamps) {
1694
+ // Make sure the file is writable before setting the timestamp
1695
+ // otherwise open fails with EPERM when invoked with 'r+'
1696
+ // (through utimes call)
1697
+ if (fileIsNotWritable(srcStat.mode)) {
1698
+ await makeFileWritable(dest, srcStat.mode);
1699
+ }
1700
+
1701
+ // Set timestamps and mode correspondingly
1702
+
1703
+ // Note that The initial srcStat.atime cannot be trusted
1704
+ // because it is modified by the read(2) system call
1705
+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
1706
+ const updatedSrcStat = await fs.stat(src);
1707
+ await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
1708
+ }
1709
+
1710
+ return fs.chmod(dest, srcStat.mode)
1711
+ }
1712
+
1713
+ function fileIsNotWritable (srcMode) {
1714
+ return (srcMode & 0o200) === 0
1715
+ }
1716
+
1717
+ function makeFileWritable (dest, srcMode) {
1718
+ return fs.chmod(dest, srcMode | 0o200)
1719
+ }
1720
+
1721
+ async function onDir (srcStat, destStat, src, dest, opts) {
1722
+ // the dest directory might not exist, create it
1723
+ if (!destStat) {
1724
+ await fs.mkdir(dest);
1725
+ }
1726
+
1727
+ // iterate through the files in the current directory to copy everything
1728
+ await asyncIteratorConcurrentProcess(await fs.opendir(src), async (item) => {
1729
+ const srcItem = path.join(src, item.name);
1730
+ const destItem = path.join(dest, item.name);
1731
+
1732
+ const include = await runFilter(srcItem, destItem, opts);
1733
+ // only copy the item if it matches the filter function
1734
+ if (include) {
1735
+ const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts);
1736
+ // If the item is a copyable file, `getStatsAndPerformCopy` will copy it
1737
+ // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
1738
+ await getStatsAndPerformCopy(destStat, srcItem, destItem, opts);
1739
+ }
1740
+ });
1741
+
1742
+ if (!destStat) {
1743
+ await fs.chmod(dest, srcStat.mode);
1744
+ }
1745
+ }
1746
+
1747
+ async function onLink (destStat, src, dest, opts) {
1748
+ let resolvedSrc = await fs.readlink(src);
1749
+ if (opts.dereference) {
1750
+ resolvedSrc = path.resolve(process.cwd(), resolvedSrc);
1751
+ }
1752
+ if (!destStat) {
1753
+ return fs.symlink(resolvedSrc, dest)
1754
+ }
1755
+
1756
+ let resolvedDest = null;
1757
+ try {
1758
+ resolvedDest = await fs.readlink(dest);
1759
+ } catch (e) {
1760
+ // dest exists and is a regular file or directory,
1761
+ // Windows may throw UNKNOWN error. If dest already exists,
1762
+ // fs throws error anyway, so no need to guard against it here.
1763
+ if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)
1764
+ throw e
1765
+ }
1766
+ if (opts.dereference) {
1767
+ resolvedDest = path.resolve(process.cwd(), resolvedDest);
1768
+ }
1769
+ // If both symlinks resolve to the same target, they are still distinct symlinks
1770
+ // that can be copied/overwritten. Only check subdirectory constraints when
1771
+ // the resolved paths are different.
1772
+ if (resolvedSrc !== resolvedDest) {
1773
+ if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
1774
+ throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
1775
+ }
1776
+
1777
+ // do not copy if src is a subdir of dest since unlinking
1778
+ // dest in this case would result in removing src contents
1779
+ // and therefore a broken symlink would be created.
1780
+ if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
1781
+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
1782
+ }
1783
+ }
1784
+
1785
+ // copy the link
1786
+ await fs.unlink(dest);
1787
+ return fs.symlink(resolvedSrc, dest)
1788
+ }
1789
+
1790
+ copy_1 = copy;
1791
+ return copy_1;
1792
+ }
1793
+
1794
+ var copySync_1;
1795
+ var hasRequiredCopySync;
1796
+
1797
+ function requireCopySync () {
1798
+ if (hasRequiredCopySync) return copySync_1;
1799
+ hasRequiredCopySync = 1;
1800
+
1801
+ const fs = requireGracefulFs();
1802
+ const path = require$$1$1;
1803
+ const mkdirsSync = /*@__PURE__*/ requireMkdirs().mkdirsSync;
1804
+ const utimesMillisSync = /*@__PURE__*/ requireUtimes().utimesMillisSync;
1805
+ const stat = /*@__PURE__*/ requireStat();
1806
+
1807
+ function copySync (src, dest, opts) {
1808
+ if (typeof opts === 'function') {
1809
+ opts = { filter: opts };
1810
+ }
1811
+
1812
+ opts = opts || {};
1813
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
1814
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
1815
+
1816
+ // Warn about using preserveTimestamps on 32-bit node
1817
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
1818
+ process.emitWarning(
1819
+ 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
1820
+ '\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
1821
+ 'Warning', 'fs-extra-WARN0002'
1822
+ );
1823
+ }
1824
+
1825
+ const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts);
1826
+ stat.checkParentPathsSync(src, srcStat, dest, 'copy');
1827
+ if (opts.filter && !opts.filter(src, dest)) return
1828
+ const destParent = path.dirname(dest);
1829
+ if (!fs.existsSync(destParent)) mkdirsSync(destParent);
1830
+ return getStats(destStat, src, dest, opts)
1831
+ }
1832
+
1833
+ function getStats (destStat, src, dest, opts) {
1834
+ const statSync = opts.dereference ? fs.statSync : fs.lstatSync;
1835
+ const srcStat = statSync(src);
1836
+
1837
+ if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
1838
+ else if (srcStat.isFile() ||
1839
+ srcStat.isCharacterDevice() ||
1840
+ srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
1841
+ else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
1842
+ else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
1843
+ else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
1844
+ throw new Error(`Unknown file: ${src}`)
1845
+ }
1846
+
1847
+ function onFile (srcStat, destStat, src, dest, opts) {
1848
+ if (!destStat) return copyFile(srcStat, src, dest, opts)
1849
+ return mayCopyFile(srcStat, src, dest, opts)
1850
+ }
1851
+
1852
+ function mayCopyFile (srcStat, src, dest, opts) {
1853
+ if (opts.overwrite) {
1854
+ fs.unlinkSync(dest);
1855
+ return copyFile(srcStat, src, dest, opts)
1856
+ } else if (opts.errorOnExist) {
1857
+ throw new Error(`'${dest}' already exists`)
1858
+ }
1859
+ }
1860
+
1861
+ function copyFile (srcStat, src, dest, opts) {
1862
+ fs.copyFileSync(src, dest);
1863
+ if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest);
1864
+ return setDestMode(dest, srcStat.mode)
1865
+ }
1866
+
1867
+ function handleTimestamps (srcMode, src, dest) {
1868
+ // Make sure the file is writable before setting the timestamp
1869
+ // otherwise open fails with EPERM when invoked with 'r+'
1870
+ // (through utimes call)
1871
+ if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode);
1872
+ return setDestTimestamps(src, dest)
1873
+ }
1874
+
1875
+ function fileIsNotWritable (srcMode) {
1876
+ return (srcMode & 0o200) === 0
1877
+ }
1878
+
1879
+ function makeFileWritable (dest, srcMode) {
1880
+ return setDestMode(dest, srcMode | 0o200)
1881
+ }
1882
+
1883
+ function setDestMode (dest, srcMode) {
1884
+ return fs.chmodSync(dest, srcMode)
1885
+ }
1886
+
1887
+ function setDestTimestamps (src, dest) {
1888
+ // The initial srcStat.atime cannot be trusted
1889
+ // because it is modified by the read(2) system call
1890
+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
1891
+ const updatedSrcStat = fs.statSync(src);
1892
+ return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
1893
+ }
1894
+
1895
+ function onDir (srcStat, destStat, src, dest, opts) {
1896
+ if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
1897
+ return copyDir(src, dest, opts)
1898
+ }
1899
+
1900
+ function mkDirAndCopy (srcMode, src, dest, opts) {
1901
+ fs.mkdirSync(dest);
1902
+ copyDir(src, dest, opts);
1903
+ return setDestMode(dest, srcMode)
1904
+ }
1905
+
1906
+ function copyDir (src, dest, opts) {
1907
+ const dir = fs.opendirSync(src);
1908
+
1909
+ try {
1910
+ let dirent;
1911
+
1912
+ while ((dirent = dir.readSync()) !== null) {
1913
+ copyDirItem(dirent.name, src, dest, opts);
1914
+ }
1915
+ } finally {
1916
+ dir.closeSync();
1917
+ }
1918
+ }
1919
+
1920
+ function copyDirItem (item, src, dest, opts) {
1921
+ const srcItem = path.join(src, item);
1922
+ const destItem = path.join(dest, item);
1923
+ if (opts.filter && !opts.filter(srcItem, destItem)) return
1924
+ const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts);
1925
+ return getStats(destStat, srcItem, destItem, opts)
1926
+ }
1927
+
1928
+ function onLink (destStat, src, dest, opts) {
1929
+ let resolvedSrc = fs.readlinkSync(src);
1930
+ if (opts.dereference) {
1931
+ resolvedSrc = path.resolve(process.cwd(), resolvedSrc);
1932
+ }
1933
+
1934
+ if (!destStat) {
1935
+ return fs.symlinkSync(resolvedSrc, dest)
1936
+ } else {
1937
+ let resolvedDest;
1938
+ try {
1939
+ resolvedDest = fs.readlinkSync(dest);
1940
+ } catch (err) {
1941
+ // dest exists and is a regular file or directory,
1942
+ // Windows may throw UNKNOWN error. If dest already exists,
1943
+ // fs throws error anyway, so no need to guard against it here.
1944
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
1945
+ throw err
1946
+ }
1947
+ if (opts.dereference) {
1948
+ resolvedDest = path.resolve(process.cwd(), resolvedDest);
1949
+ }
1950
+ // If both symlinks resolve to the same target, they are still distinct symlinks
1951
+ // that can be copied/overwritten. Only check subdirectory constraints when
1952
+ // the resolved paths are different.
1953
+ if (resolvedSrc !== resolvedDest) {
1954
+ if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
1955
+ throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
1956
+ }
1957
+
1958
+ // prevent copy if src is a subdir of dest since unlinking
1959
+ // dest in this case would result in removing src contents
1960
+ // and therefore a broken symlink would be created.
1961
+ if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
1962
+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
1963
+ }
1964
+ }
1965
+ return copyLink(resolvedSrc, dest)
1966
+ }
1967
+ }
1968
+
1969
+ function copyLink (resolvedSrc, dest) {
1970
+ fs.unlinkSync(dest);
1971
+ return fs.symlinkSync(resolvedSrc, dest)
1972
+ }
1973
+
1974
+ copySync_1 = copySync;
1975
+ return copySync_1;
1976
+ }
1977
+
1978
+ var copy;
1979
+ var hasRequiredCopy;
1980
+
1981
+ function requireCopy () {
1982
+ if (hasRequiredCopy) return copy;
1983
+ hasRequiredCopy = 1;
1984
+
1985
+ const u = requireUniversalify().fromPromise;
1986
+ copy = {
1987
+ copy: u(/*@__PURE__*/ requireCopy$1()),
1988
+ copySync: /*@__PURE__*/ requireCopySync()
1989
+ };
1990
+ return copy;
1991
+ }
1992
+
1993
+ var remove_1;
1994
+ var hasRequiredRemove;
1995
+
1996
+ function requireRemove () {
1997
+ if (hasRequiredRemove) return remove_1;
1998
+ hasRequiredRemove = 1;
1999
+
2000
+ const fs = requireGracefulFs();
2001
+ const u = requireUniversalify().fromCallback;
2002
+
2003
+ function remove (path, callback) {
2004
+ fs.rm(path, { recursive: true, force: true }, callback);
2005
+ }
2006
+
2007
+ function removeSync (path) {
2008
+ fs.rmSync(path, { recursive: true, force: true });
2009
+ }
2010
+
2011
+ remove_1 = {
2012
+ remove: u(remove),
2013
+ removeSync
2014
+ };
2015
+ return remove_1;
2016
+ }
2017
+
2018
+ var empty;
2019
+ var hasRequiredEmpty;
2020
+
2021
+ function requireEmpty () {
2022
+ if (hasRequiredEmpty) return empty;
2023
+ hasRequiredEmpty = 1;
2024
+
2025
+ const u = requireUniversalify().fromPromise;
2026
+ const fs = /*@__PURE__*/ requireFs();
2027
+ const path = require$$1$1;
2028
+ const mkdir = /*@__PURE__*/ requireMkdirs();
2029
+ const remove = /*@__PURE__*/ requireRemove();
2030
+
2031
+ const emptyDir = u(async function emptyDir (dir) {
2032
+ let items;
2033
+ try {
2034
+ items = await fs.readdir(dir);
2035
+ } catch {
2036
+ return mkdir.mkdirs(dir)
2037
+ }
2038
+
2039
+ return Promise.all(items.map(item => remove.remove(path.join(dir, item))))
2040
+ });
2041
+
2042
+ function emptyDirSync (dir) {
2043
+ let items;
2044
+ try {
2045
+ items = fs.readdirSync(dir);
2046
+ } catch {
2047
+ return mkdir.mkdirsSync(dir)
2048
+ }
2049
+
2050
+ items.forEach(item => {
2051
+ item = path.join(dir, item);
2052
+ remove.removeSync(item);
2053
+ });
2054
+ }
2055
+
2056
+ empty = {
2057
+ emptyDirSync,
2058
+ emptydirSync: emptyDirSync,
2059
+ emptyDir,
2060
+ emptydir: emptyDir
2061
+ };
2062
+ return empty;
2063
+ }
2064
+
2065
+ var file;
2066
+ var hasRequiredFile;
2067
+
2068
+ function requireFile () {
2069
+ if (hasRequiredFile) return file;
2070
+ hasRequiredFile = 1;
2071
+
2072
+ const u = requireUniversalify().fromPromise;
2073
+ const path = require$$1$1;
2074
+ const fs = /*@__PURE__*/ requireFs();
2075
+ const mkdir = /*@__PURE__*/ requireMkdirs();
2076
+
2077
+ async function createFile (file) {
2078
+ let stats;
2079
+ try {
2080
+ stats = await fs.stat(file);
2081
+ } catch { }
2082
+ if (stats && stats.isFile()) return
2083
+
2084
+ const dir = path.dirname(file);
2085
+
2086
+ let dirStats = null;
2087
+ try {
2088
+ dirStats = await fs.stat(dir);
2089
+ } catch (err) {
2090
+ // if the directory doesn't exist, make it
2091
+ if (err.code === 'ENOENT') {
2092
+ await mkdir.mkdirs(dir);
2093
+ await fs.writeFile(file, '');
2094
+ return
2095
+ } else {
2096
+ throw err
2097
+ }
2098
+ }
2099
+
2100
+ if (dirStats.isDirectory()) {
2101
+ await fs.writeFile(file, '');
2102
+ } else {
2103
+ // parent is not a directory
2104
+ // This is just to cause an internal ENOTDIR error to be thrown
2105
+ await fs.readdir(dir);
2106
+ }
2107
+ }
2108
+
2109
+ function createFileSync (file) {
2110
+ let stats;
2111
+ try {
2112
+ stats = fs.statSync(file);
2113
+ } catch { }
2114
+ if (stats && stats.isFile()) return
2115
+
2116
+ const dir = path.dirname(file);
2117
+ try {
2118
+ if (!fs.statSync(dir).isDirectory()) {
2119
+ // parent is not a directory
2120
+ // This is just to cause an internal ENOTDIR error to be thrown
2121
+ fs.readdirSync(dir);
2122
+ }
2123
+ } catch (err) {
2124
+ // If the stat call above failed because the directory doesn't exist, create it
2125
+ if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir);
2126
+ else throw err
2127
+ }
2128
+
2129
+ fs.writeFileSync(file, '');
2130
+ }
2131
+
2132
+ file = {
2133
+ createFile: u(createFile),
2134
+ createFileSync
2135
+ };
2136
+ return file;
2137
+ }
2138
+
2139
+ var link;
2140
+ var hasRequiredLink;
2141
+
2142
+ function requireLink () {
2143
+ if (hasRequiredLink) return link;
2144
+ hasRequiredLink = 1;
2145
+
2146
+ const u = requireUniversalify().fromPromise;
2147
+ const path = require$$1$1;
2148
+ const fs = /*@__PURE__*/ requireFs();
2149
+ const mkdir = /*@__PURE__*/ requireMkdirs();
2150
+ const { pathExists } = /*@__PURE__*/ requirePathExists();
2151
+ const { areIdentical } = /*@__PURE__*/ requireStat();
2152
+
2153
+ async function createLink (srcpath, dstpath) {
2154
+ let dstStat;
2155
+ try {
2156
+ dstStat = await fs.lstat(dstpath, { bigint: true });
2157
+ } catch {
2158
+ // ignore error
2159
+ }
2160
+
2161
+ let srcStat;
2162
+ try {
2163
+ srcStat = await fs.lstat(srcpath, { bigint: true });
2164
+ } catch (err) {
2165
+ err.message = err.message.replace('lstat', 'ensureLink');
2166
+ throw err
2167
+ }
2168
+
2169
+ if (dstStat && areIdentical(srcStat, dstStat)) return
2170
+
2171
+ const dir = path.dirname(dstpath);
2172
+
2173
+ const dirExists = await pathExists(dir);
2174
+
2175
+ if (!dirExists) {
2176
+ await mkdir.mkdirs(dir);
2177
+ }
2178
+
2179
+ await fs.link(srcpath, dstpath);
2180
+ }
2181
+
2182
+ function createLinkSync (srcpath, dstpath) {
2183
+ let dstStat;
2184
+ try {
2185
+ dstStat = fs.lstatSync(dstpath, { bigint: true });
2186
+ } catch {}
2187
+
2188
+ try {
2189
+ const srcStat = fs.lstatSync(srcpath, { bigint: true });
2190
+ if (dstStat && areIdentical(srcStat, dstStat)) return
2191
+ } catch (err) {
2192
+ err.message = err.message.replace('lstat', 'ensureLink');
2193
+ throw err
2194
+ }
2195
+
2196
+ const dir = path.dirname(dstpath);
2197
+ const dirExists = fs.existsSync(dir);
2198
+ if (dirExists) return fs.linkSync(srcpath, dstpath)
2199
+ mkdir.mkdirsSync(dir);
2200
+
2201
+ return fs.linkSync(srcpath, dstpath)
2202
+ }
2203
+
2204
+ link = {
2205
+ createLink: u(createLink),
2206
+ createLinkSync
2207
+ };
2208
+ return link;
2209
+ }
2210
+
2211
+ var symlinkPaths_1;
2212
+ var hasRequiredSymlinkPaths;
2213
+
2214
+ function requireSymlinkPaths () {
2215
+ if (hasRequiredSymlinkPaths) return symlinkPaths_1;
2216
+ hasRequiredSymlinkPaths = 1;
2217
+
2218
+ const path = require$$1$1;
2219
+ const fs = /*@__PURE__*/ requireFs();
2220
+ const { pathExists } = /*@__PURE__*/ requirePathExists();
2221
+
2222
+ const u = requireUniversalify().fromPromise;
2223
+
2224
+ /**
2225
+ * Function that returns two types of paths, one relative to symlink, and one
2226
+ * relative to the current working directory. Checks if path is absolute or
2227
+ * relative. If the path is relative, this function checks if the path is
2228
+ * relative to symlink or relative to current working directory. This is an
2229
+ * initiative to find a smarter `srcpath` to supply when building symlinks.
2230
+ * This allows you to determine which path to use out of one of three possible
2231
+ * types of source paths. The first is an absolute path. This is detected by
2232
+ * `path.isAbsolute()`. When an absolute path is provided, it is checked to
2233
+ * see if it exists. If it does it's used, if not an error is returned
2234
+ * (callback)/ thrown (sync). The other two options for `srcpath` are a
2235
+ * relative url. By default Node's `fs.symlink` works by creating a symlink
2236
+ * using `dstpath` and expects the `srcpath` to be relative to the newly
2237
+ * created symlink. If you provide a `srcpath` that does not exist on the file
2238
+ * system it results in a broken symlink. To minimize this, the function
2239
+ * checks to see if the 'relative to symlink' source file exists, and if it
2240
+ * does it will use it. If it does not, it checks if there's a file that
2241
+ * exists that is relative to the current working directory, if does its used.
2242
+ * This preserves the expectations of the original fs.symlink spec and adds
2243
+ * the ability to pass in `relative to current working direcotry` paths.
2244
+ */
2245
+
2246
+ async function symlinkPaths (srcpath, dstpath) {
2247
+ if (path.isAbsolute(srcpath)) {
2248
+ try {
2249
+ await fs.lstat(srcpath);
2250
+ } catch (err) {
2251
+ err.message = err.message.replace('lstat', 'ensureSymlink');
2252
+ throw err
2253
+ }
2254
+
2255
+ return {
2256
+ toCwd: srcpath,
2257
+ toDst: srcpath
2258
+ }
2259
+ }
2260
+
2261
+ const dstdir = path.dirname(dstpath);
2262
+ const relativeToDst = path.join(dstdir, srcpath);
2263
+
2264
+ const exists = await pathExists(relativeToDst);
2265
+ if (exists) {
2266
+ return {
2267
+ toCwd: relativeToDst,
2268
+ toDst: srcpath
2269
+ }
2270
+ }
2271
+
2272
+ try {
2273
+ await fs.lstat(srcpath);
2274
+ } catch (err) {
2275
+ err.message = err.message.replace('lstat', 'ensureSymlink');
2276
+ throw err
2277
+ }
2278
+
2279
+ return {
2280
+ toCwd: srcpath,
2281
+ toDst: path.relative(dstdir, srcpath)
2282
+ }
2283
+ }
2284
+
2285
+ function symlinkPathsSync (srcpath, dstpath) {
2286
+ if (path.isAbsolute(srcpath)) {
2287
+ const exists = fs.existsSync(srcpath);
2288
+ if (!exists) throw new Error('absolute srcpath does not exist')
2289
+ return {
2290
+ toCwd: srcpath,
2291
+ toDst: srcpath
2292
+ }
2293
+ }
2294
+
2295
+ const dstdir = path.dirname(dstpath);
2296
+ const relativeToDst = path.join(dstdir, srcpath);
2297
+ const exists = fs.existsSync(relativeToDst);
2298
+ if (exists) {
2299
+ return {
2300
+ toCwd: relativeToDst,
2301
+ toDst: srcpath
2302
+ }
2303
+ }
2304
+
2305
+ const srcExists = fs.existsSync(srcpath);
2306
+ if (!srcExists) throw new Error('relative srcpath does not exist')
2307
+ return {
2308
+ toCwd: srcpath,
2309
+ toDst: path.relative(dstdir, srcpath)
2310
+ }
2311
+ }
2312
+
2313
+ symlinkPaths_1 = {
2314
+ symlinkPaths: u(symlinkPaths),
2315
+ symlinkPathsSync
2316
+ };
2317
+ return symlinkPaths_1;
2318
+ }
2319
+
2320
+ var symlinkType_1;
2321
+ var hasRequiredSymlinkType;
2322
+
2323
+ function requireSymlinkType () {
2324
+ if (hasRequiredSymlinkType) return symlinkType_1;
2325
+ hasRequiredSymlinkType = 1;
2326
+
2327
+ const fs = /*@__PURE__*/ requireFs();
2328
+ const u = requireUniversalify().fromPromise;
2329
+
2330
+ async function symlinkType (srcpath, type) {
2331
+ if (type) return type
2332
+
2333
+ let stats;
2334
+ try {
2335
+ stats = await fs.lstat(srcpath);
2336
+ } catch {
2337
+ return 'file'
2338
+ }
2339
+
2340
+ return (stats && stats.isDirectory()) ? 'dir' : 'file'
2341
+ }
2342
+
2343
+ function symlinkTypeSync (srcpath, type) {
2344
+ if (type) return type
2345
+
2346
+ let stats;
2347
+ try {
2348
+ stats = fs.lstatSync(srcpath);
2349
+ } catch {
2350
+ return 'file'
2351
+ }
2352
+ return (stats && stats.isDirectory()) ? 'dir' : 'file'
2353
+ }
2354
+
2355
+ symlinkType_1 = {
2356
+ symlinkType: u(symlinkType),
2357
+ symlinkTypeSync
2358
+ };
2359
+ return symlinkType_1;
2360
+ }
2361
+
2362
+ var symlink;
2363
+ var hasRequiredSymlink;
2364
+
2365
+ function requireSymlink () {
2366
+ if (hasRequiredSymlink) return symlink;
2367
+ hasRequiredSymlink = 1;
2368
+
2369
+ const u = requireUniversalify().fromPromise;
2370
+ const path = require$$1$1;
2371
+ const fs = /*@__PURE__*/ requireFs();
2372
+
2373
+ const { mkdirs, mkdirsSync } = /*@__PURE__*/ requireMkdirs();
2374
+
2375
+ const { symlinkPaths, symlinkPathsSync } = /*@__PURE__*/ requireSymlinkPaths();
2376
+ const { symlinkType, symlinkTypeSync } = /*@__PURE__*/ requireSymlinkType();
2377
+
2378
+ const { pathExists } = /*@__PURE__*/ requirePathExists();
2379
+
2380
+ const { areIdentical } = /*@__PURE__*/ requireStat();
2381
+
2382
+ async function createSymlink (srcpath, dstpath, type) {
2383
+ let stats;
2384
+ try {
2385
+ stats = await fs.lstat(dstpath);
2386
+ } catch { }
2387
+
2388
+ if (stats && stats.isSymbolicLink()) {
2389
+ // When srcpath is relative, resolve it relative to dstpath's directory
2390
+ // (standard symlink behavior) or fall back to cwd if that doesn't exist
2391
+ let srcStat;
2392
+ if (path.isAbsolute(srcpath)) {
2393
+ srcStat = await fs.stat(srcpath, { bigint: true });
2394
+ } else {
2395
+ const dstdir = path.dirname(dstpath);
2396
+ const relativeToDst = path.join(dstdir, srcpath);
2397
+ try {
2398
+ srcStat = await fs.stat(relativeToDst, { bigint: true });
2399
+ } catch {
2400
+ srcStat = await fs.stat(srcpath, { bigint: true });
2401
+ }
2402
+ }
2403
+
2404
+ const dstStat = await fs.stat(dstpath, { bigint: true });
2405
+ if (areIdentical(srcStat, dstStat)) return
2406
+ }
2407
+
2408
+ const relative = await symlinkPaths(srcpath, dstpath);
2409
+ srcpath = relative.toDst;
2410
+ const toType = await symlinkType(relative.toCwd, type);
2411
+ const dir = path.dirname(dstpath);
2412
+
2413
+ if (!(await pathExists(dir))) {
2414
+ await mkdirs(dir);
2415
+ }
2416
+
2417
+ return fs.symlink(srcpath, dstpath, toType)
2418
+ }
2419
+
2420
+ function createSymlinkSync (srcpath, dstpath, type) {
2421
+ let stats;
2422
+ try {
2423
+ stats = fs.lstatSync(dstpath);
2424
+ } catch { }
2425
+ if (stats && stats.isSymbolicLink()) {
2426
+ // When srcpath is relative, resolve it relative to dstpath's directory
2427
+ // (standard symlink behavior) or fall back to cwd if that doesn't exist
2428
+ let srcStat;
2429
+ if (path.isAbsolute(srcpath)) {
2430
+ srcStat = fs.statSync(srcpath, { bigint: true });
2431
+ } else {
2432
+ const dstdir = path.dirname(dstpath);
2433
+ const relativeToDst = path.join(dstdir, srcpath);
2434
+ try {
2435
+ srcStat = fs.statSync(relativeToDst, { bigint: true });
2436
+ } catch {
2437
+ srcStat = fs.statSync(srcpath, { bigint: true });
2438
+ }
2439
+ }
2440
+
2441
+ const dstStat = fs.statSync(dstpath, { bigint: true });
2442
+ if (areIdentical(srcStat, dstStat)) return
2443
+ }
2444
+
2445
+ const relative = symlinkPathsSync(srcpath, dstpath);
2446
+ srcpath = relative.toDst;
2447
+ type = symlinkTypeSync(relative.toCwd, type);
2448
+ const dir = path.dirname(dstpath);
2449
+ const exists = fs.existsSync(dir);
2450
+ if (exists) return fs.symlinkSync(srcpath, dstpath, type)
2451
+ mkdirsSync(dir);
2452
+ return fs.symlinkSync(srcpath, dstpath, type)
2453
+ }
2454
+
2455
+ symlink = {
2456
+ createSymlink: u(createSymlink),
2457
+ createSymlinkSync
2458
+ };
2459
+ return symlink;
2460
+ }
2461
+
2462
+ var ensure;
2463
+ var hasRequiredEnsure;
2464
+
2465
+ function requireEnsure () {
2466
+ if (hasRequiredEnsure) return ensure;
2467
+ hasRequiredEnsure = 1;
2468
+
2469
+ const { createFile, createFileSync } = /*@__PURE__*/ requireFile();
2470
+ const { createLink, createLinkSync } = /*@__PURE__*/ requireLink();
2471
+ const { createSymlink, createSymlinkSync } = /*@__PURE__*/ requireSymlink();
2472
+
2473
+ ensure = {
2474
+ // file
2475
+ createFile,
2476
+ createFileSync,
2477
+ ensureFile: createFile,
2478
+ ensureFileSync: createFileSync,
2479
+ // link
2480
+ createLink,
2481
+ createLinkSync,
2482
+ ensureLink: createLink,
2483
+ ensureLinkSync: createLinkSync,
2484
+ // symlink
2485
+ createSymlink,
2486
+ createSymlinkSync,
2487
+ ensureSymlink: createSymlink,
2488
+ ensureSymlinkSync: createSymlinkSync
2489
+ };
2490
+ return ensure;
2491
+ }
2492
+
2493
+ var utils;
2494
+ var hasRequiredUtils;
2495
+
2496
+ function requireUtils () {
2497
+ if (hasRequiredUtils) return utils;
2498
+ hasRequiredUtils = 1;
2499
+ function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
2500
+ const EOF = finalEOL ? EOL : '';
2501
+ const str = JSON.stringify(obj, replacer, spaces);
2502
+
2503
+ if (str === undefined) {
2504
+ throw new TypeError(`Converting ${typeof obj} value to JSON is not supported`)
2505
+ }
2506
+
2507
+ return str.replace(/\n/g, EOL) + EOF
2508
+ }
2509
+
2510
+ function stripBom (content) {
2511
+ // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
2512
+ if (Buffer.isBuffer(content)) content = content.toString('utf8');
2513
+ return content.replace(/^\uFEFF/, '')
2514
+ }
2515
+
2516
+ utils = { stringify, stripBom };
2517
+ return utils;
2518
+ }
2519
+
2520
+ var jsonfile$1;
2521
+ var hasRequiredJsonfile$1;
2522
+
2523
+ function requireJsonfile$1 () {
2524
+ if (hasRequiredJsonfile$1) return jsonfile$1;
2525
+ hasRequiredJsonfile$1 = 1;
2526
+ let _fs;
2527
+ try {
2528
+ _fs = requireGracefulFs();
2529
+ } catch (_) {
2530
+ _fs = require$$0$2;
2531
+ }
2532
+ const universalify = requireUniversalify();
2533
+ const { stringify, stripBom } = requireUtils();
2534
+
2535
+ async function _readFile (file, options = {}) {
2536
+ if (typeof options === 'string') {
2537
+ options = { encoding: options };
2538
+ }
2539
+
2540
+ const fs = options.fs || _fs;
2541
+
2542
+ const shouldThrow = 'throws' in options ? options.throws : true;
2543
+
2544
+ let data = await universalify.fromCallback(fs.readFile)(file, options);
2545
+
2546
+ data = stripBom(data);
2547
+
2548
+ let obj;
2549
+ try {
2550
+ obj = JSON.parse(data, options ? options.reviver : null);
2551
+ } catch (err) {
2552
+ if (shouldThrow) {
2553
+ err.message = `${file}: ${err.message}`;
2554
+ throw err
2555
+ } else {
2556
+ return null
2557
+ }
2558
+ }
2559
+
2560
+ return obj
2561
+ }
2562
+
2563
+ const readFile = universalify.fromPromise(_readFile);
2564
+
2565
+ function readFileSync (file, options = {}) {
2566
+ if (typeof options === 'string') {
2567
+ options = { encoding: options };
2568
+ }
2569
+
2570
+ const fs = options.fs || _fs;
2571
+
2572
+ const shouldThrow = 'throws' in options ? options.throws : true;
2573
+
2574
+ try {
2575
+ let content = fs.readFileSync(file, options);
2576
+ content = stripBom(content);
2577
+ return JSON.parse(content, options.reviver)
2578
+ } catch (err) {
2579
+ if (shouldThrow) {
2580
+ err.message = `${file}: ${err.message}`;
2581
+ throw err
2582
+ } else {
2583
+ return null
2584
+ }
2585
+ }
2586
+ }
2587
+
2588
+ async function _writeFile (file, obj, options = {}) {
2589
+ const fs = options.fs || _fs;
2590
+
2591
+ const str = stringify(obj, options);
2592
+
2593
+ await universalify.fromCallback(fs.writeFile)(file, str, options);
2594
+ }
2595
+
2596
+ const writeFile = universalify.fromPromise(_writeFile);
2597
+
2598
+ function writeFileSync (file, obj, options = {}) {
2599
+ const fs = options.fs || _fs;
2600
+
2601
+ const str = stringify(obj, options);
2602
+ // not sure if fs.writeFileSync returns anything, but just in case
2603
+ return fs.writeFileSync(file, str, options)
2604
+ }
2605
+
2606
+ // NOTE: do not change this export format; required for ESM compat
2607
+ // see https://github.com/jprichardson/node-jsonfile/pull/162 for details
2608
+ jsonfile$1 = {
2609
+ readFile,
2610
+ readFileSync,
2611
+ writeFile,
2612
+ writeFileSync
2613
+ };
2614
+ return jsonfile$1;
2615
+ }
2616
+
2617
+ var jsonfile;
2618
+ var hasRequiredJsonfile;
2619
+
2620
+ function requireJsonfile () {
2621
+ if (hasRequiredJsonfile) return jsonfile;
2622
+ hasRequiredJsonfile = 1;
2623
+
2624
+ const jsonFile = requireJsonfile$1();
2625
+
2626
+ jsonfile = {
2627
+ // jsonfile exports
2628
+ readJson: jsonFile.readFile,
2629
+ readJsonSync: jsonFile.readFileSync,
2630
+ writeJson: jsonFile.writeFile,
2631
+ writeJsonSync: jsonFile.writeFileSync
2632
+ };
2633
+ return jsonfile;
2634
+ }
2635
+
2636
+ var outputFile_1;
2637
+ var hasRequiredOutputFile;
2638
+
2639
+ function requireOutputFile () {
2640
+ if (hasRequiredOutputFile) return outputFile_1;
2641
+ hasRequiredOutputFile = 1;
2642
+
2643
+ const u = requireUniversalify().fromPromise;
2644
+ const fs = /*@__PURE__*/ requireFs();
2645
+ const path = require$$1$1;
2646
+ const mkdir = /*@__PURE__*/ requireMkdirs();
2647
+ const pathExists = /*@__PURE__*/ requirePathExists().pathExists;
2648
+
2649
+ async function outputFile (file, data, encoding = 'utf-8') {
2650
+ const dir = path.dirname(file);
2651
+
2652
+ if (!(await pathExists(dir))) {
2653
+ await mkdir.mkdirs(dir);
2654
+ }
2655
+
2656
+ return fs.writeFile(file, data, encoding)
2657
+ }
2658
+
2659
+ function outputFileSync (file, ...args) {
2660
+ const dir = path.dirname(file);
2661
+ if (!fs.existsSync(dir)) {
2662
+ mkdir.mkdirsSync(dir);
2663
+ }
2664
+
2665
+ fs.writeFileSync(file, ...args);
2666
+ }
2667
+
2668
+ outputFile_1 = {
2669
+ outputFile: u(outputFile),
2670
+ outputFileSync
2671
+ };
2672
+ return outputFile_1;
2673
+ }
2674
+
2675
+ var outputJson_1;
2676
+ var hasRequiredOutputJson;
2677
+
2678
+ function requireOutputJson () {
2679
+ if (hasRequiredOutputJson) return outputJson_1;
2680
+ hasRequiredOutputJson = 1;
2681
+
2682
+ const { stringify } = requireUtils();
2683
+ const { outputFile } = /*@__PURE__*/ requireOutputFile();
2684
+
2685
+ async function outputJson (file, data, options = {}) {
2686
+ const str = stringify(data, options);
2687
+
2688
+ await outputFile(file, str, options);
2689
+ }
2690
+
2691
+ outputJson_1 = outputJson;
2692
+ return outputJson_1;
2693
+ }
2694
+
2695
+ var outputJsonSync_1;
2696
+ var hasRequiredOutputJsonSync;
2697
+
2698
+ function requireOutputJsonSync () {
2699
+ if (hasRequiredOutputJsonSync) return outputJsonSync_1;
2700
+ hasRequiredOutputJsonSync = 1;
2701
+
2702
+ const { stringify } = requireUtils();
2703
+ const { outputFileSync } = /*@__PURE__*/ requireOutputFile();
2704
+
2705
+ function outputJsonSync (file, data, options) {
2706
+ const str = stringify(data, options);
2707
+
2708
+ outputFileSync(file, str, options);
2709
+ }
2710
+
2711
+ outputJsonSync_1 = outputJsonSync;
2712
+ return outputJsonSync_1;
2713
+ }
2714
+
2715
+ var json;
2716
+ var hasRequiredJson;
2717
+
2718
+ function requireJson () {
2719
+ if (hasRequiredJson) return json;
2720
+ hasRequiredJson = 1;
2721
+
2722
+ const u = requireUniversalify().fromPromise;
2723
+ const jsonFile = /*@__PURE__*/ requireJsonfile();
2724
+
2725
+ jsonFile.outputJson = u(/*@__PURE__*/ requireOutputJson());
2726
+ jsonFile.outputJsonSync = /*@__PURE__*/ requireOutputJsonSync();
2727
+ // aliases
2728
+ jsonFile.outputJSON = jsonFile.outputJson;
2729
+ jsonFile.outputJSONSync = jsonFile.outputJsonSync;
2730
+ jsonFile.writeJSON = jsonFile.writeJson;
2731
+ jsonFile.writeJSONSync = jsonFile.writeJsonSync;
2732
+ jsonFile.readJSON = jsonFile.readJson;
2733
+ jsonFile.readJSONSync = jsonFile.readJsonSync;
2734
+
2735
+ json = jsonFile;
2736
+ return json;
2737
+ }
2738
+
2739
+ var move_1;
2740
+ var hasRequiredMove$1;
2741
+
2742
+ function requireMove$1 () {
2743
+ if (hasRequiredMove$1) return move_1;
2744
+ hasRequiredMove$1 = 1;
2745
+
2746
+ const fs = /*@__PURE__*/ requireFs();
2747
+ const path = require$$1$1;
2748
+ const { copy } = /*@__PURE__*/ requireCopy();
2749
+ const { remove } = /*@__PURE__*/ requireRemove();
2750
+ const { mkdirp } = /*@__PURE__*/ requireMkdirs();
2751
+ const { pathExists } = /*@__PURE__*/ requirePathExists();
2752
+ const stat = /*@__PURE__*/ requireStat();
2753
+
2754
+ async function move (src, dest, opts = {}) {
2755
+ const overwrite = opts.overwrite || opts.clobber || false;
2756
+
2757
+ const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts);
2758
+
2759
+ await stat.checkParentPaths(src, srcStat, dest, 'move');
2760
+
2761
+ // If the parent of dest is not root, make sure it exists before proceeding
2762
+ const destParent = path.dirname(dest);
2763
+ const parsedParentPath = path.parse(destParent);
2764
+ if (parsedParentPath.root !== destParent) {
2765
+ await mkdirp(destParent);
2766
+ }
2767
+
2768
+ return doRename(src, dest, overwrite, isChangingCase)
2769
+ }
2770
+
2771
+ async function doRename (src, dest, overwrite, isChangingCase) {
2772
+ if (!isChangingCase) {
2773
+ if (overwrite) {
2774
+ await remove(dest);
2775
+ } else if (await pathExists(dest)) {
2776
+ throw new Error('dest already exists.')
2777
+ }
2778
+ }
2779
+
2780
+ try {
2781
+ // Try w/ rename first, and try copy + remove if EXDEV
2782
+ await fs.rename(src, dest);
2783
+ } catch (err) {
2784
+ if (err.code !== 'EXDEV') {
2785
+ throw err
2786
+ }
2787
+ await moveAcrossDevice(src, dest, overwrite);
2788
+ }
2789
+ }
2790
+
2791
+ async function moveAcrossDevice (src, dest, overwrite) {
2792
+ const opts = {
2793
+ overwrite,
2794
+ errorOnExist: true,
2795
+ preserveTimestamps: true
2796
+ };
2797
+
2798
+ await copy(src, dest, opts);
2799
+ return remove(src)
2800
+ }
2801
+
2802
+ move_1 = move;
2803
+ return move_1;
2804
+ }
2805
+
2806
+ var moveSync_1;
2807
+ var hasRequiredMoveSync;
2808
+
2809
+ function requireMoveSync () {
2810
+ if (hasRequiredMoveSync) return moveSync_1;
2811
+ hasRequiredMoveSync = 1;
2812
+
2813
+ const fs = requireGracefulFs();
2814
+ const path = require$$1$1;
2815
+ const copySync = /*@__PURE__*/ requireCopy().copySync;
2816
+ const removeSync = /*@__PURE__*/ requireRemove().removeSync;
2817
+ const mkdirpSync = /*@__PURE__*/ requireMkdirs().mkdirpSync;
2818
+ const stat = /*@__PURE__*/ requireStat();
2819
+
2820
+ function moveSync (src, dest, opts) {
2821
+ opts = opts || {};
2822
+ const overwrite = opts.overwrite || opts.clobber || false;
2823
+
2824
+ const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts);
2825
+ stat.checkParentPathsSync(src, srcStat, dest, 'move');
2826
+ if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest));
2827
+ return doRename(src, dest, overwrite, isChangingCase)
2828
+ }
2829
+
2830
+ function isParentRoot (dest) {
2831
+ const parent = path.dirname(dest);
2832
+ const parsedPath = path.parse(parent);
2833
+ return parsedPath.root === parent
2834
+ }
2835
+
2836
+ function doRename (src, dest, overwrite, isChangingCase) {
2837
+ if (isChangingCase) return rename(src, dest, overwrite)
2838
+ if (overwrite) {
2839
+ removeSync(dest);
2840
+ return rename(src, dest, overwrite)
2841
+ }
2842
+ if (fs.existsSync(dest)) throw new Error('dest already exists.')
2843
+ return rename(src, dest, overwrite)
2844
+ }
2845
+
2846
+ function rename (src, dest, overwrite) {
2847
+ try {
2848
+ fs.renameSync(src, dest);
2849
+ } catch (err) {
2850
+ if (err.code !== 'EXDEV') throw err
2851
+ return moveAcrossDevice(src, dest, overwrite)
2852
+ }
2853
+ }
2854
+
2855
+ function moveAcrossDevice (src, dest, overwrite) {
2856
+ const opts = {
2857
+ overwrite,
2858
+ errorOnExist: true,
2859
+ preserveTimestamps: true
2860
+ };
2861
+ copySync(src, dest, opts);
2862
+ return removeSync(src)
2863
+ }
2864
+
2865
+ moveSync_1 = moveSync;
2866
+ return moveSync_1;
2867
+ }
2868
+
2869
+ var move;
2870
+ var hasRequiredMove;
2871
+
2872
+ function requireMove () {
2873
+ if (hasRequiredMove) return move;
2874
+ hasRequiredMove = 1;
2875
+
2876
+ const u = requireUniversalify().fromPromise;
2877
+ move = {
2878
+ move: u(/*@__PURE__*/ requireMove$1()),
2879
+ moveSync: /*@__PURE__*/ requireMoveSync()
2880
+ };
2881
+ return move;
2882
+ }
2883
+
2884
+ var lib;
2885
+ var hasRequiredLib;
2886
+
2887
+ function requireLib () {
2888
+ if (hasRequiredLib) return lib;
2889
+ hasRequiredLib = 1;
2890
+
2891
+ lib = {
2892
+ // Export promiseified graceful-fs:
2893
+ .../*@__PURE__*/ requireFs(),
2894
+ // Export extra methods:
2895
+ .../*@__PURE__*/ requireCopy(),
2896
+ .../*@__PURE__*/ requireEmpty(),
2897
+ .../*@__PURE__*/ requireEnsure(),
2898
+ .../*@__PURE__*/ requireJson(),
2899
+ .../*@__PURE__*/ requireMkdirs(),
2900
+ .../*@__PURE__*/ requireMove(),
2901
+ .../*@__PURE__*/ requireOutputFile(),
2902
+ .../*@__PURE__*/ requirePathExists(),
2903
+ .../*@__PURE__*/ requireRemove()
2904
+ };
2905
+ return lib;
2906
+ }
2907
+
2908
+ var libExports = /*@__PURE__*/ requireLib();
2909
+ var fs = /*@__PURE__*/index.getDefaultExportFromCjs(libExports);
2910
+
2911
+ const AUTH_CACHE_VERSION = 1;
2912
+ const paths = index.envPaths('hb-sdk', { suffix: '' });
2913
+ function getAuthCacheFilePath(options = {}) {
2914
+ return options.cacheFile ?? path.join(paths.cache, 'auth.json');
2915
+ }
2916
+ function createHeyboxAuthSession(payload, options = {}) {
2917
+ return {
2918
+ heyboxId: payload.heyboxId,
2919
+ pkey: payload.pkey,
2920
+ xXhhHeyboxId: payload.xXhhHeyboxId,
2921
+ cookieHeader: createHeyboxCookieHeader(payload),
2922
+ loginBaseUrl: resolveHeyboxLoginBaseUrl(options),
2923
+ loggedInAt: (options.now?.() ?? new Date()).toISOString(),
2924
+ };
2925
+ }
2926
+ async function readAuthCache(options = {}) {
2927
+ const cacheFile = getAuthCacheFilePath(options);
2928
+ if (!(await fs.pathExists(cacheFile))) {
2929
+ return createEmptyAuthCache(options);
2930
+ }
2931
+ const parsed = (await fs.readJson(cacheFile));
2932
+ if (parsed.version !== AUTH_CACHE_VERSION) {
2933
+ throw new Error(`hb-sdk 登录缓存格式不受支持: version=${String(parsed.version)}`);
2934
+ }
2935
+ return {
2936
+ version: AUTH_CACHE_VERSION,
2937
+ updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : new Date(0).toISOString(),
2938
+ ...(isHeyboxAuthSession(parsed.heybox) ? { heybox: normalizeHeyboxAuthSession(parsed.heybox) } : {}),
2939
+ };
2940
+ }
2941
+ async function readHeyboxAuthSession(options = {}) {
2942
+ const cache = await readAuthCache(options);
2943
+ return cache.heybox;
2944
+ }
2945
+ async function requireHeyboxAuthSession(options = {}) {
2946
+ const session = await readHeyboxAuthSession(options);
2947
+ if (!session) {
2948
+ throw new Error('未发现 Heybox 登录态,请先运行 hb-sdk login');
2949
+ }
2950
+ const expectedLoginBaseUrl = resolveHeyboxLoginBaseUrl(options);
2951
+ if (session.loginBaseUrl !== expectedLoginBaseUrl) {
2952
+ throw new Error([
2953
+ 'Heybox CLI 登录环境不匹配。',
2954
+ `当前登录态: ${session.loginBaseUrl}`,
2955
+ `当前命令期望: ${expectedLoginBaseUrl}`,
2956
+ `请运行: hb-sdk login --login-base-url ${expectedLoginBaseUrl}`,
2957
+ ].join('\n'));
2958
+ }
2959
+ return session;
2960
+ }
2961
+ async function writeHeyboxAuthSession(session, options = {}) {
2962
+ const cacheFile = getAuthCacheFilePath(options);
2963
+ const cache = {
2964
+ version: AUTH_CACHE_VERSION,
2965
+ updatedAt: (options.now?.() ?? new Date()).toISOString(),
2966
+ heybox: session,
2967
+ };
2968
+ await fs.ensureDir(path.dirname(cacheFile));
2969
+ await fs.writeJson(cacheFile, cache, { spaces: 2 });
2970
+ await fs.chmod(cacheFile, 0o600);
2971
+ return cache;
2972
+ }
2973
+ async function clearHeyboxAuthSession(options = {}) {
2974
+ await fs.remove(getAuthCacheFilePath(options));
2975
+ }
2976
+ async function readRedactedHeyboxAuthStatus(options = {}) {
2977
+ const cacheFile = getAuthCacheFilePath(options);
2978
+ const session = await readHeyboxAuthSession(options);
2979
+ if (!session) {
2980
+ return {
2981
+ cacheFile,
2982
+ loggedIn: false,
2983
+ };
2984
+ }
2985
+ return {
2986
+ cacheFile,
2987
+ heyboxId: session.heyboxId,
2988
+ loginBaseUrl: session.loginBaseUrl,
2989
+ loggedIn: true,
2990
+ loggedInAt: session.loggedInAt,
2991
+ };
2992
+ }
2993
+ function createEmptyAuthCache(options = {}) {
2994
+ return {
2995
+ version: AUTH_CACHE_VERSION,
2996
+ updatedAt: (options.now?.() ?? new Date(0)).toISOString(),
2997
+ };
2998
+ }
2999
+ function createHeyboxCookieHeader(payload) {
3000
+ return [
3001
+ createCookie('heybox_id', payload.heyboxId),
3002
+ createCookie('user_heybox_id', payload.heyboxId),
3003
+ createCookie('pkey', payload.pkey),
3004
+ createCookie('user_pkey', payload.pkey),
3005
+ createCookie('x_xhh_heyboxid', payload.xXhhHeyboxId),
3006
+ ].join('; ');
3007
+ }
3008
+ function createCookie(name, value) {
3009
+ return `${name}=${value}`;
3010
+ }
3011
+ function isHeyboxAuthSession(value) {
3012
+ if (!isRecord(value)) {
3013
+ return false;
3014
+ }
3015
+ return (typeof value.heyboxId === 'string' &&
3016
+ typeof value.pkey === 'string' &&
3017
+ typeof value.xXhhHeyboxId === 'string' &&
3018
+ typeof value.cookieHeader === 'string' &&
3019
+ (value.loginBaseUrl === undefined || typeof value.loginBaseUrl === 'string') &&
3020
+ typeof value.loggedInAt === 'string');
3021
+ }
3022
+ function normalizeHeyboxAuthSession(session) {
3023
+ return {
3024
+ ...session,
3025
+ loginBaseUrl: resolveHeyboxLoginBaseUrl({ loginBaseUrl: session.loginBaseUrl }),
3026
+ };
3027
+ }
3028
+ function isRecord(value) {
3029
+ return Object.prototype.toString.call(value) === '[object Object]';
3030
+ }
3031
+
3032
+ exports.HEYBOX_API_BASE_URL = HEYBOX_API_BASE_URL;
3033
+ exports.clearHeyboxAuthSession = clearHeyboxAuthSession;
3034
+ exports.createHeyboxAuthSession = createHeyboxAuthSession;
3035
+ exports.getAuthCacheFilePath = getAuthCacheFilePath;
3036
+ exports.readRedactedHeyboxAuthStatus = readRedactedHeyboxAuthStatus;
3037
+ exports.requireHeyboxAuthSession = requireHeyboxAuthSession;
3038
+ exports.resolveHeyboxApiBaseUrl = resolveHeyboxApiBaseUrl;
3039
+ exports.resolveHeyboxLoginBaseUrl = resolveHeyboxLoginBaseUrl;
3040
+ exports.writeHeyboxAuthSession = writeHeyboxAuthSession;