@andersbakken/fisk 5.0.16 → 5.0.17

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.
@@ -0,0 +1,4892 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var crypto = require('crypto');
5
+ var EventEmitter = require('events');
6
+ var require$$1 = require('fs');
7
+ var require$$0 = require('constants');
8
+ var require$$0$1 = require('stream');
9
+ var require$$4 = require('util');
10
+ var assert$1 = require('assert');
11
+ var path$h = require('path');
12
+ var os$1 = require('os');
13
+ var net = require('net');
14
+ var require$$1$1 = require('module');
15
+
16
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
+
18
+ var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
19
+ var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
20
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
21
+ var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
22
+ var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
23
+ var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert$1);
24
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path$h);
25
+ var os__default = /*#__PURE__*/_interopDefaultLegacy(os$1);
26
+ var net__default = /*#__PURE__*/_interopDefaultLegacy(net);
27
+ var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
28
+
29
+ // Fingerprinting strategy:
30
+ //
31
+ // A compiler's "identity" for distributed-compile purposes is the set of
32
+ // behaviours that determine what code the frontend accepts and what the
33
+ // backend produces. It is NOT the bytes of the driver executable, because
34
+ // GCC and Clang bake absolute install paths into the driver at build time
35
+ // (STANDARD_EXEC_PREFIX / GCC_INSTALL_PREFIX / CLANG_RESOURCE_DIR /
36
+ // DEFAULT_SYSROOT / ...). Two machines that installed the same conan
37
+ // package for llvm end up with byte-different driver binaries whose paths
38
+ // point into per-machine conan caches, but the compilers are functionally
39
+ // identical. A file hash would say they are different; the scheduler would
40
+ // then be unable to match clients to builders.
41
+ //
42
+ // Instead, we hash the compiler's answers to a small set of probes that
43
+ // (a) are switch-independent, (b) do not embed absolute paths, and
44
+ // (c) fully determine frontend behaviour:
45
+ //
46
+ // -dumpmachine default target triple
47
+ // -dumpversion version number
48
+ // -x c -E -dM /dev/null all builtin macros for C
49
+ // -x c++ -E -dM /dev/null all builtin macros for C++
50
+ //
51
+ // The macro dumps include __clang_version__ / __GNUC__ / __GNUC_MINOR__ /
52
+ // __GNUC_PATCHLEVEL__ / __VERSION__ / target width macros / feature-test
53
+ // macros. Those strings are frozen at compiler-build time, not install
54
+ // time, so they are identical across machines that installed the same
55
+ // compiler package.
56
+ //
57
+ // Who runs the probes:
58
+ //
59
+ // The daemon never executes a compiler. The compiler generally lives inside
60
+ // the client's container and its path does not resolve in the daemon's mount
61
+ // namespace, so the daemon cannot stat it let alone run it. Instead the daemon
62
+ // asks one client to run the probes and send the raw output back, and the
63
+ // daemon does the parsing and hashing here. Keeping canonicalisation on this
64
+ // side means there is exactly one implementation of it -- a second one in the
65
+ // client would eventually diverge and silently break client/builder matching.
66
+ const PROBE_TIMEOUT_MS = 10000;
67
+ const PROBES = [
68
+ { label: "dumpmachine", args: ["-dumpmachine"], required: true },
69
+ { label: "dumpversion", args: ["-dumpversion"], required: true },
70
+ { label: "dumpfullversion", args: ["-dumpfullversion"], required: false },
71
+ { label: "builtins-c", args: ["-x", "c", "-E", "-dM", "/dev/null"], required: true },
72
+ { label: "builtins-cxx", args: ["-x", "c++", "-E", "-dM", "/dev/null"], required: true }
73
+ ];
74
+ // Emulate the C++ sscanf cascade "%d.%d.%d" -> "%d.%d" -> "%d".
75
+ function parseVersion(text) {
76
+ const three = /^(\d+)\.(\d+)\.(\d+)/.exec(text);
77
+ if (three) {
78
+ return { major: parseInt(three[1], 10), minor: parseInt(three[2], 10), patch: parseInt(three[3], 10) };
79
+ }
80
+ const two = /^(\d+)\.(\d+)/.exec(text);
81
+ if (two) {
82
+ return { major: parseInt(two[1], 10), minor: parseInt(two[2], 10), patch: 0 };
83
+ }
84
+ const one = /^(\d+)/.exec(text);
85
+ if (one) {
86
+ return { major: parseInt(one[1], 10), minor: 0, patch: 0 };
87
+ }
88
+ return { major: 0, minor: 0, patch: 0 };
89
+ }
90
+ function detectTypeFromMacros(macros) {
91
+ // clang defines __clang__ even under GCC compatibility mode.
92
+ if (/^#define __clang__ /m.test(macros)) {
93
+ return "clang";
94
+ }
95
+ // GCC defines __GNUC__ but so does clang; require __GNUC__ *without* __clang__.
96
+ if (/^#define __GNUC__ /m.test(macros)) {
97
+ return "gcc";
98
+ }
99
+ return "unknown";
100
+ }
101
+ function macroValue(macros, name) {
102
+ const m = new RegExp(`^#define ${name} (.*)$`, "m").exec(macros);
103
+ return m ? m[1].trim() : null;
104
+ }
105
+ function stripQuotes(s) {
106
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
107
+ return s.substring(1, s.length - 1);
108
+ }
109
+ return s;
110
+ }
111
+ // Extract a version tuple from the compiler's own macros. This is stable
112
+ // across install locations because these macros are frozen at compiler
113
+ // build time.
114
+ function versionFromMacros(macros, type) {
115
+ if (type === "clang") {
116
+ const v = macroValue(macros, "__clang_version__");
117
+ if (v) {
118
+ return parseVersion(stripQuotes(v));
119
+ }
120
+ const major = macroValue(macros, "__clang_major__");
121
+ const minor = macroValue(macros, "__clang_minor__");
122
+ const patch = macroValue(macros, "__clang_patchlevel__");
123
+ if (major !== null) {
124
+ return {
125
+ major: parseInt(major, 10) || 0,
126
+ minor: minor !== null ? parseInt(minor, 10) || 0 : 0,
127
+ patch: patch !== null ? parseInt(patch, 10) || 0 : 0
128
+ };
129
+ }
130
+ }
131
+ if (type === "gcc") {
132
+ const major = macroValue(macros, "__GNUC__");
133
+ const minor = macroValue(macros, "__GNUC_MINOR__");
134
+ const patch = macroValue(macros, "__GNUC_PATCHLEVEL__");
135
+ if (major !== null) {
136
+ return {
137
+ major: parseInt(major, 10) || 0,
138
+ minor: minor !== null ? parseInt(minor, 10) || 0 : 0,
139
+ patch: patch !== null ? parseInt(patch, 10) || 0 : 0
140
+ };
141
+ }
142
+ }
143
+ return { major: 0, minor: 0, patch: 0 };
144
+ }
145
+ // Turn a client's reported results into the shape the fingerprint wants,
146
+ // failing if a required probe is missing. A client that reports nothing for a
147
+ // required probe is telling us it could not identify the compiler, which must
148
+ // not silently become a fingerprint of empty strings -- every such compiler
149
+ // would hash the same.
150
+ function toProbeOutputs(results) {
151
+ for (const probe of PROBES) {
152
+ if (probe.required && !results[probe.label]) {
153
+ throw new Error(`Required probe '${probe.label}' produced no output`);
154
+ }
155
+ }
156
+ const value = (label) => { var _a; return (_a = results[label]) !== null && _a !== void 0 ? _a : ""; };
157
+ const full = results.dumpfullversion;
158
+ return {
159
+ dumpmachine: value("dumpmachine").trim(),
160
+ dumpversion: value("dumpversion").trim(),
161
+ dumpfullversion: full ? full.trim() : null,
162
+ builtinsC: value("builtins-c"),
163
+ builtinsCxx: value("builtins-cxx")
164
+ };
165
+ }
166
+ // Build the canonical fingerprint blob whose SHA becomes the compiler hash.
167
+ // Fields are separated by NUL to avoid ambiguity if any probe output
168
+ // contains our field label as a substring. Field labels are included so
169
+ // that adding a new probe in a later version deterministically changes the
170
+ // hash for the same compiler (the label acts as a schema version bump).
171
+ function canonicalFingerprint(p) {
172
+ var _a;
173
+ const parts = [
174
+ "fisk-compiler-fingerprint-v1",
175
+ "dumpmachine",
176
+ p.dumpmachine,
177
+ "dumpversion",
178
+ p.dumpversion,
179
+ "dumpfullversion",
180
+ (_a = p.dumpfullversion) !== null && _a !== void 0 ? _a : "",
181
+ "builtins-c",
182
+ p.builtinsC,
183
+ "builtins-cxx",
184
+ p.builtinsCxx
185
+ ];
186
+ return Buffer.from(parts.join("\0"), "utf8");
187
+ }
188
+ function createCompilerInfo(results) {
189
+ var _a;
190
+ const probes = toProbeOutputs(results);
191
+ const type = detectTypeFromMacros(probes.builtinsC);
192
+ const versionFromMac = versionFromMacros(probes.builtinsC, type);
193
+ const version = versionFromMac.major !== 0
194
+ ? versionFromMac
195
+ : parseVersion((_a = probes.dumpfullversion) !== null && _a !== void 0 ? _a : probes.dumpversion);
196
+ const blob = canonicalFingerprint(probes);
197
+ const hash = crypto.createHash("sha1").update(blob).digest("hex").toUpperCase();
198
+ // `input` is retained for debug/traceability: it lets a human see what
199
+ // went into the hash without needing to re-probe the compiler. Keep it
200
+ // small: just the identifying strings, not the full macro dumps.
201
+ const input = [
202
+ `type=${type}`,
203
+ `target=${probes.dumpmachine}`,
204
+ `version=${version.major}.${version.minor}.${version.patch}`,
205
+ `dumpversion=${probes.dumpversion}`,
206
+ probes.dumpfullversion ? `dumpfullversion=${probes.dumpfullversion}` : ""
207
+ ]
208
+ .filter((s) => s.length > 0)
209
+ .join("\n");
210
+ return { hash, input, type, version };
211
+ }
212
+ // A client-supplied key must not be trusted to be small: it lands in a Map
213
+ // that lives as long as the daemon.
214
+ const MAX_KEY_LENGTH = 256;
215
+ function clearTimer(entry) {
216
+ if (entry.timer) {
217
+ clearTimeout(entry.timer);
218
+ entry.timer = undefined;
219
+ }
220
+ }
221
+ // Caches compiler fingerprints, obtaining them from clients rather than by
222
+ // running anything.
223
+ //
224
+ // The key is opaque here and comes from the client -- it identifies "the same
225
+ // compiler file" well enough to decide whether to re-probe. It deliberately is
226
+ // not the fingerprint: we need something cheap to compute *before* probing.
227
+ //
228
+ // Only one client is asked per key. Everyone else waits on the same answer,
229
+ // which is what keeps a cold parallel build from probing the same compiler
230
+ // once per job. Callers get a promise, so the daemon's existing "await the
231
+ // info, then hand back a slot" flow already holds those clients' slots for
232
+ // the duration without any extra slot bookkeeping.
233
+ class CompilerInfoStore {
234
+ constructor(timeoutMs = PROBE_TIMEOUT_MS * 2, log = () => {
235
+ /* quiet by default */
236
+ }) {
237
+ this.timeoutMs = timeoutMs;
238
+ this.log = log;
239
+ this.cache = new Map();
240
+ this.pending = new Map();
241
+ }
242
+ get(key, requester) {
243
+ if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY_LENGTH) {
244
+ return Promise.reject(new Error("compiler key must be a non-empty string of sane length"));
245
+ }
246
+ const cached = this.cache.get(key);
247
+ if (cached) {
248
+ return Promise.resolve(cached);
249
+ }
250
+ return new Promise((resolve, reject) => {
251
+ let entry = this.pending.get(key);
252
+ if (!entry) {
253
+ entry = { waiters: [], triedIds: new Set() };
254
+ this.pending.set(key, entry);
255
+ }
256
+ entry.waiters.push({ requester, resolve, reject });
257
+ // Someone is already probing this compiler; just wait for them.
258
+ if (entry.electedId === undefined) {
259
+ this.elect(key, entry);
260
+ }
261
+ });
262
+ }
263
+ // The elected client reported probe output.
264
+ provide(key, results) {
265
+ const entry = this.pending.get(key);
266
+ let info;
267
+ try {
268
+ info = createCompilerInfo(results);
269
+ }
270
+ catch (err) {
271
+ const message = err instanceof Error ? err.message : String(err);
272
+ this.log("compilerInfo for", key, "was unusable:", message);
273
+ if (entry) {
274
+ this.reelect(key, entry, message);
275
+ }
276
+ return;
277
+ }
278
+ this.cache.set(key, info);
279
+ if (!entry) {
280
+ return;
281
+ }
282
+ this.finish(key, entry);
283
+ for (const waiter of entry.waiters) {
284
+ waiter.resolve(info);
285
+ }
286
+ }
287
+ // The elected client could not probe the compiler.
288
+ fail(key, error) {
289
+ const entry = this.pending.get(key);
290
+ if (entry) {
291
+ this.reelect(key, entry, error);
292
+ }
293
+ }
294
+ // A client went away. If it owed us an answer, ask someone else.
295
+ clientGone(requester) {
296
+ for (const [key, entry] of this.pending) {
297
+ entry.waiters = entry.waiters.filter((w) => w.requester.id !== requester.id);
298
+ if (entry.electedId === requester.id) {
299
+ this.reelect(key, entry, "client disconnected before reporting compiler info");
300
+ }
301
+ else if (!entry.waiters.length) {
302
+ this.finish(key, entry);
303
+ }
304
+ }
305
+ }
306
+ elect(key, entry) {
307
+ var _a, _b;
308
+ const next = entry.waiters.find((w) => !entry.triedIds.has(w.requester.id));
309
+ if (!next) {
310
+ // Nobody left who has not already failed us.
311
+ const waiters = entry.waiters;
312
+ this.finish(key, entry);
313
+ const err = new Error("no client could provide compiler info");
314
+ for (const waiter of waiters) {
315
+ waiter.reject(err);
316
+ }
317
+ return;
318
+ }
319
+ entry.electedId = next.requester.id;
320
+ entry.triedIds.add(next.requester.id);
321
+ entry.timer = setTimeout(() => {
322
+ this.log("compilerInfo probe timed out for", key, "client", next.requester.id);
323
+ this.reelect(key, entry, "timed out waiting for compiler info");
324
+ }, this.timeoutMs);
325
+ // Do not let a pending probe hold the process open.
326
+ (_b = (_a = entry.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
327
+ this.log("asking client", next.requester.id, "to probe compiler", key);
328
+ try {
329
+ next.requester.requestCompilerInfo(key, PROBES, PROBE_TIMEOUT_MS);
330
+ }
331
+ catch (err) {
332
+ this.log("failed to ask client", next.requester.id, err);
333
+ this.reelect(key, entry, "could not ask client to probe");
334
+ }
335
+ }
336
+ reelect(key, entry, why) {
337
+ this.log("re-electing for", key, "-", why);
338
+ clearTimer(entry);
339
+ entry.electedId = undefined;
340
+ this.elect(key, entry);
341
+ }
342
+ finish(key, entry) {
343
+ clearTimer(entry);
344
+ this.pending.delete(key);
345
+ }
346
+ }
347
+
348
+ const Constants = {
349
+ // client codes
350
+ get AcquireCppSlot() {
351
+ return 1;
352
+ },
353
+ get AcquireCompileSlot() {
354
+ return 2;
355
+ },
356
+ get ReleaseCppSlot() {
357
+ return 3;
358
+ },
359
+ get ReleaseCompileSlot() {
360
+ return 4;
361
+ },
362
+ get JSON() {
363
+ return 5;
364
+ },
365
+ get AcquireSlot() {
366
+ return 6;
367
+ },
368
+ get ReleaseLocalSlot() {
369
+ return 7;
370
+ },
371
+ // daemon codes
372
+ get CppSlotAcquired() {
373
+ return 10;
374
+ },
375
+ get CompileSlotAcquired() {
376
+ return 11;
377
+ },
378
+ get JSONResponse() {
379
+ return 12;
380
+ },
381
+ get LocalSlotAcquired() {
382
+ return 13;
383
+ }
384
+ };
385
+
386
+ class ClientBuffer {
387
+ constructor() {
388
+ this.buffers = [];
389
+ this.offset = 0;
390
+ }
391
+ get available() {
392
+ return this.buffers.reduce((total, buf) => total + buf.length, 0) - this.offset;
393
+ }
394
+ write(buffer) {
395
+ this.buffers.push(buffer);
396
+ // console.log("write", buffer.length, this.buffers.length, this.available);
397
+ }
398
+ peek() {
399
+ if (!this.available) {
400
+ throw new Error("No data available");
401
+ }
402
+ return this.buffers[0][this.offset];
403
+ }
404
+ read(len) {
405
+ if (!len) {
406
+ throw new Error("Don't be a tool");
407
+ }
408
+ if (len > this.available) {
409
+ throw new Error("We don't have this many bytes available " + len + ">" + this.available);
410
+ }
411
+ // console.log("read", len, this.available);
412
+ let ret;
413
+ if (this.buffers[0].length - this.offset >= len) {
414
+ // buffers[0] is enough
415
+ const buf = this.buffers[0];
416
+ if (buf.length - this.offset === len) {
417
+ ret = this.offset ? buf.slice(this.offset) : buf;
418
+ this.offset = 0;
419
+ this.buffers.splice(0, 1);
420
+ return ret;
421
+ }
422
+ ret = buf.slice(this.offset, this.offset + len);
423
+ this.offset += len;
424
+ return ret;
425
+ }
426
+ ret = Buffer.allocUnsafe(len);
427
+ let retOffset = 0;
428
+ this.buffers[0].copy(ret, 0, this.offset);
429
+ retOffset += this.buffers[0].length - this.offset;
430
+ this.offset = 0;
431
+ this.buffers.splice(0, 1);
432
+ while (retOffset < len) {
433
+ const needed = len - retOffset;
434
+ const buf = this.buffers[0];
435
+ if (buf.length <= needed) {
436
+ this.buffers[0].copy(ret, retOffset);
437
+ retOffset += this.buffers[0].length;
438
+ this.buffers.splice(0, 1);
439
+ }
440
+ else {
441
+ this.buffers[0].copy(ret, retOffset, 0, needed);
442
+ retOffset += needed;
443
+ this.offset = needed;
444
+ }
445
+ }
446
+ return ret;
447
+ }
448
+ }
449
+
450
+ class Compile extends EventEmitter__default["default"] {
451
+ constructor(connection, id, option) {
452
+ super();
453
+ this.connection = connection;
454
+ this.id = id;
455
+ this.debug = option("debug");
456
+ this.buffer = new ClientBuffer();
457
+ this.messageLength = 0;
458
+ this.pid = undefined;
459
+ this.connection.on("data", this._onData.bind(this));
460
+ this.connection.on("end", () => {
461
+ // console.log("connection ended", id);
462
+ this.emit("end");
463
+ });
464
+ this.connection.on("error", (err) => {
465
+ // console.log("connection error", id, err);
466
+ this.emit("error", err);
467
+ });
468
+ }
469
+ send(message) {
470
+ if (this.debug) {
471
+ console.log("Compile::send", message);
472
+ }
473
+ try {
474
+ if (typeof message === "number") {
475
+ this.connection.write(Buffer.from([message]));
476
+ }
477
+ else {
478
+ const msg = Buffer.from(JSON.stringify(message), "utf8");
479
+ const header = Buffer.allocUnsafe(5);
480
+ header.writeUInt8(Constants.JSONResponse, 0);
481
+ header.writeUInt32BE(msg.length, 1);
482
+ if (this.debug) {
483
+ console.log("Compile::send header", header, Constants.JSONResponse);
484
+ }
485
+ this.connection.write(header);
486
+ this.connection.write(msg);
487
+ }
488
+ }
489
+ catch (err) {
490
+ console.error("Got error sending message", err);
491
+ }
492
+ }
493
+ _onData(data) {
494
+ // console.log("got data", data.length);
495
+ this.buffer.write(data);
496
+ let available = this.buffer.available;
497
+ if (this.debug) {
498
+ console.log("Compile::_onData", "id", this.id, "pid", this.pid, data, "available", available, this.messageLength);
499
+ }
500
+ if (!this.pid) {
501
+ if (available < 4) {
502
+ return;
503
+ }
504
+ const pidBuffer = this.buffer.read(4);
505
+ available -= 4;
506
+ this.pid = pidBuffer.readUInt32BE();
507
+ if (this.debug) {
508
+ console.log("Compile::_onData got pid", "id", this.id, "pid", this.pid);
509
+ }
510
+ }
511
+ const emit = (type) => {
512
+ if (this.debug) {
513
+ console.log("Compile::_onData::emit", type, available);
514
+ }
515
+ const read = this.buffer.read(1);
516
+ if (this.debug) {
517
+ console.log("Discarded", read);
518
+ }
519
+ --available;
520
+ this.emit(type);
521
+ };
522
+ while (available) {
523
+ if (!this.messageLength) {
524
+ if (this.debug) {
525
+ console.log("peeking", this.buffer.peek());
526
+ }
527
+ switch (this.buffer.peek()) {
528
+ case Constants.AcquireCppSlot:
529
+ emit("acquireCppSlot");
530
+ continue;
531
+ case Constants.AcquireCompileSlot:
532
+ emit("acquireCompileSlot");
533
+ continue;
534
+ case Constants.ReleaseCppSlot:
535
+ emit("releaseCppSlot");
536
+ continue;
537
+ case Constants.ReleaseCompileSlot:
538
+ emit("releaseCompileSlot");
539
+ continue;
540
+ case Constants.AcquireSlot:
541
+ emit("acquireSlot");
542
+ continue;
543
+ case Constants.ReleaseLocalSlot:
544
+ emit("releaseLocalSlot");
545
+ continue;
546
+ case Constants.JSON:
547
+ if (available < 5) {
548
+ break;
549
+ }
550
+ this.buffer.read(1);
551
+ this.messageLength = this.buffer.read(4).readUInt32BE();
552
+ available -= 5;
553
+ break;
554
+ default:
555
+ console.error("Bad data", this.buffer.peek(), "available", available);
556
+ throw new Error("Got unexpected type " + this.buffer.peek());
557
+ }
558
+ }
559
+ if (!this.messageLength || this.messageLength > available) {
560
+ // console.log("Still waiting on data", this.messageLength, this.buffer.available);
561
+ break;
562
+ }
563
+ const raw = this.buffer.read(this.messageLength);
564
+ available -= this.messageLength;
565
+ this.messageLength = 0;
566
+ try {
567
+ const msg = JSON.parse(raw.toString("utf8"));
568
+ if (this.debug) {
569
+ console.log("Got json message", msg);
570
+ }
571
+ // console.log("Got message", msg);
572
+ this.emit(msg.type, msg);
573
+ }
574
+ catch (err) {
575
+ console.error("Bad JSON received", err);
576
+ this.connection.destroy();
577
+ break;
578
+ }
579
+ }
580
+ }
581
+ }
582
+
583
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
584
+
585
+ var libExports = {};
586
+ var lib$1 = {
587
+ get exports(){ return libExports; },
588
+ set exports(v){ libExports = v; },
589
+ };
590
+
591
+ var fs$j = {};
592
+
593
+ var universalify = {};
594
+
595
+ universalify.fromCallback = function (fn) {
596
+ return Object.defineProperty(function () {
597
+ if (typeof arguments[arguments.length - 1] === 'function') fn.apply(this, arguments);
598
+ else {
599
+ return new Promise((resolve, reject) => {
600
+ arguments[arguments.length] = (err, res) => {
601
+ if (err) return reject(err)
602
+ resolve(res);
603
+ };
604
+ arguments.length++;
605
+ fn.apply(this, arguments);
606
+ })
607
+ }
608
+ }, 'name', { value: fn.name })
609
+ };
610
+
611
+ universalify.fromPromise = function (fn) {
612
+ return Object.defineProperty(function () {
613
+ const cb = arguments[arguments.length - 1];
614
+ if (typeof cb !== 'function') return fn.apply(this, arguments)
615
+ else fn.apply(this, arguments).then(r => cb(null, r), cb);
616
+ }, 'name', { value: fn.name })
617
+ };
618
+
619
+ var constants = require$$0__default["default"];
620
+
621
+ var origCwd = process.cwd;
622
+ var cwd = null;
623
+
624
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
625
+
626
+ process.cwd = function() {
627
+ if (!cwd)
628
+ cwd = origCwd.call(process);
629
+ return cwd
630
+ };
631
+ try {
632
+ process.cwd();
633
+ } catch (er) {}
634
+
635
+ // This check is needed until node.js 12 is required
636
+ if (typeof process.chdir === 'function') {
637
+ var chdir = process.chdir;
638
+ process.chdir = function (d) {
639
+ cwd = null;
640
+ chdir.call(process, d);
641
+ };
642
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
643
+ }
644
+
645
+ var polyfills$1 = patch$1;
646
+
647
+ function patch$1 (fs) {
648
+ // (re-)implement some things that are known busted or missing.
649
+
650
+ // lchmod, broken prior to 0.6.2
651
+ // back-port the fix here.
652
+ if (constants.hasOwnProperty('O_SYMLINK') &&
653
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
654
+ patchLchmod(fs);
655
+ }
656
+
657
+ // lutimes implementation, or no-op
658
+ if (!fs.lutimes) {
659
+ patchLutimes(fs);
660
+ }
661
+
662
+ // https://github.com/isaacs/node-graceful-fs/issues/4
663
+ // Chown should not fail on einval or eperm if non-root.
664
+ // It should not fail on enosys ever, as this just indicates
665
+ // that a fs doesn't support the intended operation.
666
+
667
+ fs.chown = chownFix(fs.chown);
668
+ fs.fchown = chownFix(fs.fchown);
669
+ fs.lchown = chownFix(fs.lchown);
670
+
671
+ fs.chmod = chmodFix(fs.chmod);
672
+ fs.fchmod = chmodFix(fs.fchmod);
673
+ fs.lchmod = chmodFix(fs.lchmod);
674
+
675
+ fs.chownSync = chownFixSync(fs.chownSync);
676
+ fs.fchownSync = chownFixSync(fs.fchownSync);
677
+ fs.lchownSync = chownFixSync(fs.lchownSync);
678
+
679
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
680
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
681
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
682
+
683
+ fs.stat = statFix(fs.stat);
684
+ fs.fstat = statFix(fs.fstat);
685
+ fs.lstat = statFix(fs.lstat);
686
+
687
+ fs.statSync = statFixSync(fs.statSync);
688
+ fs.fstatSync = statFixSync(fs.fstatSync);
689
+ fs.lstatSync = statFixSync(fs.lstatSync);
690
+
691
+ // if lchmod/lchown do not exist, then make them no-ops
692
+ if (fs.chmod && !fs.lchmod) {
693
+ fs.lchmod = function (path, mode, cb) {
694
+ if (cb) process.nextTick(cb);
695
+ };
696
+ fs.lchmodSync = function () {};
697
+ }
698
+ if (fs.chown && !fs.lchown) {
699
+ fs.lchown = function (path, uid, gid, cb) {
700
+ if (cb) process.nextTick(cb);
701
+ };
702
+ fs.lchownSync = function () {};
703
+ }
704
+
705
+ // on Windows, A/V software can lock the directory, causing this
706
+ // to fail with an EACCES or EPERM if the directory contains newly
707
+ // created files. Try again on failure, for up to 60 seconds.
708
+
709
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
710
+ // bit9, may lock files for up to a minute, causing npm package install
711
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
712
+ // CPU to a busy looping process, which can cause the program causing the lock
713
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
714
+ if (platform === "win32") {
715
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
716
+ : (function (fs$rename) {
717
+ function rename (from, to, cb) {
718
+ var start = Date.now();
719
+ var backoff = 0;
720
+ fs$rename(from, to, function CB (er) {
721
+ if (er
722
+ && (er.code === "EACCES" || er.code === "EPERM")
723
+ && Date.now() - start < 60000) {
724
+ setTimeout(function() {
725
+ fs.stat(to, function (stater, st) {
726
+ if (stater && stater.code === "ENOENT")
727
+ fs$rename(from, to, CB);
728
+ else
729
+ cb(er);
730
+ });
731
+ }, backoff);
732
+ if (backoff < 100)
733
+ backoff += 10;
734
+ return;
735
+ }
736
+ if (cb) cb(er);
737
+ });
738
+ }
739
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
740
+ return rename
741
+ })(fs.rename);
742
+ }
743
+
744
+ // if read() returns EAGAIN, then just try it again.
745
+ fs.read = typeof fs.read !== 'function' ? fs.read
746
+ : (function (fs$read) {
747
+ function read (fd, buffer, offset, length, position, callback_) {
748
+ var callback;
749
+ if (callback_ && typeof callback_ === 'function') {
750
+ var eagCounter = 0;
751
+ callback = function (er, _, __) {
752
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
753
+ eagCounter ++;
754
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
755
+ }
756
+ callback_.apply(this, arguments);
757
+ };
758
+ }
759
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
760
+ }
761
+
762
+ // This ensures `util.promisify` works as it does for native `fs.read`.
763
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
764
+ return read
765
+ })(fs.read);
766
+
767
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
768
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
769
+ var eagCounter = 0;
770
+ while (true) {
771
+ try {
772
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
773
+ } catch (er) {
774
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
775
+ eagCounter ++;
776
+ continue
777
+ }
778
+ throw er
779
+ }
780
+ }
781
+ }})(fs.readSync);
782
+
783
+ function patchLchmod (fs) {
784
+ fs.lchmod = function (path, mode, callback) {
785
+ fs.open( path
786
+ , constants.O_WRONLY | constants.O_SYMLINK
787
+ , mode
788
+ , function (err, fd) {
789
+ if (err) {
790
+ if (callback) callback(err);
791
+ return
792
+ }
793
+ // prefer to return the chmod error, if one occurs,
794
+ // but still try to close, and report closing errors if they occur.
795
+ fs.fchmod(fd, mode, function (err) {
796
+ fs.close(fd, function(err2) {
797
+ if (callback) callback(err || err2);
798
+ });
799
+ });
800
+ });
801
+ };
802
+
803
+ fs.lchmodSync = function (path, mode) {
804
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
805
+
806
+ // prefer to return the chmod error, if one occurs,
807
+ // but still try to close, and report closing errors if they occur.
808
+ var threw = true;
809
+ var ret;
810
+ try {
811
+ ret = fs.fchmodSync(fd, mode);
812
+ threw = false;
813
+ } finally {
814
+ if (threw) {
815
+ try {
816
+ fs.closeSync(fd);
817
+ } catch (er) {}
818
+ } else {
819
+ fs.closeSync(fd);
820
+ }
821
+ }
822
+ return ret
823
+ };
824
+ }
825
+
826
+ function patchLutimes (fs) {
827
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
828
+ fs.lutimes = function (path, at, mt, cb) {
829
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
830
+ if (er) {
831
+ if (cb) cb(er);
832
+ return
833
+ }
834
+ fs.futimes(fd, at, mt, function (er) {
835
+ fs.close(fd, function (er2) {
836
+ if (cb) cb(er || er2);
837
+ });
838
+ });
839
+ });
840
+ };
841
+
842
+ fs.lutimesSync = function (path, at, mt) {
843
+ var fd = fs.openSync(path, constants.O_SYMLINK);
844
+ var ret;
845
+ var threw = true;
846
+ try {
847
+ ret = fs.futimesSync(fd, at, mt);
848
+ threw = false;
849
+ } finally {
850
+ if (threw) {
851
+ try {
852
+ fs.closeSync(fd);
853
+ } catch (er) {}
854
+ } else {
855
+ fs.closeSync(fd);
856
+ }
857
+ }
858
+ return ret
859
+ };
860
+
861
+ } else if (fs.futimes) {
862
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
863
+ fs.lutimesSync = function () {};
864
+ }
865
+ }
866
+
867
+ function chmodFix (orig) {
868
+ if (!orig) return orig
869
+ return function (target, mode, cb) {
870
+ return orig.call(fs, target, mode, function (er) {
871
+ if (chownErOk(er)) er = null;
872
+ if (cb) cb.apply(this, arguments);
873
+ })
874
+ }
875
+ }
876
+
877
+ function chmodFixSync (orig) {
878
+ if (!orig) return orig
879
+ return function (target, mode) {
880
+ try {
881
+ return orig.call(fs, target, mode)
882
+ } catch (er) {
883
+ if (!chownErOk(er)) throw er
884
+ }
885
+ }
886
+ }
887
+
888
+
889
+ function chownFix (orig) {
890
+ if (!orig) return orig
891
+ return function (target, uid, gid, cb) {
892
+ return orig.call(fs, target, uid, gid, function (er) {
893
+ if (chownErOk(er)) er = null;
894
+ if (cb) cb.apply(this, arguments);
895
+ })
896
+ }
897
+ }
898
+
899
+ function chownFixSync (orig) {
900
+ if (!orig) return orig
901
+ return function (target, uid, gid) {
902
+ try {
903
+ return orig.call(fs, target, uid, gid)
904
+ } catch (er) {
905
+ if (!chownErOk(er)) throw er
906
+ }
907
+ }
908
+ }
909
+
910
+ function statFix (orig) {
911
+ if (!orig) return orig
912
+ // Older versions of Node erroneously returned signed integers for
913
+ // uid + gid.
914
+ return function (target, options, cb) {
915
+ if (typeof options === 'function') {
916
+ cb = options;
917
+ options = null;
918
+ }
919
+ function callback (er, stats) {
920
+ if (stats) {
921
+ if (stats.uid < 0) stats.uid += 0x100000000;
922
+ if (stats.gid < 0) stats.gid += 0x100000000;
923
+ }
924
+ if (cb) cb.apply(this, arguments);
925
+ }
926
+ return options ? orig.call(fs, target, options, callback)
927
+ : orig.call(fs, target, callback)
928
+ }
929
+ }
930
+
931
+ function statFixSync (orig) {
932
+ if (!orig) return orig
933
+ // Older versions of Node erroneously returned signed integers for
934
+ // uid + gid.
935
+ return function (target, options) {
936
+ var stats = options ? orig.call(fs, target, options)
937
+ : orig.call(fs, target);
938
+ if (stats) {
939
+ if (stats.uid < 0) stats.uid += 0x100000000;
940
+ if (stats.gid < 0) stats.gid += 0x100000000;
941
+ }
942
+ return stats;
943
+ }
944
+ }
945
+
946
+ // ENOSYS means that the fs doesn't support the op. Just ignore
947
+ // that, because it doesn't matter.
948
+ //
949
+ // if there's no getuid, or if getuid() is something other
950
+ // than 0, and the error is EINVAL or EPERM, then just ignore
951
+ // it.
952
+ //
953
+ // This specific case is a silent failure in cp, install, tar,
954
+ // and most other unix tools that manage permissions.
955
+ //
956
+ // When running as root, or if other types of errors are
957
+ // encountered, then it's strict.
958
+ function chownErOk (er) {
959
+ if (!er)
960
+ return true
961
+
962
+ if (er.code === "ENOSYS")
963
+ return true
964
+
965
+ var nonroot = !process.getuid || process.getuid() !== 0;
966
+ if (nonroot) {
967
+ if (er.code === "EINVAL" || er.code === "EPERM")
968
+ return true
969
+ }
970
+
971
+ return false
972
+ }
973
+ }
974
+
975
+ var Stream = require$$0__default$1["default"].Stream;
976
+
977
+ var legacyStreams = legacy$1;
978
+
979
+ function legacy$1 (fs) {
980
+ return {
981
+ ReadStream: ReadStream,
982
+ WriteStream: WriteStream
983
+ }
984
+
985
+ function ReadStream (path, options) {
986
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
987
+
988
+ Stream.call(this);
989
+
990
+ var self = this;
991
+
992
+ this.path = path;
993
+ this.fd = null;
994
+ this.readable = true;
995
+ this.paused = false;
996
+
997
+ this.flags = 'r';
998
+ this.mode = 438; /*=0666*/
999
+ this.bufferSize = 64 * 1024;
1000
+
1001
+ options = options || {};
1002
+
1003
+ // Mixin options into this
1004
+ var keys = Object.keys(options);
1005
+ for (var index = 0, length = keys.length; index < length; index++) {
1006
+ var key = keys[index];
1007
+ this[key] = options[key];
1008
+ }
1009
+
1010
+ if (this.encoding) this.setEncoding(this.encoding);
1011
+
1012
+ if (this.start !== undefined) {
1013
+ if ('number' !== typeof this.start) {
1014
+ throw TypeError('start must be a Number');
1015
+ }
1016
+ if (this.end === undefined) {
1017
+ this.end = Infinity;
1018
+ } else if ('number' !== typeof this.end) {
1019
+ throw TypeError('end must be a Number');
1020
+ }
1021
+
1022
+ if (this.start > this.end) {
1023
+ throw new Error('start must be <= end');
1024
+ }
1025
+
1026
+ this.pos = this.start;
1027
+ }
1028
+
1029
+ if (this.fd !== null) {
1030
+ process.nextTick(function() {
1031
+ self._read();
1032
+ });
1033
+ return;
1034
+ }
1035
+
1036
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
1037
+ if (err) {
1038
+ self.emit('error', err);
1039
+ self.readable = false;
1040
+ return;
1041
+ }
1042
+
1043
+ self.fd = fd;
1044
+ self.emit('open', fd);
1045
+ self._read();
1046
+ });
1047
+ }
1048
+
1049
+ function WriteStream (path, options) {
1050
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
1051
+
1052
+ Stream.call(this);
1053
+
1054
+ this.path = path;
1055
+ this.fd = null;
1056
+ this.writable = true;
1057
+
1058
+ this.flags = 'w';
1059
+ this.encoding = 'binary';
1060
+ this.mode = 438; /*=0666*/
1061
+ this.bytesWritten = 0;
1062
+
1063
+ options = options || {};
1064
+
1065
+ // Mixin options into this
1066
+ var keys = Object.keys(options);
1067
+ for (var index = 0, length = keys.length; index < length; index++) {
1068
+ var key = keys[index];
1069
+ this[key] = options[key];
1070
+ }
1071
+
1072
+ if (this.start !== undefined) {
1073
+ if ('number' !== typeof this.start) {
1074
+ throw TypeError('start must be a Number');
1075
+ }
1076
+ if (this.start < 0) {
1077
+ throw new Error('start must be >= zero');
1078
+ }
1079
+
1080
+ this.pos = this.start;
1081
+ }
1082
+
1083
+ this.busy = false;
1084
+ this._queue = [];
1085
+
1086
+ if (this.fd === null) {
1087
+ this._open = fs.open;
1088
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
1089
+ this.flush();
1090
+ }
1091
+ }
1092
+ }
1093
+
1094
+ var clone_1 = clone$1;
1095
+
1096
+ var getPrototypeOf = Object.getPrototypeOf || function (obj) {
1097
+ return obj.__proto__
1098
+ };
1099
+
1100
+ function clone$1 (obj) {
1101
+ if (obj === null || typeof obj !== 'object')
1102
+ return obj
1103
+
1104
+ if (obj instanceof Object)
1105
+ var copy = { __proto__: getPrototypeOf(obj) };
1106
+ else
1107
+ var copy = Object.create(null);
1108
+
1109
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
1110
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
1111
+ });
1112
+
1113
+ return copy
1114
+ }
1115
+
1116
+ var fs$i = require$$1__default["default"];
1117
+ var polyfills = polyfills$1;
1118
+ var legacy = legacyStreams;
1119
+ var clone = clone_1;
1120
+
1121
+ var util = require$$4__default["default"];
1122
+
1123
+ /* istanbul ignore next - node 0.x polyfill */
1124
+ var gracefulQueue;
1125
+ var previousSymbol;
1126
+
1127
+ /* istanbul ignore else - node 0.x polyfill */
1128
+ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
1129
+ gracefulQueue = Symbol.for('graceful-fs.queue');
1130
+ // This is used in testing by future versions
1131
+ previousSymbol = Symbol.for('graceful-fs.previous');
1132
+ } else {
1133
+ gracefulQueue = '___graceful-fs.queue';
1134
+ previousSymbol = '___graceful-fs.previous';
1135
+ }
1136
+
1137
+ function noop () {}
1138
+
1139
+ function publishQueue(context, queue) {
1140
+ Object.defineProperty(context, gracefulQueue, {
1141
+ get: function() {
1142
+ return queue
1143
+ }
1144
+ });
1145
+ }
1146
+
1147
+ var debug$1 = noop;
1148
+ if (util.debuglog)
1149
+ debug$1 = util.debuglog('gfs4');
1150
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
1151
+ debug$1 = function() {
1152
+ var m = util.format.apply(util, arguments);
1153
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
1154
+ console.error(m);
1155
+ };
1156
+
1157
+ // Once time initialization
1158
+ if (!fs$i[gracefulQueue]) {
1159
+ // This queue can be shared by multiple loaded instances
1160
+ var queue = commonjsGlobal[gracefulQueue] || [];
1161
+ publishQueue(fs$i, queue);
1162
+
1163
+ // Patch fs.close/closeSync to shared queue version, because we need
1164
+ // to retry() whenever a close happens *anywhere* in the program.
1165
+ // This is essential when multiple graceful-fs instances are
1166
+ // in play at the same time.
1167
+ fs$i.close = (function (fs$close) {
1168
+ function close (fd, cb) {
1169
+ return fs$close.call(fs$i, fd, function (err) {
1170
+ // This function uses the graceful-fs shared queue
1171
+ if (!err) {
1172
+ resetQueue();
1173
+ }
1174
+
1175
+ if (typeof cb === 'function')
1176
+ cb.apply(this, arguments);
1177
+ })
1178
+ }
1179
+
1180
+ Object.defineProperty(close, previousSymbol, {
1181
+ value: fs$close
1182
+ });
1183
+ return close
1184
+ })(fs$i.close);
1185
+
1186
+ fs$i.closeSync = (function (fs$closeSync) {
1187
+ function closeSync (fd) {
1188
+ // This function uses the graceful-fs shared queue
1189
+ fs$closeSync.apply(fs$i, arguments);
1190
+ resetQueue();
1191
+ }
1192
+
1193
+ Object.defineProperty(closeSync, previousSymbol, {
1194
+ value: fs$closeSync
1195
+ });
1196
+ return closeSync
1197
+ })(fs$i.closeSync);
1198
+
1199
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
1200
+ process.on('exit', function() {
1201
+ debug$1(fs$i[gracefulQueue]);
1202
+ assert__default["default"].equal(fs$i[gracefulQueue].length, 0);
1203
+ });
1204
+ }
1205
+ }
1206
+
1207
+ if (!commonjsGlobal[gracefulQueue]) {
1208
+ publishQueue(commonjsGlobal, fs$i[gracefulQueue]);
1209
+ }
1210
+
1211
+ var gracefulFs = patch(clone(fs$i));
1212
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$i.__patched) {
1213
+ gracefulFs = patch(fs$i);
1214
+ fs$i.__patched = true;
1215
+ }
1216
+
1217
+ function patch (fs) {
1218
+ // Everything that references the open() function needs to be in here
1219
+ polyfills(fs);
1220
+ fs.gracefulify = patch;
1221
+
1222
+ fs.createReadStream = createReadStream;
1223
+ fs.createWriteStream = createWriteStream;
1224
+ var fs$readFile = fs.readFile;
1225
+ fs.readFile = readFile;
1226
+ function readFile (path, options, cb) {
1227
+ if (typeof options === 'function')
1228
+ cb = options, options = null;
1229
+
1230
+ return go$readFile(path, options, cb)
1231
+
1232
+ function go$readFile (path, options, cb, startTime) {
1233
+ return fs$readFile(path, options, function (err) {
1234
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1235
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
1236
+ else {
1237
+ if (typeof cb === 'function')
1238
+ cb.apply(this, arguments);
1239
+ }
1240
+ })
1241
+ }
1242
+ }
1243
+
1244
+ var fs$writeFile = fs.writeFile;
1245
+ fs.writeFile = writeFile;
1246
+ function writeFile (path, data, options, cb) {
1247
+ if (typeof options === 'function')
1248
+ cb = options, options = null;
1249
+
1250
+ return go$writeFile(path, data, options, cb)
1251
+
1252
+ function go$writeFile (path, data, options, cb, startTime) {
1253
+ return fs$writeFile(path, data, options, function (err) {
1254
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1255
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1256
+ else {
1257
+ if (typeof cb === 'function')
1258
+ cb.apply(this, arguments);
1259
+ }
1260
+ })
1261
+ }
1262
+ }
1263
+
1264
+ var fs$appendFile = fs.appendFile;
1265
+ if (fs$appendFile)
1266
+ fs.appendFile = appendFile;
1267
+ function appendFile (path, data, options, cb) {
1268
+ if (typeof options === 'function')
1269
+ cb = options, options = null;
1270
+
1271
+ return go$appendFile(path, data, options, cb)
1272
+
1273
+ function go$appendFile (path, data, options, cb, startTime) {
1274
+ return fs$appendFile(path, data, options, function (err) {
1275
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1276
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1277
+ else {
1278
+ if (typeof cb === 'function')
1279
+ cb.apply(this, arguments);
1280
+ }
1281
+ })
1282
+ }
1283
+ }
1284
+
1285
+ var fs$copyFile = fs.copyFile;
1286
+ if (fs$copyFile)
1287
+ fs.copyFile = copyFile;
1288
+ function copyFile (src, dest, flags, cb) {
1289
+ if (typeof flags === 'function') {
1290
+ cb = flags;
1291
+ flags = 0;
1292
+ }
1293
+ return go$copyFile(src, dest, flags, cb)
1294
+
1295
+ function go$copyFile (src, dest, flags, cb, startTime) {
1296
+ return fs$copyFile(src, dest, flags, function (err) {
1297
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1298
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
1299
+ else {
1300
+ if (typeof cb === 'function')
1301
+ cb.apply(this, arguments);
1302
+ }
1303
+ })
1304
+ }
1305
+ }
1306
+
1307
+ var fs$readdir = fs.readdir;
1308
+ fs.readdir = readdir;
1309
+ var noReaddirOptionVersions = /^v[0-5]\./;
1310
+ function readdir (path, options, cb) {
1311
+ if (typeof options === 'function')
1312
+ cb = options, options = null;
1313
+
1314
+ var go$readdir = noReaddirOptionVersions.test(process.version)
1315
+ ? function go$readdir (path, options, cb, startTime) {
1316
+ return fs$readdir(path, fs$readdirCallback(
1317
+ path, options, cb, startTime
1318
+ ))
1319
+ }
1320
+ : function go$readdir (path, options, cb, startTime) {
1321
+ return fs$readdir(path, options, fs$readdirCallback(
1322
+ path, options, cb, startTime
1323
+ ))
1324
+ };
1325
+
1326
+ return go$readdir(path, options, cb)
1327
+
1328
+ function fs$readdirCallback (path, options, cb, startTime) {
1329
+ return function (err, files) {
1330
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1331
+ enqueue([
1332
+ go$readdir,
1333
+ [path, options, cb],
1334
+ err,
1335
+ startTime || Date.now(),
1336
+ Date.now()
1337
+ ]);
1338
+ else {
1339
+ if (files && files.sort)
1340
+ files.sort();
1341
+
1342
+ if (typeof cb === 'function')
1343
+ cb.call(this, err, files);
1344
+ }
1345
+ }
1346
+ }
1347
+ }
1348
+
1349
+ if (process.version.substr(0, 4) === 'v0.8') {
1350
+ var legStreams = legacy(fs);
1351
+ ReadStream = legStreams.ReadStream;
1352
+ WriteStream = legStreams.WriteStream;
1353
+ }
1354
+
1355
+ var fs$ReadStream = fs.ReadStream;
1356
+ if (fs$ReadStream) {
1357
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
1358
+ ReadStream.prototype.open = ReadStream$open;
1359
+ }
1360
+
1361
+ var fs$WriteStream = fs.WriteStream;
1362
+ if (fs$WriteStream) {
1363
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
1364
+ WriteStream.prototype.open = WriteStream$open;
1365
+ }
1366
+
1367
+ Object.defineProperty(fs, 'ReadStream', {
1368
+ get: function () {
1369
+ return ReadStream
1370
+ },
1371
+ set: function (val) {
1372
+ ReadStream = val;
1373
+ },
1374
+ enumerable: true,
1375
+ configurable: true
1376
+ });
1377
+ Object.defineProperty(fs, 'WriteStream', {
1378
+ get: function () {
1379
+ return WriteStream
1380
+ },
1381
+ set: function (val) {
1382
+ WriteStream = val;
1383
+ },
1384
+ enumerable: true,
1385
+ configurable: true
1386
+ });
1387
+
1388
+ // legacy names
1389
+ var FileReadStream = ReadStream;
1390
+ Object.defineProperty(fs, 'FileReadStream', {
1391
+ get: function () {
1392
+ return FileReadStream
1393
+ },
1394
+ set: function (val) {
1395
+ FileReadStream = val;
1396
+ },
1397
+ enumerable: true,
1398
+ configurable: true
1399
+ });
1400
+ var FileWriteStream = WriteStream;
1401
+ Object.defineProperty(fs, 'FileWriteStream', {
1402
+ get: function () {
1403
+ return FileWriteStream
1404
+ },
1405
+ set: function (val) {
1406
+ FileWriteStream = val;
1407
+ },
1408
+ enumerable: true,
1409
+ configurable: true
1410
+ });
1411
+
1412
+ function ReadStream (path, options) {
1413
+ if (this instanceof ReadStream)
1414
+ return fs$ReadStream.apply(this, arguments), this
1415
+ else
1416
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
1417
+ }
1418
+
1419
+ function ReadStream$open () {
1420
+ var that = this;
1421
+ open(that.path, that.flags, that.mode, function (err, fd) {
1422
+ if (err) {
1423
+ if (that.autoClose)
1424
+ that.destroy();
1425
+
1426
+ that.emit('error', err);
1427
+ } else {
1428
+ that.fd = fd;
1429
+ that.emit('open', fd);
1430
+ that.read();
1431
+ }
1432
+ });
1433
+ }
1434
+
1435
+ function WriteStream (path, options) {
1436
+ if (this instanceof WriteStream)
1437
+ return fs$WriteStream.apply(this, arguments), this
1438
+ else
1439
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
1440
+ }
1441
+
1442
+ function WriteStream$open () {
1443
+ var that = this;
1444
+ open(that.path, that.flags, that.mode, function (err, fd) {
1445
+ if (err) {
1446
+ that.destroy();
1447
+ that.emit('error', err);
1448
+ } else {
1449
+ that.fd = fd;
1450
+ that.emit('open', fd);
1451
+ }
1452
+ });
1453
+ }
1454
+
1455
+ function createReadStream (path, options) {
1456
+ return new fs.ReadStream(path, options)
1457
+ }
1458
+
1459
+ function createWriteStream (path, options) {
1460
+ return new fs.WriteStream(path, options)
1461
+ }
1462
+
1463
+ var fs$open = fs.open;
1464
+ fs.open = open;
1465
+ function open (path, flags, mode, cb) {
1466
+ if (typeof mode === 'function')
1467
+ cb = mode, mode = null;
1468
+
1469
+ return go$open(path, flags, mode, cb)
1470
+
1471
+ function go$open (path, flags, mode, cb, startTime) {
1472
+ return fs$open(path, flags, mode, function (err, fd) {
1473
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1474
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
1475
+ else {
1476
+ if (typeof cb === 'function')
1477
+ cb.apply(this, arguments);
1478
+ }
1479
+ })
1480
+ }
1481
+ }
1482
+
1483
+ return fs
1484
+ }
1485
+
1486
+ function enqueue (elem) {
1487
+ debug$1('ENQUEUE', elem[0].name, elem[1]);
1488
+ fs$i[gracefulQueue].push(elem);
1489
+ retry();
1490
+ }
1491
+
1492
+ // keep track of the timeout between retry() calls
1493
+ var retryTimer;
1494
+
1495
+ // reset the startTime and lastTime to now
1496
+ // this resets the start of the 60 second overall timeout as well as the
1497
+ // delay between attempts so that we'll retry these jobs sooner
1498
+ function resetQueue () {
1499
+ var now = Date.now();
1500
+ for (var i = 0; i < fs$i[gracefulQueue].length; ++i) {
1501
+ // entries that are only a length of 2 are from an older version, don't
1502
+ // bother modifying those since they'll be retried anyway.
1503
+ if (fs$i[gracefulQueue][i].length > 2) {
1504
+ fs$i[gracefulQueue][i][3] = now; // startTime
1505
+ fs$i[gracefulQueue][i][4] = now; // lastTime
1506
+ }
1507
+ }
1508
+ // call retry to make sure we're actively processing the queue
1509
+ retry();
1510
+ }
1511
+
1512
+ function retry () {
1513
+ // clear the timer and remove it to help prevent unintended concurrency
1514
+ clearTimeout(retryTimer);
1515
+ retryTimer = undefined;
1516
+
1517
+ if (fs$i[gracefulQueue].length === 0)
1518
+ return
1519
+
1520
+ var elem = fs$i[gracefulQueue].shift();
1521
+ var fn = elem[0];
1522
+ var args = elem[1];
1523
+ // these items may be unset if they were added by an older graceful-fs
1524
+ var err = elem[2];
1525
+ var startTime = elem[3];
1526
+ var lastTime = elem[4];
1527
+
1528
+ // if we don't have a startTime we have no way of knowing if we've waited
1529
+ // long enough, so go ahead and retry this item now
1530
+ if (startTime === undefined) {
1531
+ debug$1('RETRY', fn.name, args);
1532
+ fn.apply(null, args);
1533
+ } else if (Date.now() - startTime >= 60000) {
1534
+ // it's been more than 60 seconds total, bail now
1535
+ debug$1('TIMEOUT', fn.name, args);
1536
+ var cb = args.pop();
1537
+ if (typeof cb === 'function')
1538
+ cb.call(null, err);
1539
+ } else {
1540
+ // the amount of time between the last attempt and right now
1541
+ var sinceAttempt = Date.now() - lastTime;
1542
+ // the amount of time between when we first tried, and when we last tried
1543
+ // rounded up to at least 1
1544
+ var sinceStart = Math.max(lastTime - startTime, 1);
1545
+ // backoff. wait longer than the total time we've been retrying, but only
1546
+ // up to a maximum of 100ms
1547
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
1548
+ // it's been long enough since the last retry, do it again
1549
+ if (sinceAttempt >= desiredDelay) {
1550
+ debug$1('RETRY', fn.name, args);
1551
+ fn.apply(null, args.concat([startTime]));
1552
+ } else {
1553
+ // if we can't do this job yet, push it to the end of the queue
1554
+ // and let the next iteration check again
1555
+ fs$i[gracefulQueue].push(elem);
1556
+ }
1557
+ }
1558
+
1559
+ // schedule our next run if one isn't already scheduled
1560
+ if (retryTimer === undefined) {
1561
+ retryTimer = setTimeout(retry, 0);
1562
+ }
1563
+ }
1564
+
1565
+ (function (exports) {
1566
+ // This is adapted from https://github.com/normalize/mz
1567
+ // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
1568
+ const u = universalify.fromCallback;
1569
+ const fs = gracefulFs;
1570
+
1571
+ const api = [
1572
+ 'access',
1573
+ 'appendFile',
1574
+ 'chmod',
1575
+ 'chown',
1576
+ 'close',
1577
+ 'copyFile',
1578
+ 'fchmod',
1579
+ 'fchown',
1580
+ 'fdatasync',
1581
+ 'fstat',
1582
+ 'fsync',
1583
+ 'ftruncate',
1584
+ 'futimes',
1585
+ 'lchown',
1586
+ 'link',
1587
+ 'lstat',
1588
+ 'mkdir',
1589
+ 'mkdtemp',
1590
+ 'open',
1591
+ 'readFile',
1592
+ 'readdir',
1593
+ 'readlink',
1594
+ 'realpath',
1595
+ 'rename',
1596
+ 'rmdir',
1597
+ 'stat',
1598
+ 'symlink',
1599
+ 'truncate',
1600
+ 'unlink',
1601
+ 'utimes',
1602
+ 'writeFile'
1603
+ ].filter(key => {
1604
+ // Some commands are not available on some systems. Ex:
1605
+ // fs.copyFile was added in Node.js v8.5.0
1606
+ // fs.mkdtemp was added in Node.js v5.10.0
1607
+ // fs.lchown is not available on at least some Linux
1608
+ return typeof fs[key] === 'function'
1609
+ });
1610
+
1611
+ // Export all keys:
1612
+ Object.keys(fs).forEach(key => {
1613
+ if (key === 'promises') {
1614
+ // fs.promises is a getter property that triggers ExperimentalWarning
1615
+ // Don't re-export it here, the getter is defined in "lib/index.js"
1616
+ return
1617
+ }
1618
+ exports[key] = fs[key];
1619
+ });
1620
+
1621
+ // Universalify async methods:
1622
+ api.forEach(method => {
1623
+ exports[method] = u(fs[method]);
1624
+ });
1625
+
1626
+ // We differ from mz/fs in that we still ship the old, broken, fs.exists()
1627
+ // since we are a drop-in replacement for the native module
1628
+ exports.exists = function (filename, callback) {
1629
+ if (typeof callback === 'function') {
1630
+ return fs.exists(filename, callback)
1631
+ }
1632
+ return new Promise(resolve => {
1633
+ return fs.exists(filename, resolve)
1634
+ })
1635
+ };
1636
+
1637
+ // fs.read() & fs.write need special treatment due to multiple callback args
1638
+
1639
+ exports.read = function (fd, buffer, offset, length, position, callback) {
1640
+ if (typeof callback === 'function') {
1641
+ return fs.read(fd, buffer, offset, length, position, callback)
1642
+ }
1643
+ return new Promise((resolve, reject) => {
1644
+ fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
1645
+ if (err) return reject(err)
1646
+ resolve({ bytesRead, buffer });
1647
+ });
1648
+ })
1649
+ };
1650
+
1651
+ // Function signature can be
1652
+ // fs.write(fd, buffer[, offset[, length[, position]]], callback)
1653
+ // OR
1654
+ // fs.write(fd, string[, position[, encoding]], callback)
1655
+ // We need to handle both cases, so we use ...args
1656
+ exports.write = function (fd, buffer, ...args) {
1657
+ if (typeof args[args.length - 1] === 'function') {
1658
+ return fs.write(fd, buffer, ...args)
1659
+ }
1660
+
1661
+ return new Promise((resolve, reject) => {
1662
+ fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
1663
+ if (err) return reject(err)
1664
+ resolve({ bytesWritten, buffer });
1665
+ });
1666
+ })
1667
+ };
1668
+ } (fs$j));
1669
+
1670
+ const path$g = path__default["default"];
1671
+
1672
+ // get drive on windows
1673
+ function getRootPath (p) {
1674
+ p = path$g.normalize(path$g.resolve(p)).split(path$g.sep);
1675
+ if (p.length > 0) return p[0]
1676
+ return null
1677
+ }
1678
+
1679
+ // http://stackoverflow.com/a/62888/10333 contains more accurate
1680
+ // TODO: expand to include the rest
1681
+ const INVALID_PATH_CHARS = /[<>:"|?*]/;
1682
+
1683
+ function invalidWin32Path$2 (p) {
1684
+ const rp = getRootPath(p);
1685
+ p = p.replace(rp, '');
1686
+ return INVALID_PATH_CHARS.test(p)
1687
+ }
1688
+
1689
+ var win32 = {
1690
+ getRootPath,
1691
+ invalidWin32Path: invalidWin32Path$2
1692
+ };
1693
+
1694
+ const fs$h = gracefulFs;
1695
+ const path$f = path__default["default"];
1696
+ const invalidWin32Path$1 = win32.invalidWin32Path;
1697
+
1698
+ const o777$1 = parseInt('0777', 8);
1699
+
1700
+ function mkdirs$2 (p, opts, callback, made) {
1701
+ if (typeof opts === 'function') {
1702
+ callback = opts;
1703
+ opts = {};
1704
+ } else if (!opts || typeof opts !== 'object') {
1705
+ opts = { mode: opts };
1706
+ }
1707
+
1708
+ if (process.platform === 'win32' && invalidWin32Path$1(p)) {
1709
+ const errInval = new Error(p + ' contains invalid WIN32 path characters.');
1710
+ errInval.code = 'EINVAL';
1711
+ return callback(errInval)
1712
+ }
1713
+
1714
+ let mode = opts.mode;
1715
+ const xfs = opts.fs || fs$h;
1716
+
1717
+ if (mode === undefined) {
1718
+ mode = o777$1 & (~process.umask());
1719
+ }
1720
+ if (!made) made = null;
1721
+
1722
+ callback = callback || function () {};
1723
+ p = path$f.resolve(p);
1724
+
1725
+ xfs.mkdir(p, mode, er => {
1726
+ if (!er) {
1727
+ made = made || p;
1728
+ return callback(null, made)
1729
+ }
1730
+ switch (er.code) {
1731
+ case 'ENOENT':
1732
+ if (path$f.dirname(p) === p) return callback(er)
1733
+ mkdirs$2(path$f.dirname(p), opts, (er, made) => {
1734
+ if (er) callback(er, made);
1735
+ else mkdirs$2(p, opts, callback, made);
1736
+ });
1737
+ break
1738
+
1739
+ // In the case of any other error, just see if there's a dir
1740
+ // there already. If so, then hooray! If not, then something
1741
+ // is borked.
1742
+ default:
1743
+ xfs.stat(p, (er2, stat) => {
1744
+ // if the stat fails, then that's super weird.
1745
+ // let the original error be the failure reason.
1746
+ if (er2 || !stat.isDirectory()) callback(er, made);
1747
+ else callback(null, made);
1748
+ });
1749
+ break
1750
+ }
1751
+ });
1752
+ }
1753
+
1754
+ var mkdirs_1$1 = mkdirs$2;
1755
+
1756
+ const fs$g = gracefulFs;
1757
+ const path$e = path__default["default"];
1758
+ const invalidWin32Path = win32.invalidWin32Path;
1759
+
1760
+ const o777 = parseInt('0777', 8);
1761
+
1762
+ function mkdirsSync$2 (p, opts, made) {
1763
+ if (!opts || typeof opts !== 'object') {
1764
+ opts = { mode: opts };
1765
+ }
1766
+
1767
+ let mode = opts.mode;
1768
+ const xfs = opts.fs || fs$g;
1769
+
1770
+ if (process.platform === 'win32' && invalidWin32Path(p)) {
1771
+ const errInval = new Error(p + ' contains invalid WIN32 path characters.');
1772
+ errInval.code = 'EINVAL';
1773
+ throw errInval
1774
+ }
1775
+
1776
+ if (mode === undefined) {
1777
+ mode = o777 & (~process.umask());
1778
+ }
1779
+ if (!made) made = null;
1780
+
1781
+ p = path$e.resolve(p);
1782
+
1783
+ try {
1784
+ xfs.mkdirSync(p, mode);
1785
+ made = made || p;
1786
+ } catch (err0) {
1787
+ if (err0.code === 'ENOENT') {
1788
+ if (path$e.dirname(p) === p) throw err0
1789
+ made = mkdirsSync$2(path$e.dirname(p), opts, made);
1790
+ mkdirsSync$2(p, opts, made);
1791
+ } else {
1792
+ // In the case of any other error, just see if there's a dir there
1793
+ // already. If so, then hooray! If not, then something is borked.
1794
+ let stat;
1795
+ try {
1796
+ stat = xfs.statSync(p);
1797
+ } catch (err1) {
1798
+ throw err0
1799
+ }
1800
+ if (!stat.isDirectory()) throw err0
1801
+ }
1802
+ }
1803
+
1804
+ return made
1805
+ }
1806
+
1807
+ var mkdirsSync_1 = mkdirsSync$2;
1808
+
1809
+ const u$b = universalify.fromCallback;
1810
+ const mkdirs$1 = u$b(mkdirs_1$1);
1811
+ const mkdirsSync$1 = mkdirsSync_1;
1812
+
1813
+ var mkdirs_1 = {
1814
+ mkdirs: mkdirs$1,
1815
+ mkdirsSync: mkdirsSync$1,
1816
+ // alias
1817
+ mkdirp: mkdirs$1,
1818
+ mkdirpSync: mkdirsSync$1,
1819
+ ensureDir: mkdirs$1,
1820
+ ensureDirSync: mkdirsSync$1
1821
+ };
1822
+
1823
+ const fs$f = gracefulFs;
1824
+ const os = os__default["default"];
1825
+ const path$d = path__default["default"];
1826
+
1827
+ // HFS, ext{2,3}, FAT do not, Node.js v0.10 does not
1828
+ function hasMillisResSync () {
1829
+ let tmpfile = path$d.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2));
1830
+ tmpfile = path$d.join(os.tmpdir(), tmpfile);
1831
+
1832
+ // 550 millis past UNIX epoch
1833
+ const d = new Date(1435410243862);
1834
+ fs$f.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141');
1835
+ const fd = fs$f.openSync(tmpfile, 'r+');
1836
+ fs$f.futimesSync(fd, d, d);
1837
+ fs$f.closeSync(fd);
1838
+ return fs$f.statSync(tmpfile).mtime > 1435410243000
1839
+ }
1840
+
1841
+ function hasMillisRes (callback) {
1842
+ let tmpfile = path$d.join('millis-test' + Date.now().toString() + Math.random().toString().slice(2));
1843
+ tmpfile = path$d.join(os.tmpdir(), tmpfile);
1844
+
1845
+ // 550 millis past UNIX epoch
1846
+ const d = new Date(1435410243862);
1847
+ fs$f.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => {
1848
+ if (err) return callback(err)
1849
+ fs$f.open(tmpfile, 'r+', (err, fd) => {
1850
+ if (err) return callback(err)
1851
+ fs$f.futimes(fd, d, d, err => {
1852
+ if (err) return callback(err)
1853
+ fs$f.close(fd, err => {
1854
+ if (err) return callback(err)
1855
+ fs$f.stat(tmpfile, (err, stats) => {
1856
+ if (err) return callback(err)
1857
+ callback(null, stats.mtime > 1435410243000);
1858
+ });
1859
+ });
1860
+ });
1861
+ });
1862
+ });
1863
+ }
1864
+
1865
+ function timeRemoveMillis (timestamp) {
1866
+ if (typeof timestamp === 'number') {
1867
+ return Math.floor(timestamp / 1000) * 1000
1868
+ } else if (timestamp instanceof Date) {
1869
+ return new Date(Math.floor(timestamp.getTime() / 1000) * 1000)
1870
+ } else {
1871
+ throw new Error('fs-extra: timeRemoveMillis() unknown parameter type')
1872
+ }
1873
+ }
1874
+
1875
+ function utimesMillis (path, atime, mtime, callback) {
1876
+ // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
1877
+ fs$f.open(path, 'r+', (err, fd) => {
1878
+ if (err) return callback(err)
1879
+ fs$f.futimes(fd, atime, mtime, futimesErr => {
1880
+ fs$f.close(fd, closeErr => {
1881
+ if (callback) callback(futimesErr || closeErr);
1882
+ });
1883
+ });
1884
+ });
1885
+ }
1886
+
1887
+ function utimesMillisSync (path, atime, mtime) {
1888
+ const fd = fs$f.openSync(path, 'r+');
1889
+ fs$f.futimesSync(fd, atime, mtime);
1890
+ return fs$f.closeSync(fd)
1891
+ }
1892
+
1893
+ var utimes$1 = {
1894
+ hasMillisRes,
1895
+ hasMillisResSync,
1896
+ timeRemoveMillis,
1897
+ utimesMillis,
1898
+ utimesMillisSync
1899
+ };
1900
+
1901
+ /* eslint-disable node/no-deprecated-api */
1902
+ var buffer$1 = function (size) {
1903
+ if (typeof Buffer.allocUnsafe === 'function') {
1904
+ try {
1905
+ return Buffer.allocUnsafe(size)
1906
+ } catch (e) {
1907
+ return new Buffer(size)
1908
+ }
1909
+ }
1910
+ return new Buffer(size)
1911
+ };
1912
+
1913
+ const fs$e = gracefulFs;
1914
+ const path$c = path__default["default"];
1915
+ const mkdirpSync$1 = mkdirs_1.mkdirsSync;
1916
+ const utimesSync = utimes$1.utimesMillisSync;
1917
+
1918
+ const notExist$1 = Symbol('notExist');
1919
+ const existsReg$1 = Symbol('existsReg');
1920
+
1921
+ function copySync$2 (src, dest, opts) {
1922
+ if (typeof opts === 'function') {
1923
+ opts = {filter: opts};
1924
+ }
1925
+
1926
+ opts = opts || {};
1927
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
1928
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
1929
+
1930
+ // Warn about using preserveTimestamps on 32-bit node
1931
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
1932
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
1933
+ see https://github.com/jprichardson/node-fs-extra/issues/269`);
1934
+ }
1935
+
1936
+ const resolvedDest = checkPaths$1(src, dest);
1937
+
1938
+ if (opts.filter && !opts.filter(src, dest)) return
1939
+
1940
+ const destParent = path$c.dirname(dest);
1941
+ if (!fs$e.existsSync(destParent)) mkdirpSync$1(destParent);
1942
+ return startCopy$1(resolvedDest, src, dest, opts)
1943
+ }
1944
+
1945
+ function startCopy$1 (resolvedDest, src, dest, opts) {
1946
+ if (opts.filter && !opts.filter(src, dest)) return
1947
+ return getStats$1(resolvedDest, src, dest, opts)
1948
+ }
1949
+
1950
+ function getStats$1 (resolvedDest, src, dest, opts) {
1951
+ const statSync = opts.dereference ? fs$e.statSync : fs$e.lstatSync;
1952
+ const st = statSync(src);
1953
+
1954
+ if (st.isDirectory()) return onDir$1(st, resolvedDest, src, dest, opts)
1955
+ else if (st.isFile() ||
1956
+ st.isCharacterDevice() ||
1957
+ st.isBlockDevice()) return onFile$1(st, resolvedDest, src, dest, opts)
1958
+ else if (st.isSymbolicLink()) return onLink$1(resolvedDest, src, dest, opts)
1959
+ }
1960
+
1961
+ function onFile$1 (srcStat, resolvedDest, src, dest, opts) {
1962
+ if (resolvedDest === notExist$1) return copyFile$1(srcStat, src, dest, opts)
1963
+ else if (resolvedDest === existsReg$1) return mayCopyFile$1(srcStat, src, dest, opts)
1964
+ return mayCopyFile$1(srcStat, src, dest, opts)
1965
+ }
1966
+
1967
+ function mayCopyFile$1 (srcStat, src, dest, opts) {
1968
+ if (opts.overwrite) {
1969
+ fs$e.unlinkSync(dest);
1970
+ return copyFile$1(srcStat, src, dest, opts)
1971
+ } else if (opts.errorOnExist) {
1972
+ throw new Error(`'${dest}' already exists`)
1973
+ }
1974
+ }
1975
+
1976
+ function copyFile$1 (srcStat, src, dest, opts) {
1977
+ if (typeof fs$e.copyFileSync === 'function') {
1978
+ fs$e.copyFileSync(src, dest);
1979
+ fs$e.chmodSync(dest, srcStat.mode);
1980
+ if (opts.preserveTimestamps) {
1981
+ return utimesSync(dest, srcStat.atime, srcStat.mtime)
1982
+ }
1983
+ return
1984
+ }
1985
+ return copyFileFallback$1(srcStat, src, dest, opts)
1986
+ }
1987
+
1988
+ function copyFileFallback$1 (srcStat, src, dest, opts) {
1989
+ const BUF_LENGTH = 64 * 1024;
1990
+ const _buff = buffer$1(BUF_LENGTH);
1991
+
1992
+ const fdr = fs$e.openSync(src, 'r');
1993
+ const fdw = fs$e.openSync(dest, 'w', srcStat.mode);
1994
+ let pos = 0;
1995
+
1996
+ while (pos < srcStat.size) {
1997
+ const bytesRead = fs$e.readSync(fdr, _buff, 0, BUF_LENGTH, pos);
1998
+ fs$e.writeSync(fdw, _buff, 0, bytesRead);
1999
+ pos += bytesRead;
2000
+ }
2001
+
2002
+ if (opts.preserveTimestamps) fs$e.futimesSync(fdw, srcStat.atime, srcStat.mtime);
2003
+
2004
+ fs$e.closeSync(fdr);
2005
+ fs$e.closeSync(fdw);
2006
+ }
2007
+
2008
+ function onDir$1 (srcStat, resolvedDest, src, dest, opts) {
2009
+ if (resolvedDest === notExist$1) {
2010
+ if (isSrcSubdir$3(src, dest)) {
2011
+ throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
2012
+ }
2013
+ return mkDirAndCopy$1(srcStat, src, dest, opts)
2014
+ } else if (resolvedDest === existsReg$1) {
2015
+ if (isSrcSubdir$3(src, dest)) {
2016
+ throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
2017
+ }
2018
+ return mayCopyDir$1(src, dest, opts)
2019
+ }
2020
+ return copyDir$1(src, dest, opts)
2021
+ }
2022
+
2023
+ function mayCopyDir$1 (src, dest, opts) {
2024
+ if (!fs$e.statSync(dest).isDirectory()) {
2025
+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
2026
+ }
2027
+ return copyDir$1(src, dest, opts)
2028
+ }
2029
+
2030
+ function mkDirAndCopy$1 (srcStat, src, dest, opts) {
2031
+ fs$e.mkdirSync(dest, srcStat.mode);
2032
+ fs$e.chmodSync(dest, srcStat.mode);
2033
+ return copyDir$1(src, dest, opts)
2034
+ }
2035
+
2036
+ function copyDir$1 (src, dest, opts) {
2037
+ fs$e.readdirSync(src).forEach(item => copyDirItem$1(item, src, dest, opts));
2038
+ }
2039
+
2040
+ function copyDirItem$1 (item, src, dest, opts) {
2041
+ const srcItem = path$c.join(src, item);
2042
+ const destItem = path$c.join(dest, item);
2043
+ const resolvedDest = checkPaths$1(srcItem, destItem);
2044
+ return startCopy$1(resolvedDest, srcItem, destItem, opts)
2045
+ }
2046
+
2047
+ function onLink$1 (resolvedDest, src, dest, opts) {
2048
+ let resolvedSrc = fs$e.readlinkSync(src);
2049
+
2050
+ if (opts.dereference) {
2051
+ resolvedSrc = path$c.resolve(process.cwd(), resolvedSrc);
2052
+ }
2053
+
2054
+ if (resolvedDest === notExist$1 || resolvedDest === existsReg$1) {
2055
+ // if dest already exists, fs throws error anyway,
2056
+ // so no need to guard against it here.
2057
+ return fs$e.symlinkSync(resolvedSrc, dest)
2058
+ } else {
2059
+ if (opts.dereference) {
2060
+ resolvedDest = path$c.resolve(process.cwd(), resolvedDest);
2061
+ }
2062
+ if (pathsAreIdentical$1(resolvedSrc, resolvedDest)) return
2063
+
2064
+ // prevent copy if src is a subdir of dest since unlinking
2065
+ // dest in this case would result in removing src contents
2066
+ // and therefore a broken symlink would be created.
2067
+ if (fs$e.statSync(dest).isDirectory() && isSrcSubdir$3(resolvedDest, resolvedSrc)) {
2068
+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
2069
+ }
2070
+ return copyLink$1(resolvedSrc, dest)
2071
+ }
2072
+ }
2073
+
2074
+ function copyLink$1 (resolvedSrc, dest) {
2075
+ fs$e.unlinkSync(dest);
2076
+ return fs$e.symlinkSync(resolvedSrc, dest)
2077
+ }
2078
+
2079
+ // return true if dest is a subdir of src, otherwise false.
2080
+ // extract dest base dir and check if that is the same as src basename.
2081
+ function isSrcSubdir$3 (src, dest) {
2082
+ const srcArray = path$c.resolve(src).split(path$c.sep);
2083
+ const destArray = path$c.resolve(dest).split(path$c.sep);
2084
+
2085
+ return srcArray.reduce((acc, current, i) => {
2086
+ return acc && destArray[i] === current
2087
+ }, true)
2088
+ }
2089
+
2090
+ // check if dest exists and is a symlink.
2091
+ function checkDest$1 (dest) {
2092
+ let resolvedPath;
2093
+ try {
2094
+ resolvedPath = fs$e.readlinkSync(dest);
2095
+ } catch (err) {
2096
+ if (err.code === 'ENOENT') return notExist$1
2097
+
2098
+ // dest exists and is a regular file or directory, Windows may throw UNKNOWN error.
2099
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return existsReg$1
2100
+
2101
+ throw err
2102
+ }
2103
+ return resolvedPath // dest exists and is a symlink
2104
+ }
2105
+
2106
+ function pathsAreIdentical$1 (src, dest) {
2107
+ const os = process.platform;
2108
+ const resolvedSrc = path$c.resolve(src);
2109
+ const resolvedDest = path$c.resolve(dest);
2110
+ // case-insensitive paths
2111
+ if (os === 'darwin' || os === 'win32') {
2112
+ return resolvedSrc.toLowerCase() === resolvedDest.toLowerCase()
2113
+ }
2114
+ return resolvedSrc === resolvedDest
2115
+ }
2116
+
2117
+ function checkPaths$1 (src, dest) {
2118
+ const resolvedDest = checkDest$1(dest);
2119
+ if (resolvedDest === notExist$1 || resolvedDest === existsReg$1) {
2120
+ if (pathsAreIdentical$1(src, dest)) throw new Error('Source and destination must not be the same.')
2121
+ return resolvedDest
2122
+ } else {
2123
+ // check resolved dest path if dest is a symlink
2124
+ if (pathsAreIdentical$1(src, resolvedDest)) throw new Error('Source and destination must not be the same.')
2125
+ return resolvedDest
2126
+ }
2127
+ }
2128
+
2129
+ var copySync_1 = copySync$2;
2130
+
2131
+ var copySync$1 = {
2132
+ copySync: copySync_1
2133
+ };
2134
+
2135
+ const u$a = universalify.fromPromise;
2136
+ const fs$d = fs$j;
2137
+
2138
+ function pathExists$8 (path) {
2139
+ return fs$d.access(path).then(() => true).catch(() => false)
2140
+ }
2141
+
2142
+ var pathExists_1 = {
2143
+ pathExists: u$a(pathExists$8),
2144
+ pathExistsSync: fs$d.existsSync
2145
+ };
2146
+
2147
+ const fs$c = gracefulFs;
2148
+ const path$b = path__default["default"];
2149
+ const mkdirp$1 = mkdirs_1.mkdirs;
2150
+ const pathExists$7 = pathExists_1.pathExists;
2151
+ const utimes = utimes$1.utimesMillis;
2152
+
2153
+ const notExist = Symbol('notExist');
2154
+ const existsReg = Symbol('existsReg');
2155
+
2156
+ function copy$2 (src, dest, opts, cb) {
2157
+ if (typeof opts === 'function' && !cb) {
2158
+ cb = opts;
2159
+ opts = {};
2160
+ } else if (typeof opts === 'function') {
2161
+ opts = {filter: opts};
2162
+ }
2163
+
2164
+ cb = cb || function () {};
2165
+ opts = opts || {};
2166
+
2167
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
2168
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
2169
+
2170
+ // Warn about using preserveTimestamps on 32-bit node
2171
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
2172
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
2173
+ see https://github.com/jprichardson/node-fs-extra/issues/269`);
2174
+ }
2175
+
2176
+ checkPaths(src, dest, (err, resolvedDest) => {
2177
+ if (err) return cb(err)
2178
+ if (opts.filter) return handleFilter(checkParentDir, resolvedDest, src, dest, opts, cb)
2179
+ return checkParentDir(resolvedDest, src, dest, opts, cb)
2180
+ });
2181
+ }
2182
+
2183
+ function checkParentDir (resolvedDest, src, dest, opts, cb) {
2184
+ const destParent = path$b.dirname(dest);
2185
+ pathExists$7(destParent, (err, dirExists) => {
2186
+ if (err) return cb(err)
2187
+ if (dirExists) return startCopy(resolvedDest, src, dest, opts, cb)
2188
+ mkdirp$1(destParent, err => {
2189
+ if (err) return cb(err)
2190
+ return startCopy(resolvedDest, src, dest, opts, cb)
2191
+ });
2192
+ });
2193
+ }
2194
+
2195
+ function startCopy (resolvedDest, src, dest, opts, cb) {
2196
+ if (opts.filter) return handleFilter(getStats, resolvedDest, src, dest, opts, cb)
2197
+ return getStats(resolvedDest, src, dest, opts, cb)
2198
+ }
2199
+
2200
+ function handleFilter (onInclude, resolvedDest, src, dest, opts, cb) {
2201
+ Promise.resolve(opts.filter(src, dest)).then(include => {
2202
+ if (include) {
2203
+ if (resolvedDest) return onInclude(resolvedDest, src, dest, opts, cb)
2204
+ return onInclude(src, dest, opts, cb)
2205
+ }
2206
+ return cb()
2207
+ }, error => cb(error));
2208
+ }
2209
+
2210
+ function getStats (resolvedDest, src, dest, opts, cb) {
2211
+ const stat = opts.dereference ? fs$c.stat : fs$c.lstat;
2212
+ stat(src, (err, st) => {
2213
+ if (err) return cb(err)
2214
+
2215
+ if (st.isDirectory()) return onDir(st, resolvedDest, src, dest, opts, cb)
2216
+ else if (st.isFile() ||
2217
+ st.isCharacterDevice() ||
2218
+ st.isBlockDevice()) return onFile(st, resolvedDest, src, dest, opts, cb)
2219
+ else if (st.isSymbolicLink()) return onLink(resolvedDest, src, dest, opts, cb)
2220
+ });
2221
+ }
2222
+
2223
+ function onFile (srcStat, resolvedDest, src, dest, opts, cb) {
2224
+ if (resolvedDest === notExist) return copyFile(srcStat, src, dest, opts, cb)
2225
+ else if (resolvedDest === existsReg) return mayCopyFile(srcStat, src, dest, opts, cb)
2226
+ return mayCopyFile(srcStat, src, dest, opts, cb)
2227
+ }
2228
+
2229
+ function mayCopyFile (srcStat, src, dest, opts, cb) {
2230
+ if (opts.overwrite) {
2231
+ fs$c.unlink(dest, err => {
2232
+ if (err) return cb(err)
2233
+ return copyFile(srcStat, src, dest, opts, cb)
2234
+ });
2235
+ } else if (opts.errorOnExist) {
2236
+ return cb(new Error(`'${dest}' already exists`))
2237
+ } else return cb()
2238
+ }
2239
+
2240
+ function copyFile (srcStat, src, dest, opts, cb) {
2241
+ if (typeof fs$c.copyFile === 'function') {
2242
+ return fs$c.copyFile(src, dest, err => {
2243
+ if (err) return cb(err)
2244
+ return setDestModeAndTimestamps(srcStat, dest, opts, cb)
2245
+ })
2246
+ }
2247
+ return copyFileFallback(srcStat, src, dest, opts, cb)
2248
+ }
2249
+
2250
+ function copyFileFallback (srcStat, src, dest, opts, cb) {
2251
+ const rs = fs$c.createReadStream(src);
2252
+ rs.on('error', err => cb(err)).once('open', () => {
2253
+ const ws = fs$c.createWriteStream(dest, { mode: srcStat.mode });
2254
+ ws.on('error', err => cb(err))
2255
+ .on('open', () => rs.pipe(ws))
2256
+ .once('close', () => setDestModeAndTimestamps(srcStat, dest, opts, cb));
2257
+ });
2258
+ }
2259
+
2260
+ function setDestModeAndTimestamps (srcStat, dest, opts, cb) {
2261
+ fs$c.chmod(dest, srcStat.mode, err => {
2262
+ if (err) return cb(err)
2263
+ if (opts.preserveTimestamps) {
2264
+ return utimes(dest, srcStat.atime, srcStat.mtime, cb)
2265
+ }
2266
+ return cb()
2267
+ });
2268
+ }
2269
+
2270
+ function onDir (srcStat, resolvedDest, src, dest, opts, cb) {
2271
+ if (resolvedDest === notExist) {
2272
+ if (isSrcSubdir$2(src, dest)) {
2273
+ return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
2274
+ }
2275
+ return mkDirAndCopy(srcStat, src, dest, opts, cb)
2276
+ } else if (resolvedDest === existsReg) {
2277
+ if (isSrcSubdir$2(src, dest)) {
2278
+ return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
2279
+ }
2280
+ return mayCopyDir(src, dest, opts, cb)
2281
+ }
2282
+ return copyDir(src, dest, opts, cb)
2283
+ }
2284
+
2285
+ function mayCopyDir (src, dest, opts, cb) {
2286
+ fs$c.stat(dest, (err, st) => {
2287
+ if (err) return cb(err)
2288
+ if (!st.isDirectory()) {
2289
+ return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
2290
+ }
2291
+ return copyDir(src, dest, opts, cb)
2292
+ });
2293
+ }
2294
+
2295
+ function mkDirAndCopy (srcStat, src, dest, opts, cb) {
2296
+ fs$c.mkdir(dest, srcStat.mode, err => {
2297
+ if (err) return cb(err)
2298
+ fs$c.chmod(dest, srcStat.mode, err => {
2299
+ if (err) return cb(err)
2300
+ return copyDir(src, dest, opts, cb)
2301
+ });
2302
+ });
2303
+ }
2304
+
2305
+ function copyDir (src, dest, opts, cb) {
2306
+ fs$c.readdir(src, (err, items) => {
2307
+ if (err) return cb(err)
2308
+ return copyDirItems(items, src, dest, opts, cb)
2309
+ });
2310
+ }
2311
+
2312
+ function copyDirItems (items, src, dest, opts, cb) {
2313
+ const item = items.pop();
2314
+ if (!item) return cb()
2315
+ return copyDirItem(items, item, src, dest, opts, cb)
2316
+ }
2317
+
2318
+ function copyDirItem (items, item, src, dest, opts, cb) {
2319
+ const srcItem = path$b.join(src, item);
2320
+ const destItem = path$b.join(dest, item);
2321
+ checkPaths(srcItem, destItem, (err, resolvedDest) => {
2322
+ if (err) return cb(err)
2323
+ startCopy(resolvedDest, srcItem, destItem, opts, err => {
2324
+ if (err) return cb(err)
2325
+ return copyDirItems(items, src, dest, opts, cb)
2326
+ });
2327
+ });
2328
+ }
2329
+
2330
+ function onLink (resolvedDest, src, dest, opts, cb) {
2331
+ fs$c.readlink(src, (err, resolvedSrc) => {
2332
+ if (err) return cb(err)
2333
+
2334
+ if (opts.dereference) {
2335
+ resolvedSrc = path$b.resolve(process.cwd(), resolvedSrc);
2336
+ }
2337
+
2338
+ if (resolvedDest === notExist || resolvedDest === existsReg) {
2339
+ // if dest already exists, fs throws error anyway,
2340
+ // so no need to guard against it here.
2341
+ return fs$c.symlink(resolvedSrc, dest, cb)
2342
+ } else {
2343
+ if (opts.dereference) {
2344
+ resolvedDest = path$b.resolve(process.cwd(), resolvedDest);
2345
+ }
2346
+ if (pathsAreIdentical(resolvedSrc, resolvedDest)) return cb()
2347
+
2348
+ // prevent copy if src is a subdir of dest since unlinking
2349
+ // dest in this case would result in removing src contents
2350
+ // and therefore a broken symlink would be created.
2351
+ fs$c.stat(dest, (err, st) => {
2352
+ if (err) return cb(err)
2353
+ if (st.isDirectory() && isSrcSubdir$2(resolvedDest, resolvedSrc)) {
2354
+ return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
2355
+ }
2356
+ return copyLink(resolvedSrc, dest, cb)
2357
+ });
2358
+ }
2359
+ });
2360
+ }
2361
+
2362
+ function copyLink (resolvedSrc, dest, cb) {
2363
+ fs$c.unlink(dest, err => {
2364
+ if (err) return cb(err)
2365
+ return fs$c.symlink(resolvedSrc, dest, cb)
2366
+ });
2367
+ }
2368
+
2369
+ // return true if dest is a subdir of src, otherwise false.
2370
+ // extract dest base dir and check if that is the same as src basename.
2371
+ function isSrcSubdir$2 (src, dest) {
2372
+ const srcArray = path$b.resolve(src).split(path$b.sep);
2373
+ const destArray = path$b.resolve(dest).split(path$b.sep);
2374
+
2375
+ return srcArray.reduce((acc, current, i) => {
2376
+ return acc && destArray[i] === current
2377
+ }, true)
2378
+ }
2379
+
2380
+ // check if dest exists and is a symlink.
2381
+ function checkDest (dest, cb) {
2382
+ fs$c.readlink(dest, (err, resolvedPath) => {
2383
+ if (err) {
2384
+ if (err.code === 'ENOENT') return cb(null, notExist)
2385
+
2386
+ // dest exists and is a regular file or directory, Windows may throw UNKNOWN error.
2387
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return cb(null, existsReg)
2388
+
2389
+ return cb(err)
2390
+ }
2391
+ return cb(null, resolvedPath) // dest exists and is a symlink
2392
+ });
2393
+ }
2394
+
2395
+ function pathsAreIdentical (src, dest) {
2396
+ const os = process.platform;
2397
+ const resolvedSrc = path$b.resolve(src);
2398
+ const resolvedDest = path$b.resolve(dest);
2399
+ // case-insensitive paths
2400
+ if (os === 'darwin' || os === 'win32') {
2401
+ return resolvedSrc.toLowerCase() === resolvedDest.toLowerCase()
2402
+ }
2403
+ return resolvedSrc === resolvedDest
2404
+ }
2405
+
2406
+ function checkPaths (src, dest, cb) {
2407
+ checkDest(dest, (err, resolvedDest) => {
2408
+ if (err) return cb(err)
2409
+ if (resolvedDest === notExist || resolvedDest === existsReg) {
2410
+ if (pathsAreIdentical(src, dest)) return cb(new Error('Source and destination must not be the same.'))
2411
+ return cb(null, resolvedDest)
2412
+ } else {
2413
+ // check resolved dest path if dest is a symlink
2414
+ if (pathsAreIdentical(src, resolvedDest)) return cb(new Error('Source and destination must not be the same.'))
2415
+ return cb(null, resolvedDest)
2416
+ }
2417
+ });
2418
+ }
2419
+
2420
+ var copy_1 = copy$2;
2421
+
2422
+ const u$9 = universalify.fromCallback;
2423
+ var copy$1 = {
2424
+ copy: u$9(copy_1)
2425
+ };
2426
+
2427
+ const fs$b = gracefulFs;
2428
+ const path$a = path__default["default"];
2429
+ const assert = assert__default["default"];
2430
+
2431
+ const isWindows = (process.platform === 'win32');
2432
+
2433
+ function defaults (options) {
2434
+ const methods = [
2435
+ 'unlink',
2436
+ 'chmod',
2437
+ 'stat',
2438
+ 'lstat',
2439
+ 'rmdir',
2440
+ 'readdir'
2441
+ ];
2442
+ methods.forEach(m => {
2443
+ options[m] = options[m] || fs$b[m];
2444
+ m = m + 'Sync';
2445
+ options[m] = options[m] || fs$b[m];
2446
+ });
2447
+
2448
+ options.maxBusyTries = options.maxBusyTries || 3;
2449
+ }
2450
+
2451
+ function rimraf$1 (p, options, cb) {
2452
+ let busyTries = 0;
2453
+
2454
+ if (typeof options === 'function') {
2455
+ cb = options;
2456
+ options = {};
2457
+ }
2458
+
2459
+ assert(p, 'rimraf: missing path');
2460
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');
2461
+ assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required');
2462
+ assert(options, 'rimraf: invalid options argument provided');
2463
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');
2464
+
2465
+ defaults(options);
2466
+
2467
+ rimraf_(p, options, function CB (er) {
2468
+ if (er) {
2469
+ if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
2470
+ busyTries < options.maxBusyTries) {
2471
+ busyTries++;
2472
+ const time = busyTries * 100;
2473
+ // try again, with the same exact callback as this one.
2474
+ return setTimeout(() => rimraf_(p, options, CB), time)
2475
+ }
2476
+
2477
+ // already gone
2478
+ if (er.code === 'ENOENT') er = null;
2479
+ }
2480
+
2481
+ cb(er);
2482
+ });
2483
+ }
2484
+
2485
+ // Two possible strategies.
2486
+ // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
2487
+ // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
2488
+ //
2489
+ // Both result in an extra syscall when you guess wrong. However, there
2490
+ // are likely far more normal files in the world than directories. This
2491
+ // is based on the assumption that a the average number of files per
2492
+ // directory is >= 1.
2493
+ //
2494
+ // If anyone ever complains about this, then I guess the strategy could
2495
+ // be made configurable somehow. But until then, YAGNI.
2496
+ function rimraf_ (p, options, cb) {
2497
+ assert(p);
2498
+ assert(options);
2499
+ assert(typeof cb === 'function');
2500
+
2501
+ // sunos lets the root user unlink directories, which is... weird.
2502
+ // so we have to lstat here and make sure it's not a dir.
2503
+ options.lstat(p, (er, st) => {
2504
+ if (er && er.code === 'ENOENT') {
2505
+ return cb(null)
2506
+ }
2507
+
2508
+ // Windows can EPERM on stat. Life is suffering.
2509
+ if (er && er.code === 'EPERM' && isWindows) {
2510
+ return fixWinEPERM(p, options, er, cb)
2511
+ }
2512
+
2513
+ if (st && st.isDirectory()) {
2514
+ return rmdir(p, options, er, cb)
2515
+ }
2516
+
2517
+ options.unlink(p, er => {
2518
+ if (er) {
2519
+ if (er.code === 'ENOENT') {
2520
+ return cb(null)
2521
+ }
2522
+ if (er.code === 'EPERM') {
2523
+ return (isWindows)
2524
+ ? fixWinEPERM(p, options, er, cb)
2525
+ : rmdir(p, options, er, cb)
2526
+ }
2527
+ if (er.code === 'EISDIR') {
2528
+ return rmdir(p, options, er, cb)
2529
+ }
2530
+ }
2531
+ return cb(er)
2532
+ });
2533
+ });
2534
+ }
2535
+
2536
+ function fixWinEPERM (p, options, er, cb) {
2537
+ assert(p);
2538
+ assert(options);
2539
+ assert(typeof cb === 'function');
2540
+ if (er) {
2541
+ assert(er instanceof Error);
2542
+ }
2543
+
2544
+ options.chmod(p, 0o666, er2 => {
2545
+ if (er2) {
2546
+ cb(er2.code === 'ENOENT' ? null : er);
2547
+ } else {
2548
+ options.stat(p, (er3, stats) => {
2549
+ if (er3) {
2550
+ cb(er3.code === 'ENOENT' ? null : er);
2551
+ } else if (stats.isDirectory()) {
2552
+ rmdir(p, options, er, cb);
2553
+ } else {
2554
+ options.unlink(p, cb);
2555
+ }
2556
+ });
2557
+ }
2558
+ });
2559
+ }
2560
+
2561
+ function fixWinEPERMSync (p, options, er) {
2562
+ let stats;
2563
+
2564
+ assert(p);
2565
+ assert(options);
2566
+ if (er) {
2567
+ assert(er instanceof Error);
2568
+ }
2569
+
2570
+ try {
2571
+ options.chmodSync(p, 0o666);
2572
+ } catch (er2) {
2573
+ if (er2.code === 'ENOENT') {
2574
+ return
2575
+ } else {
2576
+ throw er
2577
+ }
2578
+ }
2579
+
2580
+ try {
2581
+ stats = options.statSync(p);
2582
+ } catch (er3) {
2583
+ if (er3.code === 'ENOENT') {
2584
+ return
2585
+ } else {
2586
+ throw er
2587
+ }
2588
+ }
2589
+
2590
+ if (stats.isDirectory()) {
2591
+ rmdirSync(p, options, er);
2592
+ } else {
2593
+ options.unlinkSync(p);
2594
+ }
2595
+ }
2596
+
2597
+ function rmdir (p, options, originalEr, cb) {
2598
+ assert(p);
2599
+ assert(options);
2600
+ if (originalEr) {
2601
+ assert(originalEr instanceof Error);
2602
+ }
2603
+ assert(typeof cb === 'function');
2604
+
2605
+ // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
2606
+ // if we guessed wrong, and it's not a directory, then
2607
+ // raise the original error.
2608
+ options.rmdir(p, er => {
2609
+ if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
2610
+ rmkids(p, options, cb);
2611
+ } else if (er && er.code === 'ENOTDIR') {
2612
+ cb(originalEr);
2613
+ } else {
2614
+ cb(er);
2615
+ }
2616
+ });
2617
+ }
2618
+
2619
+ function rmkids (p, options, cb) {
2620
+ assert(p);
2621
+ assert(options);
2622
+ assert(typeof cb === 'function');
2623
+
2624
+ options.readdir(p, (er, files) => {
2625
+ if (er) return cb(er)
2626
+
2627
+ let n = files.length;
2628
+ let errState;
2629
+
2630
+ if (n === 0) return options.rmdir(p, cb)
2631
+
2632
+ files.forEach(f => {
2633
+ rimraf$1(path$a.join(p, f), options, er => {
2634
+ if (errState) {
2635
+ return
2636
+ }
2637
+ if (er) return cb(errState = er)
2638
+ if (--n === 0) {
2639
+ options.rmdir(p, cb);
2640
+ }
2641
+ });
2642
+ });
2643
+ });
2644
+ }
2645
+
2646
+ // this looks simpler, and is strictly *faster*, but will
2647
+ // tie up the JavaScript thread and fail on excessively
2648
+ // deep directory trees.
2649
+ function rimrafSync (p, options) {
2650
+ let st;
2651
+
2652
+ options = options || {};
2653
+ defaults(options);
2654
+
2655
+ assert(p, 'rimraf: missing path');
2656
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');
2657
+ assert(options, 'rimraf: missing options');
2658
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');
2659
+
2660
+ try {
2661
+ st = options.lstatSync(p);
2662
+ } catch (er) {
2663
+ if (er.code === 'ENOENT') {
2664
+ return
2665
+ }
2666
+
2667
+ // Windows can EPERM on stat. Life is suffering.
2668
+ if (er.code === 'EPERM' && isWindows) {
2669
+ fixWinEPERMSync(p, options, er);
2670
+ }
2671
+ }
2672
+
2673
+ try {
2674
+ // sunos lets the root user unlink directories, which is... weird.
2675
+ if (st && st.isDirectory()) {
2676
+ rmdirSync(p, options, null);
2677
+ } else {
2678
+ options.unlinkSync(p);
2679
+ }
2680
+ } catch (er) {
2681
+ if (er.code === 'ENOENT') {
2682
+ return
2683
+ } else if (er.code === 'EPERM') {
2684
+ return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
2685
+ } else if (er.code !== 'EISDIR') {
2686
+ throw er
2687
+ }
2688
+ rmdirSync(p, options, er);
2689
+ }
2690
+ }
2691
+
2692
+ function rmdirSync (p, options, originalEr) {
2693
+ assert(p);
2694
+ assert(options);
2695
+ if (originalEr) {
2696
+ assert(originalEr instanceof Error);
2697
+ }
2698
+
2699
+ try {
2700
+ options.rmdirSync(p);
2701
+ } catch (er) {
2702
+ if (er.code === 'ENOTDIR') {
2703
+ throw originalEr
2704
+ } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
2705
+ rmkidsSync(p, options);
2706
+ } else if (er.code !== 'ENOENT') {
2707
+ throw er
2708
+ }
2709
+ }
2710
+ }
2711
+
2712
+ function rmkidsSync (p, options) {
2713
+ assert(p);
2714
+ assert(options);
2715
+ options.readdirSync(p).forEach(f => rimrafSync(path$a.join(p, f), options));
2716
+
2717
+ // We only end up here once we got ENOTEMPTY at least once, and
2718
+ // at this point, we are guaranteed to have removed all the kids.
2719
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
2720
+ // try really hard to delete stuff on windows, because it has a
2721
+ // PROFOUNDLY annoying habit of not closing handles promptly when
2722
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
2723
+ const retries = isWindows ? 100 : 1;
2724
+ let i = 0;
2725
+ do {
2726
+ let threw = true;
2727
+ try {
2728
+ const ret = options.rmdirSync(p, options);
2729
+ threw = false;
2730
+ return ret
2731
+ } finally {
2732
+ if (++i < retries && threw) continue // eslint-disable-line
2733
+ }
2734
+ } while (true)
2735
+ }
2736
+
2737
+ var rimraf_1 = rimraf$1;
2738
+ rimraf$1.sync = rimrafSync;
2739
+
2740
+ const u$8 = universalify.fromCallback;
2741
+ const rimraf = rimraf_1;
2742
+
2743
+ var remove$2 = {
2744
+ remove: u$8(rimraf),
2745
+ removeSync: rimraf.sync
2746
+ };
2747
+
2748
+ const u$7 = universalify.fromCallback;
2749
+ const fs$a = require$$1__default["default"];
2750
+ const path$9 = path__default["default"];
2751
+ const mkdir$5 = mkdirs_1;
2752
+ const remove$1 = remove$2;
2753
+
2754
+ const emptyDir = u$7(function emptyDir (dir, callback) {
2755
+ callback = callback || function () {};
2756
+ fs$a.readdir(dir, (err, items) => {
2757
+ if (err) return mkdir$5.mkdirs(dir, callback)
2758
+
2759
+ items = items.map(item => path$9.join(dir, item));
2760
+
2761
+ deleteItem();
2762
+
2763
+ function deleteItem () {
2764
+ const item = items.pop();
2765
+ if (!item) return callback()
2766
+ remove$1.remove(item, err => {
2767
+ if (err) return callback(err)
2768
+ deleteItem();
2769
+ });
2770
+ }
2771
+ });
2772
+ });
2773
+
2774
+ function emptyDirSync (dir) {
2775
+ let items;
2776
+ try {
2777
+ items = fs$a.readdirSync(dir);
2778
+ } catch (err) {
2779
+ return mkdir$5.mkdirsSync(dir)
2780
+ }
2781
+
2782
+ items.forEach(item => {
2783
+ item = path$9.join(dir, item);
2784
+ remove$1.removeSync(item);
2785
+ });
2786
+ }
2787
+
2788
+ var empty = {
2789
+ emptyDirSync,
2790
+ emptydirSync: emptyDirSync,
2791
+ emptyDir,
2792
+ emptydir: emptyDir
2793
+ };
2794
+
2795
+ const u$6 = universalify.fromCallback;
2796
+ const path$8 = path__default["default"];
2797
+ const fs$9 = gracefulFs;
2798
+ const mkdir$4 = mkdirs_1;
2799
+ const pathExists$6 = pathExists_1.pathExists;
2800
+
2801
+ function createFile (file, callback) {
2802
+ function makeFile () {
2803
+ fs$9.writeFile(file, '', err => {
2804
+ if (err) return callback(err)
2805
+ callback();
2806
+ });
2807
+ }
2808
+
2809
+ fs$9.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
2810
+ if (!err && stats.isFile()) return callback()
2811
+ const dir = path$8.dirname(file);
2812
+ pathExists$6(dir, (err, dirExists) => {
2813
+ if (err) return callback(err)
2814
+ if (dirExists) return makeFile()
2815
+ mkdir$4.mkdirs(dir, err => {
2816
+ if (err) return callback(err)
2817
+ makeFile();
2818
+ });
2819
+ });
2820
+ });
2821
+ }
2822
+
2823
+ function createFileSync (file) {
2824
+ let stats;
2825
+ try {
2826
+ stats = fs$9.statSync(file);
2827
+ } catch (e) {}
2828
+ if (stats && stats.isFile()) return
2829
+
2830
+ const dir = path$8.dirname(file);
2831
+ if (!fs$9.existsSync(dir)) {
2832
+ mkdir$4.mkdirsSync(dir);
2833
+ }
2834
+
2835
+ fs$9.writeFileSync(file, '');
2836
+ }
2837
+
2838
+ var file$1 = {
2839
+ createFile: u$6(createFile),
2840
+ createFileSync
2841
+ };
2842
+
2843
+ const u$5 = universalify.fromCallback;
2844
+ const path$7 = path__default["default"];
2845
+ const fs$8 = gracefulFs;
2846
+ const mkdir$3 = mkdirs_1;
2847
+ const pathExists$5 = pathExists_1.pathExists;
2848
+
2849
+ function createLink (srcpath, dstpath, callback) {
2850
+ function makeLink (srcpath, dstpath) {
2851
+ fs$8.link(srcpath, dstpath, err => {
2852
+ if (err) return callback(err)
2853
+ callback(null);
2854
+ });
2855
+ }
2856
+
2857
+ pathExists$5(dstpath, (err, destinationExists) => {
2858
+ if (err) return callback(err)
2859
+ if (destinationExists) return callback(null)
2860
+ fs$8.lstat(srcpath, (err) => {
2861
+ if (err) {
2862
+ err.message = err.message.replace('lstat', 'ensureLink');
2863
+ return callback(err)
2864
+ }
2865
+
2866
+ const dir = path$7.dirname(dstpath);
2867
+ pathExists$5(dir, (err, dirExists) => {
2868
+ if (err) return callback(err)
2869
+ if (dirExists) return makeLink(srcpath, dstpath)
2870
+ mkdir$3.mkdirs(dir, err => {
2871
+ if (err) return callback(err)
2872
+ makeLink(srcpath, dstpath);
2873
+ });
2874
+ });
2875
+ });
2876
+ });
2877
+ }
2878
+
2879
+ function createLinkSync (srcpath, dstpath) {
2880
+ const destinationExists = fs$8.existsSync(dstpath);
2881
+ if (destinationExists) return undefined
2882
+
2883
+ try {
2884
+ fs$8.lstatSync(srcpath);
2885
+ } catch (err) {
2886
+ err.message = err.message.replace('lstat', 'ensureLink');
2887
+ throw err
2888
+ }
2889
+
2890
+ const dir = path$7.dirname(dstpath);
2891
+ const dirExists = fs$8.existsSync(dir);
2892
+ if (dirExists) return fs$8.linkSync(srcpath, dstpath)
2893
+ mkdir$3.mkdirsSync(dir);
2894
+
2895
+ return fs$8.linkSync(srcpath, dstpath)
2896
+ }
2897
+
2898
+ var link$1 = {
2899
+ createLink: u$5(createLink),
2900
+ createLinkSync
2901
+ };
2902
+
2903
+ const path$6 = path__default["default"];
2904
+ const fs$7 = gracefulFs;
2905
+ const pathExists$4 = pathExists_1.pathExists;
2906
+
2907
+ /**
2908
+ * Function that returns two types of paths, one relative to symlink, and one
2909
+ * relative to the current working directory. Checks if path is absolute or
2910
+ * relative. If the path is relative, this function checks if the path is
2911
+ * relative to symlink or relative to current working directory. This is an
2912
+ * initiative to find a smarter `srcpath` to supply when building symlinks.
2913
+ * This allows you to determine which path to use out of one of three possible
2914
+ * types of source paths. The first is an absolute path. This is detected by
2915
+ * `path.isAbsolute()`. When an absolute path is provided, it is checked to
2916
+ * see if it exists. If it does it's used, if not an error is returned
2917
+ * (callback)/ thrown (sync). The other two options for `srcpath` are a
2918
+ * relative url. By default Node's `fs.symlink` works by creating a symlink
2919
+ * using `dstpath` and expects the `srcpath` to be relative to the newly
2920
+ * created symlink. If you provide a `srcpath` that does not exist on the file
2921
+ * system it results in a broken symlink. To minimize this, the function
2922
+ * checks to see if the 'relative to symlink' source file exists, and if it
2923
+ * does it will use it. If it does not, it checks if there's a file that
2924
+ * exists that is relative to the current working directory, if does its used.
2925
+ * This preserves the expectations of the original fs.symlink spec and adds
2926
+ * the ability to pass in `relative to current working direcotry` paths.
2927
+ */
2928
+
2929
+ function symlinkPaths$1 (srcpath, dstpath, callback) {
2930
+ if (path$6.isAbsolute(srcpath)) {
2931
+ return fs$7.lstat(srcpath, (err) => {
2932
+ if (err) {
2933
+ err.message = err.message.replace('lstat', 'ensureSymlink');
2934
+ return callback(err)
2935
+ }
2936
+ return callback(null, {
2937
+ 'toCwd': srcpath,
2938
+ 'toDst': srcpath
2939
+ })
2940
+ })
2941
+ } else {
2942
+ const dstdir = path$6.dirname(dstpath);
2943
+ const relativeToDst = path$6.join(dstdir, srcpath);
2944
+ return pathExists$4(relativeToDst, (err, exists) => {
2945
+ if (err) return callback(err)
2946
+ if (exists) {
2947
+ return callback(null, {
2948
+ 'toCwd': relativeToDst,
2949
+ 'toDst': srcpath
2950
+ })
2951
+ } else {
2952
+ return fs$7.lstat(srcpath, (err) => {
2953
+ if (err) {
2954
+ err.message = err.message.replace('lstat', 'ensureSymlink');
2955
+ return callback(err)
2956
+ }
2957
+ return callback(null, {
2958
+ 'toCwd': srcpath,
2959
+ 'toDst': path$6.relative(dstdir, srcpath)
2960
+ })
2961
+ })
2962
+ }
2963
+ })
2964
+ }
2965
+ }
2966
+
2967
+ function symlinkPathsSync$1 (srcpath, dstpath) {
2968
+ let exists;
2969
+ if (path$6.isAbsolute(srcpath)) {
2970
+ exists = fs$7.existsSync(srcpath);
2971
+ if (!exists) throw new Error('absolute srcpath does not exist')
2972
+ return {
2973
+ 'toCwd': srcpath,
2974
+ 'toDst': srcpath
2975
+ }
2976
+ } else {
2977
+ const dstdir = path$6.dirname(dstpath);
2978
+ const relativeToDst = path$6.join(dstdir, srcpath);
2979
+ exists = fs$7.existsSync(relativeToDst);
2980
+ if (exists) {
2981
+ return {
2982
+ 'toCwd': relativeToDst,
2983
+ 'toDst': srcpath
2984
+ }
2985
+ } else {
2986
+ exists = fs$7.existsSync(srcpath);
2987
+ if (!exists) throw new Error('relative srcpath does not exist')
2988
+ return {
2989
+ 'toCwd': srcpath,
2990
+ 'toDst': path$6.relative(dstdir, srcpath)
2991
+ }
2992
+ }
2993
+ }
2994
+ }
2995
+
2996
+ var symlinkPaths_1 = {
2997
+ symlinkPaths: symlinkPaths$1,
2998
+ symlinkPathsSync: symlinkPathsSync$1
2999
+ };
3000
+
3001
+ const fs$6 = gracefulFs;
3002
+
3003
+ function symlinkType$1 (srcpath, type, callback) {
3004
+ callback = (typeof type === 'function') ? type : callback;
3005
+ type = (typeof type === 'function') ? false : type;
3006
+ if (type) return callback(null, type)
3007
+ fs$6.lstat(srcpath, (err, stats) => {
3008
+ if (err) return callback(null, 'file')
3009
+ type = (stats && stats.isDirectory()) ? 'dir' : 'file';
3010
+ callback(null, type);
3011
+ });
3012
+ }
3013
+
3014
+ function symlinkTypeSync$1 (srcpath, type) {
3015
+ let stats;
3016
+
3017
+ if (type) return type
3018
+ try {
3019
+ stats = fs$6.lstatSync(srcpath);
3020
+ } catch (e) {
3021
+ return 'file'
3022
+ }
3023
+ return (stats && stats.isDirectory()) ? 'dir' : 'file'
3024
+ }
3025
+
3026
+ var symlinkType_1 = {
3027
+ symlinkType: symlinkType$1,
3028
+ symlinkTypeSync: symlinkTypeSync$1
3029
+ };
3030
+
3031
+ const u$4 = universalify.fromCallback;
3032
+ const path$5 = path__default["default"];
3033
+ const fs$5 = gracefulFs;
3034
+ const _mkdirs = mkdirs_1;
3035
+ const mkdirs = _mkdirs.mkdirs;
3036
+ const mkdirsSync = _mkdirs.mkdirsSync;
3037
+
3038
+ const _symlinkPaths = symlinkPaths_1;
3039
+ const symlinkPaths = _symlinkPaths.symlinkPaths;
3040
+ const symlinkPathsSync = _symlinkPaths.symlinkPathsSync;
3041
+
3042
+ const _symlinkType = symlinkType_1;
3043
+ const symlinkType = _symlinkType.symlinkType;
3044
+ const symlinkTypeSync = _symlinkType.symlinkTypeSync;
3045
+
3046
+ const pathExists$3 = pathExists_1.pathExists;
3047
+
3048
+ function createSymlink (srcpath, dstpath, type, callback) {
3049
+ callback = (typeof type === 'function') ? type : callback;
3050
+ type = (typeof type === 'function') ? false : type;
3051
+
3052
+ pathExists$3(dstpath, (err, destinationExists) => {
3053
+ if (err) return callback(err)
3054
+ if (destinationExists) return callback(null)
3055
+ symlinkPaths(srcpath, dstpath, (err, relative) => {
3056
+ if (err) return callback(err)
3057
+ srcpath = relative.toDst;
3058
+ symlinkType(relative.toCwd, type, (err, type) => {
3059
+ if (err) return callback(err)
3060
+ const dir = path$5.dirname(dstpath);
3061
+ pathExists$3(dir, (err, dirExists) => {
3062
+ if (err) return callback(err)
3063
+ if (dirExists) return fs$5.symlink(srcpath, dstpath, type, callback)
3064
+ mkdirs(dir, err => {
3065
+ if (err) return callback(err)
3066
+ fs$5.symlink(srcpath, dstpath, type, callback);
3067
+ });
3068
+ });
3069
+ });
3070
+ });
3071
+ });
3072
+ }
3073
+
3074
+ function createSymlinkSync (srcpath, dstpath, type) {
3075
+ const destinationExists = fs$5.existsSync(dstpath);
3076
+ if (destinationExists) return undefined
3077
+
3078
+ const relative = symlinkPathsSync(srcpath, dstpath);
3079
+ srcpath = relative.toDst;
3080
+ type = symlinkTypeSync(relative.toCwd, type);
3081
+ const dir = path$5.dirname(dstpath);
3082
+ const exists = fs$5.existsSync(dir);
3083
+ if (exists) return fs$5.symlinkSync(srcpath, dstpath, type)
3084
+ mkdirsSync(dir);
3085
+ return fs$5.symlinkSync(srcpath, dstpath, type)
3086
+ }
3087
+
3088
+ var symlink$1 = {
3089
+ createSymlink: u$4(createSymlink),
3090
+ createSymlinkSync
3091
+ };
3092
+
3093
+ const file = file$1;
3094
+ const link = link$1;
3095
+ const symlink = symlink$1;
3096
+
3097
+ var ensure = {
3098
+ // file
3099
+ createFile: file.createFile,
3100
+ createFileSync: file.createFileSync,
3101
+ ensureFile: file.createFile,
3102
+ ensureFileSync: file.createFileSync,
3103
+ // link
3104
+ createLink: link.createLink,
3105
+ createLinkSync: link.createLinkSync,
3106
+ ensureLink: link.createLink,
3107
+ ensureLinkSync: link.createLinkSync,
3108
+ // symlink
3109
+ createSymlink: symlink.createSymlink,
3110
+ createSymlinkSync: symlink.createSymlinkSync,
3111
+ ensureSymlink: symlink.createSymlink,
3112
+ ensureSymlinkSync: symlink.createSymlinkSync
3113
+ };
3114
+
3115
+ var _fs;
3116
+ try {
3117
+ _fs = gracefulFs;
3118
+ } catch (_) {
3119
+ _fs = require$$1__default["default"];
3120
+ }
3121
+
3122
+ function readFile (file, options, callback) {
3123
+ if (callback == null) {
3124
+ callback = options;
3125
+ options = {};
3126
+ }
3127
+
3128
+ if (typeof options === 'string') {
3129
+ options = {encoding: options};
3130
+ }
3131
+
3132
+ options = options || {};
3133
+ var fs = options.fs || _fs;
3134
+
3135
+ var shouldThrow = true;
3136
+ if ('throws' in options) {
3137
+ shouldThrow = options.throws;
3138
+ }
3139
+
3140
+ fs.readFile(file, options, function (err, data) {
3141
+ if (err) return callback(err)
3142
+
3143
+ data = stripBom(data);
3144
+
3145
+ var obj;
3146
+ try {
3147
+ obj = JSON.parse(data, options ? options.reviver : null);
3148
+ } catch (err2) {
3149
+ if (shouldThrow) {
3150
+ err2.message = file + ': ' + err2.message;
3151
+ return callback(err2)
3152
+ } else {
3153
+ return callback(null, null)
3154
+ }
3155
+ }
3156
+
3157
+ callback(null, obj);
3158
+ });
3159
+ }
3160
+
3161
+ function readFileSync (file, options) {
3162
+ options = options || {};
3163
+ if (typeof options === 'string') {
3164
+ options = {encoding: options};
3165
+ }
3166
+
3167
+ var fs = options.fs || _fs;
3168
+
3169
+ var shouldThrow = true;
3170
+ if ('throws' in options) {
3171
+ shouldThrow = options.throws;
3172
+ }
3173
+
3174
+ try {
3175
+ var content = fs.readFileSync(file, options);
3176
+ content = stripBom(content);
3177
+ return JSON.parse(content, options.reviver)
3178
+ } catch (err) {
3179
+ if (shouldThrow) {
3180
+ err.message = file + ': ' + err.message;
3181
+ throw err
3182
+ } else {
3183
+ return null
3184
+ }
3185
+ }
3186
+ }
3187
+
3188
+ function stringify (obj, options) {
3189
+ var spaces;
3190
+ var EOL = '\n';
3191
+ if (typeof options === 'object' && options !== null) {
3192
+ if (options.spaces) {
3193
+ spaces = options.spaces;
3194
+ }
3195
+ if (options.EOL) {
3196
+ EOL = options.EOL;
3197
+ }
3198
+ }
3199
+
3200
+ var str = JSON.stringify(obj, options ? options.replacer : null, spaces);
3201
+
3202
+ return str.replace(/\n/g, EOL) + EOL
3203
+ }
3204
+
3205
+ function writeFile (file, obj, options, callback) {
3206
+ if (callback == null) {
3207
+ callback = options;
3208
+ options = {};
3209
+ }
3210
+ options = options || {};
3211
+ var fs = options.fs || _fs;
3212
+
3213
+ var str = '';
3214
+ try {
3215
+ str = stringify(obj, options);
3216
+ } catch (err) {
3217
+ // Need to return whether a callback was passed or not
3218
+ if (callback) callback(err, null);
3219
+ return
3220
+ }
3221
+
3222
+ fs.writeFile(file, str, options, callback);
3223
+ }
3224
+
3225
+ function writeFileSync (file, obj, options) {
3226
+ options = options || {};
3227
+ var fs = options.fs || _fs;
3228
+
3229
+ var str = stringify(obj, options);
3230
+ // not sure if fs.writeFileSync returns anything, but just in case
3231
+ return fs.writeFileSync(file, str, options)
3232
+ }
3233
+
3234
+ function stripBom (content) {
3235
+ // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
3236
+ if (Buffer.isBuffer(content)) content = content.toString('utf8');
3237
+ content = content.replace(/^\uFEFF/, '');
3238
+ return content
3239
+ }
3240
+
3241
+ var jsonfile$1 = {
3242
+ readFile: readFile,
3243
+ readFileSync: readFileSync,
3244
+ writeFile: writeFile,
3245
+ writeFileSync: writeFileSync
3246
+ };
3247
+
3248
+ var jsonfile_1 = jsonfile$1;
3249
+
3250
+ const u$3 = universalify.fromCallback;
3251
+ const jsonFile$3 = jsonfile_1;
3252
+
3253
+ var jsonfile = {
3254
+ // jsonfile exports
3255
+ readJson: u$3(jsonFile$3.readFile),
3256
+ readJsonSync: jsonFile$3.readFileSync,
3257
+ writeJson: u$3(jsonFile$3.writeFile),
3258
+ writeJsonSync: jsonFile$3.writeFileSync
3259
+ };
3260
+
3261
+ const path$4 = path__default["default"];
3262
+ const mkdir$2 = mkdirs_1;
3263
+ const pathExists$2 = pathExists_1.pathExists;
3264
+ const jsonFile$2 = jsonfile;
3265
+
3266
+ function outputJson (file, data, options, callback) {
3267
+ if (typeof options === 'function') {
3268
+ callback = options;
3269
+ options = {};
3270
+ }
3271
+
3272
+ const dir = path$4.dirname(file);
3273
+
3274
+ pathExists$2(dir, (err, itDoes) => {
3275
+ if (err) return callback(err)
3276
+ if (itDoes) return jsonFile$2.writeJson(file, data, options, callback)
3277
+
3278
+ mkdir$2.mkdirs(dir, err => {
3279
+ if (err) return callback(err)
3280
+ jsonFile$2.writeJson(file, data, options, callback);
3281
+ });
3282
+ });
3283
+ }
3284
+
3285
+ var outputJson_1 = outputJson;
3286
+
3287
+ const fs$4 = gracefulFs;
3288
+ const path$3 = path__default["default"];
3289
+ const mkdir$1 = mkdirs_1;
3290
+ const jsonFile$1 = jsonfile;
3291
+
3292
+ function outputJsonSync (file, data, options) {
3293
+ const dir = path$3.dirname(file);
3294
+
3295
+ if (!fs$4.existsSync(dir)) {
3296
+ mkdir$1.mkdirsSync(dir);
3297
+ }
3298
+
3299
+ jsonFile$1.writeJsonSync(file, data, options);
3300
+ }
3301
+
3302
+ var outputJsonSync_1 = outputJsonSync;
3303
+
3304
+ const u$2 = universalify.fromCallback;
3305
+ const jsonFile = jsonfile;
3306
+
3307
+ jsonFile.outputJson = u$2(outputJson_1);
3308
+ jsonFile.outputJsonSync = outputJsonSync_1;
3309
+ // aliases
3310
+ jsonFile.outputJSON = jsonFile.outputJson;
3311
+ jsonFile.outputJSONSync = jsonFile.outputJsonSync;
3312
+ jsonFile.writeJSON = jsonFile.writeJson;
3313
+ jsonFile.writeJSONSync = jsonFile.writeJsonSync;
3314
+ jsonFile.readJSON = jsonFile.readJson;
3315
+ jsonFile.readJSONSync = jsonFile.readJsonSync;
3316
+
3317
+ var json = jsonFile;
3318
+
3319
+ const fs$3 = gracefulFs;
3320
+ const path$2 = path__default["default"];
3321
+ const copySync = copySync$1.copySync;
3322
+ const removeSync = remove$2.removeSync;
3323
+ const mkdirpSync = mkdirs_1.mkdirsSync;
3324
+ const buffer = buffer$1;
3325
+
3326
+ function moveSync (src, dest, options) {
3327
+ options = options || {};
3328
+ const overwrite = options.overwrite || options.clobber || false;
3329
+
3330
+ src = path$2.resolve(src);
3331
+ dest = path$2.resolve(dest);
3332
+
3333
+ if (src === dest) return fs$3.accessSync(src)
3334
+
3335
+ if (isSrcSubdir$1(src, dest)) throw new Error(`Cannot move '${src}' into itself '${dest}'.`)
3336
+
3337
+ mkdirpSync(path$2.dirname(dest));
3338
+ tryRenameSync();
3339
+
3340
+ function tryRenameSync () {
3341
+ if (overwrite) {
3342
+ try {
3343
+ return fs$3.renameSync(src, dest)
3344
+ } catch (err) {
3345
+ if (err.code === 'ENOTEMPTY' || err.code === 'EEXIST' || err.code === 'EPERM') {
3346
+ removeSync(dest);
3347
+ options.overwrite = false; // just overwriteed it, no need to do it again
3348
+ return moveSync(src, dest, options)
3349
+ }
3350
+
3351
+ if (err.code !== 'EXDEV') throw err
3352
+ return moveSyncAcrossDevice(src, dest, overwrite)
3353
+ }
3354
+ } else {
3355
+ try {
3356
+ fs$3.linkSync(src, dest);
3357
+ return fs$3.unlinkSync(src)
3358
+ } catch (err) {
3359
+ if (err.code === 'EXDEV' || err.code === 'EISDIR' || err.code === 'EPERM' || err.code === 'ENOTSUP') {
3360
+ return moveSyncAcrossDevice(src, dest, overwrite)
3361
+ }
3362
+ throw err
3363
+ }
3364
+ }
3365
+ }
3366
+ }
3367
+
3368
+ function moveSyncAcrossDevice (src, dest, overwrite) {
3369
+ const stat = fs$3.statSync(src);
3370
+
3371
+ if (stat.isDirectory()) {
3372
+ return moveDirSyncAcrossDevice(src, dest, overwrite)
3373
+ } else {
3374
+ return moveFileSyncAcrossDevice(src, dest, overwrite)
3375
+ }
3376
+ }
3377
+
3378
+ function moveFileSyncAcrossDevice (src, dest, overwrite) {
3379
+ const BUF_LENGTH = 64 * 1024;
3380
+ const _buff = buffer(BUF_LENGTH);
3381
+
3382
+ const flags = overwrite ? 'w' : 'wx';
3383
+
3384
+ const fdr = fs$3.openSync(src, 'r');
3385
+ const stat = fs$3.fstatSync(fdr);
3386
+ const fdw = fs$3.openSync(dest, flags, stat.mode);
3387
+ let pos = 0;
3388
+
3389
+ while (pos < stat.size) {
3390
+ const bytesRead = fs$3.readSync(fdr, _buff, 0, BUF_LENGTH, pos);
3391
+ fs$3.writeSync(fdw, _buff, 0, bytesRead);
3392
+ pos += bytesRead;
3393
+ }
3394
+
3395
+ fs$3.closeSync(fdr);
3396
+ fs$3.closeSync(fdw);
3397
+ return fs$3.unlinkSync(src)
3398
+ }
3399
+
3400
+ function moveDirSyncAcrossDevice (src, dest, overwrite) {
3401
+ const options = {
3402
+ overwrite: false
3403
+ };
3404
+
3405
+ if (overwrite) {
3406
+ removeSync(dest);
3407
+ tryCopySync();
3408
+ } else {
3409
+ tryCopySync();
3410
+ }
3411
+
3412
+ function tryCopySync () {
3413
+ copySync(src, dest, options);
3414
+ return removeSync(src)
3415
+ }
3416
+ }
3417
+
3418
+ // return true if dest is a subdir of src, otherwise false.
3419
+ // extract dest base dir and check if that is the same as src basename
3420
+ function isSrcSubdir$1 (src, dest) {
3421
+ try {
3422
+ return fs$3.statSync(src).isDirectory() &&
3423
+ src !== dest &&
3424
+ dest.indexOf(src) > -1 &&
3425
+ dest.split(path$2.dirname(src) + path$2.sep)[1].split(path$2.sep)[0] === path$2.basename(src)
3426
+ } catch (e) {
3427
+ return false
3428
+ }
3429
+ }
3430
+
3431
+ var moveSync_1 = {
3432
+ moveSync
3433
+ };
3434
+
3435
+ const u$1 = universalify.fromCallback;
3436
+ const fs$2 = gracefulFs;
3437
+ const path$1 = path__default["default"];
3438
+ const copy = copy$1.copy;
3439
+ const remove = remove$2.remove;
3440
+ const mkdirp = mkdirs_1.mkdirp;
3441
+ const pathExists$1 = pathExists_1.pathExists;
3442
+
3443
+ function move (src, dest, opts, cb) {
3444
+ if (typeof opts === 'function') {
3445
+ cb = opts;
3446
+ opts = {};
3447
+ }
3448
+
3449
+ const overwrite = opts.overwrite || opts.clobber || false;
3450
+
3451
+ src = path$1.resolve(src);
3452
+ dest = path$1.resolve(dest);
3453
+
3454
+ if (src === dest) return fs$2.access(src, cb)
3455
+
3456
+ fs$2.stat(src, (err, st) => {
3457
+ if (err) return cb(err)
3458
+
3459
+ if (st.isDirectory() && isSrcSubdir(src, dest)) {
3460
+ return cb(new Error(`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`))
3461
+ }
3462
+ mkdirp(path$1.dirname(dest), err => {
3463
+ if (err) return cb(err)
3464
+ return doRename(src, dest, overwrite, cb)
3465
+ });
3466
+ });
3467
+ }
3468
+
3469
+ function doRename (src, dest, overwrite, cb) {
3470
+ if (overwrite) {
3471
+ return remove(dest, err => {
3472
+ if (err) return cb(err)
3473
+ return rename(src, dest, overwrite, cb)
3474
+ })
3475
+ }
3476
+ pathExists$1(dest, (err, destExists) => {
3477
+ if (err) return cb(err)
3478
+ if (destExists) return cb(new Error('dest already exists.'))
3479
+ return rename(src, dest, overwrite, cb)
3480
+ });
3481
+ }
3482
+
3483
+ function rename (src, dest, overwrite, cb) {
3484
+ fs$2.rename(src, dest, err => {
3485
+ if (!err) return cb()
3486
+ if (err.code !== 'EXDEV') return cb(err)
3487
+ return moveAcrossDevice(src, dest, overwrite, cb)
3488
+ });
3489
+ }
3490
+
3491
+ function moveAcrossDevice (src, dest, overwrite, cb) {
3492
+ const opts = {
3493
+ overwrite,
3494
+ errorOnExist: true
3495
+ };
3496
+
3497
+ copy(src, dest, opts, err => {
3498
+ if (err) return cb(err)
3499
+ return remove(src, cb)
3500
+ });
3501
+ }
3502
+
3503
+ function isSrcSubdir (src, dest) {
3504
+ const srcArray = src.split(path$1.sep);
3505
+ const destArray = dest.split(path$1.sep);
3506
+
3507
+ return srcArray.reduce((acc, current, i) => {
3508
+ return acc && destArray[i] === current
3509
+ }, true)
3510
+ }
3511
+
3512
+ var move_1 = {
3513
+ move: u$1(move)
3514
+ };
3515
+
3516
+ const u = universalify.fromCallback;
3517
+ const fs$1 = gracefulFs;
3518
+ const path = path__default["default"];
3519
+ const mkdir = mkdirs_1;
3520
+ const pathExists = pathExists_1.pathExists;
3521
+
3522
+ function outputFile (file, data, encoding, callback) {
3523
+ if (typeof encoding === 'function') {
3524
+ callback = encoding;
3525
+ encoding = 'utf8';
3526
+ }
3527
+
3528
+ const dir = path.dirname(file);
3529
+ pathExists(dir, (err, itDoes) => {
3530
+ if (err) return callback(err)
3531
+ if (itDoes) return fs$1.writeFile(file, data, encoding, callback)
3532
+
3533
+ mkdir.mkdirs(dir, err => {
3534
+ if (err) return callback(err)
3535
+
3536
+ fs$1.writeFile(file, data, encoding, callback);
3537
+ });
3538
+ });
3539
+ }
3540
+
3541
+ function outputFileSync (file, ...args) {
3542
+ const dir = path.dirname(file);
3543
+ if (fs$1.existsSync(dir)) {
3544
+ return fs$1.writeFileSync(file, ...args)
3545
+ }
3546
+ mkdir.mkdirsSync(dir);
3547
+ fs$1.writeFileSync(file, ...args);
3548
+ }
3549
+
3550
+ var output = {
3551
+ outputFile: u(outputFile),
3552
+ outputFileSync
3553
+ };
3554
+
3555
+ (function (module) {
3556
+
3557
+ module.exports = Object.assign(
3558
+ {},
3559
+ // Export promiseified graceful-fs:
3560
+ fs$j,
3561
+ // Export extra methods:
3562
+ copySync$1,
3563
+ copy$1,
3564
+ empty,
3565
+ ensure,
3566
+ json,
3567
+ mkdirs_1,
3568
+ moveSync_1,
3569
+ move_1,
3570
+ output,
3571
+ pathExists_1,
3572
+ remove$2
3573
+ );
3574
+
3575
+ // Export fs.promises as a getter property so that we don't trigger
3576
+ // ExperimentalWarning before fs.promises is actually accessed.
3577
+ const fs = require$$1__default["default"];
3578
+ if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
3579
+ Object.defineProperty(module.exports, 'promises', {
3580
+ get () { return fs.promises }
3581
+ });
3582
+ }
3583
+ } (lib$1));
3584
+
3585
+ var fs = libExports;
3586
+
3587
+ // systemd socket activation: the first passed fd is at SD_LISTEN_FDS_START (3).
3588
+ // See sd_listen_fds(3). systemd sets LISTEN_PID to the PID it should be
3589
+ // consumed by; a child process must be exec'd (not fork+exec of a wrapper)
3590
+ // so its own pid matches. We fail hard on any mismatch rather than silently
3591
+ // falling back to path binding, because that fallback would unlink the
3592
+ // systemd-owned socket file and re-create a new inode, defeating the whole
3593
+ // point of activation (and breaking every docker container that bind-mounted
3594
+ // the socket file).
3595
+ const SD_LISTEN_FDS_START = 3;
3596
+ function systemdListenFd() {
3597
+ const pidRaw = process.env.LISTEN_PID;
3598
+ const fdsRaw = process.env.LISTEN_FDS;
3599
+ // Consume the activation env so any subprocess we spawn does not inherit
3600
+ // stale LISTEN_PID/LISTEN_FDS. sd_listen_fds_with_names(3) recommends
3601
+ // unsetenv after use.
3602
+ delete process.env.LISTEN_PID;
3603
+ delete process.env.LISTEN_FDS;
3604
+ delete process.env.LISTEN_FDNAMES;
3605
+ if (!pidRaw && !fdsRaw) {
3606
+ return "none";
3607
+ }
3608
+ if (!pidRaw || !fdsRaw) {
3609
+ return "mismatch";
3610
+ }
3611
+ const pid = Number(pidRaw);
3612
+ const count = Number(fdsRaw);
3613
+ if (!Number.isInteger(pid) || !Number.isInteger(count) || count < 1) {
3614
+ return "mismatch";
3615
+ }
3616
+ if (pid !== process.pid) {
3617
+ return "mismatch";
3618
+ }
3619
+ return { fd: SD_LISTEN_FDS_START };
3620
+ }
3621
+ class Server extends EventEmitter__default["default"] {
3622
+ constructor(option, common) {
3623
+ super();
3624
+ this.option = option;
3625
+ this.debug = option("debug");
3626
+ this.file = option("socket", path__default["default"].join(common.cacheDir(), "socket"));
3627
+ this.server = undefined;
3628
+ this.option = option;
3629
+ this._connections = {};
3630
+ this._connectionId = 0;
3631
+ this._activated = false;
3632
+ }
3633
+ close() {
3634
+ if (this.debug) {
3635
+ console.log("Server::close");
3636
+ }
3637
+ if (this.server) {
3638
+ this.server.close();
3639
+ }
3640
+ // When socket-activated, systemd owns the socket file. Do not unlink
3641
+ // it -- that would break the bind-mount contract for existing clients.
3642
+ if (!this._activated) {
3643
+ try {
3644
+ fs.unlinkSync(this.file);
3645
+ }
3646
+ catch (err) {
3647
+ /* */
3648
+ }
3649
+ }
3650
+ }
3651
+ listen() {
3652
+ const activation = systemdListenFd();
3653
+ if (activation === "mismatch") {
3654
+ console.error("fisk-daemon: LISTEN_FDS/LISTEN_PID present but do not match our pid. Refusing to fall back to path binding -- exiting so systemd can restart us with correct activation.");
3655
+ process.exit(1);
3656
+ }
3657
+ if (activation !== "none") {
3658
+ const inheritedFd = activation.fd;
3659
+ this._activated = true;
3660
+ if (this.debug) {
3661
+ console.log("Server::listen using systemd-activated fd", inheritedFd);
3662
+ }
3663
+ return new Promise((resolve) => {
3664
+ let connected = false;
3665
+ this.server = net__default["default"].createServer(this._onConnection.bind(this));
3666
+ this.server.listen({ fd: inheritedFd }, () => {
3667
+ connected = true;
3668
+ resolve();
3669
+ });
3670
+ this.server.on("error", (err) => {
3671
+ if (!connected) {
3672
+ console.error("Got server error", err);
3673
+ setTimeout(this.listen.bind(this), 1000);
3674
+ }
3675
+ });
3676
+ this.server.on("close", () => {
3677
+ if (!connected) {
3678
+ setTimeout(this.listen.bind(this), 1000);
3679
+ }
3680
+ });
3681
+ });
3682
+ }
3683
+ try {
3684
+ fs.unlinkSync(this.file); // this should be more
3685
+ // complicated with attempts to
3686
+ // cleanly shut down and whatnot
3687
+ }
3688
+ catch (err) {
3689
+ /* */
3690
+ }
3691
+ return new Promise((resolve) => {
3692
+ let connected = false;
3693
+ this.server = net__default["default"].createServer(this._onConnection.bind(this)).listen(this.file, () => {
3694
+ fs.chmodSync(this.file, "777");
3695
+ connected = true;
3696
+ resolve();
3697
+ });
3698
+ this.server.on("error", (err) => {
3699
+ if (!connected) {
3700
+ console.error("Got server error", err);
3701
+ setTimeout(this.listen.bind(this), 1000);
3702
+ }
3703
+ });
3704
+ this.server.on("close", () => {
3705
+ if (!connected) {
3706
+ setTimeout(this.listen.bind(this), 1000);
3707
+ }
3708
+ });
3709
+ });
3710
+ }
3711
+ _onConnection(conn) {
3712
+ const compile = new Compile(conn, ++this._connectionId, this.option);
3713
+ if (this.debug) {
3714
+ console.log("Server::_onConnection", compile.id);
3715
+ }
3716
+ if (this._connectionId === Math.pow(2, 31) - 1) {
3717
+ this._connectionId = 0;
3718
+ }
3719
+ this._connections[compile.id] = conn;
3720
+ compile.on("end", () => {
3721
+ if (this.debug) {
3722
+ console.log("Compile::end");
3723
+ }
3724
+ delete this._connections[compile.id];
3725
+ });
3726
+ this.emit("compile", compile);
3727
+ }
3728
+ }
3729
+
3730
+ class Slots extends EventEmitter__default["default"] {
3731
+ constructor(count, name, debug) {
3732
+ super();
3733
+ this.count = count;
3734
+ this.name = name;
3735
+ this.debug = debug;
3736
+ this.used = new Map();
3737
+ this.pending = new Map();
3738
+ this._totalAcquired = 0;
3739
+ if (this.debug) {
3740
+ console.log("Slots created", this.toString());
3741
+ }
3742
+ }
3743
+ get capacity() {
3744
+ return this.count;
3745
+ }
3746
+ get active() {
3747
+ return this.used.size;
3748
+ }
3749
+ get totalAcquired() {
3750
+ return this._totalAcquired;
3751
+ }
3752
+ tryAcquire(id, data) {
3753
+ if (this.used.size < this.count) {
3754
+ this.used.set(id, data);
3755
+ ++this._totalAcquired;
3756
+ if (this.debug) {
3757
+ console.log("tryAcquire succeeded", id, data, this.toString());
3758
+ }
3759
+ this.emit("changed");
3760
+ return true;
3761
+ }
3762
+ return false;
3763
+ }
3764
+ acquire(id, data, cb) {
3765
+ if (this.used.size < this.count) {
3766
+ this.used.set(id, data);
3767
+ ++this._totalAcquired;
3768
+ if (this.debug) {
3769
+ console.log("acquired slot", id, data, this.toString());
3770
+ }
3771
+ this.emit("changed");
3772
+ cb();
3773
+ }
3774
+ else {
3775
+ if (this.debug) {
3776
+ console.log("pending slot", id, this.toString());
3777
+ }
3778
+ this.pending.set(id, { data: data, cb: cb });
3779
+ }
3780
+ }
3781
+ release(id) {
3782
+ this.pending.delete(id);
3783
+ if (this.used.has(id)) {
3784
+ const data = this.used.get(id);
3785
+ this.used.delete(id);
3786
+ assert__default["default"](this.used.size < this.count);
3787
+ assert__default["default"](this.used.size + 1 === this.count || this.pending.size === 0);
3788
+ if (this.debug) {
3789
+ console.log("released", id, data, this.toString());
3790
+ }
3791
+ // eslint-disable-next-line no-unreachable-loop
3792
+ for (const p of this.pending) {
3793
+ this.used.set(p[0], p[1].data);
3794
+ this.pending.delete(p[0]);
3795
+ ++this._totalAcquired;
3796
+ p[1].cb();
3797
+ break;
3798
+ }
3799
+ this.emit("changed");
3800
+ }
3801
+ }
3802
+ toString() {
3803
+ return `${this.name} ${this.used.size}/${this.count}`;
3804
+ }
3805
+ dump() {
3806
+ const pending = {};
3807
+ const used = {};
3808
+ for (const p of this.pending) {
3809
+ pending[p[0]] = p[1].data;
3810
+ }
3811
+ for (const p of this.used) {
3812
+ used[p[0]] = p[1];
3813
+ }
3814
+ return { used: used, pending: pending, capacity: this.count, usedSize: this.used.size };
3815
+ }
3816
+ }
3817
+
3818
+ const Version = 5;
3819
+ // 6: objects now carry the client's real source path and compilation dir,
3820
+ // baked in at compile time instead of the builder's /compiles paths, and the
3821
+ // stored response no longer keeps the paths the client used to patch with.
3822
+ const ObjectCacheFormatVersion = 6;
3823
+ function cacheDir(option) {
3824
+ let dir = option("cache-dir");
3825
+ if (!dir) {
3826
+ dir = path__default["default"].join(os__default["default"].homedir(), ".cache", "fisk", path__default["default"].basename(option.prefix || ""));
3827
+ }
3828
+ return dir;
3829
+ }
3830
+ function validateCache(option) {
3831
+ const dir = cacheDir(option);
3832
+ const file = path__default["default"].join(dir, "version");
3833
+ // console.log(dir);
3834
+ let version;
3835
+ try {
3836
+ version = fs.readFileSync(file);
3837
+ if (version.readUInt32BE() === Version) {
3838
+ return;
3839
+ }
3840
+ }
3841
+ catch (err) {
3842
+ /* */
3843
+ }
3844
+ if (version) {
3845
+ console.log(`Wrong version. Destroying cache ${dir}`);
3846
+ }
3847
+ fs.removeSync(dir);
3848
+ fs.mkdirpSync(dir);
3849
+ const buf = Buffer.allocUnsafe(4);
3850
+ buf.writeUInt32BE(Version);
3851
+ fs.writeFileSync(file, buf);
3852
+ }
3853
+ function validateObjectCache(option) {
3854
+ const dir = cacheDir(option);
3855
+ const objectCacheDir = option.string("object-cache-dir") || path__default["default"].join(dir, "objectcache");
3856
+ const file = path__default["default"].join(objectCacheDir, "version");
3857
+ let version;
3858
+ try {
3859
+ version = fs.readFileSync(file);
3860
+ if (version.readUInt32BE() === ObjectCacheFormatVersion) {
3861
+ return;
3862
+ }
3863
+ }
3864
+ catch (err) {
3865
+ /* */
3866
+ }
3867
+ if (version) {
3868
+ console.log(`Wrong object cache version. Destroying object cache ${objectCacheDir}`);
3869
+ }
3870
+ fs.removeSync(objectCacheDir);
3871
+ fs.mkdirpSync(objectCacheDir);
3872
+ const buf = Buffer.allocUnsafe(4);
3873
+ buf.writeUInt32BE(ObjectCacheFormatVersion);
3874
+ fs.writeFileSync(file, buf);
3875
+ }
3876
+ // Only the builder keeps an object cache on disk. The scheduler tracks which
3877
+ // builder holds which sha1 in memory, and the daemon uses cacheDir purely for
3878
+ // the default socket path -- validating an object cache for either created a
3879
+ // directory they never read and, on a format bump, tried to destroy one they do
3880
+ // not necessarily own.
3881
+ function common$1(option, hasObjectCache = false) {
3882
+ validateCache(option);
3883
+ if (hasObjectCache) {
3884
+ validateObjectCache(option);
3885
+ }
3886
+ return {
3887
+ cacheDir: cacheDir.bind(undefined, option),
3888
+ Version,
3889
+ ObjectCacheFormatVersion
3890
+ };
3891
+ }
3892
+
3893
+ var resolve;
3894
+ var hasRequiredResolve;
3895
+
3896
+ function requireResolve () {
3897
+ if (hasRequiredResolve) return resolve;
3898
+ hasRequiredResolve = 1;
3899
+
3900
+ // Dependencies
3901
+ var path = path__default["default"];
3902
+
3903
+ // Load global paths
3904
+ var globalPaths = require$$1__default$1["default"].globalPaths;
3905
+
3906
+ // Guess at NPM's global install dir
3907
+ var npmGlobalPrefix;
3908
+ if ('win32' === process.platform) {
3909
+ npmGlobalPrefix = path.dirname(process.execPath);
3910
+ } else {
3911
+ npmGlobalPrefix = path.dirname(path.dirname(process.execPath));
3912
+ }
3913
+ var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules');
3914
+
3915
+ // Save OS-specific path separator
3916
+ var sep = path.sep;
3917
+
3918
+ // If we're in webpack, force it to use the original require() method
3919
+ var requireFunction = ("function" === typeof __webpack_require__ || "function" === typeof __non_webpack_require__)
3920
+ ? __non_webpack_require__
3921
+ : require;
3922
+
3923
+ // Resolver
3924
+ resolve = function resolve(dirname) {
3925
+ // Check for environmental variable
3926
+ if (process.env.APP_ROOT_PATH) {
3927
+ return path.resolve(process.env.APP_ROOT_PATH);
3928
+ }
3929
+
3930
+ // Defer to Yarn Plug'n'Play if enabled
3931
+ if (process.versions.pnp) {
3932
+ try {
3933
+ var pnp = requireFunction('pnpapi');
3934
+ return pnp.getPackageInformation(pnp.topLevel).packageLocation;
3935
+ } catch (e) {}
3936
+ }
3937
+
3938
+ // Defer to main process in electron renderer
3939
+ if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) {
3940
+ try {
3941
+ var remote = requireFunction('electron').remote;
3942
+ return remote.require('app-root-path').path;
3943
+ } catch (e) {}
3944
+ }
3945
+
3946
+ // Defer to AWS Lambda when executing there
3947
+ if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) {
3948
+ return process.env.LAMBDA_TASK_ROOT;
3949
+ }
3950
+
3951
+ var resolved = path.resolve(dirname);
3952
+ var alternateMethod = false;
3953
+ var appRootPath = null;
3954
+
3955
+ // Make sure that we're not loaded from a global include path
3956
+ // Eg. $HOME/.node_modules
3957
+ // $HOME/.node_libraries
3958
+ // $PREFIX/lib/node
3959
+ globalPaths.forEach(function(globalPath) {
3960
+ if (!alternateMethod && 0 === resolved.indexOf(globalPath)) {
3961
+ alternateMethod = true;
3962
+ }
3963
+ });
3964
+
3965
+ // If the app-root-path library isn't loaded globally,
3966
+ // and node_modules exists in the path, just split __dirname
3967
+ var nodeModulesDir = sep + 'node_modules';
3968
+ if (!alternateMethod && -1 !== resolved.indexOf(nodeModulesDir)) {
3969
+ var parts = resolved.split(nodeModulesDir);
3970
+ if (parts.length) {
3971
+ appRootPath = parts[0];
3972
+ parts = null;
3973
+ }
3974
+ }
3975
+
3976
+ // If the above didn't work, or this module is loaded globally, then
3977
+ // resort to require.main.filename (See http://nodejs.org/api/modules.html)
3978
+ if (alternateMethod || null == appRootPath) {
3979
+ appRootPath = path.dirname(require.main.filename);
3980
+ }
3981
+
3982
+ // Handle global bin/ directory edge-case
3983
+ if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) {
3984
+ appRootPath = appRootPath.slice(0, -4);
3985
+ }
3986
+
3987
+ // Return
3988
+ return appRootPath;
3989
+ };
3990
+ return resolve;
3991
+ }
3992
+
3993
+ var appRootPath$1 = function(dirname) {
3994
+ var path = path__default["default"];
3995
+ var resolve = requireResolve();
3996
+ var appRootPath = resolve(dirname);
3997
+
3998
+ var publicInterface = {
3999
+ resolve: function(pathToModule) {
4000
+ return path.join(appRootPath, pathToModule);
4001
+ },
4002
+
4003
+ require: function(pathToModule) {
4004
+ return require(publicInterface.resolve(pathToModule));
4005
+ },
4006
+
4007
+ toString: function() {
4008
+ return appRootPath;
4009
+ },
4010
+
4011
+ setPath: function(explicitlySetPath) {
4012
+ appRootPath = path.resolve(explicitlySetPath);
4013
+ publicInterface.path = appRootPath;
4014
+ },
4015
+
4016
+ path: appRootPath
4017
+ };
4018
+
4019
+ return publicInterface;
4020
+ };
4021
+
4022
+ var lib = appRootPath$1;
4023
+ var appRootPath = lib(__dirname);
4024
+
4025
+ var xdgBasedir = {};
4026
+
4027
+ (function (exports) {
4028
+ const os = os__default["default"];
4029
+ const path = path__default["default"];
4030
+
4031
+ const home = os.homedir();
4032
+ const env = process.env;
4033
+
4034
+ exports.data = env.XDG_DATA_HOME ||
4035
+ (home ? path.join(home, '.local', 'share') : null);
4036
+
4037
+ exports.config = env.XDG_CONFIG_HOME ||
4038
+ (home ? path.join(home, '.config') : null);
4039
+
4040
+ exports.cache = env.XDG_CACHE_HOME || (home ? path.join(home, '.cache') : null);
4041
+
4042
+ exports.runtime = env.XDG_RUNTIME_DIR || null;
4043
+
4044
+ exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':');
4045
+
4046
+ if (exports.data) {
4047
+ exports.dataDirs.unshift(exports.data);
4048
+ }
4049
+
4050
+ exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':');
4051
+
4052
+ if (exports.config) {
4053
+ exports.configDirs.unshift(exports.config);
4054
+ }
4055
+ } (xdgBasedir));
4056
+
4057
+ function hasKey(obj, keys) {
4058
+ var o = obj;
4059
+ keys.slice(0, -1).forEach(function (key) {
4060
+ o = o[key] || {};
4061
+ });
4062
+
4063
+ var key = keys[keys.length - 1];
4064
+ return key in o;
4065
+ }
4066
+
4067
+ function isNumber(x) {
4068
+ if (typeof x === 'number') { return true; }
4069
+ if ((/^0x[0-9a-f]+$/i).test(x)) { return true; }
4070
+ return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x);
4071
+ }
4072
+
4073
+ function isConstructorOrProto(obj, key) {
4074
+ return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';
4075
+ }
4076
+
4077
+ var minimist = function (args, opts) {
4078
+ if (!opts) { opts = {}; }
4079
+
4080
+ var flags = {
4081
+ bools: {},
4082
+ strings: {},
4083
+ unknownFn: null,
4084
+ };
4085
+
4086
+ if (typeof opts.unknown === 'function') {
4087
+ flags.unknownFn = opts.unknown;
4088
+ }
4089
+
4090
+ if (typeof opts.boolean === 'boolean' && opts.boolean) {
4091
+ flags.allBools = true;
4092
+ } else {
4093
+ [].concat(opts.boolean).filter(Boolean).forEach(function (key) {
4094
+ flags.bools[key] = true;
4095
+ });
4096
+ }
4097
+
4098
+ var aliases = {};
4099
+
4100
+ function aliasIsBoolean(key) {
4101
+ return aliases[key].some(function (x) {
4102
+ return flags.bools[x];
4103
+ });
4104
+ }
4105
+
4106
+ Object.keys(opts.alias || {}).forEach(function (key) {
4107
+ aliases[key] = [].concat(opts.alias[key]);
4108
+ aliases[key].forEach(function (x) {
4109
+ aliases[x] = [key].concat(aliases[key].filter(function (y) {
4110
+ return x !== y;
4111
+ }));
4112
+ });
4113
+ });
4114
+
4115
+ [].concat(opts.string).filter(Boolean).forEach(function (key) {
4116
+ flags.strings[key] = true;
4117
+ if (aliases[key]) {
4118
+ [].concat(aliases[key]).forEach(function (k) {
4119
+ flags.strings[k] = true;
4120
+ });
4121
+ }
4122
+ });
4123
+
4124
+ var defaults = opts.default || {};
4125
+
4126
+ var argv = { _: [] };
4127
+
4128
+ function argDefined(key, arg) {
4129
+ return (flags.allBools && (/^--[^=]+$/).test(arg))
4130
+ || flags.strings[key]
4131
+ || flags.bools[key]
4132
+ || aliases[key];
4133
+ }
4134
+
4135
+ function setKey(obj, keys, value) {
4136
+ var o = obj;
4137
+ for (var i = 0; i < keys.length - 1; i++) {
4138
+ var key = keys[i];
4139
+ if (isConstructorOrProto(o, key)) { return; }
4140
+ if (o[key] === undefined) { o[key] = {}; }
4141
+ if (
4142
+ o[key] === Object.prototype
4143
+ || o[key] === Number.prototype
4144
+ || o[key] === String.prototype
4145
+ ) {
4146
+ o[key] = {};
4147
+ }
4148
+ if (o[key] === Array.prototype) { o[key] = []; }
4149
+ o = o[key];
4150
+ }
4151
+
4152
+ var lastKey = keys[keys.length - 1];
4153
+ if (isConstructorOrProto(o, lastKey)) { return; }
4154
+ if (
4155
+ o === Object.prototype
4156
+ || o === Number.prototype
4157
+ || o === String.prototype
4158
+ ) {
4159
+ o = {};
4160
+ }
4161
+ if (o === Array.prototype) { o = []; }
4162
+ if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {
4163
+ o[lastKey] = value;
4164
+ } else if (Array.isArray(o[lastKey])) {
4165
+ o[lastKey].push(value);
4166
+ } else {
4167
+ o[lastKey] = [o[lastKey], value];
4168
+ }
4169
+ }
4170
+
4171
+ function setArg(key, val, arg) {
4172
+ if (arg && flags.unknownFn && !argDefined(key, arg)) {
4173
+ if (flags.unknownFn(arg) === false) { return; }
4174
+ }
4175
+
4176
+ var value = !flags.strings[key] && isNumber(val)
4177
+ ? Number(val)
4178
+ : val;
4179
+ setKey(argv, key.split('.'), value);
4180
+
4181
+ (aliases[key] || []).forEach(function (x) {
4182
+ setKey(argv, x.split('.'), value);
4183
+ });
4184
+ }
4185
+
4186
+ Object.keys(flags.bools).forEach(function (key) {
4187
+ setArg(key, defaults[key] === undefined ? false : defaults[key]);
4188
+ });
4189
+
4190
+ var notFlags = [];
4191
+
4192
+ if (args.indexOf('--') !== -1) {
4193
+ notFlags = args.slice(args.indexOf('--') + 1);
4194
+ args = args.slice(0, args.indexOf('--'));
4195
+ }
4196
+
4197
+ for (var i = 0; i < args.length; i++) {
4198
+ var arg = args[i];
4199
+ var key;
4200
+ var next;
4201
+
4202
+ if ((/^--.+=/).test(arg)) {
4203
+ // Using [\s\S] instead of . because js doesn't support the
4204
+ // 'dotall' regex modifier. See:
4205
+ // http://stackoverflow.com/a/1068308/13216
4206
+ var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
4207
+ key = m[1];
4208
+ var value = m[2];
4209
+ if (flags.bools[key]) {
4210
+ value = value !== 'false';
4211
+ }
4212
+ setArg(key, value, arg);
4213
+ } else if ((/^--no-.+/).test(arg)) {
4214
+ key = arg.match(/^--no-(.+)/)[1];
4215
+ setArg(key, false, arg);
4216
+ } else if ((/^--.+/).test(arg)) {
4217
+ key = arg.match(/^--(.+)/)[1];
4218
+ next = args[i + 1];
4219
+ if (
4220
+ next !== undefined
4221
+ && !(/^(-|--)[^-]/).test(next)
4222
+ && !flags.bools[key]
4223
+ && !flags.allBools
4224
+ && (aliases[key] ? !aliasIsBoolean(key) : true)
4225
+ ) {
4226
+ setArg(key, next, arg);
4227
+ i += 1;
4228
+ } else if ((/^(true|false)$/).test(next)) {
4229
+ setArg(key, next === 'true', arg);
4230
+ i += 1;
4231
+ } else {
4232
+ setArg(key, flags.strings[key] ? '' : true, arg);
4233
+ }
4234
+ } else if ((/^-[^-]+/).test(arg)) {
4235
+ var letters = arg.slice(1, -1).split('');
4236
+
4237
+ var broken = false;
4238
+ for (var j = 0; j < letters.length; j++) {
4239
+ next = arg.slice(j + 2);
4240
+
4241
+ if (next === '-') {
4242
+ setArg(letters[j], next, arg);
4243
+ continue;
4244
+ }
4245
+
4246
+ if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {
4247
+ setArg(letters[j], next.slice(1), arg);
4248
+ broken = true;
4249
+ break;
4250
+ }
4251
+
4252
+ if (
4253
+ (/[A-Za-z]/).test(letters[j])
4254
+ && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next)
4255
+ ) {
4256
+ setArg(letters[j], next, arg);
4257
+ broken = true;
4258
+ break;
4259
+ }
4260
+
4261
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
4262
+ setArg(letters[j], arg.slice(j + 2), arg);
4263
+ broken = true;
4264
+ break;
4265
+ } else {
4266
+ setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
4267
+ }
4268
+ }
4269
+
4270
+ key = arg.slice(-1)[0];
4271
+ if (!broken && key !== '-') {
4272
+ if (
4273
+ args[i + 1]
4274
+ && !(/^(-|--)[^-]/).test(args[i + 1])
4275
+ && !flags.bools[key]
4276
+ && (aliases[key] ? !aliasIsBoolean(key) : true)
4277
+ ) {
4278
+ setArg(key, args[i + 1], arg);
4279
+ i += 1;
4280
+ } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {
4281
+ setArg(key, args[i + 1] === 'true', arg);
4282
+ i += 1;
4283
+ } else {
4284
+ setArg(key, flags.strings[key] ? '' : true, arg);
4285
+ }
4286
+ }
4287
+ } else {
4288
+ if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
4289
+ argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
4290
+ }
4291
+ if (opts.stopEarly) {
4292
+ argv._.push.apply(argv._, args.slice(i + 1));
4293
+ break;
4294
+ }
4295
+ }
4296
+ }
4297
+
4298
+ Object.keys(defaults).forEach(function (k) {
4299
+ if (!hasKey(argv, k.split('.'))) {
4300
+ setKey(argv, k.split('.'), defaults[k]);
4301
+
4302
+ (aliases[k] || []).forEach(function (x) {
4303
+ setKey(argv, x.split('.'), defaults[k]);
4304
+ });
4305
+ }
4306
+ });
4307
+
4308
+ if (opts['--']) {
4309
+ argv['--'] = notFlags.slice();
4310
+ } else {
4311
+ notFlags.forEach(function (k) {
4312
+ argv._.push(k);
4313
+ });
4314
+ }
4315
+
4316
+ return argv;
4317
+ };
4318
+
4319
+ function split(data) {
4320
+ const pre = data.split("\n");
4321
+ // rejoin with lines that starts with a whitespace
4322
+ const out = [];
4323
+ let cur = "";
4324
+ for (let i = 0; i < pre.length; ++i) {
4325
+ let line = pre[i].replace(/\t/g, " ");
4326
+ if (!line.length)
4327
+ continue;
4328
+ if (!cur.length || /\s/.test(line[0])) {
4329
+ let idx = 0;
4330
+ while (/\s/.test(line[idx]))
4331
+ ++idx;
4332
+ cur += line.substr(idx ? idx - 1 : 0);
4333
+ idx = cur.length - 1;
4334
+ while (idx >= 0 && /\s/.test(cur[idx]))
4335
+ --idx;
4336
+ if (idx < cur.length - 1)
4337
+ cur = cur.substr(0, idx + 1);
4338
+ }
4339
+ else if (cur.length > 0) {
4340
+ out.push(cur.trim());
4341
+ cur = line.trim();
4342
+ }
4343
+ }
4344
+ if (cur.length > 0) {
4345
+ out.push(cur.trim());
4346
+ }
4347
+ return out;
4348
+ }
4349
+ function realValue(v) {
4350
+ if (typeof v !== "string")
4351
+ return v;
4352
+ if (/^[-0-9.]+$/.exec(v)) {
4353
+ const vf = parseFloat(v);
4354
+ if (!isNaN(vf))
4355
+ return vf;
4356
+ }
4357
+ switch (v) {
4358
+ case "true":
4359
+ return true;
4360
+ case "false":
4361
+ return false;
4362
+ }
4363
+ return v;
4364
+ }
4365
+ class Engine {
4366
+ constructor(options, argv) {
4367
+ var _a;
4368
+ this.argv = Object.assign({}, argv);
4369
+ this.prefix = options.prefix;
4370
+ this.additionalFiles = options.additionalFiles || [];
4371
+ this.applicationPath = options.noApplicationPath ? "" : appRootPath.toString();
4372
+ this.debug = (_a = options.debug) !== null && _a !== void 0 ? _a : false;
4373
+ this.options = {};
4374
+ this.configDirs = this.argv["config-dir"] || options.configDirs || xdgBasedir.configDirs;
4375
+ this._read();
4376
+ }
4377
+ value(name) {
4378
+ // foo-bar becomes FOO_BAR as env
4379
+ if (name in this.argv) {
4380
+ return this.argv[name];
4381
+ }
4382
+ const envname = (this.prefix + "_" + name).replace(/-/g, "_").toUpperCase();
4383
+ if (envname in process.env) {
4384
+ return realValue(process.env[envname]);
4385
+ }
4386
+ if (name in this.options) {
4387
+ return this.options[name];
4388
+ }
4389
+ return undefined;
4390
+ }
4391
+ string(name) {
4392
+ const ret = this.value(name);
4393
+ if (ret === undefined) {
4394
+ return undefined;
4395
+ }
4396
+ return String(ret);
4397
+ }
4398
+ _homedir() {
4399
+ let home = process.env.home;
4400
+ if (home) {
4401
+ return path__default["default"].join(home, ".config");
4402
+ }
4403
+ return undefined;
4404
+ }
4405
+ _log(...args) {
4406
+ if (this.debug)
4407
+ console.log(...args);
4408
+ }
4409
+ _read() {
4410
+ // if we have a config file passed, read it
4411
+ let file = this.string("config-file");
4412
+ if (!file && this.prefix)
4413
+ file = this.prefix + ".conf";
4414
+ if (!file)
4415
+ return;
4416
+ let data = [];
4417
+ let seen = new Set();
4418
+ const read = (file) => {
4419
+ if (seen.has(file))
4420
+ return 2 /* OptionsReadResult.Seen */;
4421
+ seen.add(file);
4422
+ try {
4423
+ const contents = require$$1__default["default"].readFileSync(file, "utf8");
4424
+ this._log(`Loaded ${contents.length} bytes from ${file}`);
4425
+ if (contents) {
4426
+ data.push({ file, contents });
4427
+ return 1 /* OptionsReadResult.Success */;
4428
+ }
4429
+ }
4430
+ catch (e) {
4431
+ this._log(`Failed to load ${file}`);
4432
+ }
4433
+ return 0 /* OptionsReadResult.Failed */;
4434
+ };
4435
+ // console.log("about to read file", file, "additionalFiles", this.additionalFiles, "configDirs", this.configDirs, "applicationPath", this.applicationPath, "homedir", this._homedir());
4436
+ if (path__default["default"].isAbsolute(file)) {
4437
+ read(file);
4438
+ }
4439
+ else {
4440
+ this.additionalFiles.forEach(file => {
4441
+ if (path__default["default"].isAbsolute(file) && read(file) == 0 /* OptionsReadResult.Failed */) {
4442
+ read(file + ".conf");
4443
+ }
4444
+ });
4445
+ ([this.applicationPath, this._homedir()].concat(this.configDirs)).forEach(root => {
4446
+ // in case we appended with undefined
4447
+ if (!root) {
4448
+ return;
4449
+ }
4450
+ this.additionalFiles.forEach(additional => {
4451
+ if (!path__default["default"].isAbsolute(additional)) {
4452
+ let file = path__default["default"].join(root, additional);
4453
+ if (read(file) == 0 /* OptionsReadResult.Failed */)
4454
+ read(file + ".conf");
4455
+ }
4456
+ });
4457
+ let filePath = path__default["default"].join(root, file);
4458
+ if (read(filePath) == 0 /* OptionsReadResult.Failed */) {
4459
+ read(filePath + ".conf");
4460
+ }
4461
+ });
4462
+ }
4463
+ for (let i = data.length - 1; i >= 0; --i) {
4464
+ let str = data[i].contents;
4465
+ if (!str) {
4466
+ continue;
4467
+ }
4468
+ try {
4469
+ let obj = JSON.parse(str);
4470
+ for (let key in obj) {
4471
+ this._log(`Assigning ${JSON.stringify(obj[key])} over ${JSON.stringify(this.options[key])} for ${key} from ${data[i].file} (JSON)`);
4472
+ this.options[key] = obj[key];
4473
+ }
4474
+ }
4475
+ catch (err) {
4476
+ const items = split(str);
4477
+ for (let j = 0; j < items.length; ++j) {
4478
+ const item = items[j].trim();
4479
+ if (!item.length)
4480
+ continue;
4481
+ if (item[0] === "#")
4482
+ continue;
4483
+ const eq = item.indexOf("=");
4484
+ if (eq === -1) {
4485
+ this._log("Couldn't find =", item);
4486
+ continue;
4487
+ }
4488
+ const key = item.substring(0, eq).trim();
4489
+ if (!key.length) {
4490
+ this._log("empty key", item);
4491
+ continue;
4492
+ }
4493
+ const value = item.substring(eq + 1).trim();
4494
+ this._log(`Assigning ${value} over ${this.options[key]} for ${key} from ${data[i].file} (INI)`);
4495
+ this.options[key] = value;
4496
+ }
4497
+ }
4498
+ }
4499
+ }
4500
+ }
4501
+ function createOptions (optionsOptions, argv) {
4502
+ if (!argv) {
4503
+ argv = minimist(process.argv.slice(2));
4504
+ }
4505
+ if (!(optionsOptions instanceof Object)) {
4506
+ optionsOptions = { prefix: optionsOptions || "" };
4507
+ }
4508
+ const engine = new Engine(optionsOptions, argv);
4509
+ function value(name, defaultValue) {
4510
+ const val = engine.value(name);
4511
+ if (val === undefined)
4512
+ return defaultValue;
4513
+ return val;
4514
+ }
4515
+ function float(name, defaultValue) {
4516
+ const v = parseFloat(engine.string(name) || "");
4517
+ if (typeof v === "number" && !isNaN(v))
4518
+ return v;
4519
+ return defaultValue;
4520
+ }
4521
+ function int(name, defaultValue) {
4522
+ const v = parseInt(engine.string(name) || "");
4523
+ if (typeof v === "number" && !isNaN(v))
4524
+ return v;
4525
+ return defaultValue;
4526
+ }
4527
+ function json(name, defaultValue) {
4528
+ const opt = engine.value(name);
4529
+ if (opt === undefined)
4530
+ return defaultValue;
4531
+ if (typeof opt !== "string")
4532
+ return opt;
4533
+ try {
4534
+ const json = JSON.parse(opt);
4535
+ return json;
4536
+ }
4537
+ catch (e) {
4538
+ }
4539
+ return defaultValue;
4540
+ }
4541
+ function string(name, defaultValue) {
4542
+ var _a;
4543
+ return (_a = engine.string(name)) !== null && _a !== void 0 ? _a : defaultValue;
4544
+ }
4545
+ return Object.assign(value, {
4546
+ prefix: optionsOptions.prefix,
4547
+ float,
4548
+ int,
4549
+ json,
4550
+ string,
4551
+ });
4552
+ }
4553
+
4554
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
4555
+ console.log(`Usage: fisk-daemon [options]
4556
+
4557
+ Options:
4558
+ --debug Enable debug logging
4559
+ --socket=PATH Unix socket path (default: ~/.cache/fisk/daemon/socket)
4560
+ --cpp-slots=N Preprocess slot count (default: cpus * 2)
4561
+ --slots=N Compile slot count (default: cpus)
4562
+ --local-slots=N Local compile slot count (default: 0, disabled)
4563
+ --local-slots-max-load=N Max system load average (1-min) to allow local compiles (default: 0, no limit)
4564
+ --cache-dir=PATH Cache directory (default: ~/.cache/fisk/daemon)
4565
+
4566
+ Config files: ~/.config/fisk/daemon.conf, /etc/xdg/fisk/daemon.conf
4567
+ Environment variables: FISK_DAEMON_DEBUG, FISK_DAEMON_SLOTS, etc.`);
4568
+ process.exit(0);
4569
+ }
4570
+ const option = createOptions({
4571
+ prefix: "fisk/daemon",
4572
+ noApplicationPath: true,
4573
+ additionalFiles: ["fisk/daemon.conf.override"]
4574
+ });
4575
+ const common = common$1(option);
4576
+ const debug = option("debug");
4577
+ process.on("unhandledRejection", (reason, p) => {
4578
+ console.error("Unhandled Rejection at: Promise", p, "reason:", reason === null || reason === void 0 ? void 0 : reason.stack);
4579
+ process.exit();
4580
+ // if (client)
4581
+ // client.send('log', { message: `Unhandled Rejection at: Promise ${p}, reason: ${reason.stack}` });
4582
+ });
4583
+ process.on("uncaughtException", (err) => {
4584
+ console.error("Uncaught exception", err);
4585
+ process.exit();
4586
+ // if (client)
4587
+ // client.send('log', { message: `Uncaught exception ${err.toString()} ${err.stack}` });
4588
+ });
4589
+ const server = new Server(option, common);
4590
+ server.listen().then(() => {
4591
+ console.log("listening on", server.file);
4592
+ });
4593
+ // server.on("message
4594
+ server.on("error", (err) => {
4595
+ console.error("server error", err);
4596
+ });
4597
+ const cppSlots = new Slots(option.int("cpp-slots", Math.max(os__default["default"].cpus().length * 2, 1)), "cpp", debug);
4598
+ const compileSlots = new Slots(option.int("slots", Math.max(os__default["default"].cpus().length, 1)), "compile", debug);
4599
+ const localSlotCount = option.int("local-slots", 0);
4600
+ const localSlots = new Slots(localSlotCount, "local", debug);
4601
+ const localSlotsMaxLoad = option("local-slots-max-load") || 0;
4602
+ console.log(`cpp slots: ${cppSlots.capacity}, compile slots: ${compileSlots.capacity}, local slots: ${localSlots.capacity}, local max load: ${localSlotsMaxLoad}`);
4603
+ const compilerInfoStore = new CompilerInfoStore(undefined, (...args) => {
4604
+ console.log("compilerInfo:", ...args);
4605
+ });
4606
+ const slotSubscribers = [];
4607
+ function slotsInfo() {
4608
+ return {
4609
+ type: "slotsInfo",
4610
+ local: {
4611
+ active: localSlots.active,
4612
+ capacity: localSlots.capacity,
4613
+ total: localSlots.totalAcquired
4614
+ },
4615
+ cpp: {
4616
+ active: cppSlots.active,
4617
+ capacity: cppSlots.capacity,
4618
+ total: cppSlots.totalAcquired
4619
+ },
4620
+ compile: {
4621
+ active: compileSlots.active,
4622
+ capacity: compileSlots.capacity,
4623
+ total: compileSlots.totalAcquired
4624
+ }
4625
+ };
4626
+ }
4627
+ function broadcastSlotsInfo() {
4628
+ if (slotSubscribers.length === 0) {
4629
+ return;
4630
+ }
4631
+ const info = slotsInfo();
4632
+ for (const sub of slotSubscribers) {
4633
+ sub.compile.send(info);
4634
+ }
4635
+ }
4636
+ for (const slots of [localSlots, cppSlots, compileSlots]) {
4637
+ slots.on("changed", broadcastSlotsInfo);
4638
+ }
4639
+ function canAcquireLocalSlot() {
4640
+ if (localSlotCount <= 0) {
4641
+ return false;
4642
+ }
4643
+ if (localSlotsMaxLoad > 0) {
4644
+ const loadAvg = os__default["default"].loadavg()[0];
4645
+ if (loadAvg > localSlotsMaxLoad) {
4646
+ if (debug) {
4647
+ console.log(`Local slot denied: load ${loadAvg.toFixed(2)} > max ${localSlotsMaxLoad}`);
4648
+ }
4649
+ return false;
4650
+ }
4651
+ }
4652
+ return true;
4653
+ }
4654
+ server.on("compile", (compile) => {
4655
+ compile.on("dumpSlots", () => {
4656
+ const ret = { cpp: cppSlots.dump(), compile: compileSlots.dump(), local: localSlots.dump() };
4657
+ if (debug) {
4658
+ console.log("sending dump", ret);
4659
+ }
4660
+ compile.send(ret);
4661
+ });
4662
+ compile.on("subscribeSlots", () => {
4663
+ if (debug) {
4664
+ console.log("subscribeSlots from", compile.id);
4665
+ }
4666
+ const subscriber = {
4667
+ compile,
4668
+ handler: () => {
4669
+ // Remove subscriber on disconnect
4670
+ const idx = slotSubscribers.indexOf(subscriber);
4671
+ if (idx !== -1) {
4672
+ slotSubscribers.splice(idx, 1);
4673
+ }
4674
+ }
4675
+ };
4676
+ slotSubscribers.push(subscriber);
4677
+ compile.on("end", subscriber.handler);
4678
+ compile.on("error", subscriber.handler);
4679
+ // Send current state immediately
4680
+ compile.send(slotsInfo());
4681
+ });
4682
+ let requestedCppSlot = false;
4683
+ let requestedLocalSlot = false;
4684
+ let compileClosed = false;
4685
+ compile.on("acquireCppSlot", () => {
4686
+ if (debug) {
4687
+ console.log("acquireCppSlot");
4688
+ }
4689
+ assert__default["default"](!requestedCppSlot);
4690
+ requestedCppSlot = true;
4691
+ cppSlots.acquire(compile.id, { pid: compile.pid }, () => {
4692
+ // compile.send({ type: 'cppSlotAcquired' });
4693
+ compile.send(Constants.CppSlotAcquired);
4694
+ });
4695
+ });
4696
+ compile.on("releaseCppSlot", () => {
4697
+ if (debug) {
4698
+ console.log("releaseCppSlot");
4699
+ }
4700
+ assert__default["default"](requestedCppSlot);
4701
+ if (requestedCppSlot) {
4702
+ requestedCppSlot = false;
4703
+ cppSlots.release(compile.id);
4704
+ }
4705
+ });
4706
+ let requestedCompileSlot = false;
4707
+ compile.on("acquireCompileSlot", () => {
4708
+ if (debug) {
4709
+ console.log("acquireCompileSlot");
4710
+ }
4711
+ assert__default["default"](!requestedCompileSlot);
4712
+ requestedCompileSlot = true;
4713
+ compileSlots.acquire(compile.id, { pid: compile.pid }, () => {
4714
+ // compile.send({ type: 'compileSlotAcquired' });
4715
+ compile.send(Constants.CompileSlotAcquired);
4716
+ });
4717
+ });
4718
+ compile.on("releaseCompileSlot", () => {
4719
+ if (debug) {
4720
+ console.log("releaseCompileSlot");
4721
+ }
4722
+ assert__default["default"](requestedCompileSlot);
4723
+ if (requestedCompileSlot) {
4724
+ requestedCompileSlot = false;
4725
+ compileSlots.release(compile.id);
4726
+ }
4727
+ });
4728
+ // The daemon cannot see, let alone run, the compiler: it usually lives in
4729
+ // the client's container. Clients identify it with a key they compute
4730
+ // themselves and run the probes on our behalf when asked.
4731
+ const requester = {
4732
+ id: compile.id,
4733
+ requestCompilerInfo(key, probes, timeoutMs) {
4734
+ compile.send({ type: "compilerInfoRequest", key, probes, timeoutMs });
4735
+ }
4736
+ };
4737
+ compile.on("acquireSlot", (msg) => {
4738
+ console.log("acquireSlot", msg);
4739
+ const compilerKey = msg && typeof msg.compilerKey === "string" && msg.compilerKey.length > 0 ? msg.compilerKey : null;
4740
+ const infoResult = compilerKey
4741
+ ? compilerInfoStore.get(compilerKey, requester).then((info) => ({ info, error: null }), (err) => {
4742
+ const message = err instanceof Error ? err.message : String(err);
4743
+ if (debug) {
4744
+ console.log("acquireSlot -> compilerInfoStore failed", compilerKey, message);
4745
+ }
4746
+ return { info: null, error: message };
4747
+ })
4748
+ : Promise.resolve({ info: null, error: "acquireSlot missing compiler key" });
4749
+ infoResult
4750
+ .then(({ info, error }) => {
4751
+ if (compileClosed) {
4752
+ return;
4753
+ }
4754
+ const respond = (slot) => {
4755
+ const response = {
4756
+ type: "slotAcquired",
4757
+ slot,
4758
+ compilerInfo: info
4759
+ };
4760
+ if (error) {
4761
+ response.error = error;
4762
+ }
4763
+ compile.send(response);
4764
+ };
4765
+ if (!(msg === null || msg === void 0 ? void 0 : msg["no-local"]) && canAcquireLocalSlot() && localSlots.tryAcquire(compile.id, { pid: compile.pid })) {
4766
+ if (debug) {
4767
+ console.log("acquireSlot -> local slot granted");
4768
+ }
4769
+ requestedLocalSlot = true;
4770
+ respond("local");
4771
+ }
4772
+ else {
4773
+ if (debug) {
4774
+ console.log("acquireSlot -> falling back to cpp slot");
4775
+ }
4776
+ assert__default["default"](!requestedCppSlot);
4777
+ requestedCppSlot = true;
4778
+ cppSlots.acquire(compile.id, { pid: compile.pid }, () => {
4779
+ respond("cpp");
4780
+ });
4781
+ }
4782
+ })
4783
+ .catch((err) => {
4784
+ // Defensive: the process-wide unhandledRejection handler calls process.exit().
4785
+ console.error("acquireSlot handler failed unexpectedly", err);
4786
+ });
4787
+ });
4788
+ compile.on("compilerInfoResponse", (msg) => {
4789
+ const key = msg && typeof msg.key === "string" ? msg.key : "";
4790
+ if (!key) {
4791
+ console.error("compilerInfoResponse without a key from", compile.id);
4792
+ return;
4793
+ }
4794
+ if (typeof (msg === null || msg === void 0 ? void 0 : msg.error) === "string" && msg.error.length) {
4795
+ compilerInfoStore.fail(key, msg.error);
4796
+ return;
4797
+ }
4798
+ if (!(msg === null || msg === void 0 ? void 0 : msg.results) || typeof msg.results !== "object") {
4799
+ compilerInfoStore.fail(key, "compilerInfoResponse without results");
4800
+ return;
4801
+ }
4802
+ compilerInfoStore.provide(key, msg.results);
4803
+ });
4804
+ compile.on("releaseLocalSlot", () => {
4805
+ if (debug) {
4806
+ console.log("releaseLocalSlot");
4807
+ }
4808
+ assert__default["default"](requestedLocalSlot);
4809
+ if (requestedLocalSlot) {
4810
+ requestedLocalSlot = false;
4811
+ localSlots.release(compile.id);
4812
+ }
4813
+ });
4814
+ compile.on("error", (err) => {
4815
+ if (debug) {
4816
+ console.error("Got error from fiskc", compile.id, compile.pid, err);
4817
+ }
4818
+ compileClosed = true;
4819
+ // If this client owed us compiler info, hand the job to another waiter.
4820
+ compilerInfoStore.clientGone(requester);
4821
+ if (requestedCppSlot) {
4822
+ requestedCppSlot = false;
4823
+ cppSlots.release(compile.id);
4824
+ }
4825
+ if (requestedCompileSlot) {
4826
+ requestedCompileSlot = false;
4827
+ compileSlots.release(compile.id);
4828
+ }
4829
+ if (requestedLocalSlot) {
4830
+ requestedLocalSlot = false;
4831
+ localSlots.release(compile.id);
4832
+ }
4833
+ });
4834
+ compile.on("end", () => {
4835
+ if (debug) {
4836
+ console.log("got end from", compile.id, compile.pid);
4837
+ }
4838
+ compileClosed = true;
4839
+ // If this client owed us compiler info, hand the job to another waiter.
4840
+ compilerInfoStore.clientGone(requester);
4841
+ if (requestedCppSlot) {
4842
+ requestedCppSlot = false;
4843
+ cppSlots.release(compile.id);
4844
+ }
4845
+ if (requestedCompileSlot) {
4846
+ requestedCompileSlot = false;
4847
+ compileSlots.release(compile.id);
4848
+ }
4849
+ if (requestedLocalSlot) {
4850
+ requestedLocalSlot = false;
4851
+ localSlots.release(compile.id);
4852
+ }
4853
+ });
4854
+ });
4855
+ process.on("exit", () => {
4856
+ server.close();
4857
+ });
4858
+ process.on("SIGINT", () => {
4859
+ server.close();
4860
+ process.exit();
4861
+ });
4862
+ /*
4863
+ const client = new Client(option, common.Version);
4864
+
4865
+ let connectInterval;
4866
+ client.on('quit', message => {
4867
+ process.exit(message.code);
4868
+ });
4869
+
4870
+ client.on('connect', () => {
4871
+ console.log('connected');
4872
+ if (connectInterval) {
4873
+ clearInterval(connectInterval);
4874
+ connectInterval = undefined;
4875
+ }
4876
+ });
4877
+
4878
+ client.on('error', err => {
4879
+ console.error('client error', err);
4880
+ });
4881
+
4882
+ client.on('close', () => {
4883
+ console.log('client closed');
4884
+ if (!connectInterval) {
4885
+ connectInterval = setInterval(() => {
4886
+ console.log('Reconnecting...');
4887
+ client.connect();
4888
+ }, 1000);
4889
+ }
4890
+ });
4891
+ */
4892
+ //# sourceMappingURL=fisk-daemon.js.map