if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
// don't squeeze out UNC patterns
if (i === 1 && p === '' && parts[0] === '')
continue;
if (p === '.' || p === '') {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === '.' &&
parts.length === 2 &&
(parts[1] === '.' || parts[1] === '')) {
didSomething = true;
parts.pop();
}
}
// //../ -> /
let dd = 0;
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
const p = parts[dd - 1];
if (p && p !== '.' && p !== '..' && p !== '**') {
didSomething = true;
parts.splice(dd - 1, 2);
dd -= 2;
}
}
} while (didSomething);
return parts.length === 0 ? [''] : parts;
}
// First phase: single-pattern processing
// is 1 or more portions
// is 1 or more portions
// is any portion other than ., .., '', or **
// is . or ''
//
// **/.. is *brutal* for filesystem walking performance, because
// it effectively resets the recursive walk each time it occurs,
// and ** cannot be reduced out by a .. pattern part like a regexp
// or most strings (other than .., ., and '') can be.
//
// /**/..//
/ -> {/..//
/,/**//
/}
// // -> /
// //../ -> /
// **/**/ -> **/
//
// **/*/ -> */**/ <== not valid because ** doesn't follow
// this WOULD be allowed if ** did follow symlinks, or * didn't
firstPhasePreProcess(globParts) {
let didSomething = false;
do {
didSomething = false;
// /**/..//
/ -> {/..//
/,/**//
/}
for (let parts of globParts) {
let gs = -1;
while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
let gss = gs;
while (parts[gss + 1] === '**') {
// /**/**/ -> /**/
gss++;
}
// eg, if gs is 2 and gss is 4, that means we have 3 **
// parts, and can remove 2 of them.
if (gss > gs) {
parts.splice(gs + 1, gss - gs);
}
let next = parts[gs + 1];
const p = parts[gs + 2];
const p2 = parts[gs + 3];
if (next !== '..')
continue;
if (!p ||
p === '.' ||
p === '..' ||
!p2 ||
p2 === '.' ||
p2 === '..') {
continue;
}
didSomething = true;
// edit parts in place, and push the new one
parts.splice(gs, 1);
const other = parts.slice(0);
other[gs] = '**';
globParts.push(other);
gs--;
}
// // -> /
if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
// don't squeeze out UNC patterns
if (i === 1 && p === '' && parts[0] === '')
continue;
if (p === '.' || p === '') {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === '.' &&
parts.length === 2 &&
(parts[1] === '.' || parts[1] === '')) {
didSomething = true;
parts.pop();
}
}
// //../ -> /
let dd = 0;
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
const p = parts[dd - 1];
if (p && p !== '.' && p !== '..' && p !== '**') {
didSomething = true;
const needDot = dd === 1 && parts[dd + 1] === '**';
const splin = needDot ? ['.'] : [];
parts.splice(dd - 1, 2, ...splin);
if (parts.length === 0)
parts.push('');
dd -= 2;
}
}
}
} while (didSomething);
return globParts;
}
// second phase: multi-pattern dedupes
// {/*/,//} -> /*/
// {/,/} -> /
// {/**/,/} -> /**/
//
// {/**/,/**//} -> /**/
// ^-- not valid because ** doens't follow symlinks
secondPhasePreProcess(globParts) {
for (let i = 0; i < globParts.length - 1; i++) {
for (let j = i + 1; j < globParts.length; j++) {
const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
if (matched) {
globParts[i] = [];
globParts[j] = matched;
break;
}
}
}
return globParts.filter(gs => gs.length);
}
partsMatch(a, b, emptyGSMatch = false) {
let ai = 0;
let bi = 0;
let result = [];
let which = '';
while (ai < a.length && bi < b.length) {
if (a[ai] === b[bi]) {
result.push(which === 'b' ? b[bi] : a[ai]);
ai++;
bi++;
}
else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
result.push(a[ai]);
ai++;
}
else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
result.push(b[bi]);
bi++;
}
else if (a[ai] === '*' &&
b[bi] &&
(this.options.dot || !b[bi].startsWith('.')) &&
b[bi] !== '**') {
if (which === 'b')
return false;
which = 'a';
result.push(a[ai]);
ai++;
bi++;
}
else if (b[bi] === '*' &&
a[ai] &&
(this.options.dot || !a[ai].startsWith('.')) &&
a[ai] !== '**') {
if (which === 'a')
return false;
which = 'b';
result.push(b[bi]);
ai++;
bi++;
}
else {
return false;
}
}
// if we fall out of the loop, it means they two are identical
// as long as their lengths match
return a.length === b.length && result;
}
parseNegate() {
if (this.nonegate)
return;
const pattern = this.pattern;
let negate = false;
let negateOffset = 0;
for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
negate = !negate;
negateOffset++;
}
if (negateOffset)
this.pattern = pattern.slice(negateOffset);
this.negate = negate;
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne(file, pattern, partial = false) {
const options = this.options;
// UNC paths like //?/X:/... can match X:/... and vice versa
// Drive letters in absolute drive or unc paths are always compared
// case-insensitively.
if (this.isWindows) {
const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
const fileUNC = !fileDrive &&
file[0] === '' &&
file[1] === '' &&
file[2] === '?' &&
/^[a-z]:$/i.test(file[3]);
const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
const patternUNC = !patternDrive &&
pattern[0] === '' &&
pattern[1] === '' &&
pattern[2] === '?' &&
typeof pattern[3] === 'string' &&
/^[a-z]:$/i.test(pattern[3]);
const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
if (typeof fdi === 'number' && typeof pdi === 'number') {
const [fd, pd] = [file[fdi], pattern[pdi]];
if (fd.toLowerCase() === pd.toLowerCase()) {
pattern[pdi] = fd;
if (pdi > fdi) {
pattern = pattern.slice(pdi);
}
else if (fdi > pdi) {
file = file.slice(fdi);
}
}
}
}
// resolve and reduce . and .. portions in the file as well.
// dont' need to do the second phase, because it's only one string[]
const { optimizationLevel = 1 } = this.options;
if (optimizationLevel >= 2) {
file = this.levelTwoFileOptimize(file);
}
this.debug('matchOne', this, { file, pattern });
this.debug('matchOne', file.length, pattern.length);
for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
this.debug('matchOne loop');
var p = pattern[pi];
var f = file[fi];
this.debug(pattern, p, f);
// should be impossible.
// some invalid regexp stuff in the set.
/* c8 ignore start */
if (p === false) {
return false;
}
/* c8 ignore stop */
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f]);
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi;
var pr = pi + 1;
if (pr === pl) {
this.debug('** at the end');
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' ||
file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.'))
return false;
}
return true;
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr];
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee);
// found a match.
return true;
}
else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' ||
swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr);
break;
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue');
fr++;
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
/* c8 ignore start */
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
if (fr === fl) {
return true;
}
}
/* c8 ignore stop */
return false;
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
let hit;
if (typeof p === 'string') {
hit = f === p;
this.debug('string match', p, f, hit);
}
else {
hit = p.test(f);
this.debug('pattern match', p, f, hit);
}
if (!hit)
return false;
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true;
}
else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial;
}
else if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
return fi === fl - 1 && file[fi] === '';
/* c8 ignore start */
}
else {
// should be unreachable.
throw new Error('wtf?');
}
/* c8 ignore stop */
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(pattern) {
assertValidPattern(pattern);
const options = this.options;
// shortcuts
if (pattern === '**')
return GLOBSTAR;
if (pattern === '')
return '';
// far and away, the most common glob pattern parts are
// *, *.*, and *. Add a fast check method for those.
let m;
let fastTest = null;
if ((m = pattern.match(starRE))) {
fastTest = options.dot ? starTestDot : starTest;
}
else if ((m = pattern.match(starDotExtRE))) {
fastTest = (options.nocase
? options.dot
? starDotExtTestNocaseDot
: starDotExtTestNocase
: options.dot
? starDotExtTestDot
: starDotExtTest)(m[1]);
}
else if ((m = pattern.match(qmarksRE))) {
fastTest = (options.nocase
? options.dot
? qmarksTestNocaseDot
: qmarksTestNocase
: options.dot
? qmarksTestDot
: qmarksTest)(m);
}
else if ((m = pattern.match(starDotStarRE))) {
fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
}
else if ((m = pattern.match(dotStarRE))) {
fastTest = dotStarTest;
}
const re = AST.fromGlob(pattern, this.options).toMMPattern();
if (fastTest && typeof re === 'object') {
// Avoids overriding in frozen environments
Reflect.defineProperty(re, 'test', { value: fastTest });
}
return re;
}
makeRe() {
if (this.regexp || this.regexp === false)
return this.regexp;
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
const set = this.set;
if (!set.length) {
this.regexp = false;
return this.regexp;
}
const options = this.options;
const twoStar = options.noglobstar
? esm_star
: options.dot
? twoStarDot
: twoStarNoDot;
const flags = new Set(options.nocase ? ['i'] : []);
// regexpify non-globstar patterns
// if ** is only item, then we just do one twoStar
// if ** is first, and there are more, prepend (\/|twoStar\/)? to next
// if ** is last, append (\/twoStar|) to previous
// if ** is in the middle, append (\/|\/twoStar\/) to previous
// then filter out GLOBSTAR symbols
let re = set
.map(pattern => {
const pp = pattern.map(p => {
if (p instanceof RegExp) {
for (const f of p.flags.split(''))
flags.add(f);
}
return typeof p === 'string'
? esm_regExpEscape(p)
: p === GLOBSTAR
? GLOBSTAR
: p._src;
});
pp.forEach((p, i) => {
const next = pp[i + 1];
const prev = pp[i - 1];
if (p !== GLOBSTAR || prev === GLOBSTAR) {
return;
}
if (prev === undefined) {
if (next !== undefined && next !== GLOBSTAR) {
pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
}
else {
pp[i] = twoStar;
}
}
else if (next === undefined) {
pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
}
else if (next !== GLOBSTAR) {
pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
pp[i + 1] = GLOBSTAR;
}
});
return pp.filter(p => p !== GLOBSTAR).join('/');
})
.join('|');
// need to wrap in parens if we had more than one thing with |,
// otherwise only the first will be anchored to ^ and the last to $
const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^' + open + re + close + '$';
// can match anything, as long as it's not this.
if (this.negate)
re = '^(?!' + re + ').+$';
try {
this.regexp = new RegExp(re, [...flags].join(''));
/* c8 ignore start */
}
catch (ex) {
// should be impossible
this.regexp = false;
}
/* c8 ignore stop */
return this.regexp;
}
slashSplit(p) {
// if p starts with // on windows, we preserve that
// so that UNC paths aren't broken. Otherwise, any number of
// / characters are coalesced into one, unless
// preserveMultipleSlashes is set to true.
if (this.preserveMultipleSlashes) {
return p.split('/');
}
else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
// add an extra '' for the one we lose
return ['', ...p.split(/\/+/)];
}
else {
return p.split(/\/+/);
}
}
match(f, partial = this.partial) {
this.debug('match', f, this.pattern);
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) {
return false;
}
if (this.empty) {
return f === '';
}
if (f === '/' && partial) {
return true;
}
const options = this.options;
// windows: need to use /, not \
if (this.isWindows) {
f = f.split('\\').join('/');
}
// treat the test path as a set of pathparts.
const ff = this.slashSplit(f);
this.debug(this.pattern, 'split', ff);
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
const set = this.set;
this.debug(this.pattern, 'set', set);
// Find the basename of the path by looking for the last non-empty segment
let filename = ff[ff.length - 1];
if (!filename) {
for (let i = ff.length - 2; !filename && i >= 0; i--) {
filename = ff[i];
}
}
for (let i = 0; i < set.length; i++) {
const pattern = set[i];
let file = ff;
if (options.matchBase && pattern.length === 1) {
file = [filename];
}
const hit = this.matchOne(file, pattern, partial);
if (hit) {
if (options.flipNegate) {
return true;
}
return !this.negate;
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) {
return false;
}
return this.negate;
}
static defaults(def) {
return minimatch.defaults(def).Minimatch;
}
}
/* c8 ignore start */
/* c8 ignore stop */
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape_escape;
minimatch.unescape = unescape_unescape;
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: external "node:url"
var external_node_url_ = __webpack_require__(3136);
;// ./node_modules/path-scurry/node_modules/lru-cache/dist/esm/index.js
/**
* @module LRUCache
*/
const perf = typeof performance === 'object' &&
performance &&
typeof performance.now === 'function'
? performance
: Date;
const warned = new Set();
/* c8 ignore start */
const PROCESS = (typeof process === 'object' && !!process ? process : {});
/* c8 ignore start */
const emitWarning = (msg, type, code, fn) => {
typeof PROCESS.emitWarning === 'function'
? PROCESS.emitWarning(msg, type, code, fn)
: console.error(`[${code}] ${type}: ${msg}`);
};
let AC = globalThis.AbortController;
let AS = globalThis.AbortSignal;
/* c8 ignore start */
if (typeof AC === 'undefined') {
//@ts-ignore
AS = class AbortSignal {
onabort;
_onabort = [];
reason;
aborted = false;
addEventListener(_, fn) {
this._onabort.push(fn);
}
};
//@ts-ignore
AC = class AbortController {
constructor() {
warnACPolyfill();
}
signal = new AS();
abort(reason) {
if (this.signal.aborted)
return;
//@ts-ignore
this.signal.reason = reason;
//@ts-ignore
this.signal.aborted = true;
//@ts-ignore
for (const fn of this.signal._onabort) {
fn(reason);
}
this.signal.onabort?.(reason);
}
};
let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
const warnACPolyfill = () => {
if (!printACPolyfillWarning)
return;
printACPolyfillWarning = false;
emitWarning('AbortController is not defined. If using lru-cache in ' +
'node 14, load an AbortController polyfill from the ' +
'`node-abort-controller` package. A minimal polyfill is ' +
'provided for use by LRUCache.fetch(), but it should not be ' +
'relied upon in other contexts (eg, passing it to other APIs that ' +
'use AbortController/AbortSignal might have undesirable effects). ' +
'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
};
}
/* c8 ignore stop */
const shouldWarn = (code) => !warned.has(code);
const TYPE = Symbol('type');
const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
/* c8 ignore start */
// This is a little bit ridiculous, tbh.
// The maximum array length is 2^32-1 or thereabouts on most JS impls.
// And well before that point, you're caching the entire world, I mean,
// that's ~32GB of just integers for the next/prev links, plus whatever
// else to hold that many keys and values. Just filling the memory with
// zeroes at init time is brutal when you get that big.
// But why not be complete?
// Maybe in the future, these limits will have expanded.
const getUintArray = (max) => !isPosInt(max)
? null
: max <= Math.pow(2, 8)
? Uint8Array
: max <= Math.pow(2, 16)
? Uint16Array
: max <= Math.pow(2, 32)
? Uint32Array
: max <= Number.MAX_SAFE_INTEGER
? ZeroArray
: null;
/* c8 ignore stop */
class ZeroArray extends Array {
constructor(size) {
super(size);
this.fill(0);
}
}
class Stack {
heap;
length;
// private constructor
static #constructing = false;
static create(max) {
const HeapCls = getUintArray(max);
if (!HeapCls)
return [];
Stack.#constructing = true;
const s = new Stack(max, HeapCls);
Stack.#constructing = false;
return s;
}
constructor(max, HeapCls) {
/* c8 ignore start */
if (!Stack.#constructing) {
throw new TypeError('instantiate Stack using Stack.create(n)');
}
/* c8 ignore stop */
this.heap = new HeapCls(max);
this.length = 0;
}
push(n) {
this.heap[this.length++] = n;
}
pop() {
return this.heap[--this.length];
}
}
/**
* Default export, the thing you're using this module to get.
*
* The `K` and `V` types define the key and value types, respectively. The
* optional `FC` type defines the type of the `context` object passed to
* `cache.fetch()` and `cache.memo()`.
*
* Keys and values **must not** be `null` or `undefined`.
*
* All properties from the options object (with the exception of `max`,
* `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
* added as normal public members. (The listed options are read-only getters.)
*
* Changing any of these will alter the defaults for subsequent method calls.
*/
class LRUCache {
// options that cannot be changed without disaster
#max;
#maxSize;
#dispose;
#onInsert;
#disposeAfter;
#fetchMethod;
#memoMethod;
/**
* {@link LRUCache.OptionsBase.ttl}
*/
ttl;
/**
* {@link LRUCache.OptionsBase.ttlResolution}
*/
ttlResolution;
/**
* {@link LRUCache.OptionsBase.ttlAutopurge}
*/
ttlAutopurge;
/**
* {@link LRUCache.OptionsBase.updateAgeOnGet}
*/
updateAgeOnGet;
/**
* {@link LRUCache.OptionsBase.updateAgeOnHas}
*/
updateAgeOnHas;
/**
* {@link LRUCache.OptionsBase.allowStale}
*/
allowStale;
/**
* {@link LRUCache.OptionsBase.noDisposeOnSet}
*/
noDisposeOnSet;
/**
* {@link LRUCache.OptionsBase.noUpdateTTL}
*/
noUpdateTTL;
/**
* {@link LRUCache.OptionsBase.maxEntrySize}
*/
maxEntrySize;
/**
* {@link LRUCache.OptionsBase.sizeCalculation}
*/
sizeCalculation;
/**
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
*/
noDeleteOnFetchRejection;
/**
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
*/
noDeleteOnStaleGet;
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
*/
allowStaleOnFetchAbort;
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
*/
allowStaleOnFetchRejection;
/**
* {@link LRUCache.OptionsBase.ignoreFetchAbort}
*/
ignoreFetchAbort;
// computed properties
#size;
#calculatedSize;
#keyMap;
#keyList;
#valList;
#next;
#prev;
#head;
#tail;
#free;
#disposed;
#sizes;
#starts;
#ttls;
#hasDispose;
#hasFetchMethod;
#hasDisposeAfter;
#hasOnInsert;
/**
* Do not call this method unless you need to inspect the
* inner workings of the cache. If anything returned by this
* object is modified in any way, strange breakage may occur.
*
* These fields are private for a reason!
*
* @internal
*/
static unsafeExposeInternals(c) {
return {
// properties
starts: c.#starts,
ttls: c.#ttls,
sizes: c.#sizes,
keyMap: c.#keyMap,
keyList: c.#keyList,
valList: c.#valList,
next: c.#next,
prev: c.#prev,
get head() {
return c.#head;
},
get tail() {
return c.#tail;
},
free: c.#free,
// methods
isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
moveToTail: (index) => c.#moveToTail(index),
indexes: (options) => c.#indexes(options),
rindexes: (options) => c.#rindexes(options),
isStale: (index) => c.#isStale(index),
};
}
// Protected read-only members
/**
* {@link LRUCache.OptionsBase.max} (read-only)
*/
get max() {
return this.#max;
}
/**
* {@link LRUCache.OptionsBase.maxSize} (read-only)
*/
get maxSize() {
return this.#maxSize;
}
/**
* The total computed size of items in the cache (read-only)
*/
get calculatedSize() {
return this.#calculatedSize;
}
/**
* The number of items stored in the cache (read-only)
*/
get size() {
return this.#size;
}
/**
* {@link LRUCache.OptionsBase.fetchMethod} (read-only)
*/
get fetchMethod() {
return this.#fetchMethod;
}
get memoMethod() {
return this.#memoMethod;
}
/**
* {@link LRUCache.OptionsBase.dispose} (read-only)
*/
get dispose() {
return this.#dispose;
}
/**
* {@link LRUCache.OptionsBase.onInsert} (read-only)
*/
get onInsert() {
return this.#onInsert;
}
/**
* {@link LRUCache.OptionsBase.disposeAfter} (read-only)
*/
get disposeAfter() {
return this.#disposeAfter;
}
constructor(options) {
const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
if (max !== 0 && !isPosInt(max)) {
throw new TypeError('max option must be a nonnegative integer');
}
const UintArray = max ? getUintArray(max) : Array;
if (!UintArray) {
throw new Error('invalid max value: ' + max);
}
this.#max = max;
this.#maxSize = maxSize;
this.maxEntrySize = maxEntrySize || this.#maxSize;
this.sizeCalculation = sizeCalculation;
if (this.sizeCalculation) {
if (!this.#maxSize && !this.maxEntrySize) {
throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
}
if (typeof this.sizeCalculation !== 'function') {
throw new TypeError('sizeCalculation set to non-function');
}
}
if (memoMethod !== undefined &&
typeof memoMethod !== 'function') {
throw new TypeError('memoMethod must be a function if defined');
}
this.#memoMethod = memoMethod;
if (fetchMethod !== undefined &&
typeof fetchMethod !== 'function') {
throw new TypeError('fetchMethod must be a function if specified');
}
this.#fetchMethod = fetchMethod;
this.#hasFetchMethod = !!fetchMethod;
this.#keyMap = new Map();
this.#keyList = new Array(max).fill(undefined);
this.#valList = new Array(max).fill(undefined);
this.#next = new UintArray(max);
this.#prev = new UintArray(max);
this.#head = 0;
this.#tail = 0;
this.#free = Stack.create(max);
this.#size = 0;
this.#calculatedSize = 0;
if (typeof dispose === 'function') {
this.#dispose = dispose;
}
if (typeof onInsert === 'function') {
this.#onInsert = onInsert;
}
if (typeof disposeAfter === 'function') {
this.#disposeAfter = disposeAfter;
this.#disposed = [];
}
else {
this.#disposeAfter = undefined;
this.#disposed = undefined;
}
this.#hasDispose = !!this.#dispose;
this.#hasOnInsert = !!this.#onInsert;
this.#hasDisposeAfter = !!this.#disposeAfter;
this.noDisposeOnSet = !!noDisposeOnSet;
this.noUpdateTTL = !!noUpdateTTL;
this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
this.ignoreFetchAbort = !!ignoreFetchAbort;
// NB: maxEntrySize is set to maxSize if it's set
if (this.maxEntrySize !== 0) {
if (this.#maxSize !== 0) {
if (!isPosInt(this.#maxSize)) {
throw new TypeError('maxSize must be a positive integer if specified');
}
}
if (!isPosInt(this.maxEntrySize)) {
throw new TypeError('maxEntrySize must be a positive integer if specified');
}
this.#initializeSizeTracking();
}
this.allowStale = !!allowStale;
this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
this.updateAgeOnGet = !!updateAgeOnGet;
this.updateAgeOnHas = !!updateAgeOnHas;
this.ttlResolution =
isPosInt(ttlResolution) || ttlResolution === 0
? ttlResolution
: 1;
this.ttlAutopurge = !!ttlAutopurge;
this.ttl = ttl || 0;
if (this.ttl) {
if (!isPosInt(this.ttl)) {
throw new TypeError('ttl must be a positive integer if specified');
}
this.#initializeTTLTracking();
}
// do not allow completely unbounded caches
if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
throw new TypeError('At least one of max, maxSize, or ttl is required');
}
if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
const code = 'LRU_CACHE_UNBOUNDED';
if (shouldWarn(code)) {
warned.add(code);
const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
'result in unbounded memory consumption.';
emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
}
}
}
/**
* Return the number of ms left in the item's TTL. If item is not in cache,
* returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
*/
getRemainingTTL(key) {
return this.#keyMap.has(key) ? Infinity : 0;
}
#initializeTTLTracking() {
const ttls = new ZeroArray(this.#max);
const starts = new ZeroArray(this.#max);
this.#ttls = ttls;
this.#starts = starts;
this.#setItemTTL = (index, ttl, start = perf.now()) => {
starts[index] = ttl !== 0 ? start : 0;
ttls[index] = ttl;
if (ttl !== 0 && this.ttlAutopurge) {
const t = setTimeout(() => {
if (this.#isStale(index)) {
this.#delete(this.#keyList[index], 'expire');
}
}, ttl + 1);
// unref() not supported on all platforms
/* c8 ignore start */
if (t.unref) {
t.unref();
}
/* c8 ignore stop */
}
};
this.#updateItemAge = index => {
starts[index] = ttls[index] !== 0 ? perf.now() : 0;
};
this.#statusTTL = (status, index) => {
if (ttls[index]) {
const ttl = ttls[index];
const start = starts[index];
/* c8 ignore next */
if (!ttl || !start)
return;
status.ttl = ttl;
status.start = start;
status.now = cachedNow || getNow();
const age = status.now - start;
status.remainingTTL = ttl - age;
}
};
// debounce calls to perf.now() to 1s so we're not hitting
// that costly call repeatedly.
let cachedNow = 0;
const getNow = () => {
const n = perf.now();
if (this.ttlResolution > 0) {
cachedNow = n;
const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
// not available on all platforms
/* c8 ignore start */
if (t.unref) {
t.unref();
}
/* c8 ignore stop */
}
return n;
};
this.getRemainingTTL = key => {
const index = this.#keyMap.get(key);
if (index === undefined) {
return 0;
}
const ttl = ttls[index];
const start = starts[index];
if (!ttl || !start) {
return Infinity;
}
const age = (cachedNow || getNow()) - start;
return ttl - age;
};
this.#isStale = index => {
const s = starts[index];
const t = ttls[index];
return !!t && !!s && (cachedNow || getNow()) - s > t;
};
}
// conditionally set private methods related to TTL
#updateItemAge = () => { };
#statusTTL = () => { };
#setItemTTL = () => { };
/* c8 ignore stop */
#isStale = () => false;
#initializeSizeTracking() {
const sizes = new ZeroArray(this.#max);
this.#calculatedSize = 0;
this.#sizes = sizes;
this.#removeItemSize = index => {
this.#calculatedSize -= sizes[index];
sizes[index] = 0;
};
this.#requireSize = (k, v, size, sizeCalculation) => {
// provisionally accept background fetches.
// actual value size will be checked when they return.
if (this.#isBackgroundFetch(v)) {
return 0;
}
if (!isPosInt(size)) {
if (sizeCalculation) {
if (typeof sizeCalculation !== 'function') {
throw new TypeError('sizeCalculation must be a function');
}
size = sizeCalculation(v, k);
if (!isPosInt(size)) {
throw new TypeError('sizeCalculation return invalid (expect positive integer)');
}
}
else {
throw new TypeError('invalid size value (must be positive integer). ' +
'When maxSize or maxEntrySize is used, sizeCalculation ' +
'or size must be set.');
}
}
return size;
};
this.#addItemSize = (index, size, status) => {
sizes[index] = size;
if (this.#maxSize) {
const maxSize = this.#maxSize - sizes[index];
while (this.#calculatedSize > maxSize) {
this.#evict(true);
}
}
this.#calculatedSize += sizes[index];
if (status) {
status.entrySize = size;
status.totalCalculatedSize = this.#calculatedSize;
}
};
}
#removeItemSize = _i => { };
#addItemSize = (_i, _s, _st) => { };
#requireSize = (_k, _v, size, sizeCalculation) => {
if (size || sizeCalculation) {
throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
}
return 0;
};
*#indexes({ allowStale = this.allowStale } = {}) {
if (this.#size) {
for (let i = this.#tail; true;) {
if (!this.#isValidIndex(i)) {
break;
}
if (allowStale || !this.#isStale(i)) {
yield i;
}
if (i === this.#head) {
break;
}
else {
i = this.#prev[i];
}
}
}
}
*#rindexes({ allowStale = this.allowStale } = {}) {
if (this.#size) {
for (let i = this.#head; true;) {
if (!this.#isValidIndex(i)) {
break;
}
if (allowStale || !this.#isStale(i)) {
yield i;
}
if (i === this.#tail) {
break;
}
else {
i = this.#next[i];
}
}
}
}
#isValidIndex(index) {
return (index !== undefined &&
this.#keyMap.get(this.#keyList[index]) === index);
}
/**
* Return a generator yielding `[key, value]` pairs,
* in order from most recently used to least recently used.
*/
*entries() {
for (const i of this.#indexes()) {
if (this.#valList[i] !== undefined &&
this.#keyList[i] !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield [this.#keyList[i], this.#valList[i]];
}
}
}
/**
* Inverse order version of {@link LRUCache.entries}
*
* Return a generator yielding `[key, value]` pairs,
* in order from least recently used to most recently used.
*/
*rentries() {
for (const i of this.#rindexes()) {
if (this.#valList[i] !== undefined &&
this.#keyList[i] !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield [this.#keyList[i], this.#valList[i]];
}
}
}
/**
* Return a generator yielding the keys in the cache,
* in order from most recently used to least recently used.
*/
*keys() {
for (const i of this.#indexes()) {
const k = this.#keyList[i];
if (k !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield k;
}
}
}
/**
* Inverse order version of {@link LRUCache.keys}
*
* Return a generator yielding the keys in the cache,
* in order from least recently used to most recently used.
*/
*rkeys() {
for (const i of this.#rindexes()) {
const k = this.#keyList[i];
if (k !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield k;
}
}
}
/**
* Return a generator yielding the values in the cache,
* in order from most recently used to least recently used.
*/
*values() {
for (const i of this.#indexes()) {
const v = this.#valList[i];
if (v !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield this.#valList[i];
}
}
}
/**
* Inverse order version of {@link LRUCache.values}
*
* Return a generator yielding the values in the cache,
* in order from least recently used to most recently used.
*/
*rvalues() {
for (const i of this.#rindexes()) {
const v = this.#valList[i];
if (v !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield this.#valList[i];
}
}
}
/**
* Iterating over the cache itself yields the same results as
* {@link LRUCache.entries}
*/
[Symbol.iterator]() {
return this.entries();
}
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method
* `Object.prototype.toString`.
*/
[Symbol.toStringTag] = 'LRUCache';
/**
* Find a value for which the supplied fn method returns a truthy value,
* similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
*/
find(fn, getOptions = {}) {
for (const i of this.#indexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
if (fn(value, this.#keyList[i], this)) {
return this.get(this.#keyList[i], getOptions);
}
}
}
/**
* Call the supplied function on each item in the cache, in order from most
* recently used to least recently used.
*
* `fn` is called as `fn(value, key, cache)`.
*
* If `thisp` is provided, function will be called in the `this`-context of
* the provided object, or the cache if no `thisp` object is provided.
*
* Does not update age or recenty of use, or iterate over stale values.
*/
forEach(fn, thisp = this) {
for (const i of this.#indexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
fn.call(thisp, value, this.#keyList[i], this);
}
}
/**
* The same as {@link LRUCache.forEach} but items are iterated over in
* reverse order. (ie, less recently used items are iterated over first.)
*/
rforEach(fn, thisp = this) {
for (const i of this.#rindexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
fn.call(thisp, value, this.#keyList[i], this);
}
}
/**
* Delete any stale entries. Returns true if anything was removed,
* false otherwise.
*/
purgeStale() {
let deleted = false;
for (const i of this.#rindexes({ allowStale: true })) {
if (this.#isStale(i)) {
this.#delete(this.#keyList[i], 'expire');
deleted = true;
}
}
return deleted;
}
/**
* Get the extended info about a given entry, to get its value, size, and
* TTL info simultaneously. Returns `undefined` if the key is not present.
*
* Unlike {@link LRUCache#dump}, which is designed to be portable and survive
* serialization, the `start` value is always the current timestamp, and the
* `ttl` is a calculated remaining time to live (negative if expired).
*
* Always returns stale values, if their info is found in the cache, so be
* sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
* if relevant.
*/
info(key) {
const i = this.#keyMap.get(key);
if (i === undefined)
return undefined;
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
return undefined;
const entry = { value };
if (this.#ttls && this.#starts) {
const ttl = this.#ttls[i];
const start = this.#starts[i];
if (ttl && start) {
const remain = ttl - (perf.now() - start);
entry.ttl = remain;
entry.start = Date.now();
}
}
if (this.#sizes) {
entry.size = this.#sizes[i];
}
return entry;
}
/**
* Return an array of [key, {@link LRUCache.Entry}] tuples which can be
* passed to {@link LRUCache#load}.
*
* The `start` fields are calculated relative to a portable `Date.now()`
* timestamp, even if `performance.now()` is available.
*
* Stale entries are always included in the `dump`, even if
* {@link LRUCache.OptionsBase.allowStale} is false.
*
* Note: this returns an actual array, not a generator, so it can be more
* easily passed around.
*/
dump() {
const arr = [];
for (const i of this.#indexes({ allowStale: true })) {
const key = this.#keyList[i];
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined || key === undefined)
continue;
const entry = { value };
if (this.#ttls && this.#starts) {
entry.ttl = this.#ttls[i];
// always dump the start relative to a portable timestamp
// it's ok for this to be a bit slow, it's a rare operation.
const age = perf.now() - this.#starts[i];
entry.start = Math.floor(Date.now() - age);
}
if (this.#sizes) {
entry.size = this.#sizes[i];
}
arr.unshift([key, entry]);
}
return arr;
}
/**
* Reset the cache and load in the items in entries in the order listed.
*
* The shape of the resulting cache may be different if the same options are
* not used in both caches.
*
* The `start` fields are assumed to be calculated relative to a portable
* `Date.now()` timestamp, even if `performance.now()` is available.
*/
load(arr) {
this.clear();
for (const [key, entry] of arr) {
if (entry.start) {
// entry.start is a portable timestamp, but we may be using
// node's performance.now(), so calculate the offset, so that
// we get the intended remaining TTL, no matter how long it's
// been on ice.
//
// it's ok for this to be a bit slow, it's a rare operation.
const age = Date.now() - entry.start;
entry.start = perf.now() - age;
}
this.set(key, entry.value, entry);
}
}
/**
* Add a value to the cache.
*
* Note: if `undefined` is specified as a value, this is an alias for
* {@link LRUCache#delete}
*
* Fields on the {@link LRUCache.SetOptions} options param will override
* their corresponding values in the constructor options for the scope
* of this single `set()` operation.
*
* If `start` is provided, then that will set the effective start
* time for the TTL calculation. Note that this must be a previous
* value of `performance.now()` if supported, or a previous value of
* `Date.now()` if not.
*
* Options object may also include `size`, which will prevent
* calling the `sizeCalculation` function and just use the specified
* number if it is a positive integer, and `noDisposeOnSet` which
* will prevent calling a `dispose` function in the case of
* overwrites.
*
* If the `size` (or return value of `sizeCalculation`) for a given
* entry is greater than `maxEntrySize`, then the item will not be
* added to the cache.
*
* Will update the recency of the entry.
*
* If the value is `undefined`, then this is an alias for
* `cache.delete(key)`. `undefined` is never stored in the cache.
*/
set(k, v, setOptions = {}) {
if (v === undefined) {
this.delete(k);
return this;
}
const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
let { noUpdateTTL = this.noUpdateTTL } = setOptions;
const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
// if the item doesn't fit, don't do anything
// NB: maxEntrySize set to maxSize by default
if (this.maxEntrySize && size > this.maxEntrySize) {
if (status) {
status.set = 'miss';
status.maxEntrySizeExceeded = true;
}
// have to delete, in case something is there already.
this.#delete(k, 'set');
return this;
}
let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
if (index === undefined) {
// addition
index = (this.#size === 0
? this.#tail
: this.#free.length !== 0
? this.#free.pop()
: this.#size === this.#max
? this.#evict(false)
: this.#size);
this.#keyList[index] = k;
this.#valList[index] = v;
this.#keyMap.set(k, index);
this.#next[this.#tail] = index;
this.#prev[index] = this.#tail;
this.#tail = index;
this.#size++;
this.#addItemSize(index, size, status);
if (status)
status.set = 'add';
noUpdateTTL = false;
if (this.#hasOnInsert) {
this.#onInsert?.(v, k, 'add');
}
}
else {
// update
this.#moveToTail(index);
const oldVal = this.#valList[index];
if (v !== oldVal) {
if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
oldVal.__abortController.abort(new Error('replaced'));
const { __staleWhileFetching: s } = oldVal;
if (s !== undefined && !noDisposeOnSet) {
if (this.#hasDispose) {
this.#dispose?.(s, k, 'set');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([s, k, 'set']);
}
}
}
else if (!noDisposeOnSet) {
if (this.#hasDispose) {
this.#dispose?.(oldVal, k, 'set');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([oldVal, k, 'set']);
}
}
this.#removeItemSize(index);
this.#addItemSize(index, size, status);
this.#valList[index] = v;
if (status) {
status.set = 'replace';
const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
? oldVal.__staleWhileFetching
: oldVal;
if (oldValue !== undefined)
status.oldValue = oldValue;
}
}
else if (status) {
status.set = 'update';
}
if (this.#hasOnInsert) {
this.onInsert?.(v, k, v === oldVal ? 'update' : 'replace');
}
}
if (ttl !== 0 && !this.#ttls) {
this.#initializeTTLTracking();
}
if (this.#ttls) {
if (!noUpdateTTL) {
this.#setItemTTL(index, ttl, start);
}
if (status)
this.#statusTTL(status, index);
}
if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
return this;
}
/**
* Evict the least recently used item, returning its value or
* `undefined` if cache is empty.
*/
pop() {
try {
while (this.#size) {
const val = this.#valList[this.#head];
this.#evict(true);
if (this.#isBackgroundFetch(val)) {
if (val.__staleWhileFetching) {
return val.__staleWhileFetching;
}
}
else if (val !== undefined) {
return val;
}
}
}
finally {
if (this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
}
}
#evict(free) {
const head = this.#head;
const k = this.#keyList[head];
const v = this.#valList[head];
if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('evicted'));
}
else if (this.#hasDispose || this.#hasDisposeAfter) {
if (this.#hasDispose) {
this.#dispose?.(v, k, 'evict');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, 'evict']);
}
}
this.#removeItemSize(head);
// if we aren't about to use the index, then null these out
if (free) {
this.#keyList[head] = undefined;
this.#valList[head] = undefined;
this.#free.push(head);
}
if (this.#size === 1) {
this.#head = this.#tail = 0;
this.#free.length = 0;
}
else {
this.#head = this.#next[head];
}
this.#keyMap.delete(k);
this.#size--;
return head;
}
/**
* Check if a key is in the cache, without updating the recency of use.
* Will return false if the item is stale, even though it is technically
* in the cache.
*
* Check if a key is in the cache, without updating the recency of
* use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
* to `true` in either the options or the constructor.
*
* Will return `false` if the item is stale, even though it is technically in
* the cache. The difference can be determined (if it matters) by using a
* `status` argument, and inspecting the `has` field.
*
* Will not update item age unless
* {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
*/
has(k, hasOptions = {}) {
const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
const index = this.#keyMap.get(k);
if (index !== undefined) {
const v = this.#valList[index];
if (this.#isBackgroundFetch(v) &&
v.__staleWhileFetching === undefined) {
return false;
}
if (!this.#isStale(index)) {
if (updateAgeOnHas) {
this.#updateItemAge(index);
}
if (status) {
status.has = 'hit';
this.#statusTTL(status, index);
}
return true;
}
else if (status) {
status.has = 'stale';
this.#statusTTL(status, index);
}
}
else if (status) {
status.has = 'miss';
}
return false;
}
/**
* Like {@link LRUCache#get} but doesn't update recency or delete stale
* items.
*
* Returns `undefined` if the item is stale, unless
* {@link LRUCache.OptionsBase.allowStale} is set.
*/
peek(k, peekOptions = {}) {
const { allowStale = this.allowStale } = peekOptions;
const index = this.#keyMap.get(k);
if (index === undefined ||
(!allowStale && this.#isStale(index))) {
return;
}
const v = this.#valList[index];
// either stale and allowed, or forcing a refresh of non-stale value
return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
}
#backgroundFetch(k, index, options, context) {
const v = index === undefined ? undefined : this.#valList[index];
if (this.#isBackgroundFetch(v)) {
return v;
}
const ac = new AC();
const { signal } = options;
// when/if our AC signals, then stop listening to theirs.
signal?.addEventListener('abort', () => ac.abort(signal.reason), {
signal: ac.signal,
});
const fetchOpts = {
signal: ac.signal,
options,
context,
};
const cb = (v, updateCache = false) => {
const { aborted } = ac.signal;
const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
if (options.status) {
if (aborted && !updateCache) {
options.status.fetchAborted = true;
options.status.fetchError = ac.signal.reason;
if (ignoreAbort)
options.status.fetchAbortIgnored = true;
}
else {
options.status.fetchResolved = true;
}
}
if (aborted && !ignoreAbort && !updateCache) {
return fetchFail(ac.signal.reason);
}
// either we didn't abort, and are still here, or we did, and ignored
const bf = p;
if (this.#valList[index] === p) {
if (v === undefined) {
if (bf.__staleWhileFetching) {
this.#valList[index] = bf.__staleWhileFetching;
}
else {
this.#delete(k, 'fetch');
}
}
else {
if (options.status)
options.status.fetchUpdated = true;
this.set(k, v, fetchOpts.options);
}
}
return v;
};
const eb = (er) => {
if (options.status) {
options.status.fetchRejected = true;
options.status.fetchError = er;
}
return fetchFail(er);
};
const fetchFail = (er) => {
const { aborted } = ac.signal;
const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
const noDelete = allowStale || options.noDeleteOnFetchRejection;
const bf = p;
if (this.#valList[index] === p) {
// if we allow stale on fetch rejections, then we need to ensure that
// the stale value is not removed from the cache when the fetch fails.
const del = !noDelete || bf.__staleWhileFetching === undefined;
if (del) {
this.#delete(k, 'fetch');
}
else if (!allowStaleAborted) {
// still replace the *promise* with the stale value,
// since we are done with the promise at this point.
// leave it untouched if we're still waiting for an
// aborted background fetch that hasn't yet returned.
this.#valList[index] = bf.__staleWhileFetching;
}
}
if (allowStale) {
if (options.status && bf.__staleWhileFetching !== undefined) {
options.status.returnedStale = true;
}
return bf.__staleWhileFetching;
}
else if (bf.__returned === bf) {
throw er;
}
};
const pcall = (res, rej) => {
const fmp = this.#fetchMethod?.(k, v, fetchOpts);
if (fmp && fmp instanceof Promise) {
fmp.then(v => res(v === undefined ? undefined : v), rej);
}
// ignored, we go until we finish, regardless.
// defer check until we are actually aborting,
// so fetchMethod can override.
ac.signal.addEventListener('abort', () => {
if (!options.ignoreFetchAbort ||
options.allowStaleOnFetchAbort) {
res(undefined);
// when it eventually resolves, update the cache.
if (options.allowStaleOnFetchAbort) {
res = v => cb(v, true);
}
}
});
};
if (options.status)
options.status.fetchDispatched = true;
const p = new Promise(pcall).then(cb, eb);
const bf = Object.assign(p, {
__abortController: ac,
__staleWhileFetching: v,
__returned: undefined,
});
if (index === undefined) {
// internal, don't expose status.
this.set(k, bf, { ...fetchOpts.options, status: undefined });
index = this.#keyMap.get(k);
}
else {
this.#valList[index] = bf;
}
return bf;
}
#isBackgroundFetch(p) {
if (!this.#hasFetchMethod)
return false;
const b = p;
return (!!b &&
b instanceof Promise &&
b.hasOwnProperty('__staleWhileFetching') &&
b.__abortController instanceof AC);
}
async fetch(k, fetchOptions = {}) {
const {
// get options
allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
// set options
ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
// fetch exclusive options
noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
if (!this.#hasFetchMethod) {
if (status)
status.fetch = 'get';
return this.get(k, {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
status,
});
}
const options = {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
ttl,
noDisposeOnSet,
size,
sizeCalculation,
noUpdateTTL,
noDeleteOnFetchRejection,
allowStaleOnFetchRejection,
allowStaleOnFetchAbort,
ignoreFetchAbort,
status,
signal,
};
let index = this.#keyMap.get(k);
if (index === undefined) {
if (status)
status.fetch = 'miss';
const p = this.#backgroundFetch(k, index, options, context);
return (p.__returned = p);
}
else {
// in cache, maybe already fetching
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
const stale = allowStale && v.__staleWhileFetching !== undefined;
if (status) {
status.fetch = 'inflight';
if (stale)
status.returnedStale = true;
}
return stale ? v.__staleWhileFetching : (v.__returned = v);
}
// if we force a refresh, that means do NOT serve the cached value,
// unless we are already in the process of refreshing the cache.
const isStale = this.#isStale(index);
if (!forceRefresh && !isStale) {
if (status)
status.fetch = 'hit';
this.#moveToTail(index);
if (updateAgeOnGet) {
this.#updateItemAge(index);
}
if (status)
this.#statusTTL(status, index);
return v;
}
// ok, it is stale or a forced refresh, and not already fetching.
// refresh the cache.
const p = this.#backgroundFetch(k, index, options, context);
const hasStale = p.__staleWhileFetching !== undefined;
const staleVal = hasStale && allowStale;
if (status) {
status.fetch = isStale ? 'stale' : 'refresh';
if (staleVal && isStale)
status.returnedStale = true;
}
return staleVal ? p.__staleWhileFetching : (p.__returned = p);
}
}
async forceFetch(k, fetchOptions = {}) {
const v = await this.fetch(k, fetchOptions);
if (v === undefined)
throw new Error('fetch() returned undefined');
return v;
}
memo(k, memoOptions = {}) {
const memoMethod = this.#memoMethod;
if (!memoMethod) {
throw new Error('no memoMethod provided to constructor');
}
const { context, forceRefresh, ...options } = memoOptions;
const v = this.get(k, options);
if (!forceRefresh && v !== undefined)
return v;
const vv = memoMethod(k, v, {
options,
context,
});
this.set(k, vv, options);
return vv;
}
/**
* Return a value from the cache. Will update the recency of the cache
* entry found.
*
* If the key is not found, get() will return `undefined`.
*/
get(k, getOptions = {}) {
const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
const index = this.#keyMap.get(k);
if (index !== undefined) {
const value = this.#valList[index];
const fetching = this.#isBackgroundFetch(value);
if (status)
this.#statusTTL(status, index);
if (this.#isStale(index)) {
if (status)
status.get = 'stale';
// delete only if not an in-flight background fetch
if (!fetching) {
if (!noDeleteOnStaleGet) {
this.#delete(k, 'expire');
}
if (status && allowStale)
status.returnedStale = true;
return allowStale ? value : undefined;
}
else {
if (status &&
allowStale &&
value.__staleWhileFetching !== undefined) {
status.returnedStale = true;
}
return allowStale ? value.__staleWhileFetching : undefined;
}
}
else {
if (status)
status.get = 'hit';
// if we're currently fetching it, we don't actually have it yet
// it's not stale, which means this isn't a staleWhileRefetching.
// If it's not stale, and fetching, AND has a __staleWhileFetching
// value, then that means the user fetched with {forceRefresh:true},
// so it's safe to return that value.
if (fetching) {
return value.__staleWhileFetching;
}
this.#moveToTail(index);
if (updateAgeOnGet) {
this.#updateItemAge(index);
}
return value;
}
}
else if (status) {
status.get = 'miss';
}
}
#connect(p, n) {
this.#prev[n] = p;
this.#next[p] = n;
}
#moveToTail(index) {
// if tail already, nothing to do
// if head, move head to next[index]
// else
// move next[prev[index]] to next[index] (head has no prev)
// move prev[next[index]] to prev[index]
// prev[index] = tail
// next[tail] = index
// tail = index
if (index !== this.#tail) {
if (index === this.#head) {
this.#head = this.#next[index];
}
else {
this.#connect(this.#prev[index], this.#next[index]);
}
this.#connect(this.#tail, index);
this.#tail = index;
}
}
/**
* Deletes a key out of the cache.
*
* Returns true if the key was deleted, false otherwise.
*/
delete(k) {
return this.#delete(k, 'delete');
}
#delete(k, reason) {
let deleted = false;
if (this.#size !== 0) {
const index = this.#keyMap.get(k);
if (index !== undefined) {
deleted = true;
if (this.#size === 1) {
this.#clear(reason);
}
else {
this.#removeItemSize(index);
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('deleted'));
}
else if (this.#hasDispose || this.#hasDisposeAfter) {
if (this.#hasDispose) {
this.#dispose?.(v, k, reason);
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, reason]);
}
}
this.#keyMap.delete(k);
this.#keyList[index] = undefined;
this.#valList[index] = undefined;
if (index === this.#tail) {
this.#tail = this.#prev[index];
}
else if (index === this.#head) {
this.#head = this.#next[index];
}
else {
const pi = this.#prev[index];
this.#next[pi] = this.#next[index];
const ni = this.#next[index];
this.#prev[ni] = this.#prev[index];
}
this.#size--;
this.#free.push(index);
}
}
}
if (this.#hasDisposeAfter && this.#disposed?.length) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
return deleted;
}
/**
* Clear the cache entirely, throwing away all values.
*/
clear() {
return this.#clear('delete');
}
#clear(reason) {
for (const index of this.#rindexes({ allowStale: true })) {
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('deleted'));
}
else {
const k = this.#keyList[index];
if (this.#hasDispose) {
this.#dispose?.(v, k, reason);
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, reason]);
}
}
}
this.#keyMap.clear();
this.#valList.fill(undefined);
this.#keyList.fill(undefined);
if (this.#ttls && this.#starts) {
this.#ttls.fill(0);
this.#starts.fill(0);
}
if (this.#sizes) {
this.#sizes.fill(0);
}
this.#head = 0;
this.#tail = 0;
this.#free.length = 0;
this.#calculatedSize = 0;
this.#size = 0;
if (this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
}
}
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: external "node:fs"
var external_node_fs_ = __webpack_require__(3024);
var external_node_fs_namespaceObject = /*#__PURE__*/__webpack_require__.t(external_node_fs_, 2);
// EXTERNAL MODULE: external "node:fs/promises"
var promises_ = __webpack_require__(1455);
// EXTERNAL MODULE: external "node:events"
var external_node_events_ = __webpack_require__(8474);
// EXTERNAL MODULE: external "node:stream"
var external_node_stream_ = __webpack_require__(7075);
// EXTERNAL MODULE: external "node:string_decoder"
var external_node_string_decoder_ = __webpack_require__(6193);
;// ./node_modules/minipass/dist/esm/index.js
const proc = typeof process === 'object' && process
? process
: {
stdout: null,
stderr: null,
};
/**
* Return true if the argument is a Minipass stream, Node stream, or something
* else that Minipass can interact with.
*/
const isStream = (s) => !!s &&
typeof s === 'object' &&
(s instanceof Minipass ||
s instanceof external_node_stream_ ||
isReadable(s) ||
isWritable(s));
/**
* Return true if the argument is a valid {@link Minipass.Readable}
*/
const isReadable = (s) => !!s &&
typeof s === 'object' &&
s instanceof external_node_events_.EventEmitter &&
typeof s.pipe === 'function' &&
// node core Writable streams have a pipe() method, but it throws
s.pipe !== external_node_stream_.Writable.prototype.pipe;
/**
* Return true if the argument is a valid {@link Minipass.Writable}
*/
const isWritable = (s) => !!s &&
typeof s === 'object' &&
s instanceof external_node_events_.EventEmitter &&
typeof s.write === 'function' &&
typeof s.end === 'function';
const EOF = Symbol('EOF');
const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
const EMITTED_END = Symbol('emittedEnd');
const EMITTING_END = Symbol('emittingEnd');
const EMITTED_ERROR = Symbol('emittedError');
const CLOSED = Symbol('closed');
const READ = Symbol('read');
const FLUSH = Symbol('flush');
const FLUSHCHUNK = Symbol('flushChunk');
const ENCODING = Symbol('encoding');
const DECODER = Symbol('decoder');
const FLOWING = Symbol('flowing');
const PAUSED = Symbol('paused');
const RESUME = Symbol('resume');
const BUFFER = Symbol('buffer');
const PIPES = Symbol('pipes');
const BUFFERLENGTH = Symbol('bufferLength');
const BUFFERPUSH = Symbol('bufferPush');
const BUFFERSHIFT = Symbol('bufferShift');
const OBJECTMODE = Symbol('objectMode');
// internal event when stream is destroyed
const DESTROYED = Symbol('destroyed');
// internal event when stream has an error
const ERROR = Symbol('error');
const EMITDATA = Symbol('emitData');
const EMITEND = Symbol('emitEnd');
const EMITEND2 = Symbol('emitEnd2');
const ASYNC = Symbol('async');
const ABORT = Symbol('abort');
const ABORTED = Symbol('aborted');
const SIGNAL = Symbol('signal');
const DATALISTENERS = Symbol('dataListeners');
const DISCARDED = Symbol('discarded');
const defer = (fn) => Promise.resolve().then(fn);
const nodefer = (fn) => fn();
const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
(!!b &&
typeof b === 'object' &&
b.constructor &&
b.constructor.name === 'ArrayBuffer' &&
b.byteLength >= 0);
const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
/**
* Internal class representing a pipe to a destination stream.
*
* @internal
*/
class Pipe {
src;
dest;
opts;
ondrain;
constructor(src, dest, opts) {
this.src = src;
this.dest = dest;
this.opts = opts;
this.ondrain = () => src[RESUME]();
this.dest.on('drain', this.ondrain);
}
unpipe() {
this.dest.removeListener('drain', this.ondrain);
}
// only here for the prototype
/* c8 ignore start */
proxyErrors(_er) { }
/* c8 ignore stop */
end() {
this.unpipe();
if (this.opts.end)
this.dest.end();
}
}
/**
* Internal class representing a pipe to a destination stream where
* errors are proxied.
*
* @internal
*/
class PipeProxyErrors extends Pipe {
unpipe() {
this.src.removeListener('error', this.proxyErrors);
super.unpipe();
}
constructor(src, dest, opts) {
super(src, dest, opts);
this.proxyErrors = er => dest.emit('error', er);
src.on('error', this.proxyErrors);
}
}
const isObjectModeOptions = (o) => !!o.objectMode;
const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
/**
* Main export, the Minipass class
*
* `RType` is the type of data emitted, defaults to Buffer
*
* `WType` is the type of data to be written, if RType is buffer or string,
* then any {@link Minipass.ContiguousData} is allowed.
*
* `Events` is the set of event handler signatures that this object
* will emit, see {@link Minipass.Events}
*/
class Minipass extends external_node_events_.EventEmitter {
[FLOWING] = false;
[PAUSED] = false;
[PIPES] = [];
[BUFFER] = [];
[OBJECTMODE];
[ENCODING];
[ASYNC];
[DECODER];
[EOF] = false;
[EMITTED_END] = false;
[EMITTING_END] = false;
[CLOSED] = false;
[EMITTED_ERROR] = null;
[BUFFERLENGTH] = 0;
[DESTROYED] = false;
[SIGNAL];
[ABORTED] = false;
[DATALISTENERS] = 0;
[DISCARDED] = false;
/**
* true if the stream can be written
*/
writable = true;
/**
* true if the stream can be read
*/
readable = true;
/**
* If `RType` is Buffer, then options do not need to be provided.
* Otherwise, an options object must be provided to specify either
* {@link Minipass.SharedOptions.objectMode} or
* {@link Minipass.SharedOptions.encoding}, as appropriate.
*/
constructor(...args) {
const options = (args[0] ||
{});
super();
if (options.objectMode && typeof options.encoding === 'string') {
throw new TypeError('Encoding and objectMode may not be used together');
}
if (isObjectModeOptions(options)) {
this[OBJECTMODE] = true;
this[ENCODING] = null;
}
else if (isEncodingOptions(options)) {
this[ENCODING] = options.encoding;
this[OBJECTMODE] = false;
}
else {
this[OBJECTMODE] = false;
this[ENCODING] = null;
}
this[ASYNC] = !!options.async;
this[DECODER] = this[ENCODING]
? new external_node_string_decoder_.StringDecoder(this[ENCODING])
: null;
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposeBuffer === true) {
Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
}
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposePipes === true) {
Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
}
const { signal } = options;
if (signal) {
this[SIGNAL] = signal;
if (signal.aborted) {
this[ABORT]();
}
else {
signal.addEventListener('abort', () => this[ABORT]());
}
}
}
/**
* The amount of data stored in the buffer waiting to be read.
*
* For Buffer strings, this will be the total byte length.
* For string encoding streams, this will be the string character length,
* according to JavaScript's `string.length` logic.
* For objectMode streams, this is a count of the items waiting to be
* emitted.
*/
get bufferLength() {
return this[BUFFERLENGTH];
}
/**
* The `BufferEncoding` currently in use, or `null`
*/
get encoding() {
return this[ENCODING];
}
/**
* @deprecated - This is a read only property
*/
set encoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* @deprecated - Encoding may only be set at instantiation time
*/
setEncoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* True if this is an objectMode stream
*/
get objectMode() {
return this[OBJECTMODE];
}
/**
* @deprecated - This is a read-only property
*/
set objectMode(_om) {
throw new Error('objectMode must be set at instantiation time');
}
/**
* true if this is an async stream
*/
get ['async']() {
return this[ASYNC];
}
/**
* Set to true to make this stream async.
*
* Once set, it cannot be unset, as this would potentially cause incorrect
* behavior. Ie, a sync stream can be made async, but an async stream
* cannot be safely made sync.
*/
set ['async'](a) {
this[ASYNC] = this[ASYNC] || !!a;
}
// drop everything and get out of the flow completely
[ABORT]() {
this[ABORTED] = true;
this.emit('abort', this[SIGNAL]?.reason);
this.destroy(this[SIGNAL]?.reason);
}
/**
* True if the stream has been aborted.
*/
get aborted() {
return this[ABORTED];
}
/**
* No-op setter. Stream aborted status is set via the AbortSignal provided
* in the constructor options.
*/
set aborted(_) { }
write(chunk, encoding, cb) {
if (this[ABORTED])
return false;
if (this[EOF])
throw new Error('write after end');
if (this[DESTROYED]) {
this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
return true;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (!encoding)
encoding = 'utf8';
const fn = this[ASYNC] ? defer : nodefer;
// convert array buffers and typed array views into buffers
// at some point in the future, we may want to do the opposite!
// leave strings and buffers as-is
// anything is only allowed if in object mode, so throw
if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
if (isArrayBufferView(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
else if (isArrayBufferLike(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk);
}
else if (typeof chunk !== 'string') {
throw new Error('Non-contiguous data written to non-objectMode stream');
}
}
// handle object mode up front, since it's simpler
// this yields better performance, fewer checks later.
if (this[OBJECTMODE]) {
// maybe impossible?
/* c8 ignore start */
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
/* c8 ignore stop */
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// at this point the chunk is a buffer or string
// don't buffer it up or send it to the decoder
if (!chunk.length) {
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// fast-path writing strings of same encoding to a stream with
// an empty buffer, skipping the buffer/decoder dance
if (typeof chunk === 'string' &&
// unless it is a string already ready for us to use
!(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
//@ts-ignore - sinful unsafe type change
chunk = Buffer.from(chunk, encoding);
}
if (Buffer.isBuffer(chunk) && this[ENCODING]) {
//@ts-ignore - sinful unsafe type change
chunk = this[DECODER].write(chunk);
}
// Note: flushing CAN potentially switch us into not-flowing mode
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
/**
* Low-level explicit read method.
*
* In objectMode, the argument is ignored, and one item is returned if
* available.
*
* `n` is the number of bytes (or in the case of encoding streams,
* characters) to consume. If `n` is not provided, then the entire buffer
* is returned, or `null` is returned if no data is available.
*
* If `n` is greater that the amount of data in the internal buffer,
* then `null` is returned.
*/
read(n) {
if (this[DESTROYED])
return null;
this[DISCARDED] = false;
if (this[BUFFERLENGTH] === 0 ||
n === 0 ||
(n && n > this[BUFFERLENGTH])) {
this[MAYBE_EMIT_END]();
return null;
}
if (this[OBJECTMODE])
n = null;
if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
// not object mode, so if we have an encoding, then RType is string
// otherwise, must be Buffer
this[BUFFER] = [
(this[ENCODING]
? this[BUFFER].join('')
: Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
];
}
const ret = this[READ](n || null, this[BUFFER][0]);
this[MAYBE_EMIT_END]();
return ret;
}
[READ](n, chunk) {
if (this[OBJECTMODE])
this[BUFFERSHIFT]();
else {
const c = chunk;
if (n === c.length || n === null)
this[BUFFERSHIFT]();
else if (typeof c === 'string') {
this[BUFFER][0] = c.slice(n);
chunk = c.slice(0, n);
this[BUFFERLENGTH] -= n;
}
else {
this[BUFFER][0] = c.subarray(n);
chunk = c.subarray(0, n);
this[BUFFERLENGTH] -= n;
}
}
this.emit('data', chunk);
if (!this[BUFFER].length && !this[EOF])
this.emit('drain');
return chunk;
}
end(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = undefined;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (chunk !== undefined)
this.write(chunk, encoding);
if (cb)
this.once('end', cb);
this[EOF] = true;
this.writable = false;
// if we haven't written anything, then go ahead and emit,
// even if we're not reading.
// we'll re-emit if a new 'end' listener is added anyway.
// This makes MP more suitable to write-only use cases.
if (this[FLOWING] || !this[PAUSED])
this[MAYBE_EMIT_END]();
return this;
}
// don't let the internal resume be overwritten
[RESUME]() {
if (this[DESTROYED])
return;
if (!this[DATALISTENERS] && !this[PIPES].length) {
this[DISCARDED] = true;
}
this[PAUSED] = false;
this[FLOWING] = true;
this.emit('resume');
if (this[BUFFER].length)
this[FLUSH]();
else if (this[EOF])
this[MAYBE_EMIT_END]();
else
this.emit('drain');
}
/**
* Resume the stream if it is currently in a paused state
*
* If called when there are no pipe destinations or `data` event listeners,
* this will place the stream in a "discarded" state, where all data will
* be thrown away. The discarded state is removed if a pipe destination or
* data handler is added, if pause() is called, or if any synchronous or
* asynchronous iteration is started.
*/
resume() {
return this[RESUME]();
}
/**
* Pause the stream
*/
pause() {
this[FLOWING] = false;
this[PAUSED] = true;
this[DISCARDED] = false;
}
/**
* true if the stream has been forcibly destroyed
*/
get destroyed() {
return this[DESTROYED];
}
/**
* true if the stream is currently in a flowing state, meaning that
* any writes will be immediately emitted.
*/
get flowing() {
return this[FLOWING];
}
/**
* true if the stream is currently in a paused state
*/
get paused() {
return this[PAUSED];
}
[BUFFERPUSH](chunk) {
if (this[OBJECTMODE])
this[BUFFERLENGTH] += 1;
else
this[BUFFERLENGTH] += chunk.length;
this[BUFFER].push(chunk);
}
[BUFFERSHIFT]() {
if (this[OBJECTMODE])
this[BUFFERLENGTH] -= 1;
else
this[BUFFERLENGTH] -= this[BUFFER][0].length;
return this[BUFFER].shift();
}
[FLUSH](noDrain = false) {
do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
this[BUFFER].length);
if (!noDrain && !this[BUFFER].length && !this[EOF])
this.emit('drain');
}
[FLUSHCHUNK](chunk) {
this.emit('data', chunk);
return this[FLOWING];
}
/**
* Pipe all data emitted by this stream into the destination provided.
*
* Triggers the flow of data.
*/
pipe(dest, opts) {
if (this[DESTROYED])
return dest;
this[DISCARDED] = false;
const ended = this[EMITTED_END];
opts = opts || {};
if (dest === proc.stdout || dest === proc.stderr)
opts.end = false;
else
opts.end = opts.end !== false;
opts.proxyErrors = !!opts.proxyErrors;
// piping an ended stream ends immediately
if (ended) {
if (opts.end)
dest.end();
}
else {
// "as" here just ignores the WType, which pipes don't care about,
// since they're only consuming from us, and writing to the dest
this[PIPES].push(!opts.proxyErrors
? new Pipe(this, dest, opts)
: new PipeProxyErrors(this, dest, opts));
if (this[ASYNC])
defer(() => this[RESUME]());
else
this[RESUME]();
}
return dest;
}
/**
* Fully unhook a piped destination stream.
*
* If the destination stream was the only consumer of this stream (ie,
* there are no other piped destinations or `'data'` event listeners)
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
unpipe(dest) {
const p = this[PIPES].find(p => p.dest === dest);
if (p) {
if (this[PIPES].length === 1) {
if (this[FLOWING] && this[DATALISTENERS] === 0) {
this[FLOWING] = false;
}
this[PIPES] = [];
}
else
this[PIPES].splice(this[PIPES].indexOf(p), 1);
p.unpipe();
}
}
/**
* Alias for {@link Minipass#on}
*/
addListener(ev, handler) {
return this.on(ev, handler);
}
/**
* Mostly identical to `EventEmitter.on`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* - Adding a 'data' event handler will trigger the flow of data
*
* - Adding a 'readable' event handler when there is data waiting to be read
* will cause 'readable' to be emitted immediately.
*
* - Adding an 'endish' event handler ('end', 'finish', etc.) which has
* already passed will cause the event to be emitted immediately and all
* handlers removed.
*
* - Adding an 'error' event handler after an error has been emitted will
* cause the event to be re-emitted immediately with the error previously
* raised.
*/
on(ev, handler) {
const ret = super.on(ev, handler);
if (ev === 'data') {
this[DISCARDED] = false;
this[DATALISTENERS]++;
if (!this[PIPES].length && !this[FLOWING]) {
this[RESUME]();
}
}
else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
super.emit('readable');
}
else if (isEndish(ev) && this[EMITTED_END]) {
super.emit(ev);
this.removeAllListeners(ev);
}
else if (ev === 'error' && this[EMITTED_ERROR]) {
const h = handler;
if (this[ASYNC])
defer(() => h.call(this, this[EMITTED_ERROR]));
else
h.call(this, this[EMITTED_ERROR]);
}
return ret;
}
/**
* Alias for {@link Minipass#off}
*/
removeListener(ev, handler) {
return this.off(ev, handler);
}
/**
* Mostly identical to `EventEmitter.off`
*
* If a 'data' event handler is removed, and it was the last consumer
* (ie, there are no pipe destinations or other 'data' event listeners),
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
off(ev, handler) {
const ret = super.off(ev, handler);
// if we previously had listeners, and now we don't, and we don't
// have any pipes, then stop the flow, unless it's been explicitly
// put in a discarded flowing state via stream.resume().
if (ev === 'data') {
this[DATALISTENERS] = this.listeners('data').length;
if (this[DATALISTENERS] === 0 &&
!this[DISCARDED] &&
!this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* Mostly identical to `EventEmitter.removeAllListeners`
*
* If all 'data' event handlers are removed, and they were the last consumer
* (ie, there are no pipe destinations), then the flow of data will stop
* until there is another consumer or {@link Minipass#resume} is explicitly
* called.
*/
removeAllListeners(ev) {
const ret = super.removeAllListeners(ev);
if (ev === 'data' || ev === undefined) {
this[DATALISTENERS] = 0;
if (!this[DISCARDED] && !this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* true if the 'end' event has been emitted
*/
get emittedEnd() {
return this[EMITTED_END];
}
[MAYBE_EMIT_END]() {
if (!this[EMITTING_END] &&
!this[EMITTED_END] &&
!this[DESTROYED] &&
this[BUFFER].length === 0 &&
this[EOF]) {
this[EMITTING_END] = true;
this.emit('end');
this.emit('prefinish');
this.emit('finish');
if (this[CLOSED])
this.emit('close');
this[EMITTING_END] = false;
}
}
/**
* Mostly identical to `EventEmitter.emit`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* If the stream has been destroyed, and the event is something other
* than 'close' or 'error', then `false` is returned and no handlers
* are called.
*
* If the event is 'end', and has already been emitted, then the event
* is ignored. If the stream is in a paused or non-flowing state, then
* the event will be deferred until data flow resumes. If the stream is
* async, then handlers will be called on the next tick rather than
* immediately.
*
* If the event is 'close', and 'end' has not yet been emitted, then
* the event will be deferred until after 'end' is emitted.
*
* If the event is 'error', and an AbortSignal was provided for the stream,
* and there are no listeners, then the event is ignored, matching the
* behavior of node core streams in the presense of an AbortSignal.
*
* If the event is 'finish' or 'prefinish', then all listeners will be
* removed after emitting the event, to prevent double-firing.
*/
emit(ev, ...args) {
const data = args[0];
// error and close are only events allowed after calling destroy()
if (ev !== 'error' &&
ev !== 'close' &&
ev !== DESTROYED &&
this[DESTROYED]) {
return false;
}
else if (ev === 'data') {
return !this[OBJECTMODE] && !data
? false
: this[ASYNC]
? (defer(() => this[EMITDATA](data)), true)
: this[EMITDATA](data);
}
else if (ev === 'end') {
return this[EMITEND]();
}
else if (ev === 'close') {
this[CLOSED] = true;
// don't emit close before 'end' and 'finish'
if (!this[EMITTED_END] && !this[DESTROYED])
return false;
const ret = super.emit('close');
this.removeAllListeners('close');
return ret;
}
else if (ev === 'error') {
this[EMITTED_ERROR] = data;
super.emit(ERROR, data);
const ret = !this[SIGNAL] || this.listeners('error').length
? super.emit('error', data)
: false;
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'resume') {
const ret = super.emit('resume');
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'finish' || ev === 'prefinish') {
const ret = super.emit(ev);
this.removeAllListeners(ev);
return ret;
}
// Some other unknown event
const ret = super.emit(ev, ...args);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITDATA](data) {
for (const p of this[PIPES]) {
if (p.dest.write(data) === false)
this.pause();
}
const ret = this[DISCARDED] ? false : super.emit('data', data);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITEND]() {
if (this[EMITTED_END])
return false;
this[EMITTED_END] = true;
this.readable = false;
return this[ASYNC]
? (defer(() => this[EMITEND2]()), true)
: this[EMITEND2]();
}
[EMITEND2]() {
if (this[DECODER]) {
const data = this[DECODER].end();
if (data) {
for (const p of this[PIPES]) {
p.dest.write(data);
}
if (!this[DISCARDED])
super.emit('data', data);
}
}
for (const p of this[PIPES]) {
p.end();
}
const ret = super.emit('end');
this.removeAllListeners('end');
return ret;
}
/**
* Return a Promise that resolves to an array of all emitted data once
* the stream ends.
*/
async collect() {
const buf = Object.assign([], {
dataLength: 0,
});
if (!this[OBJECTMODE])
buf.dataLength = 0;
// set the promise first, in case an error is raised
// by triggering the flow here.
const p = this.promise();
this.on('data', c => {
buf.push(c);
if (!this[OBJECTMODE])
buf.dataLength += c.length;
});
await p;
return buf;
}
/**
* Return a Promise that resolves to the concatenation of all emitted data
* once the stream ends.
*
* Not allowed on objectMode streams.
*/
async concat() {
if (this[OBJECTMODE]) {
throw new Error('cannot concat in objectMode');
}
const buf = await this.collect();
return (this[ENCODING]
? buf.join('')
: Buffer.concat(buf, buf.dataLength));
}
/**
* Return a void Promise that resolves once the stream ends.
*/
async promise() {
return new Promise((resolve, reject) => {
this.on(DESTROYED, () => reject(new Error('stream destroyed')));
this.on('error', er => reject(er));
this.on('end', () => resolve());
});
}
/**
* Asynchronous `for await of` iteration.
*
* This will continue emitting all chunks until the stream terminates.
*/
[Symbol.asyncIterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = async () => {
this.pause();
stopped = true;
return { value: undefined, done: true };
};
const next = () => {
if (stopped)
return stop();
const res = this.read();
if (res !== null)
return Promise.resolve({ done: false, value: res });
if (this[EOF])
return stop();
let resolve;
let reject;
const onerr = (er) => {
this.off('data', ondata);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
stop();
reject(er);
};
const ondata = (value) => {
this.off('error', onerr);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
this.pause();
resolve({ value, done: !!this[EOF] });
};
const onend = () => {
this.off('error', onerr);
this.off('data', ondata);
this.off(DESTROYED, ondestroy);
stop();
resolve({ done: true, value: undefined });
};
const ondestroy = () => onerr(new Error('stream destroyed'));
return new Promise((res, rej) => {
reject = rej;
resolve = res;
this.once(DESTROYED, ondestroy);
this.once('error', onerr);
this.once('end', onend);
this.once('data', ondata);
});
};
return {
next,
throw: stop,
return: stop,
[Symbol.asyncIterator]() {
return this;
},
};
}
/**
* Synchronous `for of` iteration.
*
* The iteration will terminate when the internal buffer runs out, even
* if the stream has not yet terminated.
*/
[Symbol.iterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = () => {
this.pause();
this.off(ERROR, stop);
this.off(DESTROYED, stop);
this.off('end', stop);
stopped = true;
return { done: true, value: undefined };
};
const next = () => {
if (stopped)
return stop();
const value = this.read();
return value === null ? stop() : { done: false, value };
};
this.once('end', stop);
this.once(ERROR, stop);
this.once(DESTROYED, stop);
return {
next,
throw: stop,
return: stop,
[Symbol.iterator]() {
return this;
},
};
}
/**
* Destroy a stream, preventing it from being used for any further purpose.
*
* If the stream has a `close()` method, then it will be called on
* destruction.
*
* After destruction, any attempt to write data, read data, or emit most
* events will be ignored.
*
* If an error argument is provided, then it will be emitted in an
* 'error' event.
*/
destroy(er) {
if (this[DESTROYED]) {
if (er)
this.emit('error', er);
else
this.emit(DESTROYED);
return this;
}
this[DESTROYED] = true;
this[DISCARDED] = true;
// throw away all buffered data, it's never coming out
this[BUFFER].length = 0;
this[BUFFERLENGTH] = 0;
const wc = this;
if (typeof wc.close === 'function' && !this[CLOSED])
wc.close();
if (er)
this.emit('error', er);
// if no error to emit, still reject pending promises
else
this.emit(DESTROYED);
return this;
}
/**
* Alias for {@link isStream}
*
* Former export location, maintained for backwards compatibility.
*
* @deprecated
*/
static get isStream() {
return isStream;
}
}
//# sourceMappingURL=index.js.map
;// ./node_modules/path-scurry/dist/esm/index.js
const realpathSync = external_fs_.realpathSync.native;
// TODO: test perf of fs/promises realpath vs realpathCB,
// since the promises one uses realpath.native
const defaultFS = {
lstatSync: external_fs_.lstatSync,
readdir: external_fs_.readdir,
readdirSync: external_fs_.readdirSync,
readlinkSync: external_fs_.readlinkSync,
realpathSync,
promises: {
lstat: promises_.lstat,
readdir: promises_.readdir,
readlink: promises_.readlink,
realpath: promises_.realpath,
},
};
// if they just gave us require('fs') then use our default
const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === external_node_fs_namespaceObject ?
defaultFS
: {
...defaultFS,
...fsOption,
promises: {
...defaultFS.promises,
...(fsOption.promises || {}),
},
};
// turn something like //?/c:/ into c:\
const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
// windows paths are separated by either / or \
const eitherSep = /[\\\/]/;
const UNKNOWN = 0; // may not even exist, for all we know
const IFIFO = 0b0001;
const IFCHR = 0b0010;
const IFDIR = 0b0100;
const IFBLK = 0b0110;
const IFREG = 0b1000;
const IFLNK = 0b1010;
const IFSOCK = 0b1100;
const IFMT = 0b1111;
// mask to unset low 4 bits
const IFMT_UNKNOWN = ~IFMT;
// set after successfully calling readdir() and getting entries.
const READDIR_CALLED = 0b0000_0001_0000;
// set after a successful lstat()
const LSTAT_CALLED = 0b0000_0010_0000;
// set if an entry (or one of its parents) is definitely not a dir
const ENOTDIR = 0b0000_0100_0000;
// set if an entry (or one of its parents) does not exist
// (can also be set on lstat errors like EACCES or ENAMETOOLONG)
const ENOENT = 0b0000_1000_0000;
// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK
// set if we fail to readlink
const ENOREADLINK = 0b0001_0000_0000;
// set if we know realpath() will fail
const ENOREALPATH = 0b0010_0000_0000;
const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
const TYPEMASK = 0b0011_1111_1111;
const entToType = (s) => s.isFile() ? IFREG
: s.isDirectory() ? IFDIR
: s.isSymbolicLink() ? IFLNK
: s.isCharacterDevice() ? IFCHR
: s.isBlockDevice() ? IFBLK
: s.isSocket() ? IFSOCK
: s.isFIFO() ? IFIFO
: UNKNOWN;
// normalize unicode path names
const normalizeCache = new Map();
const normalize = (s) => {
const c = normalizeCache.get(s);
if (c)
return c;
const n = s.normalize('NFKD');
normalizeCache.set(s, n);
return n;
};
const normalizeNocaseCache = new Map();
const normalizeNocase = (s) => {
const c = normalizeNocaseCache.get(s);
if (c)
return c;
const n = normalize(s.toLowerCase());
normalizeNocaseCache.set(s, n);
return n;
};
/**
* An LRUCache for storing resolved path strings or Path objects.
* @internal
*/
class ResolveCache extends LRUCache {
constructor() {
super({ max: 256 });
}
}
// In order to prevent blowing out the js heap by allocating hundreds of
// thousands of Path entries when walking extremely large trees, the "children"
// in this tree are represented by storing an array of Path entries in an
// LRUCache, indexed by the parent. At any time, Path.children() may return an
// empty array, indicating that it doesn't know about any of its children, and
// thus has to rebuild that cache. This is fine, it just means that we don't
// benefit as much from having the cached entries, but huge directory walks
// don't blow out the stack, and smaller ones are still as fast as possible.
//
//It does impose some complexity when building up the readdir data, because we
//need to pass a reference to the children array that we started with.
/**
* an LRUCache for storing child entries.
* @internal
*/
class ChildrenCache extends LRUCache {
constructor(maxSize = 16 * 1024) {
super({
maxSize,
// parent + children
sizeCalculation: a => a.length + 1,
});
}
}
const setAsCwd = Symbol('PathScurry setAsCwd');
/**
* Path objects are sort of like a super-powered
* {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}
*
* Each one represents a single filesystem entry on disk, which may or may not
* exist. It includes methods for reading various types of information via
* lstat, readlink, and readdir, and caches all information to the greatest
* degree possible.
*
* Note that fs operations that would normally throw will instead return an
* "empty" value. This is in order to prevent excessive overhead from error
* stack traces.
*/
class PathBase {
/**
* the basename of this path
*
* **Important**: *always* test the path name against any test string
* usingthe {@link isNamed} method, and not by directly comparing this
* string. Otherwise, unicode path strings that the system sees as identical
* will not be properly treated as the same path, leading to incorrect
* behavior and possible security issues.
*/
name;
/**
* the Path entry corresponding to the path root.
*
* @internal
*/
root;
/**
* All roots found within the current PathScurry family
*
* @internal
*/
roots;
/**
* a reference to the parent path, or undefined in the case of root entries
*
* @internal
*/
parent;
/**
* boolean indicating whether paths are compared case-insensitively
* @internal
*/
nocase;
/**
* boolean indicating that this path is the current working directory
* of the PathScurry collection that contains it.
*/
isCWD = false;
// potential default fs override
#fs;
// Stats fields
#dev;
get dev() {
return this.#dev;
}
#mode;
get mode() {
return this.#mode;
}
#nlink;
get nlink() {
return this.#nlink;
}
#uid;
get uid() {
return this.#uid;
}
#gid;
get gid() {
return this.#gid;
}
#rdev;
get rdev() {
return this.#rdev;
}
#blksize;
get blksize() {
return this.#blksize;
}
#ino;
get ino() {
return this.#ino;
}
#size;
get size() {
return this.#size;
}
#blocks;
get blocks() {
return this.#blocks;
}
#atimeMs;
get atimeMs() {
return this.#atimeMs;
}
#mtimeMs;
get mtimeMs() {
return this.#mtimeMs;
}
#ctimeMs;
get ctimeMs() {
return this.#ctimeMs;
}
#birthtimeMs;
get birthtimeMs() {
return this.#birthtimeMs;
}
#atime;
get atime() {
return this.#atime;
}
#mtime;
get mtime() {
return this.#mtime;
}
#ctime;
get ctime() {
return this.#ctime;
}
#birthtime;
get birthtime() {
return this.#birthtime;
}
#matchName;
#depth;
#fullpath;
#fullpathPosix;
#relative;
#relativePosix;
#type;
#children;
#linkTarget;
#realpath;
/**
* This property is for compatibility with the Dirent class as of
* Node v20, where Dirent['parentPath'] refers to the path of the
* directory that was passed to readdir. For root entries, it's the path
* to the entry itself.
*/
get parentPath() {
return (this.parent || this).fullpath();
}
/**
* Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
* this property refers to the *parent* path, not the path object itself.
*
* @deprecated
*/
get path() {
return this.parentPath;
}
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
this.name = name;
this.#matchName = nocase ? normalizeNocase(name) : normalize(name);
this.#type = type & TYPEMASK;
this.nocase = nocase;
this.roots = roots;
this.root = root || this;
this.#children = children;
this.#fullpath = opts.fullpath;
this.#relative = opts.relative;
this.#relativePosix = opts.relativePosix;
this.parent = opts.parent;
if (this.parent) {
this.#fs = this.parent.#fs;
}
else {
this.#fs = fsFromOption(opts.fs);
}
}
/**
* Returns the depth of the Path object from its root.
*
* For example, a path at `/foo/bar` would have a depth of 2.
*/
depth() {
if (this.#depth !== undefined)
return this.#depth;
if (!this.parent)
return (this.#depth = 0);
return (this.#depth = this.parent.depth() + 1);
}
/**
* @internal
*/
childrenCache() {
return this.#children;
}
/**
* Get the Path object referenced by the string path, resolved from this Path
*/
resolve(path) {
if (!path) {
return this;
}
const rootPath = this.getRootString(path);
const dir = path.substring(rootPath.length);
const dirParts = dir.split(this.splitSep);
const result = rootPath ?
this.getRoot(rootPath).#resolveParts(dirParts)
: this.#resolveParts(dirParts);
return result;
}
#resolveParts(dirParts) {
let p = this;
for (const part of dirParts) {
p = p.child(part);
}
return p;
}
/**
* Returns the cached children Path objects, if still available. If they
* have fallen out of the cache, then returns an empty array, and resets the
* READDIR_CALLED bit, so that future calls to readdir() will require an fs
* lookup.
*
* @internal
*/
children() {
const cached = this.#children.get(this);
if (cached) {
return cached;
}
const children = Object.assign([], { provisional: 0 });
this.#children.set(this, children);
this.#type &= ~READDIR_CALLED;
return children;
}
/**
* Resolves a path portion and returns or creates the child Path.
*
* Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
* `'..'`.
*
* This should not be called directly. If `pathPart` contains any path
* separators, it will lead to unsafe undefined behavior.
*
* Use `Path.resolve()` instead.
*
* @internal
*/
child(pathPart, opts) {
if (pathPart === '' || pathPart === '.') {
return this;
}
if (pathPart === '..') {
return this.parent || this;
}
// find the child
const children = this.children();
const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
for (const p of children) {
if (p.#matchName === name) {
return p;
}
}
// didn't find it, create provisional child, since it might not
// actually exist. If we know the parent isn't a dir, then
// in fact it CAN'T exist.
const s = this.parent ? this.sep : '';
const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined;
const pchild = this.newChild(pathPart, UNKNOWN, {
...opts,
parent: this,
fullpath,
});
if (!this.canReaddir()) {
pchild.#type |= ENOENT;
}
// don't have to update provisional, because if we have real children,
// then provisional is set to children.length, otherwise a lower number
children.push(pchild);
return pchild;
}
/**
* The relative path from the cwd. If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpath()
*/
relative() {
if (this.isCWD)
return '';
if (this.#relative !== undefined) {
return this.#relative;
}
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#relative = this.name);
}
const pv = p.relative();
return pv + (!pv || !p.parent ? '' : this.sep) + name;
}
/**
* The relative path from the cwd, using / as the path separator.
* If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpathPosix()
* On posix systems, this is identical to relative().
*/
relativePosix() {
if (this.sep === '/')
return this.relative();
if (this.isCWD)
return '';
if (this.#relativePosix !== undefined)
return this.#relativePosix;
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#relativePosix = this.fullpathPosix());
}
const pv = p.relativePosix();
return pv + (!pv || !p.parent ? '' : '/') + name;
}
/**
* The fully resolved path string for this Path entry
*/
fullpath() {
if (this.#fullpath !== undefined) {
return this.#fullpath;
}
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#fullpath = this.name);
}
const pv = p.fullpath();
const fp = pv + (!p.parent ? '' : this.sep) + name;
return (this.#fullpath = fp);
}
/**
* On platforms other than windows, this is identical to fullpath.
*
* On windows, this is overridden to return the forward-slash form of the
* full UNC path.
*/
fullpathPosix() {
if (this.#fullpathPosix !== undefined)
return this.#fullpathPosix;
if (this.sep === '/')
return (this.#fullpathPosix = this.fullpath());
if (!this.parent) {
const p = this.fullpath().replace(/\\/g, '/');
if (/^[a-z]:\//i.test(p)) {
return (this.#fullpathPosix = `//?/${p}`);
}
else {
return (this.#fullpathPosix = p);
}
}
const p = this.parent;
const pfpp = p.fullpathPosix();
const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name;
return (this.#fullpathPosix = fpp);
}
/**
* Is the Path of an unknown type?
*
* Note that we might know *something* about it if there has been a previous
* filesystem operation, for example that it does not exist, or is not a
* link, or whether it has child entries.
*/
isUnknown() {
return (this.#type & IFMT) === UNKNOWN;
}
isType(type) {
return this[`is${type}`]();
}
getType() {
return (this.isUnknown() ? 'Unknown'
: this.isDirectory() ? 'Directory'
: this.isFile() ? 'File'
: this.isSymbolicLink() ? 'SymbolicLink'
: this.isFIFO() ? 'FIFO'
: this.isCharacterDevice() ? 'CharacterDevice'
: this.isBlockDevice() ? 'BlockDevice'
: /* c8 ignore start */ this.isSocket() ? 'Socket'
: 'Unknown');
/* c8 ignore stop */
}
/**
* Is the Path a regular file?
*/
isFile() {
return (this.#type & IFMT) === IFREG;
}
/**
* Is the Path a directory?
*/
isDirectory() {
return (this.#type & IFMT) === IFDIR;
}
/**
* Is the path a character device?
*/
isCharacterDevice() {
return (this.#type & IFMT) === IFCHR;
}
/**
* Is the path a block device?
*/
isBlockDevice() {
return (this.#type & IFMT) === IFBLK;
}
/**
* Is the path a FIFO pipe?
*/
isFIFO() {
return (this.#type & IFMT) === IFIFO;
}
/**
* Is the path a socket?
*/
isSocket() {
return (this.#type & IFMT) === IFSOCK;
}
/**
* Is the path a symbolic link?
*/
isSymbolicLink() {
return (this.#type & IFLNK) === IFLNK;
}
/**
* Return the entry if it has been subject of a successful lstat, or
* undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* simply
* mean that we haven't called lstat on it.
*/
lstatCached() {
return this.#type & LSTAT_CALLED ? this : undefined;
}
/**
* Return the cached link target if the entry has been the subject of a
* successful readlink, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readlink() has been called at some point.
*/
readlinkCached() {
return this.#linkTarget;
}
/**
* Returns the cached realpath target if the entry has been the subject
* of a successful realpath, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* realpath() has been called at some point.
*/
realpathCached() {
return this.#realpath;
}
/**
* Returns the cached child Path entries array if the entry has been the
* subject of a successful readdir(), or [] otherwise.
*
* Does not read the filesystem, so an empty array *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readdir() has been called recently enough to still be valid.
*/
readdirCached() {
const children = this.children();
return children.slice(0, children.provisional);
}
/**
* Return true if it's worth trying to readlink. Ie, we don't (yet) have
* any indication that readlink will definitely fail.
*
* Returns false if the path is known to not be a symlink, if a previous
* readlink failed, or if the entry does not exist.
*/
canReadlink() {
if (this.#linkTarget)
return true;
if (!this.parent)
return false;
// cases where it cannot possibly succeed
const ifmt = this.#type & IFMT;
return !((ifmt !== UNKNOWN && ifmt !== IFLNK) ||
this.#type & ENOREADLINK ||
this.#type & ENOENT);
}
/**
* Return true if readdir has previously been successfully called on this
* path, indicating that cachedReaddir() is likely valid.
*/
calledReaddir() {
return !!(this.#type & READDIR_CALLED);
}
/**
* Returns true if the path is known to not exist. That is, a previous lstat
* or readdir failed to verify its existence when that would have been
* expected, or a parent entry was marked either enoent or enotdir.
*/
isENOENT() {
return !!(this.#type & ENOENT);
}
/**
* Return true if the path is a match for the given path name. This handles
* case sensitivity and unicode normalization.
*
* Note: even on case-sensitive systems, it is **not** safe to test the
* equality of the `.name` property to determine whether a given pathname
* matches, due to unicode normalization mismatches.
*
* Always use this method instead of testing the `path.name` property
* directly.
*/
isNamed(n) {
return !this.nocase ?
this.#matchName === normalize(n)
: this.#matchName === normalizeNocase(n);
}
/**
* Return the Path object corresponding to the target of a symbolic link.
*
* If the Path is not a symbolic link, or if the readlink call fails for any
* reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
*/
async readlink() {
const target = this.#linkTarget;
if (target) {
return target;
}
if (!this.canReadlink()) {
return undefined;
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined;
}
/* c8 ignore stop */
try {
const read = await this.#fs.promises.readlink(this.fullpath());
const linkTarget = (await this.parent.realpath())?.resolve(read);
if (linkTarget) {
return (this.#linkTarget = linkTarget);
}
}
catch (er) {
this.#readlinkFail(er.code);
return undefined;
}
}
/**
* Synchronous {@link PathBase.readlink}
*/
readlinkSync() {
const target = this.#linkTarget;
if (target) {
return target;
}
if (!this.canReadlink()) {
return undefined;
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined;
}
/* c8 ignore stop */
try {
const read = this.#fs.readlinkSync(this.fullpath());
const linkTarget = this.parent.realpathSync()?.resolve(read);
if (linkTarget) {
return (this.#linkTarget = linkTarget);
}
}
catch (er) {
this.#readlinkFail(er.code);
return undefined;
}
}
#readdirSuccess(children) {
// succeeded, mark readdir called bit
this.#type |= READDIR_CALLED;
// mark all remaining provisional children as ENOENT
for (let p = children.provisional; p < children.length; p++) {
const c = children[p];
if (c)
c.#markENOENT();
}
}
#markENOENT() {
// mark as UNKNOWN and ENOENT
if (this.#type & ENOENT)
return;
this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
this.#markChildrenENOENT();
}
#markChildrenENOENT() {
// all children are provisional and do not exist
const children = this.children();
children.provisional = 0;
for (const p of children) {
p.#markENOENT();
}
}
#markENOREALPATH() {
this.#type |= ENOREALPATH;
this.#markENOTDIR();
}
// save the information when we know the entry is not a dir
#markENOTDIR() {
// entry is not a directory, so any children can't exist.
// this *should* be impossible, since any children created
// after it's been marked ENOTDIR should be marked ENOENT,
// so it won't even get to this point.
/* c8 ignore start */
if (this.#type & ENOTDIR)
return;
/* c8 ignore stop */
let t = this.#type;
// this could happen if we stat a dir, then delete it,
// then try to read it or one of its children.
if ((t & IFMT) === IFDIR)
t &= IFMT_UNKNOWN;
this.#type = t | ENOTDIR;
this.#markChildrenENOENT();
}
#readdirFail(code = '') {
// markENOTDIR and markENOENT also set provisional=0
if (code === 'ENOTDIR' || code === 'EPERM') {
this.#markENOTDIR();
}
else if (code === 'ENOENT') {
this.#markENOENT();
}
else {
this.children().provisional = 0;
}
}
#lstatFail(code = '') {
// Windows just raises ENOENT in this case, disable for win CI
/* c8 ignore start */
if (code === 'ENOTDIR') {
// already know it has a parent by this point
const p = this.parent;
p.#markENOTDIR();
}
else if (code === 'ENOENT') {
/* c8 ignore stop */
this.#markENOENT();
}
}
#readlinkFail(code = '') {
let ter = this.#type;
ter |= ENOREADLINK;
if (code === 'ENOENT')
ter |= ENOENT;
// windows gets a weird error when you try to readlink a file
if (code === 'EINVAL' || code === 'UNKNOWN') {
// exists, but not a symlink, we don't know WHAT it is, so remove
// all IFMT bits.
ter &= IFMT_UNKNOWN;
}
this.#type = ter;
// windows just gets ENOENT in this case. We do cover the case,
// just disabled because it's impossible on Windows CI
/* c8 ignore start */
if (code === 'ENOTDIR' && this.parent) {
this.parent.#markENOTDIR();
}
/* c8 ignore stop */
}
#readdirAddChild(e, c) {
return (this.#readdirMaybePromoteChild(e, c) ||
this.#readdirAddNewChild(e, c));
}
#readdirAddNewChild(e, c) {
// alloc new entry at head, so it's never provisional
const type = entToType(e);
const child = this.newChild(e.name, type, { parent: this });
const ifmt = child.#type & IFMT;
if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
child.#type |= ENOTDIR;
}
c.unshift(child);
c.provisional++;
return child;
}
#readdirMaybePromoteChild(e, c) {
for (let p = c.provisional; p < c.length; p++) {
const pchild = c[p];
const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name);
if (name !== pchild.#matchName) {
continue;
}
return this.#readdirPromoteChild(e, pchild, p, c);
}
}
#readdirPromoteChild(e, p, index, c) {
const v = p.name;
// retain any other flags, but set ifmt from dirent
p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e);
// case sensitivity fixing when we learn the true name.
if (v !== e.name)
p.name = e.name;
// just advance provisional index (potentially off the list),
// otherwise we have to splice/pop it out and re-insert at head
if (index !== c.provisional) {
if (index === c.length - 1)
c.pop();
else
c.splice(index, 1);
c.unshift(p);
}
c.provisional++;
return p;
}
/**
* Call lstat() on this Path, and update all known information that can be
* determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat() {
if ((this.#type & ENOENT) === 0) {
try {
this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
return this;
}
catch (er) {
this.#lstatFail(er.code);
}
}
}
/**
* synchronous {@link PathBase.lstat}
*/
lstatSync() {
if ((this.#type & ENOENT) === 0) {
try {
this.#applyStat(this.#fs.lstatSync(this.fullpath()));
return this;
}
catch (er) {
this.#lstatFail(er.code);
}
}
}
#applyStat(st) {
const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st;
this.#atime = atime;
this.#atimeMs = atimeMs;
this.#birthtime = birthtime;
this.#birthtimeMs = birthtimeMs;
this.#blksize = blksize;
this.#blocks = blocks;
this.#ctime = ctime;
this.#ctimeMs = ctimeMs;
this.#dev = dev;
this.#gid = gid;
this.#ino = ino;
this.#mode = mode;
this.#mtime = mtime;
this.#mtimeMs = mtimeMs;
this.#nlink = nlink;
this.#rdev = rdev;
this.#size = size;
this.#uid = uid;
const ifmt = entToType(st);
// retain any other flags, but set the ifmt
this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED;
if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
this.#type |= ENOTDIR;
}
}
#onReaddirCB = [];
#readdirCBInFlight = false;
#callOnReaddirCB(children) {
this.#readdirCBInFlight = false;
const cbs = this.#onReaddirCB.slice();
this.#onReaddirCB.length = 0;
cbs.forEach(cb => cb(null, children));
}
/**
* Standard node-style callback interface to get list of directory entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*
* @param cb The callback called with (er, entries). Note that the `er`
* param is somewhat extraneous, as all readdir() errors are handled and
* simply result in an empty set of entries being returned.
* @param allowZalgo Boolean indicating that immediately known results should
* *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
* zalgo at your peril, the dark pony lord is devious and unforgiving.
*/
readdirCB(cb, allowZalgo = false) {
if (!this.canReaddir()) {
if (allowZalgo)
cb(null, []);
else
queueMicrotask(() => cb(null, []));
return;
}
const children = this.children();
if (this.calledReaddir()) {
const c = children.slice(0, children.provisional);
if (allowZalgo)
cb(null, c);
else
queueMicrotask(() => cb(null, c));
return;
}
// don't have to worry about zalgo at this point.
this.#onReaddirCB.push(cb);
if (this.#readdirCBInFlight) {
return;
}
this.#readdirCBInFlight = true;
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
if (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
else {
// if we didn't get an error, we always get entries.
//@ts-ignore
for (const e of entries) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
this.#callOnReaddirCB(children.slice(0, children.provisional));
return;
});
}
#asyncReaddirInFlight;
/**
* Return an array of known child entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async readdir() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
if (this.#asyncReaddirInFlight) {
await this.#asyncReaddirInFlight;
}
else {
/* c8 ignore start */
let resolve = () => { };
/* c8 ignore stop */
this.#asyncReaddirInFlight = new Promise(res => (resolve = res));
try {
for (const e of await this.#fs.promises.readdir(fullpath, {
withFileTypes: true,
})) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
catch (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
this.#asyncReaddirInFlight = undefined;
resolve();
}
return children.slice(0, children.provisional);
}
/**
* synchronous {@link PathBase.readdir}
*/
readdirSync() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
try {
for (const e of this.#fs.readdirSync(fullpath, {
withFileTypes: true,
})) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
catch (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
return children.slice(0, children.provisional);
}
canReaddir() {
if (this.#type & ENOCHILD)
return false;
const ifmt = IFMT & this.#type;
// we always set ENOTDIR when setting IFMT, so should be impossible
/* c8 ignore start */
if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
return false;
}
/* c8 ignore stop */
return true;
}
shouldWalk(dirs, walkFilter) {
return ((this.#type & IFDIR) === IFDIR &&
!(this.#type & ENOCHILD) &&
!dirs.has(this) &&
(!walkFilter || walkFilter(this)));
}
/**
* Return the Path object corresponding to path as resolved
* by realpath(3).
*
* If the realpath call fails for any reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
* On success, returns a Path object.
*/
async realpath() {
if (this.#realpath)
return this.#realpath;
if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
return undefined;
try {
const rp = await this.#fs.promises.realpath(this.fullpath());
return (this.#realpath = this.resolve(rp));
}
catch (_) {
this.#markENOREALPATH();
}
}
/**
* Synchronous {@link realpath}
*/
realpathSync() {
if (this.#realpath)
return this.#realpath;
if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
return undefined;
try {
const rp = this.#fs.realpathSync(this.fullpath());
return (this.#realpath = this.resolve(rp));
}
catch (_) {
this.#markENOREALPATH();
}
}
/**
* Internal method to mark this Path object as the scurry cwd,
* called by {@link PathScurry#chdir}
*
* @internal
*/
[setAsCwd](oldCwd) {
if (oldCwd === this)
return;
oldCwd.isCWD = false;
this.isCWD = true;
const changed = new Set([]);
let rp = [];
let p = this;
while (p && p.parent) {
changed.add(p);
p.#relative = rp.join(this.sep);
p.#relativePosix = rp.join('/');
p = p.parent;
rp.push('..');
}
// now un-memoize parents of old cwd
p = oldCwd;
while (p && p.parent && !changed.has(p)) {
p.#relative = undefined;
p.#relativePosix = undefined;
p = p.parent;
}
}
}
/**
* Path class used on win32 systems
*
* Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'`
* as the path separator for parsing paths.
*/
class PathWin32 extends PathBase {
/**
* Separator for generating path strings.
*/
sep = '\\';
/**
* Separator for parsing path strings.
*/
splitSep = eitherSep;
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name, type, root, roots, nocase, children, opts);
}
/**
* @internal
*/
newChild(name, type = UNKNOWN, opts = {}) {
return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
/**
* @internal
*/
getRootString(path) {
return external_node_path_.win32.parse(path).root;
}
/**
* @internal
*/
getRoot(rootPath) {
rootPath = uncToDrive(rootPath.toUpperCase());
if (rootPath === this.root.name) {
return this.root;
}
// ok, not that one, check if it matches another we know about
for (const [compare, root] of Object.entries(this.roots)) {
if (this.sameRoot(rootPath, compare)) {
return (this.roots[rootPath] = root);
}
}
// otherwise, have to create a new one.
return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
}
/**
* @internal
*/
sameRoot(rootPath, compare = this.root.name) {
// windows can (rarely) have case-sensitive filesystem, but
// UNC and drive letters are always case-insensitive, and canonically
// represented uppercase.
rootPath = rootPath
.toUpperCase()
.replace(/\//g, '\\')
.replace(uncDriveRegexp, '$1\\');
return rootPath === compare;
}
}
/**
* Path class used on all posix systems.
*
* Uses `'/'` as the path separator.
*/
class PathPosix extends PathBase {
/**
* separator for parsing path strings
*/
splitSep = '/';
/**
* separator for generating path strings
*/
sep = '/';
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name, type, root, roots, nocase, children, opts);
}
/**
* @internal
*/
getRootString(path) {
return path.startsWith('/') ? '/' : '';
}
/**
* @internal
*/
getRoot(_rootPath) {
return this.root;
}
/**
* @internal
*/
newChild(name, type = UNKNOWN, opts = {}) {
return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
}
/**
* The base class for all PathScurry classes, providing the interface for path
* resolution and filesystem operations.
*
* Typically, you should *not* instantiate this class directly, but rather one
* of the platform-specific classes, or the exported {@link PathScurry} which
* defaults to the current platform.
*/
class PathScurryBase {
/**
* The root Path entry for the current working directory of this Scurry
*/
root;
/**
* The string path for the root of this Scurry's current working directory
*/
rootPath;
/**
* A collection of all roots encountered, referenced by rootPath
*/
roots;
/**
* The Path entry corresponding to this PathScurry's current working directory.
*/
cwd;
#resolveCache;
#resolvePosixCache;
#children;
/**
* Perform path comparisons case-insensitively.
*
* Defaults true on Darwin and Windows systems, false elsewhere.
*/
nocase;
#fs;
/**
* This class should not be instantiated directly.
*
* Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
*
* @internal
*/
constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) {
this.#fs = fsFromOption(fs);
if (cwd instanceof URL || cwd.startsWith('file://')) {
cwd = (0,external_node_url_.fileURLToPath)(cwd);
}
// resolve and split root, and then add to the store.
// this is the only time we call path.resolve()
const cwdPath = pathImpl.resolve(cwd);
this.roots = Object.create(null);
this.rootPath = this.parseRootPath(cwdPath);
this.#resolveCache = new ResolveCache();
this.#resolvePosixCache = new ResolveCache();
this.#children = new ChildrenCache(childrenCacheSize);
const split = cwdPath.substring(this.rootPath.length).split(sep);
// resolve('/') leaves '', splits to [''], we don't want that.
if (split.length === 1 && !split[0]) {
split.pop();
}
/* c8 ignore start */
if (nocase === undefined) {
throw new TypeError('must provide nocase setting to PathScurryBase ctor');
}
/* c8 ignore stop */
this.nocase = nocase;
this.root = this.newRoot(this.#fs);
this.roots[this.rootPath] = this.root;
let prev = this.root;
let len = split.length - 1;
const joinSep = pathImpl.sep;
let abs = this.rootPath;
let sawFirst = false;
for (const part of split) {
const l = len--;
prev = prev.child(part, {
relative: new Array(l).fill('..').join(joinSep),
relativePosix: new Array(l).fill('..').join('/'),
fullpath: (abs += (sawFirst ? '' : joinSep) + part),
});
sawFirst = true;
}
this.cwd = prev;
}
/**
* Get the depth of a provided path, string, or the cwd
*/
depth(path = this.cwd) {
if (typeof path === 'string') {
path = this.cwd.resolve(path);
}
return path.depth();
}
/**
* Return the cache of child entries. Exposed so subclasses can create
* child Path objects in a platform-specific way.
*
* @internal
*/
childrenCache() {
return this.#children;
}
/**
* Resolve one or more path strings to a resolved string
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolve(...paths) {
// first figure out the minimum number of paths we have to test
// we always start at cwd, but any absolutes will bump the start
let r = '';
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === '.')
continue;
r = r ? `${p}/${r}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = this.#resolveCache.get(r);
if (cached !== undefined) {
return cached;
}
const result = this.cwd.resolve(r).fullpath();
this.#resolveCache.set(r, result);
return result;
}
/**
* Resolve one or more path strings to a resolved string, returning
* the posix path. Identical to .resolve() on posix systems, but on
* windows will return a forward-slash separated UNC path.
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolvePosix(...paths) {
// first figure out the minimum number of paths we have to test
// we always start at cwd, but any absolutes will bump the start
let r = '';
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === '.')
continue;
r = r ? `${p}/${r}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = this.#resolvePosixCache.get(r);
if (cached !== undefined) {
return cached;
}
const result = this.cwd.resolve(r).fullpathPosix();
this.#resolvePosixCache.set(r, result);
return result;
}
/**
* find the relative path from the cwd to the supplied path string or entry
*/
relative(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.relative();
}
/**
* find the relative path from the cwd to the supplied path string or
* entry, using / as the path delimiter, even on Windows.
*/
relativePosix(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.relativePosix();
}
/**
* Return the basename for the provided string or Path object
*/
basename(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.name;
}
/**
* Return the dirname for the provided string or Path object
*/
dirname(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return (entry.parent || entry).fullpath();
}
async readdir(entry = this.cwd, opts = {
withFileTypes: true,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes } = opts;
if (!entry.canReaddir()) {
return [];
}
else {
const p = await entry.readdir();
return withFileTypes ? p : p.map(e => e.name);
}
}
readdirSync(entry = this.cwd, opts = {
withFileTypes: true,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true } = opts;
if (!entry.canReaddir()) {
return [];
}
else if (withFileTypes) {
return entry.readdirSync();
}
else {
return entry.readdirSync().map(e => e.name);
}
}
/**
* Call lstat() on the string or Path object, and update all known
* information that can be determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.lstat();
}
/**
* synchronous {@link PathScurryBase.lstat}
*/
lstatSync(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.lstatSync();
}
async readlink(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = await entry.readlink();
return withFileTypes ? e : e?.fullpath();
}
readlinkSync(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = entry.readlinkSync();
return withFileTypes ? e : e?.fullpath();
}
async realpath(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = await entry.realpath();
return withFileTypes ? e : e?.fullpath();
}
realpathSync(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = entry.realpathSync();
return withFileTypes ? e : e?.fullpath();
}
async walk(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = [];
if (!filter || filter(entry)) {
results.push(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set();
const walk = (dir, cb) => {
dirs.add(dir);
dir.readdirCB((er, entries) => {
/* c8 ignore start */
if (er) {
return cb(er);
}
/* c8 ignore stop */
let len = entries.length;
if (!len)
return cb();
const next = () => {
if (--len === 0) {
cb();
}
};
for (const e of entries) {
if (!filter || filter(e)) {
results.push(withFileTypes ? e : e.fullpath());
}
if (follow && e.isSymbolicLink()) {
e.realpath()
.then(r => (r?.isUnknown() ? r.lstat() : r))
.then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
}
else {
if (e.shouldWalk(dirs, walkFilter)) {
walk(e, next);
}
else {
next();
}
}
}
}, true); // zalgooooooo
};
const start = entry;
return new Promise((res, rej) => {
walk(start, er => {
/* c8 ignore start */
if (er)
return rej(er);
/* c8 ignore stop */
res(results);
});
});
}
walkSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = [];
if (!filter || filter(entry)) {
results.push(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set([entry]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
results.push(withFileTypes ? e : e.fullpath());
}
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
dirs.add(r);
}
}
}
return results;
}
/**
* Support for `for await`
*
* Alias for {@link PathScurryBase.iterate}
*
* Note: As of Node 19, this is very slow, compared to other methods of
* walking. Consider using {@link PathScurryBase.stream} if memory overhead
* and backpressure are concerns, or {@link PathScurryBase.walk} if not.
*/
[Symbol.asyncIterator]() {
return this.iterate();
}
iterate(entry = this.cwd, options = {}) {
// iterating async over the stream is significantly more performant,
// especially in the warm-cache scenario, because it buffers up directory
// entries in the background instead of waiting for a yield for each one.
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
options = entry;
entry = this.cwd;
}
return this.stream(entry, options)[Symbol.asyncIterator]();
}
/**
* Iterating over a PathScurry performs a synchronous walk.
*
* Alias for {@link PathScurryBase.iterateSync}
*/
[Symbol.iterator]() {
return this.iterateSync();
}
*iterateSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
if (!filter || filter(entry)) {
yield withFileTypes ? entry : entry.fullpath();
}
const dirs = new Set([entry]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
yield withFileTypes ? e : e.fullpath();
}
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
dirs.add(r);
}
}
}
}
stream(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = new Minipass({ objectMode: true });
if (!filter || filter(entry)) {
results.write(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set();
const queue = [entry];
let processing = 0;
const process = () => {
let paused = false;
while (!paused) {
const dir = queue.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const onReaddir = (er, entries, didRealpaths = false) => {
/* c8 ignore start */
if (er)
return results.emit('error', er);
/* c8 ignore stop */
if (follow && !didRealpaths) {
const promises = [];
for (const e of entries) {
if (e.isSymbolicLink()) {
promises.push(e
.realpath()
.then((r) => r?.isUnknown() ? r.lstat() : r));
}
}
if (promises.length) {
Promise.all(promises).then(() => onReaddir(null, entries, true));
return;
}
}
for (const e of entries) {
if (e && (!filter || filter(e))) {
if (!results.write(withFileTypes ? e : e.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e of entries) {
const r = e.realpathCached() || e;
if (r.shouldWalk(dirs, walkFilter)) {
queue.push(r);
}
}
if (paused && !results.flowing) {
results.once('drain', process);
}
else if (!sync) {
process();
}
};
// zalgo containment
let sync = true;
dir.readdirCB(onReaddir, true);
sync = false;
}
};
process();
return results;
}
streamSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = new Minipass({ objectMode: true });
const dirs = new Set();
if (!filter || filter(entry)) {
results.write(withFileTypes ? entry : entry.fullpath());
}
const queue = [entry];
let processing = 0;
const process = () => {
let paused = false;
while (!paused) {
const dir = queue.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
if (!results.write(withFileTypes ? e : e.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e of entries) {
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
queue.push(r);
}
}
}
if (paused && !results.flowing)
results.once('drain', process);
};
process();
return results;
}
chdir(path = this.cwd) {
const oldCwd = this.cwd;
this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path;
this.cwd[setAsCwd](oldCwd);
}
}
/**
* Windows implementation of {@link PathScurryBase}
*
* Defaults to case insensitve, uses `'\\'` to generate path strings. Uses
* {@link PathWin32} for Path objects.
*/
class PathScurryWin32 extends PathScurryBase {
/**
* separator for generating path strings
*/
sep = '\\';
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, external_node_path_.win32, '\\', { ...opts, nocase });
this.nocase = nocase;
for (let p = this.cwd; p; p = p.parent) {
p.nocase = this.nocase;
}
}
/**
* @internal
*/
parseRootPath(dir) {
// if the path starts with a single separator, it's not a UNC, and we'll
// just get separator as the root, and driveFromUNC will return \
// In that case, mount \ on the root from the cwd.
return external_node_path_.win32.parse(dir).root.toUpperCase();
}
/**
* @internal
*/
newRoot(fs) {
return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p));
}
}
/**
* {@link PathScurryBase} implementation for all posix systems other than Darwin.
*
* Defaults to case-sensitive matching, uses `'/'` to generate path strings.
*
* Uses {@link PathPosix} for Path objects.
*/
class PathScurryPosix extends PathScurryBase {
/**
* separator for generating path strings
*/
sep = '/';
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = false } = opts;
super(cwd, external_node_path_.posix, '/', { ...opts, nocase });
this.nocase = nocase;
}
/**
* @internal
*/
parseRootPath(_dir) {
return '/';
}
/**
* @internal
*/
newRoot(fs) {
return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return p.startsWith('/');
}
}
/**
* {@link PathScurryBase} implementation for Darwin (macOS) systems.
*
* Defaults to case-insensitive matching, uses `'/'` for generating path
* strings.
*
* Uses {@link PathPosix} for Path objects.
*/
class PathScurryDarwin extends PathScurryPosix {
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, { ...opts, nocase });
}
}
/**
* Default {@link PathBase} implementation for the current platform.
*
* {@link PathWin32} on Windows systems, {@link PathPosix} on all others.
*/
const Path = process.platform === 'win32' ? PathWin32 : PathPosix;
/**
* Default {@link PathScurryBase} implementation for the current platform.
*
* {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on
* Darwin (macOS) systems, {@link PathScurryPosix} on all others.
*/
const PathScurry = process.platform === 'win32' ? PathScurryWin32
: process.platform === 'darwin' ? PathScurryDarwin
: PathScurryPosix;
//# sourceMappingURL=index.js.map
;// ./node_modules/glob/dist/esm/pattern.js
// this is just a very light wrapper around 2 arrays with an offset index
const isPatternList = (pl) => pl.length >= 1;
const isGlobList = (gl) => gl.length >= 1;
/**
* An immutable-ish view on an array of glob parts and their parsed
* results
*/
class Pattern {
#patternList;
#globList;
#index;
length;
#platform;
#rest;
#globString;
#isDrive;
#isUNC;
#isAbsolute;
#followGlobstar = true;
constructor(patternList, globList, index, platform) {
if (!isPatternList(patternList)) {
throw new TypeError('empty pattern list');
}
if (!isGlobList(globList)) {
throw new TypeError('empty glob list');
}
if (globList.length !== patternList.length) {
throw new TypeError('mismatched pattern list and glob list lengths');
}
this.length = patternList.length;
if (index < 0 || index >= this.length) {
throw new TypeError('index out of range');
}
this.#patternList = patternList;
this.#globList = globList;
this.#index = index;
this.#platform = platform;
// normalize root entries of absolute patterns on initial creation.
if (this.#index === 0) {
// c: => ['c:/']
// C:/ => ['C:/']
// C:/x => ['C:/', 'x']
// //host/share => ['//host/share/']
// //host/share/ => ['//host/share/']
// //host/share/x => ['//host/share/', 'x']
// /etc => ['/', 'etc']
// / => ['/']
if (this.isUNC()) {
// '' / '' / 'host' / 'share'
const [p0, p1, p2, p3, ...prest] = this.#patternList;
const [g0, g1, g2, g3, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = [p0, p1, p2, p3, ''].join('/');
const g = [g0, g1, g2, g3, ''].join('/');
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
else if (this.isDrive() || this.isAbsolute()) {
const [p1, ...prest] = this.#patternList;
const [g1, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = p1 + '/';
const g = g1 + '/';
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
}
}
/**
* The first entry in the parsed list of patterns
*/
pattern() {
return this.#patternList[this.#index];
}
/**
* true of if pattern() returns a string
*/
isString() {
return typeof this.#patternList[this.#index] === 'string';
}
/**
* true of if pattern() returns GLOBSTAR
*/
isGlobstar() {
return this.#patternList[this.#index] === GLOBSTAR;
}
/**
* true if pattern() returns a regexp
*/
isRegExp() {
return this.#patternList[this.#index] instanceof RegExp;
}
/**
* The /-joined set of glob parts that make up this pattern
*/
globString() {
return (this.#globString =
this.#globString ||
(this.#index === 0 ?
this.isAbsolute() ?
this.#globList[0] + this.#globList.slice(1).join('/')
: this.#globList.join('/')
: this.#globList.slice(this.#index).join('/')));
}
/**
* true if there are more pattern parts after this one
*/
hasMore() {
return this.length > this.#index + 1;
}
/**
* The rest of the pattern after this part, or null if this is the end
*/
rest() {
if (this.#rest !== undefined)
return this.#rest;
if (!this.hasMore())
return (this.#rest = null);
this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
this.#rest.#isAbsolute = this.#isAbsolute;
this.#rest.#isUNC = this.#isUNC;
this.#rest.#isDrive = this.#isDrive;
return this.#rest;
}
/**
* true if the pattern represents a //unc/path/ on windows
*/
isUNC() {
const pl = this.#patternList;
return this.#isUNC !== undefined ?
this.#isUNC
: (this.#isUNC =
this.#platform === 'win32' &&
this.#index === 0 &&
pl[0] === '' &&
pl[1] === '' &&
typeof pl[2] === 'string' &&
!!pl[2] &&
typeof pl[3] === 'string' &&
!!pl[3]);
}
// pattern like C:/...
// split = ['C:', ...]
// XXX: would be nice to handle patterns like `c:*` to test the cwd
// in c: for *, but I don't know of a way to even figure out what that
// cwd is without actually chdir'ing into it?
/**
* True if the pattern starts with a drive letter on Windows
*/
isDrive() {
const pl = this.#patternList;
return this.#isDrive !== undefined ?
this.#isDrive
: (this.#isDrive =
this.#platform === 'win32' &&
this.#index === 0 &&
this.length > 1 &&
typeof pl[0] === 'string' &&
/^[a-z]:$/i.test(pl[0]));
}
// pattern = '/' or '/...' or '/x/...'
// split = ['', ''] or ['', ...] or ['', 'x', ...]
// Drive and UNC both considered absolute on windows
/**
* True if the pattern is rooted on an absolute path
*/
isAbsolute() {
const pl = this.#patternList;
return this.#isAbsolute !== undefined ?
this.#isAbsolute
: (this.#isAbsolute =
(pl[0] === '' && pl.length > 1) ||
this.isDrive() ||
this.isUNC());
}
/**
* consume the root of the pattern, and return it
*/
root() {
const p = this.#patternList[0];
return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
p
: '';
}
/**
* Check to see if the current globstar pattern is allowed to follow
* a symbolic link.
*/
checkFollowGlobstar() {
return !(this.#index === 0 ||
!this.isGlobstar() ||
!this.#followGlobstar);
}
/**
* Mark that the current globstar pattern is following a symbolic link
*/
markFollowGlobstar() {
if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
return false;
this.#followGlobstar = false;
return true;
}
}
//# sourceMappingURL=pattern.js.map
;// ./node_modules/glob/dist/esm/ignore.js
// give it a pattern, and it'll be able to tell you if
// a given path should be ignored.
// Ignoring a path ignores its children if the pattern ends in /**
// Ignores are always parsed in dot:true mode
const ignore_defaultPlatform = (typeof process === 'object' &&
process &&
typeof process.platform === 'string') ?
process.platform
: 'linux';
/**
* Class used to process ignored patterns
*/
class Ignore {
relative;
relativeChildren;
absolute;
absoluteChildren;
platform;
mmopts;
constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = ignore_defaultPlatform, }) {
this.relative = [];
this.absolute = [];
this.relativeChildren = [];
this.absoluteChildren = [];
this.platform = platform;
this.mmopts = {
dot: true,
nobrace,
nocase,
noext,
noglobstar,
optimizationLevel: 2,
platform,
nocomment: true,
nonegate: true,
};
for (const ign of ignored)
this.add(ign);
}
add(ign) {
// this is a little weird, but it gives us a clean set of optimized
// minimatch matchers, without getting tripped up if one of them
// ends in /** inside a brace section, and it's only inefficient at
// the start of the walk, not along it.
// It'd be nice if the Pattern class just had a .test() method, but
// handling globstars is a bit of a pita, and that code already lives
// in minimatch anyway.
// Another way would be if maybe Minimatch could take its set/globParts
// as an option, and then we could at least just use Pattern to test
// for absolute-ness.
// Yet another way, Minimatch could take an array of glob strings, and
// a cwd option, and do the right thing.
const mm = new Minimatch(ign, this.mmopts);
for (let i = 0; i < mm.set.length; i++) {
const parsed = mm.set[i];
const globParts = mm.globParts[i];
/* c8 ignore start */
if (!parsed || !globParts) {
throw new Error('invalid pattern object');
}
// strip off leading ./ portions
// https://github.com/isaacs/node-glob/issues/570
while (parsed[0] === '.' && globParts[0] === '.') {
parsed.shift();
globParts.shift();
}
/* c8 ignore stop */
const p = new Pattern(parsed, globParts, 0, this.platform);
const m = new Minimatch(p.globString(), this.mmopts);
const children = globParts[globParts.length - 1] === '**';
const absolute = p.isAbsolute();
if (absolute)
this.absolute.push(m);
else
this.relative.push(m);
if (children) {
if (absolute)
this.absoluteChildren.push(m);
else
this.relativeChildren.push(m);
}
}
}
ignored(p) {
const fullpath = p.fullpath();
const fullpaths = `${fullpath}/`;
const relative = p.relative() || '.';
const relatives = `${relative}/`;
for (const m of this.relative) {
if (m.match(relative) || m.match(relatives))
return true;
}
for (const m of this.absolute) {
if (m.match(fullpath) || m.match(fullpaths))
return true;
}
return false;
}
childrenIgnored(p) {
const fullpath = p.fullpath() + '/';
const relative = (p.relative() || '.') + '/';
for (const m of this.relativeChildren) {
if (m.match(relative))
return true;
}
for (const m of this.absoluteChildren) {
if (m.match(fullpath))
return true;
}
return false;
}
}
//# sourceMappingURL=ignore.js.map
;// ./node_modules/glob/dist/esm/processor.js
// synchronous utility for filtering entries and calculating subwalks
/**
* A cache of which patterns have been processed for a given Path
*/
class HasWalkedCache {
store;
constructor(store = new Map()) {
this.store = store;
}
copy() {
return new HasWalkedCache(new Map(this.store));
}
hasWalked(target, pattern) {
return this.store.get(target.fullpath())?.has(pattern.globString());
}
storeWalked(target, pattern) {
const fullpath = target.fullpath();
const cached = this.store.get(fullpath);
if (cached)
cached.add(pattern.globString());
else
this.store.set(fullpath, new Set([pattern.globString()]));
}
}
/**
* A record of which paths have been matched in a given walk step,
* and whether they only are considered a match if they are a directory,
* and whether their absolute or relative path should be returned.
*/
class MatchRecord {
store = new Map();
add(target, absolute, ifDir) {
const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
const current = this.store.get(target);
this.store.set(target, current === undefined ? n : n & current);
}
// match, absolute, ifdir
entries() {
return [...this.store.entries()].map(([path, n]) => [
path,
!!(n & 2),
!!(n & 1),
]);
}
}
/**
* A collection of patterns that must be processed in a subsequent step
* for a given path.
*/
class SubWalks {
store = new Map();
add(target, pattern) {
if (!target.canReaddir()) {
return;
}
const subs = this.store.get(target);
if (subs) {
if (!subs.find(p => p.globString() === pattern.globString())) {
subs.push(pattern);
}
}
else
this.store.set(target, [pattern]);
}
get(target) {
const subs = this.store.get(target);
/* c8 ignore start */
if (!subs) {
throw new Error('attempting to walk unknown path');
}
/* c8 ignore stop */
return subs;
}
entries() {
return this.keys().map(k => [k, this.store.get(k)]);
}
keys() {
return [...this.store.keys()].filter(t => t.canReaddir());
}
}
/**
* The class that processes patterns for a given path.
*
* Handles child entry filtering, and determining whether a path's
* directory contents must be read.
*/
class Processor {
hasWalkedCache;
matches = new MatchRecord();
subwalks = new SubWalks();
patterns;
follow;
dot;
opts;
constructor(opts, hasWalkedCache) {
this.opts = opts;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.hasWalkedCache =
hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
}
processPatterns(target, patterns) {
this.patterns = patterns;
const processingSet = patterns.map(p => [target, p]);
// map of paths to the magic-starting subwalks they need to walk
// first item in patterns is the filter
for (let [t, pattern] of processingSet) {
this.hasWalkedCache.storeWalked(t, pattern);
const root = pattern.root();
const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
// start absolute patterns at root
if (root) {
t = t.resolve(root === '/' && this.opts.root !== undefined ?
this.opts.root
: root);
const rest = pattern.rest();
if (!rest) {
this.matches.add(t, true, false);
continue;
}
else {
pattern = rest;
}
}
if (t.isENOENT())
continue;
let p;
let rest;
let changed = false;
while (typeof (p = pattern.pattern()) === 'string' &&
(rest = pattern.rest())) {
const c = t.resolve(p);
t = c;
pattern = rest;
changed = true;
}
p = pattern.pattern();
rest = pattern.rest();
if (changed) {
if (this.hasWalkedCache.hasWalked(t, pattern))
continue;
this.hasWalkedCache.storeWalked(t, pattern);
}
// now we have either a final string for a known entry,
// more strings for an unknown entry,
// or a pattern starting with magic, mounted on t.
if (typeof p === 'string') {
// must not be final entry, otherwise we would have
// concatenated it earlier.
const ifDir = p === '..' || p === '' || p === '.';
this.matches.add(t.resolve(p), absolute, ifDir);
continue;
}
else if (p === GLOBSTAR) {
// if no rest, match and subwalk pattern
// if rest, process rest and subwalk pattern
// if it's a symlink, but we didn't get here by way of a
// globstar match (meaning it's the first time THIS globstar
// has traversed a symlink), then we follow it. Otherwise, stop.
if (!t.isSymbolicLink() ||
this.follow ||
pattern.checkFollowGlobstar()) {
this.subwalks.add(t, pattern);
}
const rp = rest?.pattern();
const rrest = rest?.rest();
if (!rest || ((rp === '' || rp === '.') && !rrest)) {
// only HAS to be a dir if it ends in **/ or **/.
// but ending in ** will match files as well.
this.matches.add(t, absolute, rp === '' || rp === '.');
}
else {
if (rp === '..') {
// this would mean you're matching **/.. at the fs root,
// and no thanks, I'm not gonna test that specific case.
/* c8 ignore start */
const tp = t.parent || t;
/* c8 ignore stop */
if (!rrest)
this.matches.add(tp, absolute, true);
else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
this.subwalks.add(tp, rrest);
}
}
}
}
else if (p instanceof RegExp) {
this.subwalks.add(t, pattern);
}
}
return this;
}
subwalkTargets() {
return this.subwalks.keys();
}
child() {
return new Processor(this.opts, this.hasWalkedCache);
}
// return a new Processor containing the subwalks for each
// child entry, and a set of matches, and
// a hasWalkedCache that's a copy of this one
// then we're going to call
filterEntries(parent, entries) {
const patterns = this.subwalks.get(parent);
// put matches and entry walks into the results processor
const results = this.child();
for (const e of entries) {
for (const pattern of patterns) {
const absolute = pattern.isAbsolute();
const p = pattern.pattern();
const rest = pattern.rest();
if (p === GLOBSTAR) {
results.testGlobstar(e, pattern, rest, absolute);
}
else if (p instanceof RegExp) {
results.testRegExp(e, p, rest, absolute);
}
else {
results.testString(e, p, rest, absolute);
}
}
}
return results;
}
testGlobstar(e, pattern, rest, absolute) {
if (this.dot || !e.name.startsWith('.')) {
if (!pattern.hasMore()) {
this.matches.add(e, absolute, false);
}
if (e.canReaddir()) {
// if we're in follow mode or it's not a symlink, just keep
// testing the same pattern. If there's more after the globstar,
// then this symlink consumes the globstar. If not, then we can
// follow at most ONE symlink along the way, so we mark it, which
// also checks to ensure that it wasn't already marked.
if (this.follow || !e.isSymbolicLink()) {
this.subwalks.add(e, pattern);
}
else if (e.isSymbolicLink()) {
if (rest && pattern.checkFollowGlobstar()) {
this.subwalks.add(e, rest);
}
else if (pattern.markFollowGlobstar()) {
this.subwalks.add(e, pattern);
}
}
}
}
// if the NEXT thing matches this entry, then also add
// the rest.
if (rest) {
const rp = rest.pattern();
if (typeof rp === 'string' &&
// dots and empty were handled already
rp !== '..' &&
rp !== '' &&
rp !== '.') {
this.testString(e, rp, rest.rest(), absolute);
}
else if (rp === '..') {
/* c8 ignore start */
const ep = e.parent || e;
/* c8 ignore stop */
this.subwalks.add(ep, rest);
}
else if (rp instanceof RegExp) {
this.testRegExp(e, rp, rest.rest(), absolute);
}
}
}
testRegExp(e, p, rest, absolute) {
if (!p.test(e.name))
return;
if (!rest) {
this.matches.add(e, absolute, false);
}
else {
this.subwalks.add(e, rest);
}
}
testString(e, p, rest, absolute) {
// should never happen?
if (!e.isNamed(p))
return;
if (!rest) {
this.matches.add(e, absolute, false);
}
else {
this.subwalks.add(e, rest);
}
}
}
//# sourceMappingURL=processor.js.map
;// ./node_modules/glob/dist/esm/walker.js
/**
* Single-use utility classes to provide functionality to the {@link Glob}
* methods.
*
* @module
*/
const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts)
: Array.isArray(ignore) ? new Ignore(ignore, opts)
: ignore;
/**
* basic walking utilities that all the glob walker types use
*/
class GlobUtil {
path;
patterns;
opts;
seen = new Set();
paused = false;
aborted = false;
#onResume = [];
#ignore;
#sep;
signal;
maxDepth;
includeChildMatches;
constructor(patterns, path, opts) {
this.patterns = patterns;
this.path = path;
this.opts = opts;
this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
this.includeChildMatches = opts.includeChildMatches !== false;
if (opts.ignore || !this.includeChildMatches) {
this.#ignore = makeIgnore(opts.ignore ?? [], opts);
if (!this.includeChildMatches &&
typeof this.#ignore.add !== 'function') {
const m = 'cannot ignore child matches, ignore lacks add() method.';
throw new Error(m);
}
}
// ignore, always set with maxDepth, but it's optional on the
// GlobOptions type
/* c8 ignore start */
this.maxDepth = opts.maxDepth || Infinity;
/* c8 ignore stop */
if (opts.signal) {
this.signal = opts.signal;
this.signal.addEventListener('abort', () => {
this.#onResume.length = 0;
});
}
}
#ignored(path) {
return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
}
#childrenIgnored(path) {
return !!this.#ignore?.childrenIgnored?.(path);
}
// backpressure mechanism
pause() {
this.paused = true;
}
resume() {
/* c8 ignore start */
if (this.signal?.aborted)
return;
/* c8 ignore stop */
this.paused = false;
let fn = undefined;
while (!this.paused && (fn = this.#onResume.shift())) {
fn();
}
}
onResume(fn) {
if (this.signal?.aborted)
return;
/* c8 ignore start */
if (!this.paused) {
fn();
}
else {
/* c8 ignore stop */
this.#onResume.push(fn);
}
}
// do the requisite realpath/stat checking, and return the path
// to add or undefined to filter it out.
async matchCheck(e, ifDir) {
if (ifDir && this.opts.nodir)
return undefined;
let rpc;
if (this.opts.realpath) {
rpc = e.realpathCached() || (await e.realpath());
if (!rpc)
return undefined;
e = rpc;
}
const needStat = e.isUnknown() || this.opts.stat;
const s = needStat ? await e.lstat() : e;
if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
const target = await s.realpath();
/* c8 ignore start */
if (target && (target.isUnknown() || this.opts.stat)) {
await target.lstat();
}
/* c8 ignore stop */
}
return this.matchCheckTest(s, ifDir);
}
matchCheckTest(e, ifDir) {
return (e &&
(this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
(!ifDir || e.canReaddir()) &&
(!this.opts.nodir || !e.isDirectory()) &&
(!this.opts.nodir ||
!this.opts.follow ||
!e.isSymbolicLink() ||
!e.realpathCached()?.isDirectory()) &&
!this.#ignored(e)) ?
e
: undefined;
}
matchCheckSync(e, ifDir) {
if (ifDir && this.opts.nodir)
return undefined;
let rpc;
if (this.opts.realpath) {
rpc = e.realpathCached() || e.realpathSync();
if (!rpc)
return undefined;
e = rpc;
}
const needStat = e.isUnknown() || this.opts.stat;
const s = needStat ? e.lstatSync() : e;
if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
const target = s.realpathSync();
if (target && (target?.isUnknown() || this.opts.stat)) {
target.lstatSync();
}
}
return this.matchCheckTest(s, ifDir);
}
matchFinish(e, absolute) {
if (this.#ignored(e))
return;
// we know we have an ignore if this is false, but TS doesn't
if (!this.includeChildMatches && this.#ignore?.add) {
const ign = `${e.relativePosix()}/**`;
this.#ignore.add(ign);
}
const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
this.seen.add(e);
const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
// ok, we have what we need!
if (this.opts.withFileTypes) {
this.matchEmit(e);
}
else if (abs) {
const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
this.matchEmit(abs + mark);
}
else {
const rel = this.opts.posix ? e.relativePosix() : e.relative();
const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
'.' + this.#sep
: '';
this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
}
}
async match(e, absolute, ifDir) {
const p = await this.matchCheck(e, ifDir);
if (p)
this.matchFinish(p, absolute);
}
matchSync(e, absolute, ifDir) {
const p = this.matchCheckSync(e, ifDir);
if (p)
this.matchFinish(p, absolute);
}
walkCB(target, patterns, cb) {
/* c8 ignore start */
if (this.signal?.aborted)
cb();
/* c8 ignore stop */
this.walkCB2(target, patterns, new Processor(this.opts), cb);
}
walkCB2(target, patterns, processor, cb) {
if (this.#childrenIgnored(target))
return cb();
if (this.signal?.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
// done processing. all of the above is sync, can be abstracted out.
// subwalks is a map of paths to the entry filters they need
// matches is a map of paths to [absolute, ifDir] tuples.
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
tasks++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const t of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
continue;
}
tasks++;
const childrenCached = t.readdirCached();
if (t.calledReaddir())
this.walkCB3(t, childrenCached, processor, next);
else {
t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
}
}
next();
}
walkCB3(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
tasks++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const [target, patterns] of processor.subwalks.entries()) {
tasks++;
this.walkCB2(target, patterns, processor.child(), next);
}
next();
}
walkCBSync(target, patterns, cb) {
/* c8 ignore start */
if (this.signal?.aborted)
cb();
/* c8 ignore stop */
this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
}
walkCB2Sync(target, patterns, processor, cb) {
if (this.#childrenIgnored(target))
return cb();
if (this.signal?.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
// done processing. all of the above is sync, can be abstracted out.
// subwalks is a map of paths to the entry filters they need
// matches is a map of paths to [absolute, ifDir] tuples.
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const t of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
continue;
}
tasks++;
const children = t.readdirSync();
this.walkCB3Sync(t, children, processor, next);
}
next();
}
walkCB3Sync(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const [target, patterns] of processor.subwalks.entries()) {
tasks++;
this.walkCB2Sync(target, patterns, processor.child(), next);
}
next();
}
}
class GlobWalker extends GlobUtil {
matches = new Set();
constructor(patterns, path, opts) {
super(patterns, path, opts);
}
matchEmit(e) {
this.matches.add(e);
}
async walk() {
if (this.signal?.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
await this.path.lstat();
}
await new Promise((res, rej) => {
this.walkCB(this.path, this.patterns, () => {
if (this.signal?.aborted) {
rej(this.signal.reason);
}
else {
res(this.matches);
}
});
});
return this.matches;
}
walkSync() {
if (this.signal?.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
this.path.lstatSync();
}
// nothing for the callback to do, because this never pauses
this.walkCBSync(this.path, this.patterns, () => {
if (this.signal?.aborted)
throw this.signal.reason;
});
return this.matches;
}
}
class GlobStream extends GlobUtil {
results;
constructor(patterns, path, opts) {
super(patterns, path, opts);
this.results = new Minipass({
signal: this.signal,
objectMode: true,
});
this.results.on('drain', () => this.resume());
this.results.on('resume', () => this.resume());
}
matchEmit(e) {
this.results.write(e);
if (!this.results.flowing)
this.pause();
}
stream() {
const target = this.path;
if (target.isUnknown()) {
target.lstat().then(() => {
this.walkCB(target, this.patterns, () => this.results.end());
});
}
else {
this.walkCB(target, this.patterns, () => this.results.end());
}
return this.results;
}
streamSync() {
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => this.results.end());
return this.results;
}
}
//# sourceMappingURL=walker.js.map
;// ./node_modules/glob/dist/esm/glob.js
// if no process global, just call it linux.
// so we default to case-sensitive, / separators
const glob_defaultPlatform = (typeof process === 'object' &&
process &&
typeof process.platform === 'string') ?
process.platform
: 'linux';
/**
* An object that can perform glob pattern traversals.
*/
class Glob {
absolute;
cwd;
root;
dot;
dotRelative;
follow;
ignore;
magicalBraces;
mark;
matchBase;
maxDepth;
nobrace;
nocase;
nodir;
noext;
noglobstar;
pattern;
platform;
realpath;
scurry;
stat;
signal;
windowsPathsNoEscape;
withFileTypes;
includeChildMatches;
/**
* The options provided to the constructor.
*/
opts;
/**
* An array of parsed immutable {@link Pattern} objects.
*/
patterns;
/**
* All options are stored as properties on the `Glob` object.
*
* See {@link GlobOptions} for full options descriptions.
*
* Note that a previous `Glob` object can be passed as the
* `GlobOptions` to another `Glob` instantiation to re-use settings
* and caches with a new pattern.
*
* Traversal functions can be called multiple times to run the walk
* again.
*/
constructor(pattern, opts) {
/* c8 ignore start */
if (!opts)
throw new TypeError('glob options required');
/* c8 ignore stop */
this.withFileTypes = !!opts.withFileTypes;
this.signal = opts.signal;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.dotRelative = !!opts.dotRelative;
this.nodir = !!opts.nodir;
this.mark = !!opts.mark;
if (!opts.cwd) {
this.cwd = '';
}
else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
opts.cwd = (0,external_node_url_.fileURLToPath)(opts.cwd);
}
this.cwd = opts.cwd || '';
this.root = opts.root;
this.magicalBraces = !!opts.magicalBraces;
this.nobrace = !!opts.nobrace;
this.noext = !!opts.noext;
this.realpath = !!opts.realpath;
this.absolute = opts.absolute;
this.includeChildMatches = opts.includeChildMatches !== false;
this.noglobstar = !!opts.noglobstar;
this.matchBase = !!opts.matchBase;
this.maxDepth =
typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
this.stat = !!opts.stat;
this.ignore = opts.ignore;
if (this.withFileTypes && this.absolute !== undefined) {
throw new Error('cannot set absolute and withFileTypes:true');
}
if (typeof pattern === 'string') {
pattern = [pattern];
}
this.windowsPathsNoEscape =
!!opts.windowsPathsNoEscape ||
opts.allowWindowsEscape ===
false;
if (this.windowsPathsNoEscape) {
pattern = pattern.map(p => p.replace(/\\/g, '/'));
}
if (this.matchBase) {
if (opts.noglobstar) {
throw new TypeError('base matching requires globstar');
}
pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
}
this.pattern = pattern;
this.platform = opts.platform || glob_defaultPlatform;
this.opts = { ...opts, platform: this.platform };
if (opts.scurry) {
this.scurry = opts.scurry;
if (opts.nocase !== undefined &&
opts.nocase !== opts.scurry.nocase) {
throw new Error('nocase option contradicts provided scurry option');
}
}
else {
const Scurry = opts.platform === 'win32' ? PathScurryWin32
: opts.platform === 'darwin' ? PathScurryDarwin
: opts.platform ? PathScurryPosix
: PathScurry;
this.scurry = new Scurry(this.cwd, {
nocase: opts.nocase,
fs: opts.fs,
});
}
this.nocase = this.scurry.nocase;
// If you do nocase:true on a case-sensitive file system, then
// we need to use regexps instead of strings for non-magic
// path portions, because statting `aBc` won't return results
// for the file `AbC` for example.
const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
const mmo = {
// default nocase based on platform
...opts,
dot: this.dot,
matchBase: this.matchBase,
nobrace: this.nobrace,
nocase: this.nocase,
nocaseMagicOnly,
nocomment: true,
noext: this.noext,
nonegate: true,
optimizationLevel: 2,
platform: this.platform,
windowsPathsNoEscape: this.windowsPathsNoEscape,
debug: !!this.opts.debug,
};
const mms = this.pattern.map(p => new Minimatch(p, mmo));
const [matchSet, globParts] = mms.reduce((set, m) => {
set[0].push(...m.set);
set[1].push(...m.globParts);
return set;
}, [[], []]);
this.patterns = matchSet.map((set, i) => {
const g = globParts[i];
/* c8 ignore start */
if (!g)
throw new Error('invalid pattern object');
/* c8 ignore stop */
return new Pattern(set, g, 0, this.platform);
});
}
async walk() {
// Walkers always return array of Path objects, so we just have to
// coerce them into the right shape. It will have already called
// realpath() if the option was set to do so, so we know that's cached.
// start out knowing the cwd, at least
return [
...(await new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).walk()),
];
}
walkSync() {
return [
...new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).walkSync(),
];
}
stream() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).stream();
}
streamSync() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).streamSync();
}
/**
* Default sync iteration function. Returns a Generator that
* iterates over the results.
*/
iterateSync() {
return this.streamSync()[Symbol.iterator]();
}
[Symbol.iterator]() {
return this.iterateSync();
}
/**
* Default async iteration function. Returns an AsyncGenerator that
* iterates over the results.
*/
iterate() {
return this.stream()[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
}
//# sourceMappingURL=glob.js.map
;// ./node_modules/glob/dist/esm/has-magic.js
/**
* Return true if the patterns provided contain any magic glob characters,
* given the options provided.
*
* Brace expansion is not considered "magic" unless the `magicalBraces` option
* is set, as brace expansion just turns one string into an array of strings.
* So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
* `'xby'` both do not contain any magic glob characters, and it's treated the
* same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
* is in the options, brace expansion _is_ treated as a pattern having magic.
*/
const hasMagic = (pattern, options = {}) => {
if (!Array.isArray(pattern)) {
pattern = [pattern];
}
for (const p of pattern) {
if (new Minimatch(p, options).hasMagic())
return true;
}
return false;
};
//# sourceMappingURL=has-magic.js.map
;// ./node_modules/glob/dist/esm/index.js
function globStreamSync(pattern, options = {}) {
return new Glob(pattern, options).streamSync();
}
function globStream(pattern, options = {}) {
return new Glob(pattern, options).stream();
}
function globSync(pattern, options = {}) {
return new Glob(pattern, options).walkSync();
}
async function glob_(pattern, options = {}) {
return new Glob(pattern, options).walk();
}
function globIterateSync(pattern, options = {}) {
return new Glob(pattern, options).iterateSync();
}
function globIterate(pattern, options = {}) {
return new Glob(pattern, options).iterate();
}
// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
const streamSync = globStreamSync;
const stream = Object.assign(globStream, { sync: globStreamSync });
const iterateSync = globIterateSync;
const iterate = Object.assign(globIterate, {
sync: globIterateSync,
});
const sync = Object.assign(globSync, {
stream: globStreamSync,
iterate: globIterateSync,
});
const esm_glob = Object.assign(glob_, {
glob: glob_,
globSync,
sync,
globStream,
stream,
globStreamSync,
streamSync,
globIterate,
iterate,
globIterateSync,
iterateSync,
Glob: Glob,
hasMagic: hasMagic,
escape: escape_escape,
unescape: unescape_unescape,
});
esm_glob.glob = esm_glob;
//# sourceMappingURL=index.js.map
;// ./dist-in/lib/media/images/index.js
// export * from './watermark.js' // Commented out to avoid naming conflicts with schemas/types functions
//https://www.lightgalleryjs.com/demos/responsive/
const GLOB_BASIC = 'png|jpg|tiff|jpeg|webp';
const GLOB_MIN = '*.{png,jpg,jpeg,PNG,JPG,JPEG}';
const getFormats = (src, folder) => {
return [{
src: `${src}/${folder}/${GLOB_MIN}`,
dist: `${src}/${folder}/webp`,
format: 'webp',
}];
};
const getThumbnailOptions = (src, format) => {
return [{
src: `${src}/${GLOB_MIN}`,
dist: "${SRC_DIR}/${SRC_NAME}_thumb.${FORMAT}",
format
}];
};
const thumbnails = async (options) => {
options = sanitize(options);
logger.settings.minLevel = options.logLevel;
return await resizeDefault(options);
};
const meta = async (file) => {
try {
return await sharp(file).metadata();
}
catch (err) {
logger.error(`Error retrieving meta data for ${file}`, err);
}
};
const format = async (formats, options = {
cache: true,
png: false
}) => {
return await pMap(formats, async (format) => {
mkdir(format.dist);
let files = glob.sync(format.src);
return await pMap(files, async (file) => {
let fileParts = path.parse(file);
const target = path.resolve(`${format.dist}/${fileParts.name}.${format.format}`);
if (options.cache !== false && exists(target)) {
return;
}
const image = sharp(file).keepExif();
const metadata = await image.metadata();
if (options.png) {
await image
.withMetadata()
.png()
.toFile(target)
.catch(logger.error);
}
else {
await image
.withMetadata()
.rotate()
.toFile(target)
.catch(logger.error);
}
return metadata;
});
});
};
const getResizePatterns = (product, folder, percent = 20) => {
return [
{
src: `${product}/${folder}/${GLOB_MIN}`,
dist: `${product}/${folder}/${percent}`,
percent
}
];
};
const images_resize = async (patterns, options = { cache: true }) => {
return pMap(patterns, async (resize) => {
if (!fs.existsSync(resize.dist)) {
mkdir(resize.dist);
}
let files = glob.sync(resize.src);
return await pMap(files, async (file) => {
let filename = path.basename(file);
if (options.cache && exists(`${resize.dist}/${filename}`)) {
return;
}
try {
const image = sharp(file).keepExif().withMetadata();
const metadata = await image.metadata();
await image
.resize(Math.round(metadata.width * (resize.percent / 100)))
.keepExif()
.withMetadata()
.toFile(`${resize.dist}/${filename}`);
}
catch (err) {
logger.error(err);
}
});
});
};
const resizeSharp = async (patterns) => {
return await pMap(patterns, async (resize) => {
mkdir(resize.dist);
let files = glob.sync(resize.src);
return await pMap(files, async (file) => {
let filename = path.basename(file);
const image = sharp(file);
const metadata = await image.metadata();
if (exists(`${resize.dist}/${filename}`)) {
return metadata;
}
try {
const metadata = await image.metadata();
await image
.resize(Math.round(metadata.width * (resize.percent / 100)))
.toFile(`${resize.dist}/${filename}`);
return metadata;
}
catch (err) {
console.error(err);
}
});
});
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbGliL21lZGlhL2ltYWdlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLGFBQWEsQ0FBQTtBQUMzQixjQUFjLGNBQWMsQ0FBQTtBQUM1Qix5R0FBeUc7QUFDekcsT0FBTyxJQUFJLE1BQU0sT0FBTyxDQUFBO0FBQ3hCLE9BQU8sS0FBSyxJQUFJLE1BQU0sTUFBTSxDQUFBO0FBQzVCLE9BQU8sS0FBSyxFQUFFLE1BQU0sSUFBSSxDQUFBO0FBQ3hCLE9BQU8sS0FBSyxNQUFNLE9BQU8sQ0FBQTtBQUl6QixPQUFPLEVBQUUsSUFBSSxJQUFJLE1BQU0sRUFBRSxNQUFN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QUMsSUFBSSxDQUFDLENBQUE7WUFDbEMsTUFBTSxLQUFLLEdBQUcsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFBO1lBQ3pCLE1BQU0sUUFBUSxHQUFHLE1BQU0sS0FBSyxDQUFDLFFBQVEsRUFBRSxDQUFDO1lBQ3hDLElBQUksTUFBTSxDQUFDLEdBQUcsTUFBTSxDQUFDLElBQUksSUFBSSxRQUFRLEVBQUUsQ0FBQyxFQUFFLENBQUM7Z0JBQ3ZDLE9BQU8sUUFBUSxDQUFBO1lBQ25CLENBQUM7WUFDRCxJQUFJLENBQUM7Z0JBQ0QsTUFBTSxRQUFRLEdBQUcsTUFBTSxLQUFLLENBQUMsUUFBUSxFQUFFLENBQUM7Z0JBQ3hDLE1BQU0sS0FBSztxQkFDTixNQUFNLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsS0FBSyxHQUFHLENBQUMsTUFBTSxDQUFDLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDO3FCQUMzRCxNQUFNLENBQUMsR0FBRyxNQUFNLENBQUMsSUFBSSxJQUFJLFFBQVEsRUFBRSxDQUFDLENBQUE7Z0JBQ3pDLE9BQU8sUUFBUSxDQUFBO1lBQ25CLENBQUM7WUFBQyxPQUFPLEdBQUcsRUFBRSxDQUFDO2dCQUNYLE9BQU8sQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUE7WUFDdEIsQ0FBQztRQUNMLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQyxDQUFDLENBQUE7QUFDTixDQUFDLENBQUEifQ==
;// ./dist-in/_cli.js
const _cli_defaults = () => {
const DefaultCommand = 'info';
if (process.argv.length === 2) {
process.argv.push(DefaultCommand);
}
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection, reason: ', reason);
});
};
const dist_in_cli_sanitize = (argv) => {
const options = {
src: argv.src,
dst: argv.dst,
debug: argv.debug,
dry: argv.dry,
alt: argv.alt,
percent: argv.percent,
width: argv.width === false ? undefined : argv.width,
height: argv.height === false ? undefined : argv.height,
minWidth: argv.minWidth === false ? undefined : argv.minWidth,
minHeight: argv.minHeight === false ? undefined : argv.minHeight,
minSize: argv.minSize === false ? undefined : argv.minSize,
fit: argv.fit,
position: argv.position,
logLevel: argv.logLevel,
withoutEnlargement: argv.withoutEnlargement,
withoutReduction: argv.withoutReduction,
fastShrinkOnLoad: argv.fastShrinkOnLoad,
background: argv.background,
square: argv.square,
fillColor: argv.fillColor,
...argv
};
let srcInfo;
let variables = {
IMAGES: GLOB_BASIC,
...options.variables
};
if (options.src) {
const srcIn = (0,dist/* resolve */.hd)(options.src, options.alt, variables);
options.src = (0,dist/* forward_slash */.Yf)((0,dist/* substitute */.V2)(options.alt, srcIn, variables));
// in case a file with a glob pattern is provided, strip the glob
// this is a special case, enabling shared scripts in Alt-Tap Salamand
const glob_base = (0,dist/* globBase */.EI)(options.src);
const file = options.src.replace(glob_base.glob, '').replace(/\/$/, '');
if ((0,dist_exists/* sync */.OH)(file) && (0,dist/* isFile */.fo)(file)) {
options.src = file;
}
srcInfo = (0,dist/* pathInfo */.WR)((0,dist/* resolve */.hd)(options.src, options.alt, variables));
if (srcInfo && srcInfo.FILES && srcInfo.FILES.length) {
options.srcInfo = srcInfo;
for (const key in srcInfo) {
if (Object.prototype.hasOwnProperty.call(srcInfo, key)) {
variables['SRC_' + key] = srcInfo[key];
}
}
}
else {
options.src = (0,dist/* resolve */.hd)(options.src, options.alt, variables);
}
}
options.dstInfo = (0,dist/* pathInfoEx */.j4)(options.dst || "");
if (options.dstInfo && options.dst) {
if (options.srcInfo && options.dstInfo) {
options.dstInfo.PATH = options.dst;
for (const key in options.dstInfo) {
if (Object.prototype.hasOwnProperty.call(options.dstInfo, key)) {
variables['DST_' + key] = options.dstInfo[key];
}
}
}
else {
options.dst = (0,dist/* resolve */.hd)(options.dst || '', options.alt, variables);
}
}
options.variables = variables;
return options;
};
//# sourceMappingURL=data:application/json;base64,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BTSxHQUFHLElBQUksT0FBTyxDQUFDLE9BQU8sRUFBRSxDQUFDO2dCQUNoQyxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUMsY0FBYyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxFQUFFLEdBQUcsQ0FBQyxFQUFFLENBQUM7b0JBQzdELFNBQVMsQ0FBQyxNQUFNLEdBQUcsR0FBRyxDQUFDLEdBQUcsT0FBTyxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsQ0FBQTtnQkFDbEQsQ0FBQztZQUNMLENBQUM7UUFDTCxDQUFDO2FBQU0sQ0FBQztZQUNKLE9BQU8sQ0FBQyxHQUFHLEdBQUcsT0FBTyxDQUFDLE9BQU8sQ0FBQyxHQUFHLElBQUksRUFBRSxFQUFFLE9BQU8sQ0FBQyxHQUFHLEVBQUUsU0FBUyxDQUFDLENBQUE7UUFDcEUsQ0FBQztJQUNMLENBQUM7SUFDRCxPQUFPLENBQUMsU0FBUyxHQUFHLFNBQVMsQ0FBQTtJQUM3QixPQUFPLE9BQU8sQ0FBQTtBQUNsQixDQUFDLENBQUEifQ==
/***/ }),
/***/ 3045:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const outside = __webpack_require__(4448)
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr
/***/ }),
/***/ 3053:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
// this is just a very light wrapper around 2 arrays with an offset index
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Pattern = void 0;
const minimatch_1 = __webpack_require__(4361);
const isPatternList = (pl) => pl.length >= 1;
const isGlobList = (gl) => gl.length >= 1;
/**
* An immutable-ish view on an array of glob parts and their parsed
* results
*/
class Pattern {
#patternList;
#globList;
#index;
length;
#platform;
#rest;
#globString;
#isDrive;
#isUNC;
#isAbsolute;
#followGlobstar = true;
constructor(patternList, globList, index, platform) {
if (!isPatternList(patternList)) {
throw new TypeError('empty pattern list');
}
if (!isGlobList(globList)) {
throw new TypeError('empty glob list');
}
if (globList.length !== patternList.length) {
throw new TypeError('mismatched pattern list and glob list lengths');
}
this.length = patternList.length;
if (index < 0 || index >= this.length) {
throw new TypeError('index out of range');
}
this.#patternList = patternList;
this.#globList = globList;
this.#index = index;
this.#platform = platform;
// normalize root entries of absolute patterns on initial creation.
if (this.#index === 0) {
// c: => ['c:/']
// C:/ => ['C:/']
// C:/x => ['C:/', 'x']
// //host/share => ['//host/share/']
// //host/share/ => ['//host/share/']
// //host/share/x => ['//host/share/', 'x']
// /etc => ['/', 'etc']
// / => ['/']
if (this.isUNC()) {
// '' / '' / 'host' / 'share'
const [p0, p1, p2, p3, ...prest] = this.#patternList;
const [g0, g1, g2, g3, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = [p0, p1, p2, p3, ''].join('/');
const g = [g0, g1, g2, g3, ''].join('/');
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
else if (this.isDrive() || this.isAbsolute()) {
const [p1, ...prest] = this.#patternList;
const [g1, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = p1 + '/';
const g = g1 + '/';
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
}
}
/**
* The first entry in the parsed list of patterns
*/
pattern() {
return this.#patternList[this.#index];
}
/**
* true of if pattern() returns a string
*/
isString() {
return typeof this.#patternList[this.#index] === 'string';
}
/**
* true of if pattern() returns GLOBSTAR
*/
isGlobstar() {
return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
}
/**
* true if pattern() returns a regexp
*/
isRegExp() {
return this.#patternList[this.#index] instanceof RegExp;
}
/**
* The /-joined set of glob parts that make up this pattern
*/
globString() {
return (this.#globString =
this.#globString ||
(this.#index === 0 ?
this.isAbsolute() ?
this.#globList[0] + this.#globList.slice(1).join('/')
: this.#globList.join('/')
: this.#globList.slice(this.#index).join('/')));
}
/**
* true if there are more pattern parts after this one
*/
hasMore() {
return this.length > this.#index + 1;
}
/**
* The rest of the pattern after this part, or null if this is the end
*/
rest() {
if (this.#rest !== undefined)
return this.#rest;
if (!this.hasMore())
return (this.#rest = null);
this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
this.#rest.#isAbsolute = this.#isAbsolute;
this.#rest.#isUNC = this.#isUNC;
this.#rest.#isDrive = this.#isDrive;
return this.#rest;
}
/**
* true if the pattern represents a //unc/path/ on windows
*/
isUNC() {
const pl = this.#patternList;
return this.#isUNC !== undefined ?
this.#isUNC
: (this.#isUNC =
this.#platform === 'win32' &&
this.#index === 0 &&
pl[0] === '' &&
pl[1] === '' &&
typeof pl[2] === 'string' &&
!!pl[2] &&
typeof pl[3] === 'string' &&
!!pl[3]);
}
// pattern like C:/...
// split = ['C:', ...]
// XXX: would be nice to handle patterns like `c:*` to test the cwd
// in c: for *, but I don't know of a way to even figure out what that
// cwd is without actually chdir'ing into it?
/**
* True if the pattern starts with a drive letter on Windows
*/
isDrive() {
const pl = this.#patternList;
return this.#isDrive !== undefined ?
this.#isDrive
: (this.#isDrive =
this.#platform === 'win32' &&
this.#index === 0 &&
this.length > 1 &&
typeof pl[0] === 'string' &&
/^[a-z]:$/i.test(pl[0]));
}
// pattern = '/' or '/...' or '/x/...'
// split = ['', ''] or ['', ...] or ['', 'x', ...]
// Drive and UNC both considered absolute on windows
/**
* True if the pattern is rooted on an absolute path
*/
isAbsolute() {
const pl = this.#patternList;
return this.#isAbsolute !== undefined ?
this.#isAbsolute
: (this.#isAbsolute =
(pl[0] === '' && pl.length > 1) ||
this.isDrive() ||
this.isUNC());
}
/**
* consume the root of the pattern, and return it
*/
root() {
const p = this.#patternList[0];
return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
p
: '';
}
/**
* Check to see if the current globstar pattern is allowed to follow
* a symbolic link.
*/
checkFollowGlobstar() {
return !(this.#index === 0 ||
!this.isGlobstar() ||
!this.#followGlobstar);
}
/**
* Mark that the current globstar pattern is following a symbolic link
*/
markFollowGlobstar() {
if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
return false;
this.#followGlobstar = false;
return true;
}
}
exports.Pattern = Pattern;
//# sourceMappingURL=pattern.js.map
/***/ }),
/***/ 3070:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const fs = __webpack_require__(1943)
const fsm = __webpack_require__(8150)
const ssri = __webpack_require__(5433)
const contentPath = __webpack_require__(6257)
const Pipeline = __webpack_require__(6155)
module.exports = read
const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024
async function read (cache, integrity, opts = {}) {
const { size } = opts
const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
// get size
const stat = size ? { size } : await fs.stat(cpath)
return { stat, cpath, sri }
})
if (stat.size > MAX_SINGLE_READ_SIZE) {
return readPipeline(cpath, stat.size, sri, new Pipeline()).concat()
}
const data = await fs.readFile(cpath, { encoding: null })
if (stat.size !== data.length) {
throw sizeError(stat.size, data.length)
}
if (!ssri.checkData(data, sri)) {
throw integrityError(sri, cpath)
}
return data
}
const readPipeline = (cpath, size, sri, stream) => {
stream.push(
new fsm.ReadStream(cpath, {
size,
readSize: MAX_SINGLE_READ_SIZE,
}),
ssri.integrityStream({
integrity: sri,
size,
})
)
return stream
}
module.exports.stream = readStream
module.exports.readStream = readStream
function readStream (cache, integrity, opts = {}) {
const { size } = opts
const stream = new Pipeline()
// Set all this up to run on the stream and then just return the stream
Promise.resolve().then(async () => {
const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
// get size
const stat = size ? { size } : await fs.stat(cpath)
return { stat, cpath, sri }
})
return readPipeline(cpath, stat.size, sri, stream)
}).catch(err => stream.emit('error', err))
return stream
}
module.exports.copy = copy
function copy (cache, integrity, dest) {
return withContentSri(cache, integrity, (cpath) => {
return fs.copyFile(cpath, dest)
})
}
module.exports.hasContent = hasContent
async function hasContent (cache, integrity) {
if (!integrity) {
return false
}
try {
return await withContentSri(cache, integrity, async (cpath, sri) => {
const stat = await fs.stat(cpath)
return { size: stat.size, sri, stat }
})
} catch (err) {
if (err.code === 'ENOENT') {
return false
}
if (err.code === 'EPERM') {
/* istanbul ignore else */
if (process.platform !== 'win32') {
throw err
} else {
return false
}
}
}
}
async function withContentSri (cache, integrity, fn) {
const sri = ssri.parse(integrity)
// If `integrity` has multiple entries, pick the first digest
// with available local data.
const algo = sri.pickAlgorithm()
const digests = sri[algo]
if (digests.length <= 1) {
const cpath = contentPath(cache, digests[0])
return fn(cpath, digests[0])
} else {
// Can't use race here because a generic error can happen before
// a ENOENT error, and can happen before a valid result
const results = await Promise.all(digests.map(async (meta) => {
try {
return await withContentSri(cache, meta, fn)
} catch (err) {
if (err.code === 'ENOENT') {
return Object.assign(
new Error('No matching content found for ' + sri.toString()),
{ code: 'ENOENT' }
)
}
return err
}
}))
// Return the first non error if it is found
const result = results.find((r) => !(r instanceof Error))
if (result) {
return result
}
// Throw the No matching content found error
const enoentError = results.find((r) => r.code === 'ENOENT')
if (enoentError) {
throw enoentError
}
// Throw generic error
throw results.find((r) => r instanceof Error)
}
}
function sizeError (expected, found) {
/* eslint-disable-next-line max-len */
const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
err.expected = expected
err.found = found
err.code = 'EBADSIZE'
return err
}
function integrityError (sri, path) {
const err = new Error(`Integrity verification failed for ${sri} (${path})`)
err.code = 'EINTEGRITY'
err.sri = sri
err.path = path
return err
}
/***/ }),
/***/ 3083:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const events = __webpack_require__(4434)
const contentPath = __webpack_require__(6257)
const fs = __webpack_require__(1943)
const { moveFile } = __webpack_require__(1693)
const { Minipass } = __webpack_require__(4383)
const Pipeline = __webpack_require__(6155)
const Flush = __webpack_require__(4233)
const path = __webpack_require__(6928)
const ssri = __webpack_require__(5433)
const uniqueFilename = __webpack_require__(5787)
const fsm = __webpack_require__(8150)
module.exports = write
// Cache of move operations in process so we don't duplicate
const moveOperations = new Map()
async function write (cache, data, opts = {}) {
const { algorithms, size, integrity } = opts
if (typeof size === 'number' && data.length !== size) {
throw sizeError(size, data.length)
}
const sri = ssri.fromData(data, algorithms ? { algorithms } : {})
if (integrity && !ssri.checkData(data, integrity, opts)) {
throw checksumError(integrity, sri)
}
for (const algo in sri) {
const tmp = await makeTmp(cache, opts)
const hash = sri[algo].toString()
try {
await fs.writeFile(tmp.target, data, { flag: 'wx' })
await moveToDestination(tmp, cache, hash, opts)
} finally {
if (!tmp.moved) {
await fs.rm(tmp.target, { recursive: true, force: true })
}
}
}
return { integrity: sri, size: data.length }
}
module.exports.stream = writeStream
// writes proxied to the 'inputStream' that is passed to the Promise
// 'end' is deferred until content is handled.
class CacacheWriteStream extends Flush {
constructor (cache, opts) {
super()
this.opts = opts
this.cache = cache
this.inputStream = new Minipass()
this.inputStream.on('error', er => this.emit('error', er))
this.inputStream.on('drain', () => this.emit('drain'))
this.handleContentP = null
}
write (chunk, encoding, cb) {
if (!this.handleContentP) {
this.handleContentP = handleContent(
this.inputStream,
this.cache,
this.opts
)
this.handleContentP.catch(error => this.emit('error', error))
}
return this.inputStream.write(chunk, encoding, cb)
}
flush (cb) {
this.inputStream.end(() => {
if (!this.handleContentP) {
const e = new Error('Cache input stream was empty')
e.code = 'ENODATA'
// empty streams are probably emitting end right away.
// defer this one tick by rejecting a promise on it.
return Promise.reject(e).catch(cb)
}
// eslint-disable-next-line promise/catch-or-return
this.handleContentP.then(
(res) => {
res.integrity && this.emit('integrity', res.integrity)
// eslint-disable-next-line promise/always-return
res.size !== null && this.emit('size', res.size)
cb()
},
(er) => cb(er)
)
})
}
}
function writeStream (cache, opts = {}) {
return new CacacheWriteStream(cache, opts)
}
async function handleContent (inputStream, cache, opts) {
const tmp = await makeTmp(cache, opts)
try {
const res = await pipeToTmp(inputStream, cache, tmp.target, opts)
await moveToDestination(
tmp,
cache,
res.integrity,
opts
)
return res
} finally {
if (!tmp.moved) {
await fs.rm(tmp.target, { recursive: true, force: true })
}
}
}
async function pipeToTmp (inputStream, cache, tmpTarget, opts) {
const outStream = new fsm.WriteStream(tmpTarget, {
flags: 'wx',
})
if (opts.integrityEmitter) {
// we need to create these all simultaneously since they can fire in any order
const [integrity, size] = await Promise.all([
events.once(opts.integrityEmitter, 'integrity').then(res => res[0]),
events.once(opts.integrityEmitter, 'size').then(res => res[0]),
new Pipeline(inputStream, outStream).promise(),
])
return { integrity, size }
}
let integrity
let size
const hashStream = ssri.integrityStream({
integrity: opts.integrity,
algorithms: opts.algorithms,
size: opts.size,
})
hashStream.on('integrity', i => {
integrity = i
})
hashStream.on('size', s => {
size = s
})
const pipeline = new Pipeline(inputStream, hashStream, outStream)
await pipeline.promise()
return { integrity, size }
}
async function makeTmp (cache, opts) {
const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix)
await fs.mkdir(path.dirname(tmpTarget), { recursive: true })
return {
target: tmpTarget,
moved: false,
}
}
async function moveToDestination (tmp, cache, sri) {
const destination = contentPath(cache, sri)
const destDir = path.dirname(destination)
if (moveOperations.has(destination)) {
return moveOperations.get(destination)
}
moveOperations.set(
destination,
fs.mkdir(destDir, { recursive: true })
.then(async () => {
await moveFile(tmp.target, destination, { overwrite: false })
tmp.moved = true
return tmp.moved
})
.catch(err => {
if (!err.message.startsWith('The destination file exists')) {
throw Object.assign(err, { code: 'EEXIST' })
}
}).finally(() => {
moveOperations.delete(destination)
})
)
return moveOperations.get(destination)
}
function sizeError (expected, found) {
/* eslint-disable-next-line max-len */
const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
err.expected = expected
err.found = found
err.code = 'EBADSIZE'
return err
}
function checksumError (expected, found) {
const err = new Error(`Integrity check failed:
Wanted: ${expected}
Found: ${found}`)
err.code = 'EINTEGRITY'
err.expected = expected
err.found = found
return err
}
/***/ }),
/***/ 3136:
/***/ ((module) => {
"use strict";
module.exports = require("node:url");
/***/ }),
/***/ 3145:
/***/ ((module) => {
"use strict";
/**
* @param typeMap [Object] Map of MIME type -> Array[extensions]
* @param ...
*/
function Mime() {
this._types = Object.create(null);
this._extensions = Object.create(null);
for (let i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
/**
* Define mimetype -> extension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* If a type declares an extension that has already been defined, an error will
* be thrown. To suppress this error and force the extension to be associated
* with the new type, pass `force`=true. Alternatively, you may prefix the
* extension with "*" to map the type to extension, without mapping the
* extension to the type.
*
* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
*
*
* @param map (Object) type definitions
* @param force (Boolean) if true, force overriding of existing definitions
*/
Mime.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t) {
return t.toLowerCase();
});
type = type.toLowerCase();
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
// '*' prefix = not the preferred type for this extension. So fixup the
// extension, and skip it.
if (ext[0] === '*') {
continue;
}
if (!force && (ext in this._types)) {
throw new Error(
'Attempt to change mapping for "' + ext +
'" extension from "' + this._types[ext] + '" to "' + type +
'". Pass `force=true` to allow this, otherwise remove "' + ext +
'" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
// Use first extension as default
if (force || !this._extensions[type]) {
const ext = extensions[0];
this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
}
}
};
/**
* Lookup a mime type based on extension
*/
Mime.prototype.getType = function(path) {
path = String(path);
let last = path.replace(/^.*[/\\]/, '').toLowerCase();
let ext = last.replace(/^.*\./, '').toLowerCase();
let hasPath = last.length < path.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
/**
* Return file extension associated with a mime type
*/
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module.exports = Mime;
/***/ }),
/***/ 3193:
/***/ ((module) => {
"use strict";
module.exports = require("string_decoder");
/***/ }),
/***/ 3235:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
bI: () => (/* binding */ dir_async),
OH: () => (/* binding */ sync)
});
// UNUSED EXPORTS: validateInput
// EXTERNAL MODULE: external "node:fs"
var external_node_fs_ = __webpack_require__(3024);
// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __webpack_require__(6760);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
// EXTERNAL MODULE: external "util"
var external_util_ = __webpack_require__(9023);
// EXTERNAL MODULE: ../fs/dist/remove.js
var remove = __webpack_require__(4581);
;// ../fs/dist/utils/mode.js
// Converts mode to string 3 characters long.
const normalizeFileMode = (mode) => {
let modeAsString;
if (typeof mode === 'number') {
modeAsString = mode.toString(8);
}
else {
modeAsString = mode;
}
return modeAsString.substring(modeAsString.length - 3);
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlscy9tb2RlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDZDQUE2QztBQUM3QyxNQUFNLENBQUMsTUFBTSxpQkFBaUIsR0FBRyxDQUFDLElBQXFCLEVBQVUsRUFBRTtJQUNsRSxJQUFJLFlBQW9CLENBQUM7SUFDekIsSUFBSSxPQUFPLElBQUksS0FBSyxRQUFRLEVBQUUsQ0FBQztRQUM5QixZQUFZLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUNqQyxDQUFDO1NBQU0sQ0FBQztRQUNQLFlBQVksR0FBRyxJQUFJLENBQUM7SUFDckIsQ0FBQztJQUNELE9BQU8sWUFBWSxDQUFDLFNBQVMsQ0FBQyxZQUFZLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQyxDQUFDO0FBQ3hELENBQUMsQ0FBQyJ9
// EXTERNAL MODULE: ../fs/dist/errors.js + 1 modules
var errors = __webpack_require__(2719);
// EXTERNAL MODULE: ../fs/dist/interfaces.js
var interfaces = __webpack_require__(7405);
// EXTERNAL MODULE: ../fs/node_modules/mkdirp/dist/mjs/index.js + 6 modules
var mjs = __webpack_require__(2971);
;// ../fs/dist/dir.js
const validateInput = (methodName, path, options) => {
const methodSignature = methodName + '(path, [criteria])';
validateArgument(methodSignature, 'path', path, ['string']);
validateOptions(methodSignature, 'criteria', options, {
empty: ['boolean'],
mode: ['string', 'number']
});
};
const defaults = (options) => {
const result = options || {};
if (typeof result.empty !== 'boolean') {
result.empty = false;
}
if (result.mode !== undefined) {
result.mode = normalizeFileMode(result.mode);
}
return result;
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
const dirStatsSync = (path) => {
let _stat;
try {
_stat = (0,external_fs_.statSync)(path);
}
catch (err) {
// Detection if path already exists
if (err.code !== interfaces/* EError */.aJ.NOEXISTS) {
throw err;
}
}
if (_stat && !_stat.isDirectory()) {
throw (0,errors/* ErrNoDirectory */.M8)(path);
}
return _stat;
};
function mkdirSync(path, criteria) {
(0,mjs/* sync */.OH)(path, { mode: criteria.mode, fs: null });
}
function checkDirSync(path, _stat, options) {
const check = function () {
if (options.mode !== undefined) {
external_node_fs_.chmodSync(path, options.mode);
}
};
const checkEmptiness = function () {
let list;
if (options.empty) {
// Delete everything inside this directory
list = (0,external_fs_.readdirSync)(path);
list.forEach(function (filename) {
(0,remove/* sync */.OH)(external_node_path_.resolve(path, filename));
});
}
};
check();
checkEmptiness();
}
const sync = (path, options) => {
const criteria = defaults(options);
const _stat = dirStatsSync(path);
if (_stat) {
checkDirSync(path, _stat, criteria);
}
else {
mkdirSync(path, criteria);
}
};
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
const promisedStat = (0,external_util_.promisify)(external_fs_.stat);
const promisedReaddir = (0,external_util_.promisify)(external_fs_.readdir);
const dirStatAsync = (path) => {
return new Promise((resolve, reject) => {
promisedStat(path)
.then((_stat) => {
if (_stat.isDirectory()) {
resolve(_stat);
}
else {
reject((0,errors/* ErrNoDirectory */.M8)(path));
}
})
.catch((err) => (err.code === interfaces/* EError */.aJ.NOEXISTS ? resolve(undefined) : reject(err)));
});
};
// Delete all files and directores inside given directory
const emptyAsync = (path) => {
return new Promise((resolve, reject) => {
promisedReaddir(path)
.then(function (list) {
const doOne = function (index) {
let subPath;
if (index === list.length) {
resolve(1);
}
else {
subPath = external_node_path_.resolve(path, list[index]);
(0,remove/* async */.bI)(subPath).then(() => doOne(index + 1));
}
};
doOne(0);
})
.catch(reject);
});
};
const checkMode = function (criteria, _stat, path) {
if (criteria.mode !== undefined) {
return (0,external_util_.promisify)(external_node_fs_.chmod)(path, criteria.mode);
}
return Promise.resolve(null);
};
const checkDirAsync = (path, _stat, options) => {
return new Promise((resolve, reject) => {
const checkEmptiness = function () {
if (options.empty) {
return emptyAsync(path);
}
return Promise.resolve();
};
checkMode(options, _stat, path)
.then(checkEmptiness)
.then(resolve, reject);
});
};
const mkdirAsync = (path, criteria) => {
const options = criteria || {};
return new Promise((resolve, reject) => {
(0,external_util_.promisify)(external_node_fs_.mkdir)(path, options.mode)
.then(resolve)
.catch((err) => {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist. Need to create it first.
mkdirAsync(external_node_path_.dirname(path), options)
.then(() => {
// Now retry creating this directory.
return (0,external_util_.promisify)(external_node_fs_.mkdir)(path, options.mode);
})
.then(resolve)
.catch((err2) => {
if (err2.code === 'EEXIST') {
// Hmm, something other have already created the directory?
// No problem for us.
resolve(1);
}
else {
reject(err2);
}
});
}
else if (err.code === 'EEXIST') {
// The path already exists. We're fine.
resolve(1);
}
else {
reject(err);
}
});
});
};
const dir_async = (path, passedCriteria) => {
const criteria = defaults(passedCriteria);
return new Promise((resolve, reject) => {
dirStatAsync(path)
.then((_stat) => {
if (_stat !== undefined) {
return checkDirAsync(path, _stat, criteria);
}
return mkdirAsync(path, criteria);
})
.then(resolve, reject);
});
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGlyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2Rpci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxNQUFNLFNBQVMsQ0FBQTtBQUM3QixPQUFPLEtBQUssUUFBUSxNQUFNLFdBQVcsQ0FBQztBQUN0QyxPQUFPLEVBQVMsSUFBSSxFQUFFLFFBQVEsRUFBRSxXQUFXLEVBQUUsT0FBTyxFQUFFLE1BQU0sSUFBSSxDQUFBO0FBQ2hFLE9BQU8sRUFBRSxTQUFTLEVBQUUsTUFBTSxNQUFNLENBQUE7QUFDaEMsT0FBTyxFQUFFLElBQUksSUFBSSxVQUFVLEVBQUUsS0FBSyxJQUFJLFdBQVcsRUFBRSxNQUFNLGFBQWEsQ0FBQTtBQUN0RSxPQUFPLEVBQUUsaUJBQWlCLElBQUksUUFBUSxFQUFFLE1BQU0saUJBQWlCLENBQUE7QUFDL0QsT0FBTyxFQUFFLGdCQUFnQixFQUFFLGVBQWUsRUFBRSxNQUFNLHFCQUFxQixDQUFBO0FBQ3ZFLE9BQU8sRUFBRSxjQUFjLEVBQUUsTUFBTSxhQUFhLENBQUE7QUFDNUMsT0FBTyxFQUFFLE1BQU0sRUFBRSxNQUFNLGlCQUFpQixDQUFBO0FBQ3hDLE9BQU8sRUFBRSxJQUFJLElBQUksTUFBTSxFQUFFLE1BQU0sUUFBUSxDQUFBO0FBT3ZDLE1BQU0sQ0FBQyxNQUFNLGFBQWEsR0FBRyx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DQUFDIn0=
/***/ }),
/***/ 3250:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
LV: () => (/* reexport */ CONFIG_DEFAULT),
Yx: () => (/* reexport */ DEFAULT_ROOTS),
hc: () => (/* reexport */ variables_DEFAULT_VARS),
p7: () => (/* reexport */ ZodMetaMap),
Yf: () => (/* reexport */ _glob_forward_slash),
BR: () => (/* reexport */ generate_interfaces),
EI: () => (/* reexport */ globBase),
fo: () => (/* reexport */ isFile),
WR: () => (/* reexport */ pathInfo),
j4: () => (/* reexport */ _glob_pathInfoEx),
hd: () => (/* reexport */ variables_resolve),
CO: () => (/* reexport */ resolveVariables),
V2: () => (/* reexport */ variables_substitute),
aH: () => (/* reexport */ toYargs),
M9: () => (/* reexport */ schemas_write)
});
// UNUSED EXPORTS: API_NAMESPACE, API_PREFIX, API_PREFIX_NEXT, AssetImageSchema, AssetsSchema, AuthorSchema, CADMetaSchema, CONFIG_DEFAULT_PATH, ComponentConfigSchema, ContentSchema, DATE_VARS, EArch, ENSURE_DIRECTORY_WRITABLE, ENSURE_PATH_EXISTS, EPlatform, E_PATH, ExifSchema, GalleryConfig, GalleryConfigsSchema, HOME, IS_VALID_STRING, ImageMetaSchema, KB_ROOT, MODULE_NAME, ManufacturingSchema, OA_LATEST, OA_LATEST_CENSORED, OA_LATEST_INVALID, OA_LATEST_MERGED, OA_ROOT, OSR_CACHE, OSR_CUSTOMER_DRIVE, OSR_LIBRARY, OSR_LIBRARY_DIRECTORY, OSR_LIBRARY_MACHINES, OSR_PRIVATE, OSR_ROOT, OSR_SUB_DEFAULT, OSR_TEMP, OSR_USER_ASSETS, POLYMECH_ROOT, PP_BAZAR_LATEST_INDEX, PP_BAZAR_LATEST_INDEX_MERGED, PRODUCT_ROOT, PROFILE_FILE_NAME, ProductionSchema, ResourceSchema, ShippingSchema, Templates, Transformers, TransformersDescription, UNC_REGEX, UrlSchema, VersionSchema, WIN32_PATH_REGEX, WRITERS, _substitute, combineValidatorsOr, combineValidatorsOrUsingZod, combineValidatorsOrUsingZod2, createLogger, defaultLogger, enumerateHelpStrings, extend, extendSchema, files, filesEx, find_items, get, getDefaultValue, getDescription, getExtensions, getFieldDefaultValue, getInnerSchema, getInnerType, get_var, globParent, isFolder, is_absolute, is_windows, logger, parse, readNPMMeta, readOSRConfig, readOSRMeta, readPackage, resolveConfig, template, test, writer, yargsDefaults
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
;// ../commons/dist/os.js
var EPlatform;
(function (EPlatform) {
EPlatform["Linux"] = "linux";
EPlatform["Windows"] = "win32";
EPlatform["OSX"] = "darwin";
})(EPlatform || (EPlatform = {}));
var EArch;
(function (EArch) {
EArch["x64"] = "64";
EArch["x32"] = "32";
})(EArch || (EArch = {}));
const os_is_windows = () => process && (process.platform === 'win32');
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib3MuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvb3MudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsTUFBTSxDQUFOLElBQVksU0FJWDtBQUpELFdBQVksU0FBUztJQUNwQiw0QkFBZSxDQUFBO0lBQ2YsOEJBQWlCLENBQUE7SUFDakIsMkJBQWMsQ0FBQTtBQUNmLENBQUMsRUFKVyxTQUFTLEtBQVQsU0FBUyxRQUlwQjtBQUNELE1BQU0sQ0FBTixJQUFZLEtBR1g7QUFIRCxXQUFZLEtBQUs7SUFDaEIsbUJBQVUsQ0FBQTtJQUNWLG1CQUFVLENBQUE7QUFDWCxDQUFDLEVBSFcsS0FBSyxLQUFMLEtBQUssUUFHaEI7QUFDRCxNQUFNLENBQUMsTUFBTSxVQUFVLEdBQUcsR0FBRyxFQUFFLENBQUMsT0FBTyxJQUFJLENBQUMsT0FBTyxDQUFDLFFBQVEsS0FBSyxPQUFPLENBQUMsQ0FBQSJ9
;// ../commons/dist/fs.js
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#namespaces
// https://github.com/isaacs/node-glob/blob/main/src/pattern.ts
const UNC_REGEX = /^[\\\/]{2,}[^\\\/]+[\\\/]+[^\\\/]+/;
const WIN32_PATH_REGEX = /^([a-z]:)?[\\\/]/i;
const isFile = (src) => {
let srcIsFile = false;
try {
srcIsFile = external_fs_.lstatSync(src).isFile();
}
catch (e) { }
return srcIsFile;
};
const isFolder = (src) => {
let srcIsFolder = false;
try {
srcIsFolder = external_fs_.lstatSync(src).isDirectory();
}
catch (e) { }
return srcIsFolder;
};
const is_relative_win32 = (fp) => !fp.test(UNC_REGEX) && !WIN32_PATH_REGEX.test(fp);
const is_absolute_posix = (fp) => fp.charAt(0) === '/';
const is_absolute_win32 = (fp) => {
if (/[a-z]/i.test(fp.charAt(0)) && fp.charAt(1) === ':' && fp.charAt(2) === '\\') {
return true;
}
// Microsoft Azure absolute filepath
if (fp.slice(0, 2) === '\\\\') {
return true;
}
return !is_relative_win32(fp);
};
const is_absolute = (fp) => is_windows() ? is_absolute_win32(fp) : is_absolute_posix(fp);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvZnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLEVBQUUsTUFBTSxJQUFJLENBQUE7QUFFeEIsa0ZBQWtGO0FBQ2xGLCtEQUErRDtBQUUvRCxNQUFNLENBQUMsTUFBTSxTQUFTLEdBQUcsb0NBQW9DLENBQUE7QUFDN0QsTUFBTSxDQUFDLE1BQU0sZ0JBQWdCLEdBQUcsbUJBQW1CLENBQUE7QUFFbkQsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLFNBQVMsQ0FBQTtBQUdwQyxNQUFNLENBQUMsTUFBTSxNQUFNLEdBQUcsQ0FB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FDLENBQUMsSUFBSSxFQUFFLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxLQUFLLEdBQUcsSUFBSSxFQUFFLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxLQUFLLElBQUksRUFBRSxDQUFDO1FBQy9FLE9BQU8sSUFBSSxDQUFBO0lBQ2YsQ0FBQztJQUNELG9DQUFvQztJQUNwQyxJQUFJLEVBQUUsQ0FBQyxLQUFLLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxLQUFLLE1BQU0sRUFBRSxDQUFDO1FBQzVCLE9BQU8sSUFBSSxDQUFDO0lBQ2hCLENBQUM7SUFDRCxPQUFPLENBQUMsaUJBQWlCLENBQUMsRUFBRSxDQUFDLENBQUE7QUFDakMsQ0FBQyxDQUFBO0FBQ0QsTUFBTSxDQUFDLE1BQU0sV0FBVyxHQUFHLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBRSxVQUFVLEVBQUUsQ0FBQyxDQUFDLENBQUMsaUJBQWlCLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDLGlCQUFpQixDQUFDLEVBQUUsQ0FBQyxDQUFBIn0=
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(6928);
// EXTERNAL MODULE: ../commons/node_modules/env-var/env-var.js
var env_var = __webpack_require__(4128);
// EXTERNAL MODULE: ../fs/dist/read.js
var dist_read = __webpack_require__(417);
// EXTERNAL MODULE: ../fs/dist/exists.js
var dist_exists = __webpack_require__(2449);
// EXTERNAL MODULE: ../core/dist/primitives.js
var primitives = __webpack_require__(8275);
;// ../commons/dist/constants.js
const MODULE_NAME = `OSR-Commons`;
const PROFILE_FILE_NAME = (/* unused pure expression or super */ null && (`.osrl.json`));
////////////////////////////////////////
//
// OA Migration
const OA_LATEST = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}.json';
const OA_LATEST_INVALID = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_INVALID.json';
const OA_LATEST_CENSORED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_CENSORED.json';
const OA_LATEST_MERGED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_MERGED.json';
// fecking bazar
const PP_BAZAR_LATEST_INDEX = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index.json';
const PP_BAZAR_LATEST_INDEX_MERGED = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index_merged.json';
// Namespaces
const API_NAMESPACE = '@polymech';
const API_PREFIX = 'polymech';
const API_PREFIX_NEXT = 'polymech';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uc3RhbnRzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NvbnN0YW50cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxNQUFNLENBQUMsTUFBTSxXQUFXLEdBQUcsYUFBYSxDQUFBO0FBQ3hDLE1BQU0sQ0FBQyxNQUFNLGlCQUFpQixHQUFHLFlBQVksQ0FBQTtBQUM3Qyx3Q0FBd0M7QUFDeEMsRUFBRTtBQUNGLGdCQUFnQjtBQUVoQixNQUFNLENBQUMsTUFBTSxTQUFTLEdBQUcsaURBQWlELENBQUE7QUFDMUUsTUFBTSxDQUFDLE1BQU0saUJBQWlCLEdBQUcseURBQXlELENBQUE7QUFDMUYsTUFBTSxDQUFDLE1BQU0sa0JBQWtCLEdBQUcsMERBQTBELENBQUE7QUFDNUYsTUFBTSxDQUFDLE1BQU0sZ0JBQWdCLEdBQUcsd0RBQXdELENBQUE7QUFFeEYsZ0JBQWdCO0FBQ2hCLE1BQU0sQ0FBQyxNQUFNLHFCQUFxQixHQUFHLCtDQUErQyxDQUFBO0FBQ3BGLE1BQU0sQ0FBQyxNQUFNLDRCQUE0QixHQUFHLHNEQUFzRCxDQUFBO0FBRWxHLGFBQWE7QUFDYixNQUFNLENBQUMsTUFBTSxhQUFhLEdBQUcsV0FBVyxDQUFBO0FBQ3hDLE1BQU0sQ0FBQyxNQUFNLFVBQVUsR0FBRyxVQUFVLENBQUE7QUFDcEMsTUFBTSxDQUFDLE1BQU0sZUFBZSxHQUFHLFVBQVUsQ0FBQSJ9
;// ../commons/dist/config.js
const { get } = env_var;
const HOME = (sub = '') => external_path_.join(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], sub);
const get_var = (key = '') => get(key).asString() || get(key.replace(/-/g, '_')).asString() || get(key.replace(/_/g, '-')).asString();
const OSR_ROOT = (key = 'OSR-ROOT') => get_var(key) || external_path_.join(HOME('desktop'), API_PREFIX);
const OSR_SUB_DEFAULT = (key = '') => get_var(key) || external_path_.join(OSR_ROOT(), key);
const CONFIG_DEFAULT_PATH = (key = 'OSR-CONFIG') => get_var(key) || external_path_.join(HOME(`${API_PREFIX}`), '.config.json');
const OSR_TEMP = (key = 'OSR-TEMP') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/temp`);
const OSR_CACHE = (key = 'OSR-CACHE') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/cache`);
const OSR_PRIVATE = (key = 'OSR-PRIVATE') => get_var(key);
const KB_ROOT = (key = 'OSR-KB') => get_var(key);
const OSR_LIBRARY = (key = 'OSR-LIBRARY') => get_var(key);
const OSR_LIBRARY_MACHINES = (key = 'OSR-LIBRARY-MACHINES') => get_var(key);
const OSR_LIBRARY_DIRECTORY = (key = 'OSR-LIBRARY-DIRECTORY') => get_var(key);
const PRODUCT_ROOT = (key = 'PRODUCT-ROOT') => get_var(key);
const OSR_CUSTOMER_DRIVE = (key = 'OSR-CUSTOMER-DRIVE') => get_var(key);
const OA_ROOT = (key = 'OA-ROOT') => get_var(key);
const OSR_USER_ASSETS = (key = 'OSR-USER-ASSETS') => get_var(key);
const POLYMECH_ROOT = (key = 'POLYMECH-ROOT') => get_var(key) || external_path_.join(HOME('desktop'), API_PREFIX_NEXT);
const DEFAULT_ROOTS = {
OSR_ROOT: OSR_ROOT(),
OSR_TEMP: OSR_TEMP(),
PRODUCT_ROOT: PRODUCT_ROOT(),
OA_ROOT: OA_ROOT(),
KB_ROOT: KB_ROOT(),
OSR_CACHE: OSR_CACHE(),
OSR_LIBRARY: OSR_LIBRARY(),
OSR_LIBRARY_MACHINES: OSR_LIBRARY_MACHINES(),
OSR_LIBRARY_DIRECTORY: OSR_LIBRARY_DIRECTORY(),
OSR_USER_ASSETS: OSR_USER_ASSETS(),
OSR_PRIVATE: OSR_PRIVATE(),
OSR_TEMPLATES: external_path_.join(OSR_SUB_DEFAULT('osr-templates')),
OSR_CONTENT: external_path_.join(OSR_SUB_DEFAULT('osr-content')),
OSR_PROFILES: external_path_.join(OSR_SUB_DEFAULT('osr-profiles')),
OSR_CUSTOMER_DRIVE: OSR_CUSTOMER_DRIVE(),
POLYMECH_ROOT: POLYMECH_ROOT()
};
const CONFIG_DEFAULT = (key = 'OSR-CONFIG') => {
const cPath = external_path_.resolve(CONFIG_DEFAULT_PATH(key));
if ((0,dist_exists/* sync */.OH)(cPath)) {
return (0,dist_read/* sync */.OH)(cPath, 'json');
}
return false;
};
//////////////////////////////////////////////////////
//
// NPM related
const readNPMMeta = (_path) => (0,dist_read/* sync */.OH)(_path, 'json') || {};
const config_readPackage = (val) => {
if ((0,primitives/* isString */.Kg)(val)) {
return readNPMMeta(val);
}
else if ((0,primitives/* isObject */.Gv)(val)) {
return val;
}
return {};
};
//////////////////////////////////////////////////////
//
// OSR related
const readOSRMeta = (_path) => (0,dist_read/* sync */.OH)(_path, 'json');
const config_readOSRConfig = (val) => {
if ((0,primitives/* isString */.Kg)(val)) {
return readOSRMeta(val);
}
else if ((0,primitives/* isObject */.Gv)(val)) {
return val;
}
return null;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NvbmZpZy50cyJdLCJuYW1lc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QUFBO0lBQzNCLENBQUM7U0FBTSxJQUFJLFFBQVEsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDO1FBQ3ZCLE9BQU8sR0FBRyxDQUFBO0lBQ2QsQ0FBQztJQUNELE9BQU8sSUFBSSxDQUFBO0FBQ2YsQ0FBQyxDQUFBIn0=
;// ../core/dist/constants.js
// standard expression for variables, eg : ${foo}
const constants_REGEX_VAR = /\$\{([^\s:}]+)(?::([^\s:}]+))?\}/g;
// alternate expression for variables, eg : %{foo}. this is required
// to deal with parent expression parsers where '$' is reserved, eg: %{my_var}
const REGEX_VAR_ALT = /&\{([^\s:}]+)(?::([^\s:}]+))?\}/g;
//# sourceMappingURL=constants.js.map
;// ../commons/dist/variables.js
const DATE_VARS = () => {
return {
YYYY: new Date(Date.now()).getFullYear(),
MM: new Date(Date.now()).getMonth() + 1,
DD: new Date(Date.now()).getDate(),
HH: new Date(Date.now()).getHours(),
SS: new Date(Date.now()).getSeconds()
};
};
const _substitute = (template, map, keep = true, alt = false) => {
const transform = (k) => k || '';
return template.replace(alt ? REGEX_VAR_ALT : constants_REGEX_VAR, (match, key, format) => {
if (map[key]) {
return transform(map[key]).toString();
}
else if (map[key.replace(/-/g, '_')]) {
return transform(map[key.replace(/-/g, '_')]).toString();
}
else if (keep) {
return "${" + key + "}";
}
else {
return "";
}
});
};
const variables_substitute = (alt, template, vars = {}, keep = true) => alt ? _substitute(template, vars, keep, alt) : _substitute(template, vars, keep, alt);
const variables_DEFAULT_VARS = (vars) => {
return {
...DEFAULT_ROOTS,
...DATE_VARS(),
...vars
};
};
const resolveVariables = (path, alt = false, vars = {}, keep = false) => variables_substitute(alt, path, variables_DEFAULT_VARS(vars), keep);
const variables_resolve = (path, alt = false, vars = {}, keep = false) => resolveVariables(path, alt, vars, keep);
const variables_template = (path, vars = {}, keep = false, depth = 3) => {
const map = variables_DEFAULT_VARS(vars);
let oldValue = path;
let newValue = variables_resolve(oldValue, false, map);
let iterationCount = 0;
while (newValue !== oldValue && iterationCount < depth) {
iterationCount++;
oldValue = newValue;
newValue = variables_resolve(oldValue, false, map, keep);
}
return newValue;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmFyaWFibGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL3ZhcmlhYmxlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsU0FBUyxFQUFFLGFBQWEsRUFBRSxNQUFNLDBCQUEwQixDQUFBO0FBRW5FLE9BQU8sRUFBRSxhQUFhLEVBQUUsTUFBTSxhQUFhLENBQUE7QUFFM0MsTUFBTSxDQUFDLE1BQU0sU0FBUyxHQUFHLEdBQUcsRUFBRTtJQUMxQixPQUFPO1FBQ0gsSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLElBQUksQ0FBQyxHQUFHLEVBQUUsQ0FBQyxDQUFDLFdBQVcsRUFBRTtRQUN4QyxFQUFFLEVBQUUsSUFBSSxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsUUFBUSxFQUFFLEdBQUcsQ0FBQztRQUN2QyxFQUFFLEVBQUUsSUFBSSxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsT0FBTyxFQUFFO1FBQ2xDLEVBQUUsRUFBRSxJQUFJLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxFQUFFLENBQUMsQ0FBQyxRQUFRLEVBQUU7UUFDbkMsRUFBRSxFQUFFLElBQUksSUFBSSxDQUFDLElBQUksQ0FBQyxHQUFHLEVBQUUsQ0FBQyxDQUFDLFVBQVUsRUFBRTtLQUN4QyxDQUFBO0FBQ0wsQ0FBQyxDQUFBO0FBRUQsTUFBTSxDQUFDLE1BQU0sV0FBVyxHQUFHLENBQUMsUUFBUSxFQUFFLEdBQXdCLEVBQUUsT0FBZ0IsSUFBSSxFQUFFL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UFBO0lBQ25CLElBQUksUUFBUSxHQUFHLE9BQU8sQ0FBQyxRQUFRLEVBQUUsS0FBSyxFQUFFLEdBQUcsQ0FBQyxDQUFBO0lBQzVDLElBQUksY0FBYyxHQUFHLENBQUMsQ0FBQTtJQUN0QixPQUFPLFFBQVEsS0FBSyxRQUFRLElBQUksY0FBYyxHQUFHLEtBQUssRUFBRSxDQUFDO1FBQ3JELGNBQWMsRUFBRSxDQUFBO1FBQ2hCLFFBQVEsR0FBRyxRQUFRLENBQUE7UUFDbkIsUUFBUSxHQUFHLE9BQU8sQ0FBQyxRQUFRLEVBQUUsS0FBSyxFQUFFLEdBQUcsRUFBRSxJQUFJLENBQUMsQ0FBQTtJQUNsRCxDQUFDO0lBQ0QsT0FBTyxRQUFRLENBQUE7QUFDbkIsQ0FBQyxDQUFBIn0=
;// ../core/dist/errors.js
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Avoid circular dependency on EventEmitter by implementing a subset of the interface.
class ErrorHandler {
unexpectedErrorHandler;
listeners;
constructor() {
this.listeners = [];
this.unexpectedErrorHandler = function (e) {
setTimeout(() => {
if (e.stack) {
if (ErrorNoTelemetry.isErrorNoTelemetry(e)) {
throw new ErrorNoTelemetry(e.message + '\n\n' + e.stack);
}
throw new Error(e.message + '\n\n' + e.stack);
}
throw e;
}, 0);
};
}
addListener(listener) {
this.listeners.push(listener);
return () => {
this._removeListener(listener);
};
}
emit(e) {
this.listeners.forEach((listener) => {
listener(e);
});
}
_removeListener(listener) {
this.listeners.splice(this.listeners.indexOf(listener), 1);
}
setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
this.unexpectedErrorHandler = newUnexpectedErrorHandler;
}
getUnexpectedErrorHandler() {
return this.unexpectedErrorHandler;
}
onUnexpectedError(e) {
this.unexpectedErrorHandler(e);
this.emit(e);
}
// For external errors, we don't want the listeners to be called
onUnexpectedExternalError(e) {
this.unexpectedErrorHandler(e);
}
}
const errorHandler = new ErrorHandler();
/** @skipMangle */
function setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
}
/**
* Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be
* logged at most once, to avoid a loop.
*
* @see https://github.com/microsoft/vscode-remote-release/issues/6481
*/
function isSigPipeError(e) {
if (!e || typeof e !== 'object') {
return false;
}
const cast = e;
return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE';
}
/**
* This function should only be called with errors that indicate a bug in the product.
* E.g. buggy extensions/invalid user-input/network issues should not be able to trigger this code path.
* If they are, this indicates there is also a bug in the product.
*/
function onBugIndicatingError(e) {
errorHandler.onUnexpectedError(e);
return undefined;
}
function errors_onUnexpectedError(e) {
// ignore errors from cancelled promises
if (!isCancellationError(e)) {
errorHandler.onUnexpectedError(e);
}
return undefined;
}
function onUnexpectedExternalError(e) {
// ignore errors from cancelled promises
if (!isCancellationError(e)) {
errorHandler.onUnexpectedExternalError(e);
}
return undefined;
}
function transformErrorForSerialization(error) {
if (error instanceof Error) {
const { name, message, cause } = error;
const stack = error.stacktrace || error.stack;
return {
$isError: true,
name,
message,
stack,
noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error),
cause: cause ? transformErrorForSerialization(cause) : undefined,
code: error.code
};
}
// return as is
return error;
}
function transformErrorFromSerialization(data) {
let error;
if (data.noTelemetry) {
error = new ErrorNoTelemetry();
}
else {
error = new Error();
error.name = data.name;
}
error.message = data.message;
error.stack = data.stack;
if (data.code) {
error.code = data.code;
}
if (data.cause) {
error.cause = transformErrorFromSerialization(data.cause);
}
return error;
}
const canceledName = 'Canceled';
/**
* Checks if the given error is a promise in canceled state
*/
function isCancellationError(error) {
if (error instanceof CancellationError) {
return true;
}
return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
// !!!IMPORTANT!!!
// Do NOT change this class because it is also used as an API-type.
class CancellationError extends Error {
constructor() {
super(canceledName);
this.name = this.message;
}
}
/**
* @deprecated use {@link CancellationError `new CancellationError()`} instead
*/
function canceled() {
const error = new Error(canceledName);
error.name = error.message;
return error;
}
function illegalArgument(name) {
if (name) {
return new Error(`Illegal argument: ${name}`);
}
else {
return new Error('Illegal argument');
}
}
function illegalState(name) {
if (name) {
return new Error(`Illegal state: ${name}`);
}
else {
return new Error('Illegal state');
}
}
class ReadonlyError extends TypeError {
constructor(name) {
super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property');
}
}
function getErrorMessage(err) {
if (!err) {
return 'Error';
}
if (err.message) {
return err.message;
}
if (err.stack) {
return err.stack.split('\n')[0];
}
return String(err);
}
class NotImplementedError extends Error {
constructor(message) {
super('NotImplemented');
if (message) {
this.message = message;
}
}
}
class NotSupportedError extends Error {
constructor(message) {
super('NotSupported');
if (message) {
this.message = message;
}
}
}
class ExpectedError extends (/* unused pure expression or super */ null && (Error)) {
isExpected = true;
}
/**
* Error that when thrown won't be logged in telemetry as an unhandled error.
*/
class ErrorNoTelemetry extends Error {
name;
constructor(msg) {
super(msg);
this.name = 'CodeExpectedError';
}
static fromError(err) {
if (err instanceof ErrorNoTelemetry) {
return err;
}
const result = new ErrorNoTelemetry();
result.message = err.message;
result.stack = err.stack;
return result;
}
static isErrorNoTelemetry(err) {
return err.name === 'CodeExpectedError';
}
}
/**
* This error indicates a bug.
* Do not throw this for invalid user input.
* Only catch this error to recover gracefully from bugs.
*/
class errors_BugIndicatingError extends Error {
constructor(message) {
super(message || 'An unexpected bug occurred.');
Object.setPrototypeOf(this, errors_BugIndicatingError.prototype);
// Because we know for sure only buggy code throws this,
// we definitely want to break here and fix the bug.
// debugger;
}
}
//# sourceMappingURL=errors.js.map
;// ../core/dist/assert.js
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
*
* @deprecated Use `assert(...)` instead.
* This method is usually used like this:
* ```ts
* import * as assert from 'vs/base/common/assert';
* assert.ok(...);
* ```
*
* However, `assert` in that example is a user chosen name.
* There is no tooling for generating such an import statement.
* Thus, the `assert(...)` function should be used instead.
*/
function ok(value, message) {
if (!value) {
throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
}
}
function assertNever(value, message = 'Unreachable') {
throw new Error(message);
}
function assert_assert(condition, message = 'unexpected state') {
if (!condition) {
throw new BugIndicatingError(`Assertion Failed: ${message}`);
}
}
/**
* Like assert, but doesn't throw.
*/
function softAssert(condition) {
if (!condition) {
onUnexpectedError(new BugIndicatingError('Soft Assertion Failed'));
}
}
/**
* condition must be side-effect free!
*/
function assertFn(condition) {
if (!condition()) {
// eslint-disable-next-line no-debugger
debugger;
// Reevaluate `condition` again to make debugging easier
condition();
onUnexpectedError(new BugIndicatingError('Assertion Failed'));
}
}
function checkAdjacentItems(items, predicate) {
let i = 0;
while (i < items.length - 1) {
const a = items[i];
const b = items[i + 1];
if (!predicate(a, b)) {
return false;
}
i++;
}
return true;
}
//# sourceMappingURL=assert.js.map
;// ../core/dist/types.js
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* @returns whether the provided parameter is a JavaScript String or not.
*/
function types_isString(str) {
return (typeof str === 'string');
}
/**
* @returns whether the provided parameter is a JavaScript Array and each element in the array is a string.
*/
function isStringArray(value) {
return Array.isArray(value) && value.every(elem => types_isString(elem));
}
/**
* @returns whether the provided parameter is of type `object` but **not**
* `null`, an `array`, a `regexp`, nor a `date`.
*/
function isObject(obj) {
// The method can't do a type cast since there are type (like strings) which
// are subclasses of any put not positvely matched by the function. Hence type
// narrowing results in wrong results.
return typeof obj === 'object'
&& obj !== null
&& !Array.isArray(obj)
&& !(obj instanceof RegExp)
&& !(obj instanceof Date);
}
/**
* @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type
*/
function isTypedArray(obj) {
const TypedArray = Object.getPrototypeOf(Uint8Array);
return typeof obj === 'object'
&& obj instanceof TypedArray;
}
/**
* In **contrast** to just checking `typeof` this will return `false` for `NaN`.
* @returns whether the provided parameter is a JavaScript Number or not.
*/
function isNumber(obj) {
return (typeof obj === 'number' && !isNaN(obj));
}
/**
* @returns whether the provided parameter is an Iterable, casting to the given generic
*/
function isIterable(obj) {
return !!obj && typeof obj[Symbol.iterator] === 'function';
}
/**
* @returns whether the provided parameter is a JavaScript Boolean or not.
*/
function isBoolean(obj) {
return (obj === true || obj === false);
}
/**
* @returns whether the provided parameter is undefined.
*/
function isUndefined(obj) {
return (typeof obj === 'undefined');
}
/**
* @returns whether the provided parameter is defined.
*/
function isDefined(arg) {
return !isUndefinedOrNull(arg);
}
/**
* @returns whether the provided parameter is undefined or null.
*/
function isUndefinedOrNull(obj) {
return (isUndefined(obj) || obj === null);
}
function assertType(condition, type) {
if (!condition) {
throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
}
}
/**
* Asserts that the argument passed in is neither undefined nor null.
*
* @see {@link assertDefined} for a similar utility that leverages TS assertion functions to narrow down the type of `arg` to be non-nullable.
*/
function assertIsDefined(arg) {
assert(arg !== null && arg !== undefined, 'Argument is `undefined` or `null`.');
return arg;
}
/**
* Asserts that a provided `value` is `defined` - not `null` or `undefined`,
* throwing an error with the provided error or error message, while also
* narrowing down the type of the `value` to be `NonNullable` using TS
* assertion functions.
*
* @throws if the provided `value` is `null` or `undefined`.
*
* ## Examples
*
* ```typescript
* // an assert with an error message
* assertDefined('some value', 'String constant is not defined o_O.');
*
* // `throws!` the provided error
* assertDefined(null, new Error('Should throw this error.'));
*
* // narrows down the type of `someValue` to be non-nullable
* const someValue: string | undefined | null = blackbox();
* assertDefined(someValue, 'Some value must be defined.');
* console.log(someValue.length); // now type of `someValue` is `string`
* ```
*
* @see {@link assertIsDefined} for a similar utility but without assertion.
* @see {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions typescript-3-7.html#assertion-functions}
*/
function assertDefined(value, error) {
if (value === null || value === undefined) {
const errorToThrow = typeof error === 'string' ? new Error(error) : error;
throw errorToThrow;
}
}
function assertAllDefined(...args) {
const result = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (isUndefinedOrNull(arg)) {
throw new Error(`Assertion Failed: argument at index ${i} is undefined or null`);
}
result.push(arg);
}
return result;
}
const types_hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @returns whether the provided parameter is an empty JavaScript Object or not.
*/
function isEmptyObject(obj) {
if (!isObject(obj)) {
return false;
}
for (const key in obj) {
if (types_hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
/**
* @returns whether the provided parameter is a JavaScript Function or not.
*/
function isFunction(obj) {
return (typeof obj === 'function');
}
/**
* @returns whether the provided parameters is are JavaScript Function or not.
*/
function areFunctions(...objects) {
return objects.length > 0 && objects.every(isFunction);
}
function validateConstraints(args, constraints) {
const len = Math.min(args.length, constraints.length);
for (let i = 0; i < len; i++) {
validateConstraint(args[i], constraints[i]);
}
}
function validateConstraint(arg, constraint) {
if (types_isString(constraint)) {
if (typeof arg !== constraint) {
throw new Error(`argument does not match constraint: typeof ${constraint}`);
}
}
else if (isFunction(constraint)) {
try {
if (arg instanceof constraint) {
return;
}
}
catch {
// ignore
}
if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
return;
}
if (constraint.length === 1 && constraint.call(undefined, arg) === true) {
return;
}
throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
}
}
/**
* Helper type assertion that safely upcasts a type to a supertype.
*
* This can be used to make sure the argument correctly conforms to the subtype while still being able to pass it
* to contexts that expects the supertype.
*/
function upcast(x) {
return x;
}
//# sourceMappingURL=types.js.map
;// ../commons/dist/profile.js
const _resolve = (config) => {
for (const key in config) {
if (isString(config[key])) {
config[key] = template(config[key], config);
}
}
return config;
};
const resolveConfig = (config) => _resolve(config);
const parse = (profilePath, profile, options = { env: 'default' }, rel) => {
profilePath = path.resolve(resolve(profilePath, false, profile.variables));
if (!exists(profilePath)) {
return;
}
const _profile = read(profilePath, 'json') || { includes: [], variables: {} };
_profile.includes = _profile.includes || [];
_profile.variables = _profile.variables || {};
if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].includes) {
profile.includes = [
...profile.includes,
..._profile.includes,
..._profile.env[options.env].includes
];
}
else {
profile.includes = [
...profile.includes,
..._profile.includes
];
}
if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].variables) {
profile.variables = {
...profile.variables,
..._profile.variables,
..._profile.env[options.env].variables
};
}
for (const k in _profile.variables) {
if (isString(_profile.variables[k])) {
_profile.variables[k] = substitute(false, _profile.variables[k], profile.variables);
}
}
profile.variables = { ...profile.variables, ..._profile.variables, ..._profile.env[options.env]?.variables || {} };
for (const k in profile.variables) {
if (isString(profile.variables[k])) {
profile.variables[k] = substitute(false, profile.variables[k], profile.variables);
}
}
profile.includes = Array.from(new Set(profile.includes));
profile.includes = [
...profile.includes.map((i) => {
if (!path.isAbsolute(i) && rel && !i.match(REGEX_VAR)) {
return path.resolve(`${rel}/${i}`);
}
let ret = resolve(i, false, profile.variables);
ret = path.resolve(substitute(false, ret, profile.variables));
return ret;
})
];
profile.includes = profile.includes.filter((include) => include !== null &&
include !== '');
profile.includes = Array.from(new Set(profile.includes));
return profile;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJvZmlsZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9wcm9maWxlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxJQUFJLE1BQU0sTUFBTSxDQUFBO0FBQzVCLE9BQU8sRUFBRSxTQUFTLEVBQUUsTUFBTSwwQkFBMEIsQ0FBQTtBQUNwRCx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QUFDLE9BQU8sRUFBRSxFQUFFLENBQ25ELE9BQU8sS0FBSyxJQUFJO1FBQ2hCLE9BQU8sS0FBSyxFQUFFLENBQUMsQ0FBQTtJQUNuQixPQUFPLENBQUMsUUFBUSxHQUFHLEtBQUssQ0FBQyxJQUFJLENBQUMsSUFBSSxHQUFHLENBQUMsT0FBTyxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUE7SUFDeEQsT0FBTyxPQUFPLENBQUE7QUFDbEIsQ0FBQyxDQUFBIn0=
// EXTERNAL MODULE: ../commons/node_modules/brace-expansion/index.js
var brace_expansion = __webpack_require__(3987);
;// ../commons/node_modules/minimatch/dist/esm/assert-valid-pattern.js
const MAX_PATTERN_LENGTH = 1024 * 64;
const assertValidPattern = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern');
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long');
}
};
//# sourceMappingURL=assert-valid-pattern.js.map
;// ../commons/node_modules/minimatch/dist/esm/brace-expressions.js
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { : [, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length
? '(' + sranges + '|' + snegs + ')'
: ranges.length
? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
//# sourceMappingURL=brace-expressions.js.map
;// ../commons/node_modules/minimatch/dist/esm/unescape.js
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link windowsPathsNoEscape} option is used, then square-brace
* escapes are removed, but not backslash escapes. For example, it will turn
* the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
* becuase `\` is a path separator in `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both brace escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*/
const unescape_unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
return windowsPathsNoEscape
? s.replace(/\[([^\/\\])\]/g, '$1')
: s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
//# sourceMappingURL=unescape.js.map
;// ../commons/node_modules/minimatch/dist/esm/ast.js
// parse a single path portion
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
class AST {
type;
#root;
#hasMagic;
#uflag = false;
#parts = [];
#parent;
#parentIndex;
#negs;
#filledNegs = false;
#options;
#toString;
// set to true if it's an extglob with no children
// (which really means one child of '')
#emptyExt = false;
constructor(type, parent, options = {}) {
this.type = type;
// extglobs are inherently magical
if (type)
this.#hasMagic = true;
this.#parent = parent;
this.#root = this.#parent ? this.#parent.#root : this;
this.#options = this.#root === this ? options : this.#root.#options;
this.#negs = this.#root === this ? [] : this.#root.#negs;
if (type === '!' && !this.#root.#filledNegs)
this.#negs.push(this);
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
}
get hasMagic() {
/* c8 ignore start */
if (this.#hasMagic !== undefined)
return this.#hasMagic;
/* c8 ignore stop */
for (const p of this.#parts) {
if (typeof p === 'string')
continue;
if (p.type || p.hasMagic)
return (this.#hasMagic = true);
}
// note: will be undefined until we generate the regexp src and find out
return this.#hasMagic;
}
// reconstructs the pattern
toString() {
if (this.#toString !== undefined)
return this.#toString;
if (!this.type) {
return (this.#toString = this.#parts.map(p => String(p)).join(''));
}
else {
return (this.#toString =
this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
}
}
#fillNegs() {
/* c8 ignore start */
if (this !== this.#root)
throw new Error('should only call on root');
if (this.#filledNegs)
return this;
/* c8 ignore stop */
// call toString() once to fill this out
this.toString();
this.#filledNegs = true;
let n;
while ((n = this.#negs.pop())) {
if (n.type !== '!')
continue;
// walk up the tree, appending everthing that comes AFTER parentIndex
let p = n;
let pp = p.#parent;
while (pp) {
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
for (const part of n.#parts) {
/* c8 ignore start */
if (typeof part === 'string') {
throw new Error('string part in extglob AST??');
}
/* c8 ignore stop */
part.copyIn(pp.#parts[i]);
}
}
p = pp;
pp = p.#parent;
}
}
return this;
}
push(...parts) {
for (const p of parts) {
if (p === '')
continue;
/* c8 ignore start */
if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
throw new Error('invalid part: ' + p);
}
/* c8 ignore stop */
this.#parts.push(p);
}
}
toJSON() {
const ret = this.type === null
? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
: [this.type, ...this.#parts.map(p => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() &&
(this === this.#root ||
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
ret.push({});
}
return ret;
}
isStart() {
if (this.#root === this)
return true;
// if (this.type) return !!this.#parent?.isStart()
if (!this.#parent?.isStart())
return false;
if (this.#parentIndex === 0)
return true;
// if everything AHEAD of this is a negation, then it's still the "start"
const p = this.#parent;
for (let i = 0; i < this.#parentIndex; i++) {
const pp = p.#parts[i];
if (!(pp instanceof AST && pp.type === '!')) {
return false;
}
}
return true;
}
isEnd() {
if (this.#root === this)
return true;
if (this.#parent?.type === '!')
return true;
if (!this.#parent?.isEnd())
return false;
if (!this.type)
return this.#parent?.isEnd();
// if not root, it'll always have a parent
/* c8 ignore start */
const pl = this.#parent ? this.#parent.#parts.length : 0;
/* c8 ignore stop */
return this.#parentIndex === pl - 1;
}
copyIn(part) {
if (typeof part === 'string')
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new AST(this.type, parent);
for (const p of this.#parts) {
c.copyIn(p);
}
return c;
}
static #parseAST(str, ast, pos, opt) {
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
// outside of a extglob, append until we find a start
let i = pos;
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
ast.push(acc);
acc = '';
const ext = new AST(c, ast);
i = AST.#parseAST(str, ext, i, opt);
ast.push(ext);
continue;
}
acc += c;
}
ast.push(acc);
return i;
}
// some kind of extglob, pos is at the (
// find the next | or )
let i = pos + 1;
let part = new AST(null, ast);
const parts = [];
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (isExtglobType(c) && str.charAt(i) === '(') {
part.push(acc);
acc = '';
const ext = new AST(c, part);
part.push(ext);
i = AST.#parseAST(str, ext, i, opt);
continue;
}
if (c === '|') {
part.push(acc);
acc = '';
parts.push(part);
part = new AST(null, ast);
continue;
}
if (c === ')') {
if (acc === '' && ast.#parts.length === 0) {
ast.#emptyExt = true;
}
part.push(acc);
acc = '';
ast.push(...parts, part);
return i;
}
acc += c;
}
// unfinished extglob
// if we got here, it was a malformed extglob! not an extglob, but
// maybe something else in there.
ast.type = null;
ast.#hasMagic = undefined;
ast.#parts = [str.substring(pos - 1)];
return i;
}
static fromGlob(pattern, options = {}) {
const ast = new AST(null, undefined, options);
AST.#parseAST(pattern, ast, 0, options);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
// should only be called on root
/* c8 ignore start */
if (this !== this.#root)
return this.#root.toMMPattern();
/* c8 ignore stop */
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
// if we're in nocase mode, and not nocaseMagicOnly, then we do
// still need a regular expression if we have to case-insensitively
// match capital/lowercase characters.
const anyMagic = hasMagic ||
this.#hasMagic ||
(this.#options.nocase &&
!this.#options.nocaseMagicOnly &&
glob.toUpperCase() !== glob.toLowerCase());
if (!anyMagic) {
return body;
}
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob,
});
}
get options() {
return this.#options;
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
const dot = allowDot ?? !!this.#options.dot;
if (this.#root === this)
this.#fillNegs();
if (!this.type) {
const noEmpty = this.isStart() && this.isEnd();
const src = this.#parts
.map(p => {
const [re, _, hasMagic, uflag] = typeof p === 'string'
? AST.#parseGlob(p, this.#hasMagic, noEmpty)
: p.toRegExpSource(allowDot);
this.#hasMagic = this.#hasMagic || hasMagic;
this.#uflag = this.#uflag || uflag;
return re;
})
.join('');
let start = '';
if (this.isStart()) {
if (typeof this.#parts[0] === 'string') {
// this is the string that will match the start of the pattern,
// so we need to protect against dots and such.
// '.' and '..' cannot match unless the pattern is that exactly,
// even if it starts with . or dot:true is set.
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
// check if we have a possibility of matching . or ..,
// and prevent that.
const needNoTrav =
// dots are allowed, and the pattern starts with [ or .
(dot && aps.has(src.charAt(0))) ||
// the pattern starts with \., and then [ or .
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
// the pattern starts with \.\., and then [ or .
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
// no need to prevent dots if it can't match a dot, or if a
// sub-pattern will be preventing it anyway.
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
}
}
}
// append the "end of path portion" pattern to negation tails
let end = '';
if (this.isEnd() &&
this.#root.#filledNegs &&
this.#parent?.type === '!') {
end = '(?:$|\\/)';
}
const final = start + src + end;
return [
final,
unescape_unescape(src),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
// We need to calculate the body *twice* if it's a repeat pattern
// at the start, once in nodot mode, then again in dot mode, so a
// pattern like *(?) can match 'x.y'
const repeated = this.type === '*' || this.type === '+';
// some kind of extglob
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
let body = this.#partsToRegExp(dot);
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
// invalid extglob, has to at least be *something* present, if it's
// the entire path portion.
const s = this.toString();
this.#parts = [s];
this.type = null;
this.#hasMagic = undefined;
return [s, unescape_unescape(this.toString()), false, false];
}
// XXX abstract out this map method
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
? ''
: this.#partsToRegExp(true);
if (bodyDotAllowed === body) {
bodyDotAllowed = '';
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
// an empty !() is exactly equivalent to a starNoEmpty
let final = '';
if (this.type === '!' && this.#emptyExt) {
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
}
else {
const close = this.type === '!'
? // !() must match something,but !(x) can match ''
'))' +
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
star +
')'
: this.type === '@'
? ')'
: this.type === '?'
? ')?'
: this.type === '+' && bodyDotAllowed
? ')'
: this.type === '*' && bodyDotAllowed
? `)?`
: `)${this.type}`;
final = start + body + close;
}
return [
final,
unescape_unescape(body),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
#partsToRegExp(dot) {
return this.#parts
.map(p => {
// extglob ASTs should only contain parent ASTs
/* c8 ignore start */
if (typeof p === 'string') {
throw new Error('string type in extglob ast??');
}
/* c8 ignore stop */
// can ignore hasMagic, because extglobs are already always magic
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
this.#uflag = this.#uflag || uflag;
return re;
})
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
.join('|');
}
static #parseGlob(glob, hasMagic, noEmpty = false) {
let escaping = false;
let re = '';
let uflag = false;
for (let i = 0; i < glob.length; i++) {
const c = glob.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? '\\' : '') + c;
continue;
}
if (c === '\\') {
if (i === glob.length - 1) {
re += '\\\\';
}
else {
escaping = true;
}
continue;
}
if (c === '[') {
const [src, needUflag, consumed, magic] = parseClass(glob, i);
if (consumed) {
re += src;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic = hasMagic || magic;
continue;
}
}
if (c === '*') {
if (noEmpty && glob === '*')
re += starNoEmpty;
else
re += star;
hasMagic = true;
continue;
}
if (c === '?') {
re += qmark;
hasMagic = true;
continue;
}
re += regExpEscape(c);
}
return [re, unescape_unescape(glob), !!hasMagic, uflag];
}
}
//# sourceMappingURL=ast.js.map
;// ../commons/node_modules/minimatch/dist/esm/escape.js
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*/
const escape_escape = (s, { windowsPathsNoEscape = false, } = {}) => {
// don't need to escape +@! because we escape the parens
// that make those magic, and escaping ! as [!] isn't valid,
// because [!]] is a valid glob class meaning not ']'.
return windowsPathsNoEscape
? s.replace(/[?*()[\]]/g, '[$&]')
: s.replace(/[?*()[\]\\]/g, '\\$&');
};
//# sourceMappingURL=escape.js.map
;// ../commons/node_modules/minimatch/dist/esm/index.js
const minimatch = (p, pattern, options = {}) => {
assertValidPattern(pattern);
// shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
return false;
}
return new Minimatch(pattern, options).match(p);
};
// Optimized checking for the most common glob patterns.
const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
const starDotExtTestNocase = (ext) => {
ext = ext.toLowerCase();
return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
};
const starDotExtTestNocaseDot = (ext) => {
ext = ext.toLowerCase();
return (f) => f.toLowerCase().endsWith(ext);
};
const starDotStarRE = /^\*+\.\*+$/;
const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
const dotStarRE = /^\.\*+$/;
const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
const starRE = /^\*+$/;
const starTest = (f) => f.length !== 0 && !f.startsWith('.');
const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
const qmarksTestNocase = ([$0, ext = '']) => {
const noext = qmarksTestNoExt([$0]);
if (!ext)
return noext;
ext = ext.toLowerCase();
return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestNocaseDot = ([$0, ext = '']) => {
const noext = qmarksTestNoExtDot([$0]);
if (!ext)
return noext;
ext = ext.toLowerCase();
return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestDot = ([$0, ext = '']) => {
const noext = qmarksTestNoExtDot([$0]);
return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTest = ([$0, ext = '']) => {
const noext = qmarksTestNoExt([$0]);
return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTestNoExt = ([$0]) => {
const len = $0.length;
return (f) => f.length === len && !f.startsWith('.');
};
const qmarksTestNoExtDot = ([$0]) => {
const len = $0.length;
return (f) => f.length === len && f !== '.' && f !== '..';
};
/* c8 ignore start */
const defaultPlatform = (typeof process === 'object' && process
? (typeof process.env === 'object' &&
process.env &&
process.env.__MINIMATCH_TESTING_PLATFORM__) ||
process.platform
: 'posix');
const esm_path = {
win32: { sep: '\\' },
posix: { sep: '/' },
};
/* c8 ignore stop */
const sep = defaultPlatform === 'win32' ? esm_path.win32.sep : esm_path.posix.sep;
minimatch.sep = sep;
const GLOBSTAR = Symbol('globstar **');
minimatch.GLOBSTAR = GLOBSTAR;
// any single thing other than /
// don't need to escape / when using new RegExp()
const esm_qmark = '[^/]';
// * => any number of characters
const esm_star = esm_qmark + '*?';
// ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
minimatch.filter = filter;
const ext = (a, b = {}) => Object.assign({}, a, b);
const defaults = (def) => {
if (!def || typeof def !== 'object' || !Object.keys(def).length) {
return minimatch;
}
const orig = minimatch;
const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
return Object.assign(m, {
Minimatch: class Minimatch extends orig.Minimatch {
constructor(pattern, options = {}) {
super(pattern, ext(def, options));
}
static defaults(options) {
return orig.defaults(ext(def, options)).Minimatch;
}
},
AST: class AST extends orig.AST {
/* c8 ignore start */
constructor(type, parent, options = {}) {
super(type, parent, ext(def, options));
}
/* c8 ignore stop */
static fromGlob(pattern, options = {}) {
return orig.AST.fromGlob(pattern, ext(def, options));
}
},
unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
escape: (s, options = {}) => orig.escape(s, ext(def, options)),
filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
defaults: (options) => orig.defaults(ext(def, options)),
makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
sep: orig.sep,
GLOBSTAR: GLOBSTAR,
});
};
minimatch.defaults = defaults;
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
const braceExpand = (pattern, options = {}) => {
assertValidPattern(pattern);
// Thanks to Yeting Li for
// improving this regexp to avoid a ReDOS vulnerability.
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
// shortcut. no need to expand.
return [pattern];
}
return brace_expansion(pattern);
};
minimatch.braceExpand = braceExpand;
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
const match = (list, pattern, options = {}) => {
const mm = new Minimatch(pattern, options);
list = list.filter(f => mm.match(f));
if (mm.options.nonull && !list.length) {
list.push(pattern);
}
return list;
};
minimatch.match = match;
// replace stuff like \* with *
const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
const esm_regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
class Minimatch {
options;
set;
pattern;
windowsPathsNoEscape;
nonegate;
negate;
comment;
empty;
preserveMultipleSlashes;
partial;
globSet;
globParts;
nocase;
isWindows;
platform;
windowsNoMagicRoot;
regexp;
constructor(pattern, options = {}) {
assertValidPattern(pattern);
options = options || {};
this.options = options;
this.pattern = pattern;
this.platform = options.platform || defaultPlatform;
this.isWindows = this.platform === 'win32';
this.windowsPathsNoEscape =
!!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, '/');
}
this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
this.regexp = null;
this.negate = false;
this.nonegate = !!options.nonegate;
this.comment = false;
this.empty = false;
this.partial = !!options.partial;
this.nocase = !!this.options.nocase;
this.windowsNoMagicRoot =
options.windowsNoMagicRoot !== undefined
? options.windowsNoMagicRoot
: !!(this.isWindows && this.nocase);
this.globSet = [];
this.globParts = [];
this.set = [];
// make the set of regexps etc.
this.make();
}
hasMagic() {
if (this.options.magicalBraces && this.set.length > 1) {
return true;
}
for (const pattern of this.set) {
for (const part of pattern) {
if (typeof part !== 'string')
return true;
}
}
return false;
}
debug(..._) { }
make() {
const pattern = this.pattern;
const options = this.options;
// empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
this.comment = true;
return;
}
if (!pattern) {
this.empty = true;
return;
}
// step 1: figure out negation, etc.
this.parseNegate();
// step 2: expand braces
this.globSet = [...new Set(this.braceExpand())];
if (options.debug) {
this.debug = (...args) => console.error(...args);
}
this.debug(this.pattern, this.globSet);
// step 3: now we have a set, so turn each one into a series of
// path-portion matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
//
// First, we preprocess to make the glob pattern sets a bit simpler
// and deduped. There are some perf-killing patterns that can cause
// problems with a glob walk, but we can simplify them down a bit.
const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
this.globParts = this.preprocess(rawGlobParts);
this.debug(this.pattern, this.globParts);
// glob --> regexps
let set = this.globParts.map((s, _, __) => {
if (this.isWindows && this.windowsNoMagicRoot) {
// check if it's a drive or unc path.
const isUNC = s[0] === '' &&
s[1] === '' &&
(s[2] === '?' || !globMagic.test(s[2])) &&
!globMagic.test(s[3]);
const isDrive = /^[a-z]:/i.test(s[0]);
if (isUNC) {
return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
}
else if (isDrive) {
return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
}
}
return s.map(ss => this.parse(ss));
});
this.debug(this.pattern, set);
// filter out everything that didn't compile properly.
this.set = set.filter(s => s.indexOf(false) === -1);
// do not treat the ? in UNC paths as magic
if (this.isWindows) {
for (let i = 0; i < this.set.length; i++) {
const p = this.set[i];
if (p[0] === '' &&
p[1] === '' &&
this.globParts[i][2] === '?' &&
typeof p[3] === 'string' &&
/^[a-z]:$/i.test(p[3])) {
p[2] = '?';
}
}
}
this.debug(this.pattern, this.set);
}
// various transforms to equivalent pattern sets that are
// faster to process in a filesystem walk. The goal is to
// eliminate what we can, and push all ** patterns as far
// to the right as possible, even if it increases the number
// of patterns that we have to process.
preprocess(globParts) {
// if we're not in globstar mode, then turn all ** into *
if (this.options.noglobstar) {
for (let i = 0; i < globParts.length; i++) {
for (let j = 0; j < globParts[i].length; j++) {
if (globParts[i][j] === '**') {
globParts[i][j] = '*';
}
}
}
}
const { optimizationLevel = 1 } = this.options;
if (optimizationLevel >= 2) {
// aggressive optimization for the purpose of fs walking
globParts = this.firstPhasePreProcess(globParts);
globParts = this.secondPhasePreProcess(globParts);
}
else if (optimizationLevel >= 1) {
// just basic optimizations to remove some .. parts
globParts = this.levelOneOptimize(globParts);
}
else {
// just collapse multiple ** portions into one
globParts = this.adjascentGlobstarOptimize(globParts);
}
return globParts;
}
// just get rid of adjascent ** portions
adjascentGlobstarOptimize(globParts) {
return globParts.map(parts => {
let gs = -1;
while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
let i = gs;
while (parts[i + 1] === '**') {
i++;
}
if (i !== gs) {
parts.splice(gs, i - gs);
}
}
return parts;
});
}
// get rid of adjascent ** and resolve .. portions
levelOneOptimize(globParts) {
return globParts.map(parts => {
parts = parts.reduce((set, part) => {
const prev = set[set.length - 1];
if (part === '**' && prev === '**') {
return set;
}
if (part === '..') {
if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
set.pop();
return set;
}
}
set.push(part);
return set;
}, []);
return parts.length === 0 ? [''] : parts;
});
}
levelTwoFileOptimize(parts) {
if (!Array.isArray(parts)) {
parts = this.slashSplit(parts);
}
let didSomething = false;
do {
didSomething = false;
// // -> /
if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
// don't squeeze out UNC patterns
if (i === 1 && p === '' && parts[0] === '')
continue;
if (p === '.' || p === '') {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === '.' &&
parts.length === 2 &&
(parts[1] === '.' || parts[1] === '')) {
didSomething = true;
parts.pop();
}
}
// //../ -> /
let dd = 0;
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
const p = parts[dd - 1];
if (p && p !== '.' && p !== '..' && p !== '**') {
didSomething = true;
parts.splice(dd - 1, 2);
dd -= 2;
}
}
} while (didSomething);
return parts.length === 0 ? [''] : parts;
}
// First phase: single-pattern processing
// is 1 or more portions
// is 1 or more portions
// is any portion other than ., .., '', or **
// is . or ''
//
// **/.. is *brutal* for filesystem walking performance, because
// it effectively resets the recursive walk each time it occurs,
// and ** cannot be reduced out by a .. pattern part like a regexp
// or most strings (other than .., ., and '') can be.
//
// /**/..//
/ -> {/..//
/,/**//
/}
// // -> /
// //../ -> /
// **/**/ -> **/
//
// **/*/ -> */**/ <== not valid because ** doesn't follow
// this WOULD be allowed if ** did follow symlinks, or * didn't
firstPhasePreProcess(globParts) {
let didSomething = false;
do {
didSomething = false;
// /**/..//
/ -> {/..//
/,/**//
/}
for (let parts of globParts) {
let gs = -1;
while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
let gss = gs;
while (parts[gss + 1] === '**') {
// /**/**/ -> /**/
gss++;
}
// eg, if gs is 2 and gss is 4, that means we have 3 **
// parts, and can remove 2 of them.
if (gss > gs) {
parts.splice(gs + 1, gss - gs);
}
let next = parts[gs + 1];
const p = parts[gs + 2];
const p2 = parts[gs + 3];
if (next !== '..')
continue;
if (!p ||
p === '.' ||
p === '..' ||
!p2 ||
p2 === '.' ||
p2 === '..') {
continue;
}
didSomething = true;
// edit parts in place, and push the new one
parts.splice(gs, 1);
const other = parts.slice(0);
other[gs] = '**';
globParts.push(other);
gs--;
}
// // -> /
if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
// don't squeeze out UNC patterns
if (i === 1 && p === '' && parts[0] === '')
continue;
if (p === '.' || p === '') {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === '.' &&
parts.length === 2 &&
(parts[1] === '.' || parts[1] === '')) {
didSomething = true;
parts.pop();
}
}
// //../ -> /
let dd = 0;
while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
const p = parts[dd - 1];
if (p && p !== '.' && p !== '..' && p !== '**') {
didSomething = true;
const needDot = dd === 1 && parts[dd + 1] === '**';
const splin = needDot ? ['.'] : [];
parts.splice(dd - 1, 2, ...splin);
if (parts.length === 0)
parts.push('');
dd -= 2;
}
}
}
} while (didSomething);
return globParts;
}
// second phase: multi-pattern dedupes
// {/*/,//} -> /*/
// {/,/} -> /
// {/**/,/} -> /**/
//
// {/**/,/**//} -> /**/
// ^-- not valid because ** doens't follow symlinks
secondPhasePreProcess(globParts) {
for (let i = 0; i < globParts.length - 1; i++) {
for (let j = i + 1; j < globParts.length; j++) {
const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
if (matched) {
globParts[i] = [];
globParts[j] = matched;
break;
}
}
}
return globParts.filter(gs => gs.length);
}
partsMatch(a, b, emptyGSMatch = false) {
let ai = 0;
let bi = 0;
let result = [];
let which = '';
while (ai < a.length && bi < b.length) {
if (a[ai] === b[bi]) {
result.push(which === 'b' ? b[bi] : a[ai]);
ai++;
bi++;
}
else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
result.push(a[ai]);
ai++;
}
else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
result.push(b[bi]);
bi++;
}
else if (a[ai] === '*' &&
b[bi] &&
(this.options.dot || !b[bi].startsWith('.')) &&
b[bi] !== '**') {
if (which === 'b')
return false;
which = 'a';
result.push(a[ai]);
ai++;
bi++;
}
else if (b[bi] === '*' &&
a[ai] &&
(this.options.dot || !a[ai].startsWith('.')) &&
a[ai] !== '**') {
if (which === 'a')
return false;
which = 'b';
result.push(b[bi]);
ai++;
bi++;
}
else {
return false;
}
}
// if we fall out of the loop, it means they two are identical
// as long as their lengths match
return a.length === b.length && result;
}
parseNegate() {
if (this.nonegate)
return;
const pattern = this.pattern;
let negate = false;
let negateOffset = 0;
for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
negate = !negate;
negateOffset++;
}
if (negateOffset)
this.pattern = pattern.slice(negateOffset);
this.negate = negate;
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne(file, pattern, partial = false) {
const options = this.options;
// UNC paths like //?/X:/... can match X:/... and vice versa
// Drive letters in absolute drive or unc paths are always compared
// case-insensitively.
if (this.isWindows) {
const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
const fileUNC = !fileDrive &&
file[0] === '' &&
file[1] === '' &&
file[2] === '?' &&
/^[a-z]:$/i.test(file[3]);
const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
const patternUNC = !patternDrive &&
pattern[0] === '' &&
pattern[1] === '' &&
pattern[2] === '?' &&
typeof pattern[3] === 'string' &&
/^[a-z]:$/i.test(pattern[3]);
const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
if (typeof fdi === 'number' && typeof pdi === 'number') {
const [fd, pd] = [file[fdi], pattern[pdi]];
if (fd.toLowerCase() === pd.toLowerCase()) {
pattern[pdi] = fd;
if (pdi > fdi) {
pattern = pattern.slice(pdi);
}
else if (fdi > pdi) {
file = file.slice(fdi);
}
}
}
}
// resolve and reduce . and .. portions in the file as well.
// dont' need to do the second phase, because it's only one string[]
const { optimizationLevel = 1 } = this.options;
if (optimizationLevel >= 2) {
file = this.levelTwoFileOptimize(file);
}
this.debug('matchOne', this, { file, pattern });
this.debug('matchOne', file.length, pattern.length);
for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
this.debug('matchOne loop');
var p = pattern[pi];
var f = file[fi];
this.debug(pattern, p, f);
// should be impossible.
// some invalid regexp stuff in the set.
/* c8 ignore start */
if (p === false) {
return false;
}
/* c8 ignore stop */
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f]);
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi;
var pr = pi + 1;
if (pr === pl) {
this.debug('** at the end');
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' ||
file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.'))
return false;
}
return true;
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr];
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee);
// found a match.
return true;
}
else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' ||
swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr);
break;
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue');
fr++;
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
/* c8 ignore start */
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
if (fr === fl) {
return true;
}
}
/* c8 ignore stop */
return false;
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
let hit;
if (typeof p === 'string') {
hit = f === p;
this.debug('string match', p, f, hit);
}
else {
hit = p.test(f);
this.debug('pattern match', p, f, hit);
}
if (!hit)
return false;
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true;
}
else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial;
}
else if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
return fi === fl - 1 && file[fi] === '';
/* c8 ignore start */
}
else {
// should be unreachable.
throw new Error('wtf?');
}
/* c8 ignore stop */
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(pattern) {
assertValidPattern(pattern);
const options = this.options;
// shortcuts
if (pattern === '**')
return GLOBSTAR;
if (pattern === '')
return '';
// far and away, the most common glob pattern parts are
// *, *.*, and *. Add a fast check method for those.
let m;
let fastTest = null;
if ((m = pattern.match(starRE))) {
fastTest = options.dot ? starTestDot : starTest;
}
else if ((m = pattern.match(starDotExtRE))) {
fastTest = (options.nocase
? options.dot
? starDotExtTestNocaseDot
: starDotExtTestNocase
: options.dot
? starDotExtTestDot
: starDotExtTest)(m[1]);
}
else if ((m = pattern.match(qmarksRE))) {
fastTest = (options.nocase
? options.dot
? qmarksTestNocaseDot
: qmarksTestNocase
: options.dot
? qmarksTestDot
: qmarksTest)(m);
}
else if ((m = pattern.match(starDotStarRE))) {
fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
}
else if ((m = pattern.match(dotStarRE))) {
fastTest = dotStarTest;
}
const re = AST.fromGlob(pattern, this.options).toMMPattern();
if (fastTest && typeof re === 'object') {
// Avoids overriding in frozen environments
Reflect.defineProperty(re, 'test', { value: fastTest });
}
return re;
}
makeRe() {
if (this.regexp || this.regexp === false)
return this.regexp;
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
const set = this.set;
if (!set.length) {
this.regexp = false;
return this.regexp;
}
const options = this.options;
const twoStar = options.noglobstar
? esm_star
: options.dot
? twoStarDot
: twoStarNoDot;
const flags = new Set(options.nocase ? ['i'] : []);
// regexpify non-globstar patterns
// if ** is only item, then we just do one twoStar
// if ** is first, and there are more, prepend (\/|twoStar\/)? to next
// if ** is last, append (\/twoStar|) to previous
// if ** is in the middle, append (\/|\/twoStar\/) to previous
// then filter out GLOBSTAR symbols
let re = set
.map(pattern => {
const pp = pattern.map(p => {
if (p instanceof RegExp) {
for (const f of p.flags.split(''))
flags.add(f);
}
return typeof p === 'string'
? esm_regExpEscape(p)
: p === GLOBSTAR
? GLOBSTAR
: p._src;
});
pp.forEach((p, i) => {
const next = pp[i + 1];
const prev = pp[i - 1];
if (p !== GLOBSTAR || prev === GLOBSTAR) {
return;
}
if (prev === undefined) {
if (next !== undefined && next !== GLOBSTAR) {
pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
}
else {
pp[i] = twoStar;
}
}
else if (next === undefined) {
pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
}
else if (next !== GLOBSTAR) {
pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
pp[i + 1] = GLOBSTAR;
}
});
return pp.filter(p => p !== GLOBSTAR).join('/');
})
.join('|');
// need to wrap in parens if we had more than one thing with |,
// otherwise only the first will be anchored to ^ and the last to $
const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^' + open + re + close + '$';
// can match anything, as long as it's not this.
if (this.negate)
re = '^(?!' + re + ').+$';
try {
this.regexp = new RegExp(re, [...flags].join(''));
/* c8 ignore start */
}
catch (ex) {
// should be impossible
this.regexp = false;
}
/* c8 ignore stop */
return this.regexp;
}
slashSplit(p) {
// if p starts with // on windows, we preserve that
// so that UNC paths aren't broken. Otherwise, any number of
// / characters are coalesced into one, unless
// preserveMultipleSlashes is set to true.
if (this.preserveMultipleSlashes) {
return p.split('/');
}
else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
// add an extra '' for the one we lose
return ['', ...p.split(/\/+/)];
}
else {
return p.split(/\/+/);
}
}
match(f, partial = this.partial) {
this.debug('match', f, this.pattern);
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) {
return false;
}
if (this.empty) {
return f === '';
}
if (f === '/' && partial) {
return true;
}
const options = this.options;
// windows: need to use /, not \
if (this.isWindows) {
f = f.split('\\').join('/');
}
// treat the test path as a set of pathparts.
const ff = this.slashSplit(f);
this.debug(this.pattern, 'split', ff);
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
const set = this.set;
this.debug(this.pattern, 'set', set);
// Find the basename of the path by looking for the last non-empty segment
let filename = ff[ff.length - 1];
if (!filename) {
for (let i = ff.length - 2; !filename && i >= 0; i--) {
filename = ff[i];
}
}
for (let i = 0; i < set.length; i++) {
const pattern = set[i];
let file = ff;
if (options.matchBase && pattern.length === 1) {
file = [filename];
}
const hit = this.matchOne(file, pattern, partial);
if (hit) {
if (options.flipNegate) {
return true;
}
return !this.negate;
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) {
return false;
}
return this.negate;
}
static defaults(def) {
return minimatch.defaults(def).Minimatch;
}
}
/* c8 ignore start */
/* c8 ignore stop */
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape_escape;
minimatch.unescape = unescape_unescape;
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: external "node:url"
var external_node_url_ = __webpack_require__(3136);
;// ../commons/node_modules/lru-cache/dist/esm/index.js
/**
* @module LRUCache
*/
const perf = typeof performance === 'object' &&
performance &&
typeof performance.now === 'function'
? performance
: Date;
const warned = new Set();
/* c8 ignore start */
const PROCESS = (typeof process === 'object' && !!process ? process : {});
/* c8 ignore start */
const emitWarning = (msg, type, code, fn) => {
typeof PROCESS.emitWarning === 'function'
? PROCESS.emitWarning(msg, type, code, fn)
: console.error(`[${code}] ${type}: ${msg}`);
};
let AC = globalThis.AbortController;
let AS = globalThis.AbortSignal;
/* c8 ignore start */
if (typeof AC === 'undefined') {
//@ts-ignore
AS = class AbortSignal {
onabort;
_onabort = [];
reason;
aborted = false;
addEventListener(_, fn) {
this._onabort.push(fn);
}
};
//@ts-ignore
AC = class AbortController {
constructor() {
warnACPolyfill();
}
signal = new AS();
abort(reason) {
if (this.signal.aborted)
return;
//@ts-ignore
this.signal.reason = reason;
//@ts-ignore
this.signal.aborted = true;
//@ts-ignore
for (const fn of this.signal._onabort) {
fn(reason);
}
this.signal.onabort?.(reason);
}
};
let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
const warnACPolyfill = () => {
if (!printACPolyfillWarning)
return;
printACPolyfillWarning = false;
emitWarning('AbortController is not defined. If using lru-cache in ' +
'node 14, load an AbortController polyfill from the ' +
'`node-abort-controller` package. A minimal polyfill is ' +
'provided for use by LRUCache.fetch(), but it should not be ' +
'relied upon in other contexts (eg, passing it to other APIs that ' +
'use AbortController/AbortSignal might have undesirable effects). ' +
'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
};
}
/* c8 ignore stop */
const shouldWarn = (code) => !warned.has(code);
const TYPE = Symbol('type');
const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
/* c8 ignore start */
// This is a little bit ridiculous, tbh.
// The maximum array length is 2^32-1 or thereabouts on most JS impls.
// And well before that point, you're caching the entire world, I mean,
// that's ~32GB of just integers for the next/prev links, plus whatever
// else to hold that many keys and values. Just filling the memory with
// zeroes at init time is brutal when you get that big.
// But why not be complete?
// Maybe in the future, these limits will have expanded.
const getUintArray = (max) => !isPosInt(max)
? null
: max <= Math.pow(2, 8)
? Uint8Array
: max <= Math.pow(2, 16)
? Uint16Array
: max <= Math.pow(2, 32)
? Uint32Array
: max <= Number.MAX_SAFE_INTEGER
? ZeroArray
: null;
/* c8 ignore stop */
class ZeroArray extends Array {
constructor(size) {
super(size);
this.fill(0);
}
}
class Stack {
heap;
length;
// private constructor
static #constructing = false;
static create(max) {
const HeapCls = getUintArray(max);
if (!HeapCls)
return [];
Stack.#constructing = true;
const s = new Stack(max, HeapCls);
Stack.#constructing = false;
return s;
}
constructor(max, HeapCls) {
/* c8 ignore start */
if (!Stack.#constructing) {
throw new TypeError('instantiate Stack using Stack.create(n)');
}
/* c8 ignore stop */
this.heap = new HeapCls(max);
this.length = 0;
}
push(n) {
this.heap[this.length++] = n;
}
pop() {
return this.heap[--this.length];
}
}
/**
* Default export, the thing you're using this module to get.
*
* The `K` and `V` types define the key and value types, respectively. The
* optional `FC` type defines the type of the `context` object passed to
* `cache.fetch()` and `cache.memo()`.
*
* Keys and values **must not** be `null` or `undefined`.
*
* All properties from the options object (with the exception of `max`,
* `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
* added as normal public members. (The listed options are read-only getters.)
*
* Changing any of these will alter the defaults for subsequent method calls.
*/
class LRUCache {
// options that cannot be changed without disaster
#max;
#maxSize;
#dispose;
#disposeAfter;
#fetchMethod;
#memoMethod;
/**
* {@link LRUCache.OptionsBase.ttl}
*/
ttl;
/**
* {@link LRUCache.OptionsBase.ttlResolution}
*/
ttlResolution;
/**
* {@link LRUCache.OptionsBase.ttlAutopurge}
*/
ttlAutopurge;
/**
* {@link LRUCache.OptionsBase.updateAgeOnGet}
*/
updateAgeOnGet;
/**
* {@link LRUCache.OptionsBase.updateAgeOnHas}
*/
updateAgeOnHas;
/**
* {@link LRUCache.OptionsBase.allowStale}
*/
allowStale;
/**
* {@link LRUCache.OptionsBase.noDisposeOnSet}
*/
noDisposeOnSet;
/**
* {@link LRUCache.OptionsBase.noUpdateTTL}
*/
noUpdateTTL;
/**
* {@link LRUCache.OptionsBase.maxEntrySize}
*/
maxEntrySize;
/**
* {@link LRUCache.OptionsBase.sizeCalculation}
*/
sizeCalculation;
/**
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
*/
noDeleteOnFetchRejection;
/**
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
*/
noDeleteOnStaleGet;
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
*/
allowStaleOnFetchAbort;
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
*/
allowStaleOnFetchRejection;
/**
* {@link LRUCache.OptionsBase.ignoreFetchAbort}
*/
ignoreFetchAbort;
// computed properties
#size;
#calculatedSize;
#keyMap;
#keyList;
#valList;
#next;
#prev;
#head;
#tail;
#free;
#disposed;
#sizes;
#starts;
#ttls;
#hasDispose;
#hasFetchMethod;
#hasDisposeAfter;
/**
* Do not call this method unless you need to inspect the
* inner workings of the cache. If anything returned by this
* object is modified in any way, strange breakage may occur.
*
* These fields are private for a reason!
*
* @internal
*/
static unsafeExposeInternals(c) {
return {
// properties
starts: c.#starts,
ttls: c.#ttls,
sizes: c.#sizes,
keyMap: c.#keyMap,
keyList: c.#keyList,
valList: c.#valList,
next: c.#next,
prev: c.#prev,
get head() {
return c.#head;
},
get tail() {
return c.#tail;
},
free: c.#free,
// methods
isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
moveToTail: (index) => c.#moveToTail(index),
indexes: (options) => c.#indexes(options),
rindexes: (options) => c.#rindexes(options),
isStale: (index) => c.#isStale(index),
};
}
// Protected read-only members
/**
* {@link LRUCache.OptionsBase.max} (read-only)
*/
get max() {
return this.#max;
}
/**
* {@link LRUCache.OptionsBase.maxSize} (read-only)
*/
get maxSize() {
return this.#maxSize;
}
/**
* The total computed size of items in the cache (read-only)
*/
get calculatedSize() {
return this.#calculatedSize;
}
/**
* The number of items stored in the cache (read-only)
*/
get size() {
return this.#size;
}
/**
* {@link LRUCache.OptionsBase.fetchMethod} (read-only)
*/
get fetchMethod() {
return this.#fetchMethod;
}
get memoMethod() {
return this.#memoMethod;
}
/**
* {@link LRUCache.OptionsBase.dispose} (read-only)
*/
get dispose() {
return this.#dispose;
}
/**
* {@link LRUCache.OptionsBase.disposeAfter} (read-only)
*/
get disposeAfter() {
return this.#disposeAfter;
}
constructor(options) {
const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
if (max !== 0 && !isPosInt(max)) {
throw new TypeError('max option must be a nonnegative integer');
}
const UintArray = max ? getUintArray(max) : Array;
if (!UintArray) {
throw new Error('invalid max value: ' + max);
}
this.#max = max;
this.#maxSize = maxSize;
this.maxEntrySize = maxEntrySize || this.#maxSize;
this.sizeCalculation = sizeCalculation;
if (this.sizeCalculation) {
if (!this.#maxSize && !this.maxEntrySize) {
throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
}
if (typeof this.sizeCalculation !== 'function') {
throw new TypeError('sizeCalculation set to non-function');
}
}
if (memoMethod !== undefined &&
typeof memoMethod !== 'function') {
throw new TypeError('memoMethod must be a function if defined');
}
this.#memoMethod = memoMethod;
if (fetchMethod !== undefined &&
typeof fetchMethod !== 'function') {
throw new TypeError('fetchMethod must be a function if specified');
}
this.#fetchMethod = fetchMethod;
this.#hasFetchMethod = !!fetchMethod;
this.#keyMap = new Map();
this.#keyList = new Array(max).fill(undefined);
this.#valList = new Array(max).fill(undefined);
this.#next = new UintArray(max);
this.#prev = new UintArray(max);
this.#head = 0;
this.#tail = 0;
this.#free = Stack.create(max);
this.#size = 0;
this.#calculatedSize = 0;
if (typeof dispose === 'function') {
this.#dispose = dispose;
}
if (typeof disposeAfter === 'function') {
this.#disposeAfter = disposeAfter;
this.#disposed = [];
}
else {
this.#disposeAfter = undefined;
this.#disposed = undefined;
}
this.#hasDispose = !!this.#dispose;
this.#hasDisposeAfter = !!this.#disposeAfter;
this.noDisposeOnSet = !!noDisposeOnSet;
this.noUpdateTTL = !!noUpdateTTL;
this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
this.ignoreFetchAbort = !!ignoreFetchAbort;
// NB: maxEntrySize is set to maxSize if it's set
if (this.maxEntrySize !== 0) {
if (this.#maxSize !== 0) {
if (!isPosInt(this.#maxSize)) {
throw new TypeError('maxSize must be a positive integer if specified');
}
}
if (!isPosInt(this.maxEntrySize)) {
throw new TypeError('maxEntrySize must be a positive integer if specified');
}
this.#initializeSizeTracking();
}
this.allowStale = !!allowStale;
this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
this.updateAgeOnGet = !!updateAgeOnGet;
this.updateAgeOnHas = !!updateAgeOnHas;
this.ttlResolution =
isPosInt(ttlResolution) || ttlResolution === 0
? ttlResolution
: 1;
this.ttlAutopurge = !!ttlAutopurge;
this.ttl = ttl || 0;
if (this.ttl) {
if (!isPosInt(this.ttl)) {
throw new TypeError('ttl must be a positive integer if specified');
}
this.#initializeTTLTracking();
}
// do not allow completely unbounded caches
if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
throw new TypeError('At least one of max, maxSize, or ttl is required');
}
if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
const code = 'LRU_CACHE_UNBOUNDED';
if (shouldWarn(code)) {
warned.add(code);
const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
'result in unbounded memory consumption.';
emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
}
}
}
/**
* Return the number of ms left in the item's TTL. If item is not in cache,
* returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
*/
getRemainingTTL(key) {
return this.#keyMap.has(key) ? Infinity : 0;
}
#initializeTTLTracking() {
const ttls = new ZeroArray(this.#max);
const starts = new ZeroArray(this.#max);
this.#ttls = ttls;
this.#starts = starts;
this.#setItemTTL = (index, ttl, start = perf.now()) => {
starts[index] = ttl !== 0 ? start : 0;
ttls[index] = ttl;
if (ttl !== 0 && this.ttlAutopurge) {
const t = setTimeout(() => {
if (this.#isStale(index)) {
this.#delete(this.#keyList[index], 'expire');
}
}, ttl + 1);
// unref() not supported on all platforms
/* c8 ignore start */
if (t.unref) {
t.unref();
}
/* c8 ignore stop */
}
};
this.#updateItemAge = index => {
starts[index] = ttls[index] !== 0 ? perf.now() : 0;
};
this.#statusTTL = (status, index) => {
if (ttls[index]) {
const ttl = ttls[index];
const start = starts[index];
/* c8 ignore next */
if (!ttl || !start)
return;
status.ttl = ttl;
status.start = start;
status.now = cachedNow || getNow();
const age = status.now - start;
status.remainingTTL = ttl - age;
}
};
// debounce calls to perf.now() to 1s so we're not hitting
// that costly call repeatedly.
let cachedNow = 0;
const getNow = () => {
const n = perf.now();
if (this.ttlResolution > 0) {
cachedNow = n;
const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
// not available on all platforms
/* c8 ignore start */
if (t.unref) {
t.unref();
}
/* c8 ignore stop */
}
return n;
};
this.getRemainingTTL = key => {
const index = this.#keyMap.get(key);
if (index === undefined) {
return 0;
}
const ttl = ttls[index];
const start = starts[index];
if (!ttl || !start) {
return Infinity;
}
const age = (cachedNow || getNow()) - start;
return ttl - age;
};
this.#isStale = index => {
const s = starts[index];
const t = ttls[index];
return !!t && !!s && (cachedNow || getNow()) - s > t;
};
}
// conditionally set private methods related to TTL
#updateItemAge = () => { };
#statusTTL = () => { };
#setItemTTL = () => { };
/* c8 ignore stop */
#isStale = () => false;
#initializeSizeTracking() {
const sizes = new ZeroArray(this.#max);
this.#calculatedSize = 0;
this.#sizes = sizes;
this.#removeItemSize = index => {
this.#calculatedSize -= sizes[index];
sizes[index] = 0;
};
this.#requireSize = (k, v, size, sizeCalculation) => {
// provisionally accept background fetches.
// actual value size will be checked when they return.
if (this.#isBackgroundFetch(v)) {
return 0;
}
if (!isPosInt(size)) {
if (sizeCalculation) {
if (typeof sizeCalculation !== 'function') {
throw new TypeError('sizeCalculation must be a function');
}
size = sizeCalculation(v, k);
if (!isPosInt(size)) {
throw new TypeError('sizeCalculation return invalid (expect positive integer)');
}
}
else {
throw new TypeError('invalid size value (must be positive integer). ' +
'When maxSize or maxEntrySize is used, sizeCalculation ' +
'or size must be set.');
}
}
return size;
};
this.#addItemSize = (index, size, status) => {
sizes[index] = size;
if (this.#maxSize) {
const maxSize = this.#maxSize - sizes[index];
while (this.#calculatedSize > maxSize) {
this.#evict(true);
}
}
this.#calculatedSize += sizes[index];
if (status) {
status.entrySize = size;
status.totalCalculatedSize = this.#calculatedSize;
}
};
}
#removeItemSize = _i => { };
#addItemSize = (_i, _s, _st) => { };
#requireSize = (_k, _v, size, sizeCalculation) => {
if (size || sizeCalculation) {
throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
}
return 0;
};
*#indexes({ allowStale = this.allowStale } = {}) {
if (this.#size) {
for (let i = this.#tail; true;) {
if (!this.#isValidIndex(i)) {
break;
}
if (allowStale || !this.#isStale(i)) {
yield i;
}
if (i === this.#head) {
break;
}
else {
i = this.#prev[i];
}
}
}
}
*#rindexes({ allowStale = this.allowStale } = {}) {
if (this.#size) {
for (let i = this.#head; true;) {
if (!this.#isValidIndex(i)) {
break;
}
if (allowStale || !this.#isStale(i)) {
yield i;
}
if (i === this.#tail) {
break;
}
else {
i = this.#next[i];
}
}
}
}
#isValidIndex(index) {
return (index !== undefined &&
this.#keyMap.get(this.#keyList[index]) === index);
}
/**
* Return a generator yielding `[key, value]` pairs,
* in order from most recently used to least recently used.
*/
*entries() {
for (const i of this.#indexes()) {
if (this.#valList[i] !== undefined &&
this.#keyList[i] !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield [this.#keyList[i], this.#valList[i]];
}
}
}
/**
* Inverse order version of {@link LRUCache.entries}
*
* Return a generator yielding `[key, value]` pairs,
* in order from least recently used to most recently used.
*/
*rentries() {
for (const i of this.#rindexes()) {
if (this.#valList[i] !== undefined &&
this.#keyList[i] !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield [this.#keyList[i], this.#valList[i]];
}
}
}
/**
* Return a generator yielding the keys in the cache,
* in order from most recently used to least recently used.
*/
*keys() {
for (const i of this.#indexes()) {
const k = this.#keyList[i];
if (k !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield k;
}
}
}
/**
* Inverse order version of {@link LRUCache.keys}
*
* Return a generator yielding the keys in the cache,
* in order from least recently used to most recently used.
*/
*rkeys() {
for (const i of this.#rindexes()) {
const k = this.#keyList[i];
if (k !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield k;
}
}
}
/**
* Return a generator yielding the values in the cache,
* in order from most recently used to least recently used.
*/
*values() {
for (const i of this.#indexes()) {
const v = this.#valList[i];
if (v !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield this.#valList[i];
}
}
}
/**
* Inverse order version of {@link LRUCache.values}
*
* Return a generator yielding the values in the cache,
* in order from least recently used to most recently used.
*/
*rvalues() {
for (const i of this.#rindexes()) {
const v = this.#valList[i];
if (v !== undefined &&
!this.#isBackgroundFetch(this.#valList[i])) {
yield this.#valList[i];
}
}
}
/**
* Iterating over the cache itself yields the same results as
* {@link LRUCache.entries}
*/
[Symbol.iterator]() {
return this.entries();
}
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method
* `Object.prototype.toString`.
*/
[Symbol.toStringTag] = 'LRUCache';
/**
* Find a value for which the supplied fn method returns a truthy value,
* similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
*/
find(fn, getOptions = {}) {
for (const i of this.#indexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
if (fn(value, this.#keyList[i], this)) {
return this.get(this.#keyList[i], getOptions);
}
}
}
/**
* Call the supplied function on each item in the cache, in order from most
* recently used to least recently used.
*
* `fn` is called as `fn(value, key, cache)`.
*
* If `thisp` is provided, function will be called in the `this`-context of
* the provided object, or the cache if no `thisp` object is provided.
*
* Does not update age or recenty of use, or iterate over stale values.
*/
forEach(fn, thisp = this) {
for (const i of this.#indexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
fn.call(thisp, value, this.#keyList[i], this);
}
}
/**
* The same as {@link LRUCache.forEach} but items are iterated over in
* reverse order. (ie, less recently used items are iterated over first.)
*/
rforEach(fn, thisp = this) {
for (const i of this.#rindexes()) {
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
continue;
fn.call(thisp, value, this.#keyList[i], this);
}
}
/**
* Delete any stale entries. Returns true if anything was removed,
* false otherwise.
*/
purgeStale() {
let deleted = false;
for (const i of this.#rindexes({ allowStale: true })) {
if (this.#isStale(i)) {
this.#delete(this.#keyList[i], 'expire');
deleted = true;
}
}
return deleted;
}
/**
* Get the extended info about a given entry, to get its value, size, and
* TTL info simultaneously. Returns `undefined` if the key is not present.
*
* Unlike {@link LRUCache#dump}, which is designed to be portable and survive
* serialization, the `start` value is always the current timestamp, and the
* `ttl` is a calculated remaining time to live (negative if expired).
*
* Always returns stale values, if their info is found in the cache, so be
* sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
* if relevant.
*/
info(key) {
const i = this.#keyMap.get(key);
if (i === undefined)
return undefined;
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined)
return undefined;
const entry = { value };
if (this.#ttls && this.#starts) {
const ttl = this.#ttls[i];
const start = this.#starts[i];
if (ttl && start) {
const remain = ttl - (perf.now() - start);
entry.ttl = remain;
entry.start = Date.now();
}
}
if (this.#sizes) {
entry.size = this.#sizes[i];
}
return entry;
}
/**
* Return an array of [key, {@link LRUCache.Entry}] tuples which can be
* passed to {@link LRLUCache#load}.
*
* The `start` fields are calculated relative to a portable `Date.now()`
* timestamp, even if `performance.now()` is available.
*
* Stale entries are always included in the `dump`, even if
* {@link LRUCache.OptionsBase.allowStale} is false.
*
* Note: this returns an actual array, not a generator, so it can be more
* easily passed around.
*/
dump() {
const arr = [];
for (const i of this.#indexes({ allowStale: true })) {
const key = this.#keyList[i];
const v = this.#valList[i];
const value = this.#isBackgroundFetch(v)
? v.__staleWhileFetching
: v;
if (value === undefined || key === undefined)
continue;
const entry = { value };
if (this.#ttls && this.#starts) {
entry.ttl = this.#ttls[i];
// always dump the start relative to a portable timestamp
// it's ok for this to be a bit slow, it's a rare operation.
const age = perf.now() - this.#starts[i];
entry.start = Math.floor(Date.now() - age);
}
if (this.#sizes) {
entry.size = this.#sizes[i];
}
arr.unshift([key, entry]);
}
return arr;
}
/**
* Reset the cache and load in the items in entries in the order listed.
*
* The shape of the resulting cache may be different if the same options are
* not used in both caches.
*
* The `start` fields are assumed to be calculated relative to a portable
* `Date.now()` timestamp, even if `performance.now()` is available.
*/
load(arr) {
this.clear();
for (const [key, entry] of arr) {
if (entry.start) {
// entry.start is a portable timestamp, but we may be using
// node's performance.now(), so calculate the offset, so that
// we get the intended remaining TTL, no matter how long it's
// been on ice.
//
// it's ok for this to be a bit slow, it's a rare operation.
const age = Date.now() - entry.start;
entry.start = perf.now() - age;
}
this.set(key, entry.value, entry);
}
}
/**
* Add a value to the cache.
*
* Note: if `undefined` is specified as a value, this is an alias for
* {@link LRUCache#delete}
*
* Fields on the {@link LRUCache.SetOptions} options param will override
* their corresponding values in the constructor options for the scope
* of this single `set()` operation.
*
* If `start` is provided, then that will set the effective start
* time for the TTL calculation. Note that this must be a previous
* value of `performance.now()` if supported, or a previous value of
* `Date.now()` if not.
*
* Options object may also include `size`, which will prevent
* calling the `sizeCalculation` function and just use the specified
* number if it is a positive integer, and `noDisposeOnSet` which
* will prevent calling a `dispose` function in the case of
* overwrites.
*
* If the `size` (or return value of `sizeCalculation`) for a given
* entry is greater than `maxEntrySize`, then the item will not be
* added to the cache.
*
* Will update the recency of the entry.
*
* If the value is `undefined`, then this is an alias for
* `cache.delete(key)`. `undefined` is never stored in the cache.
*/
set(k, v, setOptions = {}) {
if (v === undefined) {
this.delete(k);
return this;
}
const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
let { noUpdateTTL = this.noUpdateTTL } = setOptions;
const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
// if the item doesn't fit, don't do anything
// NB: maxEntrySize set to maxSize by default
if (this.maxEntrySize && size > this.maxEntrySize) {
if (status) {
status.set = 'miss';
status.maxEntrySizeExceeded = true;
}
// have to delete, in case something is there already.
this.#delete(k, 'set');
return this;
}
let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
if (index === undefined) {
// addition
index = (this.#size === 0
? this.#tail
: this.#free.length !== 0
? this.#free.pop()
: this.#size === this.#max
? this.#evict(false)
: this.#size);
this.#keyList[index] = k;
this.#valList[index] = v;
this.#keyMap.set(k, index);
this.#next[this.#tail] = index;
this.#prev[index] = this.#tail;
this.#tail = index;
this.#size++;
this.#addItemSize(index, size, status);
if (status)
status.set = 'add';
noUpdateTTL = false;
}
else {
// update
this.#moveToTail(index);
const oldVal = this.#valList[index];
if (v !== oldVal) {
if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
oldVal.__abortController.abort(new Error('replaced'));
const { __staleWhileFetching: s } = oldVal;
if (s !== undefined && !noDisposeOnSet) {
if (this.#hasDispose) {
this.#dispose?.(s, k, 'set');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([s, k, 'set']);
}
}
}
else if (!noDisposeOnSet) {
if (this.#hasDispose) {
this.#dispose?.(oldVal, k, 'set');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([oldVal, k, 'set']);
}
}
this.#removeItemSize(index);
this.#addItemSize(index, size, status);
this.#valList[index] = v;
if (status) {
status.set = 'replace';
const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
? oldVal.__staleWhileFetching
: oldVal;
if (oldValue !== undefined)
status.oldValue = oldValue;
}
}
else if (status) {
status.set = 'update';
}
}
if (ttl !== 0 && !this.#ttls) {
this.#initializeTTLTracking();
}
if (this.#ttls) {
if (!noUpdateTTL) {
this.#setItemTTL(index, ttl, start);
}
if (status)
this.#statusTTL(status, index);
}
if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
return this;
}
/**
* Evict the least recently used item, returning its value or
* `undefined` if cache is empty.
*/
pop() {
try {
while (this.#size) {
const val = this.#valList[this.#head];
this.#evict(true);
if (this.#isBackgroundFetch(val)) {
if (val.__staleWhileFetching) {
return val.__staleWhileFetching;
}
}
else if (val !== undefined) {
return val;
}
}
}
finally {
if (this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
}
}
#evict(free) {
const head = this.#head;
const k = this.#keyList[head];
const v = this.#valList[head];
if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('evicted'));
}
else if (this.#hasDispose || this.#hasDisposeAfter) {
if (this.#hasDispose) {
this.#dispose?.(v, k, 'evict');
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, 'evict']);
}
}
this.#removeItemSize(head);
// if we aren't about to use the index, then null these out
if (free) {
this.#keyList[head] = undefined;
this.#valList[head] = undefined;
this.#free.push(head);
}
if (this.#size === 1) {
this.#head = this.#tail = 0;
this.#free.length = 0;
}
else {
this.#head = this.#next[head];
}
this.#keyMap.delete(k);
this.#size--;
return head;
}
/**
* Check if a key is in the cache, without updating the recency of use.
* Will return false if the item is stale, even though it is technically
* in the cache.
*
* Check if a key is in the cache, without updating the recency of
* use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
* to `true` in either the options or the constructor.
*
* Will return `false` if the item is stale, even though it is technically in
* the cache. The difference can be determined (if it matters) by using a
* `status` argument, and inspecting the `has` field.
*
* Will not update item age unless
* {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
*/
has(k, hasOptions = {}) {
const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
const index = this.#keyMap.get(k);
if (index !== undefined) {
const v = this.#valList[index];
if (this.#isBackgroundFetch(v) &&
v.__staleWhileFetching === undefined) {
return false;
}
if (!this.#isStale(index)) {
if (updateAgeOnHas) {
this.#updateItemAge(index);
}
if (status) {
status.has = 'hit';
this.#statusTTL(status, index);
}
return true;
}
else if (status) {
status.has = 'stale';
this.#statusTTL(status, index);
}
}
else if (status) {
status.has = 'miss';
}
return false;
}
/**
* Like {@link LRUCache#get} but doesn't update recency or delete stale
* items.
*
* Returns `undefined` if the item is stale, unless
* {@link LRUCache.OptionsBase.allowStale} is set.
*/
peek(k, peekOptions = {}) {
const { allowStale = this.allowStale } = peekOptions;
const index = this.#keyMap.get(k);
if (index === undefined ||
(!allowStale && this.#isStale(index))) {
return;
}
const v = this.#valList[index];
// either stale and allowed, or forcing a refresh of non-stale value
return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
}
#backgroundFetch(k, index, options, context) {
const v = index === undefined ? undefined : this.#valList[index];
if (this.#isBackgroundFetch(v)) {
return v;
}
const ac = new AC();
const { signal } = options;
// when/if our AC signals, then stop listening to theirs.
signal?.addEventListener('abort', () => ac.abort(signal.reason), {
signal: ac.signal,
});
const fetchOpts = {
signal: ac.signal,
options,
context,
};
const cb = (v, updateCache = false) => {
const { aborted } = ac.signal;
const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
if (options.status) {
if (aborted && !updateCache) {
options.status.fetchAborted = true;
options.status.fetchError = ac.signal.reason;
if (ignoreAbort)
options.status.fetchAbortIgnored = true;
}
else {
options.status.fetchResolved = true;
}
}
if (aborted && !ignoreAbort && !updateCache) {
return fetchFail(ac.signal.reason);
}
// either we didn't abort, and are still here, or we did, and ignored
const bf = p;
if (this.#valList[index] === p) {
if (v === undefined) {
if (bf.__staleWhileFetching) {
this.#valList[index] = bf.__staleWhileFetching;
}
else {
this.#delete(k, 'fetch');
}
}
else {
if (options.status)
options.status.fetchUpdated = true;
this.set(k, v, fetchOpts.options);
}
}
return v;
};
const eb = (er) => {
if (options.status) {
options.status.fetchRejected = true;
options.status.fetchError = er;
}
return fetchFail(er);
};
const fetchFail = (er) => {
const { aborted } = ac.signal;
const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
const noDelete = allowStale || options.noDeleteOnFetchRejection;
const bf = p;
if (this.#valList[index] === p) {
// if we allow stale on fetch rejections, then we need to ensure that
// the stale value is not removed from the cache when the fetch fails.
const del = !noDelete || bf.__staleWhileFetching === undefined;
if (del) {
this.#delete(k, 'fetch');
}
else if (!allowStaleAborted) {
// still replace the *promise* with the stale value,
// since we are done with the promise at this point.
// leave it untouched if we're still waiting for an
// aborted background fetch that hasn't yet returned.
this.#valList[index] = bf.__staleWhileFetching;
}
}
if (allowStale) {
if (options.status && bf.__staleWhileFetching !== undefined) {
options.status.returnedStale = true;
}
return bf.__staleWhileFetching;
}
else if (bf.__returned === bf) {
throw er;
}
};
const pcall = (res, rej) => {
const fmp = this.#fetchMethod?.(k, v, fetchOpts);
if (fmp && fmp instanceof Promise) {
fmp.then(v => res(v === undefined ? undefined : v), rej);
}
// ignored, we go until we finish, regardless.
// defer check until we are actually aborting,
// so fetchMethod can override.
ac.signal.addEventListener('abort', () => {
if (!options.ignoreFetchAbort ||
options.allowStaleOnFetchAbort) {
res(undefined);
// when it eventually resolves, update the cache.
if (options.allowStaleOnFetchAbort) {
res = v => cb(v, true);
}
}
});
};
if (options.status)
options.status.fetchDispatched = true;
const p = new Promise(pcall).then(cb, eb);
const bf = Object.assign(p, {
__abortController: ac,
__staleWhileFetching: v,
__returned: undefined,
});
if (index === undefined) {
// internal, don't expose status.
this.set(k, bf, { ...fetchOpts.options, status: undefined });
index = this.#keyMap.get(k);
}
else {
this.#valList[index] = bf;
}
return bf;
}
#isBackgroundFetch(p) {
if (!this.#hasFetchMethod)
return false;
const b = p;
return (!!b &&
b instanceof Promise &&
b.hasOwnProperty('__staleWhileFetching') &&
b.__abortController instanceof AC);
}
async fetch(k, fetchOptions = {}) {
const {
// get options
allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
// set options
ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
// fetch exclusive options
noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
if (!this.#hasFetchMethod) {
if (status)
status.fetch = 'get';
return this.get(k, {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
status,
});
}
const options = {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
ttl,
noDisposeOnSet,
size,
sizeCalculation,
noUpdateTTL,
noDeleteOnFetchRejection,
allowStaleOnFetchRejection,
allowStaleOnFetchAbort,
ignoreFetchAbort,
status,
signal,
};
let index = this.#keyMap.get(k);
if (index === undefined) {
if (status)
status.fetch = 'miss';
const p = this.#backgroundFetch(k, index, options, context);
return (p.__returned = p);
}
else {
// in cache, maybe already fetching
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
const stale = allowStale && v.__staleWhileFetching !== undefined;
if (status) {
status.fetch = 'inflight';
if (stale)
status.returnedStale = true;
}
return stale ? v.__staleWhileFetching : (v.__returned = v);
}
// if we force a refresh, that means do NOT serve the cached value,
// unless we are already in the process of refreshing the cache.
const isStale = this.#isStale(index);
if (!forceRefresh && !isStale) {
if (status)
status.fetch = 'hit';
this.#moveToTail(index);
if (updateAgeOnGet) {
this.#updateItemAge(index);
}
if (status)
this.#statusTTL(status, index);
return v;
}
// ok, it is stale or a forced refresh, and not already fetching.
// refresh the cache.
const p = this.#backgroundFetch(k, index, options, context);
const hasStale = p.__staleWhileFetching !== undefined;
const staleVal = hasStale && allowStale;
if (status) {
status.fetch = isStale ? 'stale' : 'refresh';
if (staleVal && isStale)
status.returnedStale = true;
}
return staleVal ? p.__staleWhileFetching : (p.__returned = p);
}
}
async forceFetch(k, fetchOptions = {}) {
const v = await this.fetch(k, fetchOptions);
if (v === undefined)
throw new Error('fetch() returned undefined');
return v;
}
memo(k, memoOptions = {}) {
const memoMethod = this.#memoMethod;
if (!memoMethod) {
throw new Error('no memoMethod provided to constructor');
}
const { context, forceRefresh, ...options } = memoOptions;
const v = this.get(k, options);
if (!forceRefresh && v !== undefined)
return v;
const vv = memoMethod(k, v, {
options,
context,
});
this.set(k, vv, options);
return vv;
}
/**
* Return a value from the cache. Will update the recency of the cache
* entry found.
*
* If the key is not found, get() will return `undefined`.
*/
get(k, getOptions = {}) {
const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
const index = this.#keyMap.get(k);
if (index !== undefined) {
const value = this.#valList[index];
const fetching = this.#isBackgroundFetch(value);
if (status)
this.#statusTTL(status, index);
if (this.#isStale(index)) {
if (status)
status.get = 'stale';
// delete only if not an in-flight background fetch
if (!fetching) {
if (!noDeleteOnStaleGet) {
this.#delete(k, 'expire');
}
if (status && allowStale)
status.returnedStale = true;
return allowStale ? value : undefined;
}
else {
if (status &&
allowStale &&
value.__staleWhileFetching !== undefined) {
status.returnedStale = true;
}
return allowStale ? value.__staleWhileFetching : undefined;
}
}
else {
if (status)
status.get = 'hit';
// if we're currently fetching it, we don't actually have it yet
// it's not stale, which means this isn't a staleWhileRefetching.
// If it's not stale, and fetching, AND has a __staleWhileFetching
// value, then that means the user fetched with {forceRefresh:true},
// so it's safe to return that value.
if (fetching) {
return value.__staleWhileFetching;
}
this.#moveToTail(index);
if (updateAgeOnGet) {
this.#updateItemAge(index);
}
return value;
}
}
else if (status) {
status.get = 'miss';
}
}
#connect(p, n) {
this.#prev[n] = p;
this.#next[p] = n;
}
#moveToTail(index) {
// if tail already, nothing to do
// if head, move head to next[index]
// else
// move next[prev[index]] to next[index] (head has no prev)
// move prev[next[index]] to prev[index]
// prev[index] = tail
// next[tail] = index
// tail = index
if (index !== this.#tail) {
if (index === this.#head) {
this.#head = this.#next[index];
}
else {
this.#connect(this.#prev[index], this.#next[index]);
}
this.#connect(this.#tail, index);
this.#tail = index;
}
}
/**
* Deletes a key out of the cache.
*
* Returns true if the key was deleted, false otherwise.
*/
delete(k) {
return this.#delete(k, 'delete');
}
#delete(k, reason) {
let deleted = false;
if (this.#size !== 0) {
const index = this.#keyMap.get(k);
if (index !== undefined) {
deleted = true;
if (this.#size === 1) {
this.#clear(reason);
}
else {
this.#removeItemSize(index);
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('deleted'));
}
else if (this.#hasDispose || this.#hasDisposeAfter) {
if (this.#hasDispose) {
this.#dispose?.(v, k, reason);
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, reason]);
}
}
this.#keyMap.delete(k);
this.#keyList[index] = undefined;
this.#valList[index] = undefined;
if (index === this.#tail) {
this.#tail = this.#prev[index];
}
else if (index === this.#head) {
this.#head = this.#next[index];
}
else {
const pi = this.#prev[index];
this.#next[pi] = this.#next[index];
const ni = this.#next[index];
this.#prev[ni] = this.#prev[index];
}
this.#size--;
this.#free.push(index);
}
}
}
if (this.#hasDisposeAfter && this.#disposed?.length) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
return deleted;
}
/**
* Clear the cache entirely, throwing away all values.
*/
clear() {
return this.#clear('delete');
}
#clear(reason) {
for (const index of this.#rindexes({ allowStale: true })) {
const v = this.#valList[index];
if (this.#isBackgroundFetch(v)) {
v.__abortController.abort(new Error('deleted'));
}
else {
const k = this.#keyList[index];
if (this.#hasDispose) {
this.#dispose?.(v, k, reason);
}
if (this.#hasDisposeAfter) {
this.#disposed?.push([v, k, reason]);
}
}
}
this.#keyMap.clear();
this.#valList.fill(undefined);
this.#keyList.fill(undefined);
if (this.#ttls && this.#starts) {
this.#ttls.fill(0);
this.#starts.fill(0);
}
if (this.#sizes) {
this.#sizes.fill(0);
}
this.#head = 0;
this.#tail = 0;
this.#free.length = 0;
this.#calculatedSize = 0;
this.#size = 0;
if (this.#hasDisposeAfter && this.#disposed) {
const dt = this.#disposed;
let task;
while ((task = dt?.shift())) {
this.#disposeAfter?.(...task);
}
}
}
}
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __webpack_require__(6760);
// EXTERNAL MODULE: external "node:fs"
var external_node_fs_ = __webpack_require__(3024);
var external_node_fs_namespaceObject = /*#__PURE__*/__webpack_require__.t(external_node_fs_, 2);
// EXTERNAL MODULE: external "node:fs/promises"
var promises_ = __webpack_require__(1455);
// EXTERNAL MODULE: external "node:events"
var external_node_events_ = __webpack_require__(8474);
// EXTERNAL MODULE: external "node:stream"
var external_node_stream_ = __webpack_require__(7075);
// EXTERNAL MODULE: external "node:string_decoder"
var external_node_string_decoder_ = __webpack_require__(6193);
;// ../commons/node_modules/minipass/dist/esm/index.js
const proc = typeof process === 'object' && process
? process
: {
stdout: null,
stderr: null,
};
/**
* Return true if the argument is a Minipass stream, Node stream, or something
* else that Minipass can interact with.
*/
const isStream = (s) => !!s &&
typeof s === 'object' &&
(s instanceof Minipass ||
s instanceof external_node_stream_ ||
isReadable(s) ||
isWritable(s));
/**
* Return true if the argument is a valid {@link Minipass.Readable}
*/
const isReadable = (s) => !!s &&
typeof s === 'object' &&
s instanceof external_node_events_.EventEmitter &&
typeof s.pipe === 'function' &&
// node core Writable streams have a pipe() method, but it throws
s.pipe !== external_node_stream_.Writable.prototype.pipe;
/**
* Return true if the argument is a valid {@link Minipass.Writable}
*/
const isWritable = (s) => !!s &&
typeof s === 'object' &&
s instanceof external_node_events_.EventEmitter &&
typeof s.write === 'function' &&
typeof s.end === 'function';
const EOF = Symbol('EOF');
const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
const EMITTED_END = Symbol('emittedEnd');
const EMITTING_END = Symbol('emittingEnd');
const EMITTED_ERROR = Symbol('emittedError');
const CLOSED = Symbol('closed');
const READ = Symbol('read');
const FLUSH = Symbol('flush');
const FLUSHCHUNK = Symbol('flushChunk');
const ENCODING = Symbol('encoding');
const DECODER = Symbol('decoder');
const FLOWING = Symbol('flowing');
const PAUSED = Symbol('paused');
const RESUME = Symbol('resume');
const BUFFER = Symbol('buffer');
const PIPES = Symbol('pipes');
const BUFFERLENGTH = Symbol('bufferLength');
const BUFFERPUSH = Symbol('bufferPush');
const BUFFERSHIFT = Symbol('bufferShift');
const OBJECTMODE = Symbol('objectMode');
// internal event when stream is destroyed
const DESTROYED = Symbol('destroyed');
// internal event when stream has an error
const ERROR = Symbol('error');
const EMITDATA = Symbol('emitData');
const EMITEND = Symbol('emitEnd');
const EMITEND2 = Symbol('emitEnd2');
const ASYNC = Symbol('async');
const ABORT = Symbol('abort');
const ABORTED = Symbol('aborted');
const SIGNAL = Symbol('signal');
const DATALISTENERS = Symbol('dataListeners');
const DISCARDED = Symbol('discarded');
const defer = (fn) => Promise.resolve().then(fn);
const nodefer = (fn) => fn();
const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
(!!b &&
typeof b === 'object' &&
b.constructor &&
b.constructor.name === 'ArrayBuffer' &&
b.byteLength >= 0);
const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
/**
* Internal class representing a pipe to a destination stream.
*
* @internal
*/
class Pipe {
src;
dest;
opts;
ondrain;
constructor(src, dest, opts) {
this.src = src;
this.dest = dest;
this.opts = opts;
this.ondrain = () => src[RESUME]();
this.dest.on('drain', this.ondrain);
}
unpipe() {
this.dest.removeListener('drain', this.ondrain);
}
// only here for the prototype
/* c8 ignore start */
proxyErrors(_er) { }
/* c8 ignore stop */
end() {
this.unpipe();
if (this.opts.end)
this.dest.end();
}
}
/**
* Internal class representing a pipe to a destination stream where
* errors are proxied.
*
* @internal
*/
class PipeProxyErrors extends Pipe {
unpipe() {
this.src.removeListener('error', this.proxyErrors);
super.unpipe();
}
constructor(src, dest, opts) {
super(src, dest, opts);
this.proxyErrors = er => dest.emit('error', er);
src.on('error', this.proxyErrors);
}
}
const isObjectModeOptions = (o) => !!o.objectMode;
const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
/**
* Main export, the Minipass class
*
* `RType` is the type of data emitted, defaults to Buffer
*
* `WType` is the type of data to be written, if RType is buffer or string,
* then any {@link Minipass.ContiguousData} is allowed.
*
* `Events` is the set of event handler signatures that this object
* will emit, see {@link Minipass.Events}
*/
class Minipass extends external_node_events_.EventEmitter {
[FLOWING] = false;
[PAUSED] = false;
[PIPES] = [];
[BUFFER] = [];
[OBJECTMODE];
[ENCODING];
[ASYNC];
[DECODER];
[EOF] = false;
[EMITTED_END] = false;
[EMITTING_END] = false;
[CLOSED] = false;
[EMITTED_ERROR] = null;
[BUFFERLENGTH] = 0;
[DESTROYED] = false;
[SIGNAL];
[ABORTED] = false;
[DATALISTENERS] = 0;
[DISCARDED] = false;
/**
* true if the stream can be written
*/
writable = true;
/**
* true if the stream can be read
*/
readable = true;
/**
* If `RType` is Buffer, then options do not need to be provided.
* Otherwise, an options object must be provided to specify either
* {@link Minipass.SharedOptions.objectMode} or
* {@link Minipass.SharedOptions.encoding}, as appropriate.
*/
constructor(...args) {
const options = (args[0] ||
{});
super();
if (options.objectMode && typeof options.encoding === 'string') {
throw new TypeError('Encoding and objectMode may not be used together');
}
if (isObjectModeOptions(options)) {
this[OBJECTMODE] = true;
this[ENCODING] = null;
}
else if (isEncodingOptions(options)) {
this[ENCODING] = options.encoding;
this[OBJECTMODE] = false;
}
else {
this[OBJECTMODE] = false;
this[ENCODING] = null;
}
this[ASYNC] = !!options.async;
this[DECODER] = this[ENCODING]
? new external_node_string_decoder_.StringDecoder(this[ENCODING])
: null;
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposeBuffer === true) {
Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
}
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposePipes === true) {
Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
}
const { signal } = options;
if (signal) {
this[SIGNAL] = signal;
if (signal.aborted) {
this[ABORT]();
}
else {
signal.addEventListener('abort', () => this[ABORT]());
}
}
}
/**
* The amount of data stored in the buffer waiting to be read.
*
* For Buffer strings, this will be the total byte length.
* For string encoding streams, this will be the string character length,
* according to JavaScript's `string.length` logic.
* For objectMode streams, this is a count of the items waiting to be
* emitted.
*/
get bufferLength() {
return this[BUFFERLENGTH];
}
/**
* The `BufferEncoding` currently in use, or `null`
*/
get encoding() {
return this[ENCODING];
}
/**
* @deprecated - This is a read only property
*/
set encoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* @deprecated - Encoding may only be set at instantiation time
*/
setEncoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* True if this is an objectMode stream
*/
get objectMode() {
return this[OBJECTMODE];
}
/**
* @deprecated - This is a read-only property
*/
set objectMode(_om) {
throw new Error('objectMode must be set at instantiation time');
}
/**
* true if this is an async stream
*/
get ['async']() {
return this[ASYNC];
}
/**
* Set to true to make this stream async.
*
* Once set, it cannot be unset, as this would potentially cause incorrect
* behavior. Ie, a sync stream can be made async, but an async stream
* cannot be safely made sync.
*/
set ['async'](a) {
this[ASYNC] = this[ASYNC] || !!a;
}
// drop everything and get out of the flow completely
[ABORT]() {
this[ABORTED] = true;
this.emit('abort', this[SIGNAL]?.reason);
this.destroy(this[SIGNAL]?.reason);
}
/**
* True if the stream has been aborted.
*/
get aborted() {
return this[ABORTED];
}
/**
* No-op setter. Stream aborted status is set via the AbortSignal provided
* in the constructor options.
*/
set aborted(_) { }
write(chunk, encoding, cb) {
if (this[ABORTED])
return false;
if (this[EOF])
throw new Error('write after end');
if (this[DESTROYED]) {
this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
return true;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (!encoding)
encoding = 'utf8';
const fn = this[ASYNC] ? defer : nodefer;
// convert array buffers and typed array views into buffers
// at some point in the future, we may want to do the opposite!
// leave strings and buffers as-is
// anything is only allowed if in object mode, so throw
if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
if (isArrayBufferView(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
else if (isArrayBufferLike(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk);
}
else if (typeof chunk !== 'string') {
throw new Error('Non-contiguous data written to non-objectMode stream');
}
}
// handle object mode up front, since it's simpler
// this yields better performance, fewer checks later.
if (this[OBJECTMODE]) {
// maybe impossible?
/* c8 ignore start */
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
/* c8 ignore stop */
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// at this point the chunk is a buffer or string
// don't buffer it up or send it to the decoder
if (!chunk.length) {
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// fast-path writing strings of same encoding to a stream with
// an empty buffer, skipping the buffer/decoder dance
if (typeof chunk === 'string' &&
// unless it is a string already ready for us to use
!(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
//@ts-ignore - sinful unsafe type change
chunk = Buffer.from(chunk, encoding);
}
if (Buffer.isBuffer(chunk) && this[ENCODING]) {
//@ts-ignore - sinful unsafe type change
chunk = this[DECODER].write(chunk);
}
// Note: flushing CAN potentially switch us into not-flowing mode
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
/**
* Low-level explicit read method.
*
* In objectMode, the argument is ignored, and one item is returned if
* available.
*
* `n` is the number of bytes (or in the case of encoding streams,
* characters) to consume. If `n` is not provided, then the entire buffer
* is returned, or `null` is returned if no data is available.
*
* If `n` is greater that the amount of data in the internal buffer,
* then `null` is returned.
*/
read(n) {
if (this[DESTROYED])
return null;
this[DISCARDED] = false;
if (this[BUFFERLENGTH] === 0 ||
n === 0 ||
(n && n > this[BUFFERLENGTH])) {
this[MAYBE_EMIT_END]();
return null;
}
if (this[OBJECTMODE])
n = null;
if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
// not object mode, so if we have an encoding, then RType is string
// otherwise, must be Buffer
this[BUFFER] = [
(this[ENCODING]
? this[BUFFER].join('')
: Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
];
}
const ret = this[READ](n || null, this[BUFFER][0]);
this[MAYBE_EMIT_END]();
return ret;
}
[READ](n, chunk) {
if (this[OBJECTMODE])
this[BUFFERSHIFT]();
else {
const c = chunk;
if (n === c.length || n === null)
this[BUFFERSHIFT]();
else if (typeof c === 'string') {
this[BUFFER][0] = c.slice(n);
chunk = c.slice(0, n);
this[BUFFERLENGTH] -= n;
}
else {
this[BUFFER][0] = c.subarray(n);
chunk = c.subarray(0, n);
this[BUFFERLENGTH] -= n;
}
}
this.emit('data', chunk);
if (!this[BUFFER].length && !this[EOF])
this.emit('drain');
return chunk;
}
end(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = undefined;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (chunk !== undefined)
this.write(chunk, encoding);
if (cb)
this.once('end', cb);
this[EOF] = true;
this.writable = false;
// if we haven't written anything, then go ahead and emit,
// even if we're not reading.
// we'll re-emit if a new 'end' listener is added anyway.
// This makes MP more suitable to write-only use cases.
if (this[FLOWING] || !this[PAUSED])
this[MAYBE_EMIT_END]();
return this;
}
// don't let the internal resume be overwritten
[RESUME]() {
if (this[DESTROYED])
return;
if (!this[DATALISTENERS] && !this[PIPES].length) {
this[DISCARDED] = true;
}
this[PAUSED] = false;
this[FLOWING] = true;
this.emit('resume');
if (this[BUFFER].length)
this[FLUSH]();
else if (this[EOF])
this[MAYBE_EMIT_END]();
else
this.emit('drain');
}
/**
* Resume the stream if it is currently in a paused state
*
* If called when there are no pipe destinations or `data` event listeners,
* this will place the stream in a "discarded" state, where all data will
* be thrown away. The discarded state is removed if a pipe destination or
* data handler is added, if pause() is called, or if any synchronous or
* asynchronous iteration is started.
*/
resume() {
return this[RESUME]();
}
/**
* Pause the stream
*/
pause() {
this[FLOWING] = false;
this[PAUSED] = true;
this[DISCARDED] = false;
}
/**
* true if the stream has been forcibly destroyed
*/
get destroyed() {
return this[DESTROYED];
}
/**
* true if the stream is currently in a flowing state, meaning that
* any writes will be immediately emitted.
*/
get flowing() {
return this[FLOWING];
}
/**
* true if the stream is currently in a paused state
*/
get paused() {
return this[PAUSED];
}
[BUFFERPUSH](chunk) {
if (this[OBJECTMODE])
this[BUFFERLENGTH] += 1;
else
this[BUFFERLENGTH] += chunk.length;
this[BUFFER].push(chunk);
}
[BUFFERSHIFT]() {
if (this[OBJECTMODE])
this[BUFFERLENGTH] -= 1;
else
this[BUFFERLENGTH] -= this[BUFFER][0].length;
return this[BUFFER].shift();
}
[FLUSH](noDrain = false) {
do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
this[BUFFER].length);
if (!noDrain && !this[BUFFER].length && !this[EOF])
this.emit('drain');
}
[FLUSHCHUNK](chunk) {
this.emit('data', chunk);
return this[FLOWING];
}
/**
* Pipe all data emitted by this stream into the destination provided.
*
* Triggers the flow of data.
*/
pipe(dest, opts) {
if (this[DESTROYED])
return dest;
this[DISCARDED] = false;
const ended = this[EMITTED_END];
opts = opts || {};
if (dest === proc.stdout || dest === proc.stderr)
opts.end = false;
else
opts.end = opts.end !== false;
opts.proxyErrors = !!opts.proxyErrors;
// piping an ended stream ends immediately
if (ended) {
if (opts.end)
dest.end();
}
else {
// "as" here just ignores the WType, which pipes don't care about,
// since they're only consuming from us, and writing to the dest
this[PIPES].push(!opts.proxyErrors
? new Pipe(this, dest, opts)
: new PipeProxyErrors(this, dest, opts));
if (this[ASYNC])
defer(() => this[RESUME]());
else
this[RESUME]();
}
return dest;
}
/**
* Fully unhook a piped destination stream.
*
* If the destination stream was the only consumer of this stream (ie,
* there are no other piped destinations or `'data'` event listeners)
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
unpipe(dest) {
const p = this[PIPES].find(p => p.dest === dest);
if (p) {
if (this[PIPES].length === 1) {
if (this[FLOWING] && this[DATALISTENERS] === 0) {
this[FLOWING] = false;
}
this[PIPES] = [];
}
else
this[PIPES].splice(this[PIPES].indexOf(p), 1);
p.unpipe();
}
}
/**
* Alias for {@link Minipass#on}
*/
addListener(ev, handler) {
return this.on(ev, handler);
}
/**
* Mostly identical to `EventEmitter.on`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* - Adding a 'data' event handler will trigger the flow of data
*
* - Adding a 'readable' event handler when there is data waiting to be read
* will cause 'readable' to be emitted immediately.
*
* - Adding an 'endish' event handler ('end', 'finish', etc.) which has
* already passed will cause the event to be emitted immediately and all
* handlers removed.
*
* - Adding an 'error' event handler after an error has been emitted will
* cause the event to be re-emitted immediately with the error previously
* raised.
*/
on(ev, handler) {
const ret = super.on(ev, handler);
if (ev === 'data') {
this[DISCARDED] = false;
this[DATALISTENERS]++;
if (!this[PIPES].length && !this[FLOWING]) {
this[RESUME]();
}
}
else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
super.emit('readable');
}
else if (isEndish(ev) && this[EMITTED_END]) {
super.emit(ev);
this.removeAllListeners(ev);
}
else if (ev === 'error' && this[EMITTED_ERROR]) {
const h = handler;
if (this[ASYNC])
defer(() => h.call(this, this[EMITTED_ERROR]));
else
h.call(this, this[EMITTED_ERROR]);
}
return ret;
}
/**
* Alias for {@link Minipass#off}
*/
removeListener(ev, handler) {
return this.off(ev, handler);
}
/**
* Mostly identical to `EventEmitter.off`
*
* If a 'data' event handler is removed, and it was the last consumer
* (ie, there are no pipe destinations or other 'data' event listeners),
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
off(ev, handler) {
const ret = super.off(ev, handler);
// if we previously had listeners, and now we don't, and we don't
// have any pipes, then stop the flow, unless it's been explicitly
// put in a discarded flowing state via stream.resume().
if (ev === 'data') {
this[DATALISTENERS] = this.listeners('data').length;
if (this[DATALISTENERS] === 0 &&
!this[DISCARDED] &&
!this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* Mostly identical to `EventEmitter.removeAllListeners`
*
* If all 'data' event handlers are removed, and they were the last consumer
* (ie, there are no pipe destinations), then the flow of data will stop
* until there is another consumer or {@link Minipass#resume} is explicitly
* called.
*/
removeAllListeners(ev) {
const ret = super.removeAllListeners(ev);
if (ev === 'data' || ev === undefined) {
this[DATALISTENERS] = 0;
if (!this[DISCARDED] && !this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* true if the 'end' event has been emitted
*/
get emittedEnd() {
return this[EMITTED_END];
}
[MAYBE_EMIT_END]() {
if (!this[EMITTING_END] &&
!this[EMITTED_END] &&
!this[DESTROYED] &&
this[BUFFER].length === 0 &&
this[EOF]) {
this[EMITTING_END] = true;
this.emit('end');
this.emit('prefinish');
this.emit('finish');
if (this[CLOSED])
this.emit('close');
this[EMITTING_END] = false;
}
}
/**
* Mostly identical to `EventEmitter.emit`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* If the stream has been destroyed, and the event is something other
* than 'close' or 'error', then `false` is returned and no handlers
* are called.
*
* If the event is 'end', and has already been emitted, then the event
* is ignored. If the stream is in a paused or non-flowing state, then
* the event will be deferred until data flow resumes. If the stream is
* async, then handlers will be called on the next tick rather than
* immediately.
*
* If the event is 'close', and 'end' has not yet been emitted, then
* the event will be deferred until after 'end' is emitted.
*
* If the event is 'error', and an AbortSignal was provided for the stream,
* and there are no listeners, then the event is ignored, matching the
* behavior of node core streams in the presense of an AbortSignal.
*
* If the event is 'finish' or 'prefinish', then all listeners will be
* removed after emitting the event, to prevent double-firing.
*/
emit(ev, ...args) {
const data = args[0];
// error and close are only events allowed after calling destroy()
if (ev !== 'error' &&
ev !== 'close' &&
ev !== DESTROYED &&
this[DESTROYED]) {
return false;
}
else if (ev === 'data') {
return !this[OBJECTMODE] && !data
? false
: this[ASYNC]
? (defer(() => this[EMITDATA](data)), true)
: this[EMITDATA](data);
}
else if (ev === 'end') {
return this[EMITEND]();
}
else if (ev === 'close') {
this[CLOSED] = true;
// don't emit close before 'end' and 'finish'
if (!this[EMITTED_END] && !this[DESTROYED])
return false;
const ret = super.emit('close');
this.removeAllListeners('close');
return ret;
}
else if (ev === 'error') {
this[EMITTED_ERROR] = data;
super.emit(ERROR, data);
const ret = !this[SIGNAL] || this.listeners('error').length
? super.emit('error', data)
: false;
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'resume') {
const ret = super.emit('resume');
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'finish' || ev === 'prefinish') {
const ret = super.emit(ev);
this.removeAllListeners(ev);
return ret;
}
// Some other unknown event
const ret = super.emit(ev, ...args);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITDATA](data) {
for (const p of this[PIPES]) {
if (p.dest.write(data) === false)
this.pause();
}
const ret = this[DISCARDED] ? false : super.emit('data', data);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITEND]() {
if (this[EMITTED_END])
return false;
this[EMITTED_END] = true;
this.readable = false;
return this[ASYNC]
? (defer(() => this[EMITEND2]()), true)
: this[EMITEND2]();
}
[EMITEND2]() {
if (this[DECODER]) {
const data = this[DECODER].end();
if (data) {
for (const p of this[PIPES]) {
p.dest.write(data);
}
if (!this[DISCARDED])
super.emit('data', data);
}
}
for (const p of this[PIPES]) {
p.end();
}
const ret = super.emit('end');
this.removeAllListeners('end');
return ret;
}
/**
* Return a Promise that resolves to an array of all emitted data once
* the stream ends.
*/
async collect() {
const buf = Object.assign([], {
dataLength: 0,
});
if (!this[OBJECTMODE])
buf.dataLength = 0;
// set the promise first, in case an error is raised
// by triggering the flow here.
const p = this.promise();
this.on('data', c => {
buf.push(c);
if (!this[OBJECTMODE])
buf.dataLength += c.length;
});
await p;
return buf;
}
/**
* Return a Promise that resolves to the concatenation of all emitted data
* once the stream ends.
*
* Not allowed on objectMode streams.
*/
async concat() {
if (this[OBJECTMODE]) {
throw new Error('cannot concat in objectMode');
}
const buf = await this.collect();
return (this[ENCODING]
? buf.join('')
: Buffer.concat(buf, buf.dataLength));
}
/**
* Return a void Promise that resolves once the stream ends.
*/
async promise() {
return new Promise((resolve, reject) => {
this.on(DESTROYED, () => reject(new Error('stream destroyed')));
this.on('error', er => reject(er));
this.on('end', () => resolve());
});
}
/**
* Asynchronous `for await of` iteration.
*
* This will continue emitting all chunks until the stream terminates.
*/
[Symbol.asyncIterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = async () => {
this.pause();
stopped = true;
return { value: undefined, done: true };
};
const next = () => {
if (stopped)
return stop();
const res = this.read();
if (res !== null)
return Promise.resolve({ done: false, value: res });
if (this[EOF])
return stop();
let resolve;
let reject;
const onerr = (er) => {
this.off('data', ondata);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
stop();
reject(er);
};
const ondata = (value) => {
this.off('error', onerr);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
this.pause();
resolve({ value, done: !!this[EOF] });
};
const onend = () => {
this.off('error', onerr);
this.off('data', ondata);
this.off(DESTROYED, ondestroy);
stop();
resolve({ done: true, value: undefined });
};
const ondestroy = () => onerr(new Error('stream destroyed'));
return new Promise((res, rej) => {
reject = rej;
resolve = res;
this.once(DESTROYED, ondestroy);
this.once('error', onerr);
this.once('end', onend);
this.once('data', ondata);
});
};
return {
next,
throw: stop,
return: stop,
[Symbol.asyncIterator]() {
return this;
},
};
}
/**
* Synchronous `for of` iteration.
*
* The iteration will terminate when the internal buffer runs out, even
* if the stream has not yet terminated.
*/
[Symbol.iterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = () => {
this.pause();
this.off(ERROR, stop);
this.off(DESTROYED, stop);
this.off('end', stop);
stopped = true;
return { done: true, value: undefined };
};
const next = () => {
if (stopped)
return stop();
const value = this.read();
return value === null ? stop() : { done: false, value };
};
this.once('end', stop);
this.once(ERROR, stop);
this.once(DESTROYED, stop);
return {
next,
throw: stop,
return: stop,
[Symbol.iterator]() {
return this;
},
};
}
/**
* Destroy a stream, preventing it from being used for any further purpose.
*
* If the stream has a `close()` method, then it will be called on
* destruction.
*
* After destruction, any attempt to write data, read data, or emit most
* events will be ignored.
*
* If an error argument is provided, then it will be emitted in an
* 'error' event.
*/
destroy(er) {
if (this[DESTROYED]) {
if (er)
this.emit('error', er);
else
this.emit(DESTROYED);
return this;
}
this[DESTROYED] = true;
this[DISCARDED] = true;
// throw away all buffered data, it's never coming out
this[BUFFER].length = 0;
this[BUFFERLENGTH] = 0;
const wc = this;
if (typeof wc.close === 'function' && !this[CLOSED])
wc.close();
if (er)
this.emit('error', er);
// if no error to emit, still reject pending promises
else
this.emit(DESTROYED);
return this;
}
/**
* Alias for {@link isStream}
*
* Former export location, maintained for backwards compatibility.
*
* @deprecated
*/
static get isStream() {
return isStream;
}
}
//# sourceMappingURL=index.js.map
;// ../commons/node_modules/path-scurry/dist/esm/index.js
const realpathSync = external_fs_.realpathSync.native;
// TODO: test perf of fs/promises realpath vs realpathCB,
// since the promises one uses realpath.native
const defaultFS = {
lstatSync: external_fs_.lstatSync,
readdir: external_fs_.readdir,
readdirSync: external_fs_.readdirSync,
readlinkSync: external_fs_.readlinkSync,
realpathSync,
promises: {
lstat: promises_.lstat,
readdir: promises_.readdir,
readlink: promises_.readlink,
realpath: promises_.realpath,
},
};
// if they just gave us require('fs') then use our default
const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === external_node_fs_namespaceObject ?
defaultFS
: {
...defaultFS,
...fsOption,
promises: {
...defaultFS.promises,
...(fsOption.promises || {}),
},
};
// turn something like //?/c:/ into c:\
const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
// windows paths are separated by either / or \
const eitherSep = /[\\\/]/;
const UNKNOWN = 0; // may not even exist, for all we know
const IFIFO = 0b0001;
const IFCHR = 0b0010;
const IFDIR = 0b0100;
const IFBLK = 0b0110;
const IFREG = 0b1000;
const IFLNK = 0b1010;
const IFSOCK = 0b1100;
const IFMT = 0b1111;
// mask to unset low 4 bits
const IFMT_UNKNOWN = ~IFMT;
// set after successfully calling readdir() and getting entries.
const READDIR_CALLED = 0b0000_0001_0000;
// set after a successful lstat()
const LSTAT_CALLED = 0b0000_0010_0000;
// set if an entry (or one of its parents) is definitely not a dir
const ENOTDIR = 0b0000_0100_0000;
// set if an entry (or one of its parents) does not exist
// (can also be set on lstat errors like EACCES or ENAMETOOLONG)
const ENOENT = 0b0000_1000_0000;
// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK
// set if we fail to readlink
const ENOREADLINK = 0b0001_0000_0000;
// set if we know realpath() will fail
const ENOREALPATH = 0b0010_0000_0000;
const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
const TYPEMASK = 0b0011_1111_1111;
const entToType = (s) => s.isFile() ? IFREG
: s.isDirectory() ? IFDIR
: s.isSymbolicLink() ? IFLNK
: s.isCharacterDevice() ? IFCHR
: s.isBlockDevice() ? IFBLK
: s.isSocket() ? IFSOCK
: s.isFIFO() ? IFIFO
: UNKNOWN;
// normalize unicode path names
const normalizeCache = new Map();
const normalize = (s) => {
const c = normalizeCache.get(s);
if (c)
return c;
const n = s.normalize('NFKD');
normalizeCache.set(s, n);
return n;
};
const normalizeNocaseCache = new Map();
const normalizeNocase = (s) => {
const c = normalizeNocaseCache.get(s);
if (c)
return c;
const n = normalize(s.toLowerCase());
normalizeNocaseCache.set(s, n);
return n;
};
/**
* An LRUCache for storing resolved path strings or Path objects.
* @internal
*/
class ResolveCache extends LRUCache {
constructor() {
super({ max: 256 });
}
}
// In order to prevent blowing out the js heap by allocating hundreds of
// thousands of Path entries when walking extremely large trees, the "children"
// in this tree are represented by storing an array of Path entries in an
// LRUCache, indexed by the parent. At any time, Path.children() may return an
// empty array, indicating that it doesn't know about any of its children, and
// thus has to rebuild that cache. This is fine, it just means that we don't
// benefit as much from having the cached entries, but huge directory walks
// don't blow out the stack, and smaller ones are still as fast as possible.
//
//It does impose some complexity when building up the readdir data, because we
//need to pass a reference to the children array that we started with.
/**
* an LRUCache for storing child entries.
* @internal
*/
class ChildrenCache extends LRUCache {
constructor(maxSize = 16 * 1024) {
super({
maxSize,
// parent + children
sizeCalculation: a => a.length + 1,
});
}
}
const setAsCwd = Symbol('PathScurry setAsCwd');
/**
* Path objects are sort of like a super-powered
* {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}
*
* Each one represents a single filesystem entry on disk, which may or may not
* exist. It includes methods for reading various types of information via
* lstat, readlink, and readdir, and caches all information to the greatest
* degree possible.
*
* Note that fs operations that would normally throw will instead return an
* "empty" value. This is in order to prevent excessive overhead from error
* stack traces.
*/
class PathBase {
/**
* the basename of this path
*
* **Important**: *always* test the path name against any test string
* usingthe {@link isNamed} method, and not by directly comparing this
* string. Otherwise, unicode path strings that the system sees as identical
* will not be properly treated as the same path, leading to incorrect
* behavior and possible security issues.
*/
name;
/**
* the Path entry corresponding to the path root.
*
* @internal
*/
root;
/**
* All roots found within the current PathScurry family
*
* @internal
*/
roots;
/**
* a reference to the parent path, or undefined in the case of root entries
*
* @internal
*/
parent;
/**
* boolean indicating whether paths are compared case-insensitively
* @internal
*/
nocase;
/**
* boolean indicating that this path is the current working directory
* of the PathScurry collection that contains it.
*/
isCWD = false;
// potential default fs override
#fs;
// Stats fields
#dev;
get dev() {
return this.#dev;
}
#mode;
get mode() {
return this.#mode;
}
#nlink;
get nlink() {
return this.#nlink;
}
#uid;
get uid() {
return this.#uid;
}
#gid;
get gid() {
return this.#gid;
}
#rdev;
get rdev() {
return this.#rdev;
}
#blksize;
get blksize() {
return this.#blksize;
}
#ino;
get ino() {
return this.#ino;
}
#size;
get size() {
return this.#size;
}
#blocks;
get blocks() {
return this.#blocks;
}
#atimeMs;
get atimeMs() {
return this.#atimeMs;
}
#mtimeMs;
get mtimeMs() {
return this.#mtimeMs;
}
#ctimeMs;
get ctimeMs() {
return this.#ctimeMs;
}
#birthtimeMs;
get birthtimeMs() {
return this.#birthtimeMs;
}
#atime;
get atime() {
return this.#atime;
}
#mtime;
get mtime() {
return this.#mtime;
}
#ctime;
get ctime() {
return this.#ctime;
}
#birthtime;
get birthtime() {
return this.#birthtime;
}
#matchName;
#depth;
#fullpath;
#fullpathPosix;
#relative;
#relativePosix;
#type;
#children;
#linkTarget;
#realpath;
/**
* This property is for compatibility with the Dirent class as of
* Node v20, where Dirent['parentPath'] refers to the path of the
* directory that was passed to readdir. For root entries, it's the path
* to the entry itself.
*/
get parentPath() {
return (this.parent || this).fullpath();
}
/**
* Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
* this property refers to the *parent* path, not the path object itself.
*/
get path() {
return this.parentPath;
}
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
this.name = name;
this.#matchName = nocase ? normalizeNocase(name) : normalize(name);
this.#type = type & TYPEMASK;
this.nocase = nocase;
this.roots = roots;
this.root = root || this;
this.#children = children;
this.#fullpath = opts.fullpath;
this.#relative = opts.relative;
this.#relativePosix = opts.relativePosix;
this.parent = opts.parent;
if (this.parent) {
this.#fs = this.parent.#fs;
}
else {
this.#fs = fsFromOption(opts.fs);
}
}
/**
* Returns the depth of the Path object from its root.
*
* For example, a path at `/foo/bar` would have a depth of 2.
*/
depth() {
if (this.#depth !== undefined)
return this.#depth;
if (!this.parent)
return (this.#depth = 0);
return (this.#depth = this.parent.depth() + 1);
}
/**
* @internal
*/
childrenCache() {
return this.#children;
}
/**
* Get the Path object referenced by the string path, resolved from this Path
*/
resolve(path) {
if (!path) {
return this;
}
const rootPath = this.getRootString(path);
const dir = path.substring(rootPath.length);
const dirParts = dir.split(this.splitSep);
const result = rootPath ?
this.getRoot(rootPath).#resolveParts(dirParts)
: this.#resolveParts(dirParts);
return result;
}
#resolveParts(dirParts) {
let p = this;
for (const part of dirParts) {
p = p.child(part);
}
return p;
}
/**
* Returns the cached children Path objects, if still available. If they
* have fallen out of the cache, then returns an empty array, and resets the
* READDIR_CALLED bit, so that future calls to readdir() will require an fs
* lookup.
*
* @internal
*/
children() {
const cached = this.#children.get(this);
if (cached) {
return cached;
}
const children = Object.assign([], { provisional: 0 });
this.#children.set(this, children);
this.#type &= ~READDIR_CALLED;
return children;
}
/**
* Resolves a path portion and returns or creates the child Path.
*
* Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
* `'..'`.
*
* This should not be called directly. If `pathPart` contains any path
* separators, it will lead to unsafe undefined behavior.
*
* Use `Path.resolve()` instead.
*
* @internal
*/
child(pathPart, opts) {
if (pathPart === '' || pathPart === '.') {
return this;
}
if (pathPart === '..') {
return this.parent || this;
}
// find the child
const children = this.children();
const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
for (const p of children) {
if (p.#matchName === name) {
return p;
}
}
// didn't find it, create provisional child, since it might not
// actually exist. If we know the parent isn't a dir, then
// in fact it CAN'T exist.
const s = this.parent ? this.sep : '';
const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined;
const pchild = this.newChild(pathPart, UNKNOWN, {
...opts,
parent: this,
fullpath,
});
if (!this.canReaddir()) {
pchild.#type |= ENOENT;
}
// don't have to update provisional, because if we have real children,
// then provisional is set to children.length, otherwise a lower number
children.push(pchild);
return pchild;
}
/**
* The relative path from the cwd. If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpath()
*/
relative() {
if (this.isCWD)
return '';
if (this.#relative !== undefined) {
return this.#relative;
}
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#relative = this.name);
}
const pv = p.relative();
return pv + (!pv || !p.parent ? '' : this.sep) + name;
}
/**
* The relative path from the cwd, using / as the path separator.
* If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpathPosix()
* On posix systems, this is identical to relative().
*/
relativePosix() {
if (this.sep === '/')
return this.relative();
if (this.isCWD)
return '';
if (this.#relativePosix !== undefined)
return this.#relativePosix;
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#relativePosix = this.fullpathPosix());
}
const pv = p.relativePosix();
return pv + (!pv || !p.parent ? '' : '/') + name;
}
/**
* The fully resolved path string for this Path entry
*/
fullpath() {
if (this.#fullpath !== undefined) {
return this.#fullpath;
}
const name = this.name;
const p = this.parent;
if (!p) {
return (this.#fullpath = this.name);
}
const pv = p.fullpath();
const fp = pv + (!p.parent ? '' : this.sep) + name;
return (this.#fullpath = fp);
}
/**
* On platforms other than windows, this is identical to fullpath.
*
* On windows, this is overridden to return the forward-slash form of the
* full UNC path.
*/
fullpathPosix() {
if (this.#fullpathPosix !== undefined)
return this.#fullpathPosix;
if (this.sep === '/')
return (this.#fullpathPosix = this.fullpath());
if (!this.parent) {
const p = this.fullpath().replace(/\\/g, '/');
if (/^[a-z]:\//i.test(p)) {
return (this.#fullpathPosix = `//?/${p}`);
}
else {
return (this.#fullpathPosix = p);
}
}
const p = this.parent;
const pfpp = p.fullpathPosix();
const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name;
return (this.#fullpathPosix = fpp);
}
/**
* Is the Path of an unknown type?
*
* Note that we might know *something* about it if there has been a previous
* filesystem operation, for example that it does not exist, or is not a
* link, or whether it has child entries.
*/
isUnknown() {
return (this.#type & IFMT) === UNKNOWN;
}
isType(type) {
return this[`is${type}`]();
}
getType() {
return (this.isUnknown() ? 'Unknown'
: this.isDirectory() ? 'Directory'
: this.isFile() ? 'File'
: this.isSymbolicLink() ? 'SymbolicLink'
: this.isFIFO() ? 'FIFO'
: this.isCharacterDevice() ? 'CharacterDevice'
: this.isBlockDevice() ? 'BlockDevice'
: /* c8 ignore start */ this.isSocket() ? 'Socket'
: 'Unknown');
/* c8 ignore stop */
}
/**
* Is the Path a regular file?
*/
isFile() {
return (this.#type & IFMT) === IFREG;
}
/**
* Is the Path a directory?
*/
isDirectory() {
return (this.#type & IFMT) === IFDIR;
}
/**
* Is the path a character device?
*/
isCharacterDevice() {
return (this.#type & IFMT) === IFCHR;
}
/**
* Is the path a block device?
*/
isBlockDevice() {
return (this.#type & IFMT) === IFBLK;
}
/**
* Is the path a FIFO pipe?
*/
isFIFO() {
return (this.#type & IFMT) === IFIFO;
}
/**
* Is the path a socket?
*/
isSocket() {
return (this.#type & IFMT) === IFSOCK;
}
/**
* Is the path a symbolic link?
*/
isSymbolicLink() {
return (this.#type & IFLNK) === IFLNK;
}
/**
* Return the entry if it has been subject of a successful lstat, or
* undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* simply
* mean that we haven't called lstat on it.
*/
lstatCached() {
return this.#type & LSTAT_CALLED ? this : undefined;
}
/**
* Return the cached link target if the entry has been the subject of a
* successful readlink, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readlink() has been called at some point.
*/
readlinkCached() {
return this.#linkTarget;
}
/**
* Returns the cached realpath target if the entry has been the subject
* of a successful realpath, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* realpath() has been called at some point.
*/
realpathCached() {
return this.#realpath;
}
/**
* Returns the cached child Path entries array if the entry has been the
* subject of a successful readdir(), or [] otherwise.
*
* Does not read the filesystem, so an empty array *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readdir() has been called recently enough to still be valid.
*/
readdirCached() {
const children = this.children();
return children.slice(0, children.provisional);
}
/**
* Return true if it's worth trying to readlink. Ie, we don't (yet) have
* any indication that readlink will definitely fail.
*
* Returns false if the path is known to not be a symlink, if a previous
* readlink failed, or if the entry does not exist.
*/
canReadlink() {
if (this.#linkTarget)
return true;
if (!this.parent)
return false;
// cases where it cannot possibly succeed
const ifmt = this.#type & IFMT;
return !((ifmt !== UNKNOWN && ifmt !== IFLNK) ||
this.#type & ENOREADLINK ||
this.#type & ENOENT);
}
/**
* Return true if readdir has previously been successfully called on this
* path, indicating that cachedReaddir() is likely valid.
*/
calledReaddir() {
return !!(this.#type & READDIR_CALLED);
}
/**
* Returns true if the path is known to not exist. That is, a previous lstat
* or readdir failed to verify its existence when that would have been
* expected, or a parent entry was marked either enoent or enotdir.
*/
isENOENT() {
return !!(this.#type & ENOENT);
}
/**
* Return true if the path is a match for the given path name. This handles
* case sensitivity and unicode normalization.
*
* Note: even on case-sensitive systems, it is **not** safe to test the
* equality of the `.name` property to determine whether a given pathname
* matches, due to unicode normalization mismatches.
*
* Always use this method instead of testing the `path.name` property
* directly.
*/
isNamed(n) {
return !this.nocase ?
this.#matchName === normalize(n)
: this.#matchName === normalizeNocase(n);
}
/**
* Return the Path object corresponding to the target of a symbolic link.
*
* If the Path is not a symbolic link, or if the readlink call fails for any
* reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
*/
async readlink() {
const target = this.#linkTarget;
if (target) {
return target;
}
if (!this.canReadlink()) {
return undefined;
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined;
}
/* c8 ignore stop */
try {
const read = await this.#fs.promises.readlink(this.fullpath());
const linkTarget = (await this.parent.realpath())?.resolve(read);
if (linkTarget) {
return (this.#linkTarget = linkTarget);
}
}
catch (er) {
this.#readlinkFail(er.code);
return undefined;
}
}
/**
* Synchronous {@link PathBase.readlink}
*/
readlinkSync() {
const target = this.#linkTarget;
if (target) {
return target;
}
if (!this.canReadlink()) {
return undefined;
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined;
}
/* c8 ignore stop */
try {
const read = this.#fs.readlinkSync(this.fullpath());
const linkTarget = this.parent.realpathSync()?.resolve(read);
if (linkTarget) {
return (this.#linkTarget = linkTarget);
}
}
catch (er) {
this.#readlinkFail(er.code);
return undefined;
}
}
#readdirSuccess(children) {
// succeeded, mark readdir called bit
this.#type |= READDIR_CALLED;
// mark all remaining provisional children as ENOENT
for (let p = children.provisional; p < children.length; p++) {
const c = children[p];
if (c)
c.#markENOENT();
}
}
#markENOENT() {
// mark as UNKNOWN and ENOENT
if (this.#type & ENOENT)
return;
this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
this.#markChildrenENOENT();
}
#markChildrenENOENT() {
// all children are provisional and do not exist
const children = this.children();
children.provisional = 0;
for (const p of children) {
p.#markENOENT();
}
}
#markENOREALPATH() {
this.#type |= ENOREALPATH;
this.#markENOTDIR();
}
// save the information when we know the entry is not a dir
#markENOTDIR() {
// entry is not a directory, so any children can't exist.
// this *should* be impossible, since any children created
// after it's been marked ENOTDIR should be marked ENOENT,
// so it won't even get to this point.
/* c8 ignore start */
if (this.#type & ENOTDIR)
return;
/* c8 ignore stop */
let t = this.#type;
// this could happen if we stat a dir, then delete it,
// then try to read it or one of its children.
if ((t & IFMT) === IFDIR)
t &= IFMT_UNKNOWN;
this.#type = t | ENOTDIR;
this.#markChildrenENOENT();
}
#readdirFail(code = '') {
// markENOTDIR and markENOENT also set provisional=0
if (code === 'ENOTDIR' || code === 'EPERM') {
this.#markENOTDIR();
}
else if (code === 'ENOENT') {
this.#markENOENT();
}
else {
this.children().provisional = 0;
}
}
#lstatFail(code = '') {
// Windows just raises ENOENT in this case, disable for win CI
/* c8 ignore start */
if (code === 'ENOTDIR') {
// already know it has a parent by this point
const p = this.parent;
p.#markENOTDIR();
}
else if (code === 'ENOENT') {
/* c8 ignore stop */
this.#markENOENT();
}
}
#readlinkFail(code = '') {
let ter = this.#type;
ter |= ENOREADLINK;
if (code === 'ENOENT')
ter |= ENOENT;
// windows gets a weird error when you try to readlink a file
if (code === 'EINVAL' || code === 'UNKNOWN') {
// exists, but not a symlink, we don't know WHAT it is, so remove
// all IFMT bits.
ter &= IFMT_UNKNOWN;
}
this.#type = ter;
// windows just gets ENOENT in this case. We do cover the case,
// just disabled because it's impossible on Windows CI
/* c8 ignore start */
if (code === 'ENOTDIR' && this.parent) {
this.parent.#markENOTDIR();
}
/* c8 ignore stop */
}
#readdirAddChild(e, c) {
return (this.#readdirMaybePromoteChild(e, c) ||
this.#readdirAddNewChild(e, c));
}
#readdirAddNewChild(e, c) {
// alloc new entry at head, so it's never provisional
const type = entToType(e);
const child = this.newChild(e.name, type, { parent: this });
const ifmt = child.#type & IFMT;
if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
child.#type |= ENOTDIR;
}
c.unshift(child);
c.provisional++;
return child;
}
#readdirMaybePromoteChild(e, c) {
for (let p = c.provisional; p < c.length; p++) {
const pchild = c[p];
const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name);
if (name !== pchild.#matchName) {
continue;
}
return this.#readdirPromoteChild(e, pchild, p, c);
}
}
#readdirPromoteChild(e, p, index, c) {
const v = p.name;
// retain any other flags, but set ifmt from dirent
p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e);
// case sensitivity fixing when we learn the true name.
if (v !== e.name)
p.name = e.name;
// just advance provisional index (potentially off the list),
// otherwise we have to splice/pop it out and re-insert at head
if (index !== c.provisional) {
if (index === c.length - 1)
c.pop();
else
c.splice(index, 1);
c.unshift(p);
}
c.provisional++;
return p;
}
/**
* Call lstat() on this Path, and update all known information that can be
* determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat() {
if ((this.#type & ENOENT) === 0) {
try {
this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
return this;
}
catch (er) {
this.#lstatFail(er.code);
}
}
}
/**
* synchronous {@link PathBase.lstat}
*/
lstatSync() {
if ((this.#type & ENOENT) === 0) {
try {
this.#applyStat(this.#fs.lstatSync(this.fullpath()));
return this;
}
catch (er) {
this.#lstatFail(er.code);
}
}
}
#applyStat(st) {
const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st;
this.#atime = atime;
this.#atimeMs = atimeMs;
this.#birthtime = birthtime;
this.#birthtimeMs = birthtimeMs;
this.#blksize = blksize;
this.#blocks = blocks;
this.#ctime = ctime;
this.#ctimeMs = ctimeMs;
this.#dev = dev;
this.#gid = gid;
this.#ino = ino;
this.#mode = mode;
this.#mtime = mtime;
this.#mtimeMs = mtimeMs;
this.#nlink = nlink;
this.#rdev = rdev;
this.#size = size;
this.#uid = uid;
const ifmt = entToType(st);
// retain any other flags, but set the ifmt
this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED;
if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
this.#type |= ENOTDIR;
}
}
#onReaddirCB = [];
#readdirCBInFlight = false;
#callOnReaddirCB(children) {
this.#readdirCBInFlight = false;
const cbs = this.#onReaddirCB.slice();
this.#onReaddirCB.length = 0;
cbs.forEach(cb => cb(null, children));
}
/**
* Standard node-style callback interface to get list of directory entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*
* @param cb The callback called with (er, entries). Note that the `er`
* param is somewhat extraneous, as all readdir() errors are handled and
* simply result in an empty set of entries being returned.
* @param allowZalgo Boolean indicating that immediately known results should
* *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
* zalgo at your peril, the dark pony lord is devious and unforgiving.
*/
readdirCB(cb, allowZalgo = false) {
if (!this.canReaddir()) {
if (allowZalgo)
cb(null, []);
else
queueMicrotask(() => cb(null, []));
return;
}
const children = this.children();
if (this.calledReaddir()) {
const c = children.slice(0, children.provisional);
if (allowZalgo)
cb(null, c);
else
queueMicrotask(() => cb(null, c));
return;
}
// don't have to worry about zalgo at this point.
this.#onReaddirCB.push(cb);
if (this.#readdirCBInFlight) {
return;
}
this.#readdirCBInFlight = true;
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
if (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
else {
// if we didn't get an error, we always get entries.
//@ts-ignore
for (const e of entries) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
this.#callOnReaddirCB(children.slice(0, children.provisional));
return;
});
}
#asyncReaddirInFlight;
/**
* Return an array of known child entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async readdir() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
if (this.#asyncReaddirInFlight) {
await this.#asyncReaddirInFlight;
}
else {
/* c8 ignore start */
let resolve = () => { };
/* c8 ignore stop */
this.#asyncReaddirInFlight = new Promise(res => (resolve = res));
try {
for (const e of await this.#fs.promises.readdir(fullpath, {
withFileTypes: true,
})) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
catch (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
this.#asyncReaddirInFlight = undefined;
resolve();
}
return children.slice(0, children.provisional);
}
/**
* synchronous {@link PathBase.readdir}
*/
readdirSync() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
// else read the directory, fill up children
// de-provisionalize any provisional children.
const fullpath = this.fullpath();
try {
for (const e of this.#fs.readdirSync(fullpath, {
withFileTypes: true,
})) {
this.#readdirAddChild(e, children);
}
this.#readdirSuccess(children);
}
catch (er) {
this.#readdirFail(er.code);
children.provisional = 0;
}
return children.slice(0, children.provisional);
}
canReaddir() {
if (this.#type & ENOCHILD)
return false;
const ifmt = IFMT & this.#type;
// we always set ENOTDIR when setting IFMT, so should be impossible
/* c8 ignore start */
if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
return false;
}
/* c8 ignore stop */
return true;
}
shouldWalk(dirs, walkFilter) {
return ((this.#type & IFDIR) === IFDIR &&
!(this.#type & ENOCHILD) &&
!dirs.has(this) &&
(!walkFilter || walkFilter(this)));
}
/**
* Return the Path object corresponding to path as resolved
* by realpath(3).
*
* If the realpath call fails for any reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
* On success, returns a Path object.
*/
async realpath() {
if (this.#realpath)
return this.#realpath;
if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
return undefined;
try {
const rp = await this.#fs.promises.realpath(this.fullpath());
return (this.#realpath = this.resolve(rp));
}
catch (_) {
this.#markENOREALPATH();
}
}
/**
* Synchronous {@link realpath}
*/
realpathSync() {
if (this.#realpath)
return this.#realpath;
if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
return undefined;
try {
const rp = this.#fs.realpathSync(this.fullpath());
return (this.#realpath = this.resolve(rp));
}
catch (_) {
this.#markENOREALPATH();
}
}
/**
* Internal method to mark this Path object as the scurry cwd,
* called by {@link PathScurry#chdir}
*
* @internal
*/
[setAsCwd](oldCwd) {
if (oldCwd === this)
return;
oldCwd.isCWD = false;
this.isCWD = true;
const changed = new Set([]);
let rp = [];
let p = this;
while (p && p.parent) {
changed.add(p);
p.#relative = rp.join(this.sep);
p.#relativePosix = rp.join('/');
p = p.parent;
rp.push('..');
}
// now un-memoize parents of old cwd
p = oldCwd;
while (p && p.parent && !changed.has(p)) {
p.#relative = undefined;
p.#relativePosix = undefined;
p = p.parent;
}
}
}
/**
* Path class used on win32 systems
*
* Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'`
* as the path separator for parsing paths.
*/
class PathWin32 extends PathBase {
/**
* Separator for generating path strings.
*/
sep = '\\';
/**
* Separator for parsing path strings.
*/
splitSep = eitherSep;
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name, type, root, roots, nocase, children, opts);
}
/**
* @internal
*/
newChild(name, type = UNKNOWN, opts = {}) {
return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
/**
* @internal
*/
getRootString(path) {
return external_node_path_.win32.parse(path).root;
}
/**
* @internal
*/
getRoot(rootPath) {
rootPath = uncToDrive(rootPath.toUpperCase());
if (rootPath === this.root.name) {
return this.root;
}
// ok, not that one, check if it matches another we know about
for (const [compare, root] of Object.entries(this.roots)) {
if (this.sameRoot(rootPath, compare)) {
return (this.roots[rootPath] = root);
}
}
// otherwise, have to create a new one.
return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
}
/**
* @internal
*/
sameRoot(rootPath, compare = this.root.name) {
// windows can (rarely) have case-sensitive filesystem, but
// UNC and drive letters are always case-insensitive, and canonically
// represented uppercase.
rootPath = rootPath
.toUpperCase()
.replace(/\//g, '\\')
.replace(uncDriveRegexp, '$1\\');
return rootPath === compare;
}
}
/**
* Path class used on all posix systems.
*
* Uses `'/'` as the path separator.
*/
class PathPosix extends PathBase {
/**
* separator for parsing path strings
*/
splitSep = '/';
/**
* separator for generating path strings
*/
sep = '/';
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name, type, root, roots, nocase, children, opts);
}
/**
* @internal
*/
getRootString(path) {
return path.startsWith('/') ? '/' : '';
}
/**
* @internal
*/
getRoot(_rootPath) {
return this.root;
}
/**
* @internal
*/
newChild(name, type = UNKNOWN, opts = {}) {
return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
}
/**
* The base class for all PathScurry classes, providing the interface for path
* resolution and filesystem operations.
*
* Typically, you should *not* instantiate this class directly, but rather one
* of the platform-specific classes, or the exported {@link PathScurry} which
* defaults to the current platform.
*/
class PathScurryBase {
/**
* The root Path entry for the current working directory of this Scurry
*/
root;
/**
* The string path for the root of this Scurry's current working directory
*/
rootPath;
/**
* A collection of all roots encountered, referenced by rootPath
*/
roots;
/**
* The Path entry corresponding to this PathScurry's current working directory.
*/
cwd;
#resolveCache;
#resolvePosixCache;
#children;
/**
* Perform path comparisons case-insensitively.
*
* Defaults true on Darwin and Windows systems, false elsewhere.
*/
nocase;
#fs;
/**
* This class should not be instantiated directly.
*
* Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
*
* @internal
*/
constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) {
this.#fs = fsFromOption(fs);
if (cwd instanceof URL || cwd.startsWith('file://')) {
cwd = (0,external_node_url_.fileURLToPath)(cwd);
}
// resolve and split root, and then add to the store.
// this is the only time we call path.resolve()
const cwdPath = pathImpl.resolve(cwd);
this.roots = Object.create(null);
this.rootPath = this.parseRootPath(cwdPath);
this.#resolveCache = new ResolveCache();
this.#resolvePosixCache = new ResolveCache();
this.#children = new ChildrenCache(childrenCacheSize);
const split = cwdPath.substring(this.rootPath.length).split(sep);
// resolve('/') leaves '', splits to [''], we don't want that.
if (split.length === 1 && !split[0]) {
split.pop();
}
/* c8 ignore start */
if (nocase === undefined) {
throw new TypeError('must provide nocase setting to PathScurryBase ctor');
}
/* c8 ignore stop */
this.nocase = nocase;
this.root = this.newRoot(this.#fs);
this.roots[this.rootPath] = this.root;
let prev = this.root;
let len = split.length - 1;
const joinSep = pathImpl.sep;
let abs = this.rootPath;
let sawFirst = false;
for (const part of split) {
const l = len--;
prev = prev.child(part, {
relative: new Array(l).fill('..').join(joinSep),
relativePosix: new Array(l).fill('..').join('/'),
fullpath: (abs += (sawFirst ? '' : joinSep) + part),
});
sawFirst = true;
}
this.cwd = prev;
}
/**
* Get the depth of a provided path, string, or the cwd
*/
depth(path = this.cwd) {
if (typeof path === 'string') {
path = this.cwd.resolve(path);
}
return path.depth();
}
/**
* Return the cache of child entries. Exposed so subclasses can create
* child Path objects in a platform-specific way.
*
* @internal
*/
childrenCache() {
return this.#children;
}
/**
* Resolve one or more path strings to a resolved string
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolve(...paths) {
// first figure out the minimum number of paths we have to test
// we always start at cwd, but any absolutes will bump the start
let r = '';
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === '.')
continue;
r = r ? `${p}/${r}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = this.#resolveCache.get(r);
if (cached !== undefined) {
return cached;
}
const result = this.cwd.resolve(r).fullpath();
this.#resolveCache.set(r, result);
return result;
}
/**
* Resolve one or more path strings to a resolved string, returning
* the posix path. Identical to .resolve() on posix systems, but on
* windows will return a forward-slash separated UNC path.
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolvePosix(...paths) {
// first figure out the minimum number of paths we have to test
// we always start at cwd, but any absolutes will bump the start
let r = '';
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === '.')
continue;
r = r ? `${p}/${r}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = this.#resolvePosixCache.get(r);
if (cached !== undefined) {
return cached;
}
const result = this.cwd.resolve(r).fullpathPosix();
this.#resolvePosixCache.set(r, result);
return result;
}
/**
* find the relative path from the cwd to the supplied path string or entry
*/
relative(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.relative();
}
/**
* find the relative path from the cwd to the supplied path string or
* entry, using / as the path delimiter, even on Windows.
*/
relativePosix(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.relativePosix();
}
/**
* Return the basename for the provided string or Path object
*/
basename(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.name;
}
/**
* Return the dirname for the provided string or Path object
*/
dirname(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return (entry.parent || entry).fullpath();
}
async readdir(entry = this.cwd, opts = {
withFileTypes: true,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes } = opts;
if (!entry.canReaddir()) {
return [];
}
else {
const p = await entry.readdir();
return withFileTypes ? p : p.map(e => e.name);
}
}
readdirSync(entry = this.cwd, opts = {
withFileTypes: true,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true } = opts;
if (!entry.canReaddir()) {
return [];
}
else if (withFileTypes) {
return entry.readdirSync();
}
else {
return entry.readdirSync().map(e => e.name);
}
}
/**
* Call lstat() on the string or Path object, and update all known
* information that can be determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.lstat();
}
/**
* synchronous {@link PathScurryBase.lstat}
*/
lstatSync(entry = this.cwd) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
return entry.lstatSync();
}
async readlink(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = await entry.readlink();
return withFileTypes ? e : e?.fullpath();
}
readlinkSync(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = entry.readlinkSync();
return withFileTypes ? e : e?.fullpath();
}
async realpath(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = await entry.realpath();
return withFileTypes ? e : e?.fullpath();
}
realpathSync(entry = this.cwd, { withFileTypes } = {
withFileTypes: false,
}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
withFileTypes = entry.withFileTypes;
entry = this.cwd;
}
const e = entry.realpathSync();
return withFileTypes ? e : e?.fullpath();
}
async walk(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = [];
if (!filter || filter(entry)) {
results.push(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set();
const walk = (dir, cb) => {
dirs.add(dir);
dir.readdirCB((er, entries) => {
/* c8 ignore start */
if (er) {
return cb(er);
}
/* c8 ignore stop */
let len = entries.length;
if (!len)
return cb();
const next = () => {
if (--len === 0) {
cb();
}
};
for (const e of entries) {
if (!filter || filter(e)) {
results.push(withFileTypes ? e : e.fullpath());
}
if (follow && e.isSymbolicLink()) {
e.realpath()
.then(r => (r?.isUnknown() ? r.lstat() : r))
.then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
}
else {
if (e.shouldWalk(dirs, walkFilter)) {
walk(e, next);
}
else {
next();
}
}
}
}, true); // zalgooooooo
};
const start = entry;
return new Promise((res, rej) => {
walk(start, er => {
/* c8 ignore start */
if (er)
return rej(er);
/* c8 ignore stop */
res(results);
});
});
}
walkSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = [];
if (!filter || filter(entry)) {
results.push(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set([entry]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
results.push(withFileTypes ? e : e.fullpath());
}
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
dirs.add(r);
}
}
}
return results;
}
/**
* Support for `for await`
*
* Alias for {@link PathScurryBase.iterate}
*
* Note: As of Node 19, this is very slow, compared to other methods of
* walking. Consider using {@link PathScurryBase.stream} if memory overhead
* and backpressure are concerns, or {@link PathScurryBase.walk} if not.
*/
[Symbol.asyncIterator]() {
return this.iterate();
}
iterate(entry = this.cwd, options = {}) {
// iterating async over the stream is significantly more performant,
// especially in the warm-cache scenario, because it buffers up directory
// entries in the background instead of waiting for a yield for each one.
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
options = entry;
entry = this.cwd;
}
return this.stream(entry, options)[Symbol.asyncIterator]();
}
/**
* Iterating over a PathScurry performs a synchronous walk.
*
* Alias for {@link PathScurryBase.iterateSync}
*/
[Symbol.iterator]() {
return this.iterateSync();
}
*iterateSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
if (!filter || filter(entry)) {
yield withFileTypes ? entry : entry.fullpath();
}
const dirs = new Set([entry]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
yield withFileTypes ? e : e.fullpath();
}
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
dirs.add(r);
}
}
}
}
stream(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = new Minipass({ objectMode: true });
if (!filter || filter(entry)) {
results.write(withFileTypes ? entry : entry.fullpath());
}
const dirs = new Set();
const queue = [entry];
let processing = 0;
const process = () => {
let paused = false;
while (!paused) {
const dir = queue.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const onReaddir = (er, entries, didRealpaths = false) => {
/* c8 ignore start */
if (er)
return results.emit('error', er);
/* c8 ignore stop */
if (follow && !didRealpaths) {
const promises = [];
for (const e of entries) {
if (e.isSymbolicLink()) {
promises.push(e
.realpath()
.then((r) => r?.isUnknown() ? r.lstat() : r));
}
}
if (promises.length) {
Promise.all(promises).then(() => onReaddir(null, entries, true));
return;
}
}
for (const e of entries) {
if (e && (!filter || filter(e))) {
if (!results.write(withFileTypes ? e : e.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e of entries) {
const r = e.realpathCached() || e;
if (r.shouldWalk(dirs, walkFilter)) {
queue.push(r);
}
}
if (paused && !results.flowing) {
results.once('drain', process);
}
else if (!sync) {
process();
}
};
// zalgo containment
let sync = true;
dir.readdirCB(onReaddir, true);
sync = false;
}
};
process();
return results;
}
streamSync(entry = this.cwd, opts = {}) {
if (typeof entry === 'string') {
entry = this.cwd.resolve(entry);
}
else if (!(entry instanceof PathBase)) {
opts = entry;
entry = this.cwd;
}
const { withFileTypes = true, follow = false, filter, walkFilter, } = opts;
const results = new Minipass({ objectMode: true });
const dirs = new Set();
if (!filter || filter(entry)) {
results.write(withFileTypes ? entry : entry.fullpath());
}
const queue = [entry];
let processing = 0;
const process = () => {
let paused = false;
while (!paused) {
const dir = queue.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const entries = dir.readdirSync();
for (const e of entries) {
if (!filter || filter(e)) {
if (!results.write(withFileTypes ? e : e.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e of entries) {
let r = e;
if (e.isSymbolicLink()) {
if (!(follow && (r = e.realpathSync())))
continue;
if (r.isUnknown())
r.lstatSync();
}
if (r.shouldWalk(dirs, walkFilter)) {
queue.push(r);
}
}
}
if (paused && !results.flowing)
results.once('drain', process);
};
process();
return results;
}
chdir(path = this.cwd) {
const oldCwd = this.cwd;
this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path;
this.cwd[setAsCwd](oldCwd);
}
}
/**
* Windows implementation of {@link PathScurryBase}
*
* Defaults to case insensitve, uses `'\\'` to generate path strings. Uses
* {@link PathWin32} for Path objects.
*/
class PathScurryWin32 extends PathScurryBase {
/**
* separator for generating path strings
*/
sep = '\\';
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, external_node_path_.win32, '\\', { ...opts, nocase });
this.nocase = nocase;
for (let p = this.cwd; p; p = p.parent) {
p.nocase = this.nocase;
}
}
/**
* @internal
*/
parseRootPath(dir) {
// if the path starts with a single separator, it's not a UNC, and we'll
// just get separator as the root, and driveFromUNC will return \
// In that case, mount \ on the root from the cwd.
return external_node_path_.win32.parse(dir).root.toUpperCase();
}
/**
* @internal
*/
newRoot(fs) {
return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p));
}
}
/**
* {@link PathScurryBase} implementation for all posix systems other than Darwin.
*
* Defaults to case-sensitive matching, uses `'/'` to generate path strings.
*
* Uses {@link PathPosix} for Path objects.
*/
class PathScurryPosix extends PathScurryBase {
/**
* separator for generating path strings
*/
sep = '/';
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = false } = opts;
super(cwd, external_node_path_.posix, '/', { ...opts, nocase });
this.nocase = nocase;
}
/**
* @internal
*/
parseRootPath(_dir) {
return '/';
}
/**
* @internal
*/
newRoot(fs) {
return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return p.startsWith('/');
}
}
/**
* {@link PathScurryBase} implementation for Darwin (macOS) systems.
*
* Defaults to case-insensitive matching, uses `'/'` for generating path
* strings.
*
* Uses {@link PathPosix} for Path objects.
*/
class PathScurryDarwin extends PathScurryPosix {
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, { ...opts, nocase });
}
}
/**
* Default {@link PathBase} implementation for the current platform.
*
* {@link PathWin32} on Windows systems, {@link PathPosix} on all others.
*/
const Path = process.platform === 'win32' ? PathWin32 : PathPosix;
/**
* Default {@link PathScurryBase} implementation for the current platform.
*
* {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on
* Darwin (macOS) systems, {@link PathScurryPosix} on all others.
*/
const PathScurry = process.platform === 'win32' ? PathScurryWin32
: process.platform === 'darwin' ? PathScurryDarwin
: PathScurryPosix;
//# sourceMappingURL=index.js.map
;// ../commons/node_modules/glob/dist/esm/pattern.js
// this is just a very light wrapper around 2 arrays with an offset index
const isPatternList = (pl) => pl.length >= 1;
const isGlobList = (gl) => gl.length >= 1;
/**
* An immutable-ish view on an array of glob parts and their parsed
* results
*/
class Pattern {
#patternList;
#globList;
#index;
length;
#platform;
#rest;
#globString;
#isDrive;
#isUNC;
#isAbsolute;
#followGlobstar = true;
constructor(patternList, globList, index, platform) {
if (!isPatternList(patternList)) {
throw new TypeError('empty pattern list');
}
if (!isGlobList(globList)) {
throw new TypeError('empty glob list');
}
if (globList.length !== patternList.length) {
throw new TypeError('mismatched pattern list and glob list lengths');
}
this.length = patternList.length;
if (index < 0 || index >= this.length) {
throw new TypeError('index out of range');
}
this.#patternList = patternList;
this.#globList = globList;
this.#index = index;
this.#platform = platform;
// normalize root entries of absolute patterns on initial creation.
if (this.#index === 0) {
// c: => ['c:/']
// C:/ => ['C:/']
// C:/x => ['C:/', 'x']
// //host/share => ['//host/share/']
// //host/share/ => ['//host/share/']
// //host/share/x => ['//host/share/', 'x']
// /etc => ['/', 'etc']
// / => ['/']
if (this.isUNC()) {
// '' / '' / 'host' / 'share'
const [p0, p1, p2, p3, ...prest] = this.#patternList;
const [g0, g1, g2, g3, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = [p0, p1, p2, p3, ''].join('/');
const g = [g0, g1, g2, g3, ''].join('/');
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
else if (this.isDrive() || this.isAbsolute()) {
const [p1, ...prest] = this.#patternList;
const [g1, ...grest] = this.#globList;
if (prest[0] === '') {
// ends in /
prest.shift();
grest.shift();
}
const p = p1 + '/';
const g = g1 + '/';
this.#patternList = [p, ...prest];
this.#globList = [g, ...grest];
this.length = this.#patternList.length;
}
}
}
/**
* The first entry in the parsed list of patterns
*/
pattern() {
return this.#patternList[this.#index];
}
/**
* true of if pattern() returns a string
*/
isString() {
return typeof this.#patternList[this.#index] === 'string';
}
/**
* true of if pattern() returns GLOBSTAR
*/
isGlobstar() {
return this.#patternList[this.#index] === GLOBSTAR;
}
/**
* true if pattern() returns a regexp
*/
isRegExp() {
return this.#patternList[this.#index] instanceof RegExp;
}
/**
* The /-joined set of glob parts that make up this pattern
*/
globString() {
return (this.#globString =
this.#globString ||
(this.#index === 0 ?
this.isAbsolute() ?
this.#globList[0] + this.#globList.slice(1).join('/')
: this.#globList.join('/')
: this.#globList.slice(this.#index).join('/')));
}
/**
* true if there are more pattern parts after this one
*/
hasMore() {
return this.length > this.#index + 1;
}
/**
* The rest of the pattern after this part, or null if this is the end
*/
rest() {
if (this.#rest !== undefined)
return this.#rest;
if (!this.hasMore())
return (this.#rest = null);
this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
this.#rest.#isAbsolute = this.#isAbsolute;
this.#rest.#isUNC = this.#isUNC;
this.#rest.#isDrive = this.#isDrive;
return this.#rest;
}
/**
* true if the pattern represents a //unc/path/ on windows
*/
isUNC() {
const pl = this.#patternList;
return this.#isUNC !== undefined ?
this.#isUNC
: (this.#isUNC =
this.#platform === 'win32' &&
this.#index === 0 &&
pl[0] === '' &&
pl[1] === '' &&
typeof pl[2] === 'string' &&
!!pl[2] &&
typeof pl[3] === 'string' &&
!!pl[3]);
}
// pattern like C:/...
// split = ['C:', ...]
// XXX: would be nice to handle patterns like `c:*` to test the cwd
// in c: for *, but I don't know of a way to even figure out what that
// cwd is without actually chdir'ing into it?
/**
* True if the pattern starts with a drive letter on Windows
*/
isDrive() {
const pl = this.#patternList;
return this.#isDrive !== undefined ?
this.#isDrive
: (this.#isDrive =
this.#platform === 'win32' &&
this.#index === 0 &&
this.length > 1 &&
typeof pl[0] === 'string' &&
/^[a-z]:$/i.test(pl[0]));
}
// pattern = '/' or '/...' or '/x/...'
// split = ['', ''] or ['', ...] or ['', 'x', ...]
// Drive and UNC both considered absolute on windows
/**
* True if the pattern is rooted on an absolute path
*/
isAbsolute() {
const pl = this.#patternList;
return this.#isAbsolute !== undefined ?
this.#isAbsolute
: (this.#isAbsolute =
(pl[0] === '' && pl.length > 1) ||
this.isDrive() ||
this.isUNC());
}
/**
* consume the root of the pattern, and return it
*/
root() {
const p = this.#patternList[0];
return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
p
: '';
}
/**
* Check to see if the current globstar pattern is allowed to follow
* a symbolic link.
*/
checkFollowGlobstar() {
return !(this.#index === 0 ||
!this.isGlobstar() ||
!this.#followGlobstar);
}
/**
* Mark that the current globstar pattern is following a symbolic link
*/
markFollowGlobstar() {
if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
return false;
this.#followGlobstar = false;
return true;
}
}
//# sourceMappingURL=pattern.js.map
;// ../commons/node_modules/glob/dist/esm/ignore.js
// give it a pattern, and it'll be able to tell you if
// a given path should be ignored.
// Ignoring a path ignores its children if the pattern ends in /**
// Ignores are always parsed in dot:true mode
const ignore_defaultPlatform = (typeof process === 'object' &&
process &&
typeof process.platform === 'string') ?
process.platform
: 'linux';
/**
* Class used to process ignored patterns
*/
class Ignore {
relative;
relativeChildren;
absolute;
absoluteChildren;
platform;
mmopts;
constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = ignore_defaultPlatform, }) {
this.relative = [];
this.absolute = [];
this.relativeChildren = [];
this.absoluteChildren = [];
this.platform = platform;
this.mmopts = {
dot: true,
nobrace,
nocase,
noext,
noglobstar,
optimizationLevel: 2,
platform,
nocomment: true,
nonegate: true,
};
for (const ign of ignored)
this.add(ign);
}
add(ign) {
// this is a little weird, but it gives us a clean set of optimized
// minimatch matchers, without getting tripped up if one of them
// ends in /** inside a brace section, and it's only inefficient at
// the start of the walk, not along it.
// It'd be nice if the Pattern class just had a .test() method, but
// handling globstars is a bit of a pita, and that code already lives
// in minimatch anyway.
// Another way would be if maybe Minimatch could take its set/globParts
// as an option, and then we could at least just use Pattern to test
// for absolute-ness.
// Yet another way, Minimatch could take an array of glob strings, and
// a cwd option, and do the right thing.
const mm = new Minimatch(ign, this.mmopts);
for (let i = 0; i < mm.set.length; i++) {
const parsed = mm.set[i];
const globParts = mm.globParts[i];
/* c8 ignore start */
if (!parsed || !globParts) {
throw new Error('invalid pattern object');
}
// strip off leading ./ portions
// https://github.com/isaacs/node-glob/issues/570
while (parsed[0] === '.' && globParts[0] === '.') {
parsed.shift();
globParts.shift();
}
/* c8 ignore stop */
const p = new Pattern(parsed, globParts, 0, this.platform);
const m = new Minimatch(p.globString(), this.mmopts);
const children = globParts[globParts.length - 1] === '**';
const absolute = p.isAbsolute();
if (absolute)
this.absolute.push(m);
else
this.relative.push(m);
if (children) {
if (absolute)
this.absoluteChildren.push(m);
else
this.relativeChildren.push(m);
}
}
}
ignored(p) {
const fullpath = p.fullpath();
const fullpaths = `${fullpath}/`;
const relative = p.relative() || '.';
const relatives = `${relative}/`;
for (const m of this.relative) {
if (m.match(relative) || m.match(relatives))
return true;
}
for (const m of this.absolute) {
if (m.match(fullpath) || m.match(fullpaths))
return true;
}
return false;
}
childrenIgnored(p) {
const fullpath = p.fullpath() + '/';
const relative = (p.relative() || '.') + '/';
for (const m of this.relativeChildren) {
if (m.match(relative))
return true;
}
for (const m of this.absoluteChildren) {
if (m.match(fullpath))
return true;
}
return false;
}
}
//# sourceMappingURL=ignore.js.map
;// ../commons/node_modules/glob/dist/esm/processor.js
// synchronous utility for filtering entries and calculating subwalks
/**
* A cache of which patterns have been processed for a given Path
*/
class HasWalkedCache {
store;
constructor(store = new Map()) {
this.store = store;
}
copy() {
return new HasWalkedCache(new Map(this.store));
}
hasWalked(target, pattern) {
return this.store.get(target.fullpath())?.has(pattern.globString());
}
storeWalked(target, pattern) {
const fullpath = target.fullpath();
const cached = this.store.get(fullpath);
if (cached)
cached.add(pattern.globString());
else
this.store.set(fullpath, new Set([pattern.globString()]));
}
}
/**
* A record of which paths have been matched in a given walk step,
* and whether they only are considered a match if they are a directory,
* and whether their absolute or relative path should be returned.
*/
class MatchRecord {
store = new Map();
add(target, absolute, ifDir) {
const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
const current = this.store.get(target);
this.store.set(target, current === undefined ? n : n & current);
}
// match, absolute, ifdir
entries() {
return [...this.store.entries()].map(([path, n]) => [
path,
!!(n & 2),
!!(n & 1),
]);
}
}
/**
* A collection of patterns that must be processed in a subsequent step
* for a given path.
*/
class SubWalks {
store = new Map();
add(target, pattern) {
if (!target.canReaddir()) {
return;
}
const subs = this.store.get(target);
if (subs) {
if (!subs.find(p => p.globString() === pattern.globString())) {
subs.push(pattern);
}
}
else
this.store.set(target, [pattern]);
}
get(target) {
const subs = this.store.get(target);
/* c8 ignore start */
if (!subs) {
throw new Error('attempting to walk unknown path');
}
/* c8 ignore stop */
return subs;
}
entries() {
return this.keys().map(k => [k, this.store.get(k)]);
}
keys() {
return [...this.store.keys()].filter(t => t.canReaddir());
}
}
/**
* The class that processes patterns for a given path.
*
* Handles child entry filtering, and determining whether a path's
* directory contents must be read.
*/
class Processor {
hasWalkedCache;
matches = new MatchRecord();
subwalks = new SubWalks();
patterns;
follow;
dot;
opts;
constructor(opts, hasWalkedCache) {
this.opts = opts;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.hasWalkedCache =
hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
}
processPatterns(target, patterns) {
this.patterns = patterns;
const processingSet = patterns.map(p => [target, p]);
// map of paths to the magic-starting subwalks they need to walk
// first item in patterns is the filter
for (let [t, pattern] of processingSet) {
this.hasWalkedCache.storeWalked(t, pattern);
const root = pattern.root();
const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
// start absolute patterns at root
if (root) {
t = t.resolve(root === '/' && this.opts.root !== undefined ?
this.opts.root
: root);
const rest = pattern.rest();
if (!rest) {
this.matches.add(t, true, false);
continue;
}
else {
pattern = rest;
}
}
if (t.isENOENT())
continue;
let p;
let rest;
let changed = false;
while (typeof (p = pattern.pattern()) === 'string' &&
(rest = pattern.rest())) {
const c = t.resolve(p);
t = c;
pattern = rest;
changed = true;
}
p = pattern.pattern();
rest = pattern.rest();
if (changed) {
if (this.hasWalkedCache.hasWalked(t, pattern))
continue;
this.hasWalkedCache.storeWalked(t, pattern);
}
// now we have either a final string for a known entry,
// more strings for an unknown entry,
// or a pattern starting with magic, mounted on t.
if (typeof p === 'string') {
// must not be final entry, otherwise we would have
// concatenated it earlier.
const ifDir = p === '..' || p === '' || p === '.';
this.matches.add(t.resolve(p), absolute, ifDir);
continue;
}
else if (p === GLOBSTAR) {
// if no rest, match and subwalk pattern
// if rest, process rest and subwalk pattern
// if it's a symlink, but we didn't get here by way of a
// globstar match (meaning it's the first time THIS globstar
// has traversed a symlink), then we follow it. Otherwise, stop.
if (!t.isSymbolicLink() ||
this.follow ||
pattern.checkFollowGlobstar()) {
this.subwalks.add(t, pattern);
}
const rp = rest?.pattern();
const rrest = rest?.rest();
if (!rest || ((rp === '' || rp === '.') && !rrest)) {
// only HAS to be a dir if it ends in **/ or **/.
// but ending in ** will match files as well.
this.matches.add(t, absolute, rp === '' || rp === '.');
}
else {
if (rp === '..') {
// this would mean you're matching **/.. at the fs root,
// and no thanks, I'm not gonna test that specific case.
/* c8 ignore start */
const tp = t.parent || t;
/* c8 ignore stop */
if (!rrest)
this.matches.add(tp, absolute, true);
else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
this.subwalks.add(tp, rrest);
}
}
}
}
else if (p instanceof RegExp) {
this.subwalks.add(t, pattern);
}
}
return this;
}
subwalkTargets() {
return this.subwalks.keys();
}
child() {
return new Processor(this.opts, this.hasWalkedCache);
}
// return a new Processor containing the subwalks for each
// child entry, and a set of matches, and
// a hasWalkedCache that's a copy of this one
// then we're going to call
filterEntries(parent, entries) {
const patterns = this.subwalks.get(parent);
// put matches and entry walks into the results processor
const results = this.child();
for (const e of entries) {
for (const pattern of patterns) {
const absolute = pattern.isAbsolute();
const p = pattern.pattern();
const rest = pattern.rest();
if (p === GLOBSTAR) {
results.testGlobstar(e, pattern, rest, absolute);
}
else if (p instanceof RegExp) {
results.testRegExp(e, p, rest, absolute);
}
else {
results.testString(e, p, rest, absolute);
}
}
}
return results;
}
testGlobstar(e, pattern, rest, absolute) {
if (this.dot || !e.name.startsWith('.')) {
if (!pattern.hasMore()) {
this.matches.add(e, absolute, false);
}
if (e.canReaddir()) {
// if we're in follow mode or it's not a symlink, just keep
// testing the same pattern. If there's more after the globstar,
// then this symlink consumes the globstar. If not, then we can
// follow at most ONE symlink along the way, so we mark it, which
// also checks to ensure that it wasn't already marked.
if (this.follow || !e.isSymbolicLink()) {
this.subwalks.add(e, pattern);
}
else if (e.isSymbolicLink()) {
if (rest && pattern.checkFollowGlobstar()) {
this.subwalks.add(e, rest);
}
else if (pattern.markFollowGlobstar()) {
this.subwalks.add(e, pattern);
}
}
}
}
// if the NEXT thing matches this entry, then also add
// the rest.
if (rest) {
const rp = rest.pattern();
if (typeof rp === 'string' &&
// dots and empty were handled already
rp !== '..' &&
rp !== '' &&
rp !== '.') {
this.testString(e, rp, rest.rest(), absolute);
}
else if (rp === '..') {
/* c8 ignore start */
const ep = e.parent || e;
/* c8 ignore stop */
this.subwalks.add(ep, rest);
}
else if (rp instanceof RegExp) {
this.testRegExp(e, rp, rest.rest(), absolute);
}
}
}
testRegExp(e, p, rest, absolute) {
if (!p.test(e.name))
return;
if (!rest) {
this.matches.add(e, absolute, false);
}
else {
this.subwalks.add(e, rest);
}
}
testString(e, p, rest, absolute) {
// should never happen?
if (!e.isNamed(p))
return;
if (!rest) {
this.matches.add(e, absolute, false);
}
else {
this.subwalks.add(e, rest);
}
}
}
//# sourceMappingURL=processor.js.map
;// ../commons/node_modules/glob/dist/esm/walker.js
/**
* Single-use utility classes to provide functionality to the {@link Glob}
* methods.
*
* @module
*/
const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts)
: Array.isArray(ignore) ? new Ignore(ignore, opts)
: ignore;
/**
* basic walking utilities that all the glob walker types use
*/
class GlobUtil {
path;
patterns;
opts;
seen = new Set();
paused = false;
aborted = false;
#onResume = [];
#ignore;
#sep;
signal;
maxDepth;
includeChildMatches;
constructor(patterns, path, opts) {
this.patterns = patterns;
this.path = path;
this.opts = opts;
this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
this.includeChildMatches = opts.includeChildMatches !== false;
if (opts.ignore || !this.includeChildMatches) {
this.#ignore = makeIgnore(opts.ignore ?? [], opts);
if (!this.includeChildMatches &&
typeof this.#ignore.add !== 'function') {
const m = 'cannot ignore child matches, ignore lacks add() method.';
throw new Error(m);
}
}
// ignore, always set with maxDepth, but it's optional on the
// GlobOptions type
/* c8 ignore start */
this.maxDepth = opts.maxDepth || Infinity;
/* c8 ignore stop */
if (opts.signal) {
this.signal = opts.signal;
this.signal.addEventListener('abort', () => {
this.#onResume.length = 0;
});
}
}
#ignored(path) {
return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
}
#childrenIgnored(path) {
return !!this.#ignore?.childrenIgnored?.(path);
}
// backpressure mechanism
pause() {
this.paused = true;
}
resume() {
/* c8 ignore start */
if (this.signal?.aborted)
return;
/* c8 ignore stop */
this.paused = false;
let fn = undefined;
while (!this.paused && (fn = this.#onResume.shift())) {
fn();
}
}
onResume(fn) {
if (this.signal?.aborted)
return;
/* c8 ignore start */
if (!this.paused) {
fn();
}
else {
/* c8 ignore stop */
this.#onResume.push(fn);
}
}
// do the requisite realpath/stat checking, and return the path
// to add or undefined to filter it out.
async matchCheck(e, ifDir) {
if (ifDir && this.opts.nodir)
return undefined;
let rpc;
if (this.opts.realpath) {
rpc = e.realpathCached() || (await e.realpath());
if (!rpc)
return undefined;
e = rpc;
}
const needStat = e.isUnknown() || this.opts.stat;
const s = needStat ? await e.lstat() : e;
if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
const target = await s.realpath();
/* c8 ignore start */
if (target && (target.isUnknown() || this.opts.stat)) {
await target.lstat();
}
/* c8 ignore stop */
}
return this.matchCheckTest(s, ifDir);
}
matchCheckTest(e, ifDir) {
return (e &&
(this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
(!ifDir || e.canReaddir()) &&
(!this.opts.nodir || !e.isDirectory()) &&
(!this.opts.nodir ||
!this.opts.follow ||
!e.isSymbolicLink() ||
!e.realpathCached()?.isDirectory()) &&
!this.#ignored(e)) ?
e
: undefined;
}
matchCheckSync(e, ifDir) {
if (ifDir && this.opts.nodir)
return undefined;
let rpc;
if (this.opts.realpath) {
rpc = e.realpathCached() || e.realpathSync();
if (!rpc)
return undefined;
e = rpc;
}
const needStat = e.isUnknown() || this.opts.stat;
const s = needStat ? e.lstatSync() : e;
if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
const target = s.realpathSync();
if (target && (target?.isUnknown() || this.opts.stat)) {
target.lstatSync();
}
}
return this.matchCheckTest(s, ifDir);
}
matchFinish(e, absolute) {
if (this.#ignored(e))
return;
// we know we have an ignore if this is false, but TS doesn't
if (!this.includeChildMatches && this.#ignore?.add) {
const ign = `${e.relativePosix()}/**`;
this.#ignore.add(ign);
}
const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
this.seen.add(e);
const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
// ok, we have what we need!
if (this.opts.withFileTypes) {
this.matchEmit(e);
}
else if (abs) {
const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
this.matchEmit(abs + mark);
}
else {
const rel = this.opts.posix ? e.relativePosix() : e.relative();
const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
'.' + this.#sep
: '';
this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
}
}
async match(e, absolute, ifDir) {
const p = await this.matchCheck(e, ifDir);
if (p)
this.matchFinish(p, absolute);
}
matchSync(e, absolute, ifDir) {
const p = this.matchCheckSync(e, ifDir);
if (p)
this.matchFinish(p, absolute);
}
walkCB(target, patterns, cb) {
/* c8 ignore start */
if (this.signal?.aborted)
cb();
/* c8 ignore stop */
this.walkCB2(target, patterns, new Processor(this.opts), cb);
}
walkCB2(target, patterns, processor, cb) {
if (this.#childrenIgnored(target))
return cb();
if (this.signal?.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
// done processing. all of the above is sync, can be abstracted out.
// subwalks is a map of paths to the entry filters they need
// matches is a map of paths to [absolute, ifDir] tuples.
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
tasks++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const t of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
continue;
}
tasks++;
const childrenCached = t.readdirCached();
if (t.calledReaddir())
this.walkCB3(t, childrenCached, processor, next);
else {
t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
}
}
next();
}
walkCB3(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
tasks++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const [target, patterns] of processor.subwalks.entries()) {
tasks++;
this.walkCB2(target, patterns, processor.child(), next);
}
next();
}
walkCBSync(target, patterns, cb) {
/* c8 ignore start */
if (this.signal?.aborted)
cb();
/* c8 ignore stop */
this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
}
walkCB2Sync(target, patterns, processor, cb) {
if (this.#childrenIgnored(target))
return cb();
if (this.signal?.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
// done processing. all of the above is sync, can be abstracted out.
// subwalks is a map of paths to the entry filters they need
// matches is a map of paths to [absolute, ifDir] tuples.
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const t of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
continue;
}
tasks++;
const children = t.readdirSync();
this.walkCB3Sync(t, children, processor, next);
}
next();
}
walkCB3Sync(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks = 1;
const next = () => {
if (--tasks === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (this.#ignored(m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const [target, patterns] of processor.subwalks.entries()) {
tasks++;
this.walkCB2Sync(target, patterns, processor.child(), next);
}
next();
}
}
class GlobWalker extends GlobUtil {
matches = new Set();
constructor(patterns, path, opts) {
super(patterns, path, opts);
}
matchEmit(e) {
this.matches.add(e);
}
async walk() {
if (this.signal?.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
await this.path.lstat();
}
await new Promise((res, rej) => {
this.walkCB(this.path, this.patterns, () => {
if (this.signal?.aborted) {
rej(this.signal.reason);
}
else {
res(this.matches);
}
});
});
return this.matches;
}
walkSync() {
if (this.signal?.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
this.path.lstatSync();
}
// nothing for the callback to do, because this never pauses
this.walkCBSync(this.path, this.patterns, () => {
if (this.signal?.aborted)
throw this.signal.reason;
});
return this.matches;
}
}
class GlobStream extends GlobUtil {
results;
constructor(patterns, path, opts) {
super(patterns, path, opts);
this.results = new Minipass({
signal: this.signal,
objectMode: true,
});
this.results.on('drain', () => this.resume());
this.results.on('resume', () => this.resume());
}
matchEmit(e) {
this.results.write(e);
if (!this.results.flowing)
this.pause();
}
stream() {
const target = this.path;
if (target.isUnknown()) {
target.lstat().then(() => {
this.walkCB(target, this.patterns, () => this.results.end());
});
}
else {
this.walkCB(target, this.patterns, () => this.results.end());
}
return this.results;
}
streamSync() {
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => this.results.end());
return this.results;
}
}
//# sourceMappingURL=walker.js.map
;// ../commons/node_modules/glob/dist/esm/glob.js
// if no process global, just call it linux.
// so we default to case-sensitive, / separators
const glob_defaultPlatform = (typeof process === 'object' &&
process &&
typeof process.platform === 'string') ?
process.platform
: 'linux';
/**
* An object that can perform glob pattern traversals.
*/
class Glob {
absolute;
cwd;
root;
dot;
dotRelative;
follow;
ignore;
magicalBraces;
mark;
matchBase;
maxDepth;
nobrace;
nocase;
nodir;
noext;
noglobstar;
pattern;
platform;
realpath;
scurry;
stat;
signal;
windowsPathsNoEscape;
withFileTypes;
includeChildMatches;
/**
* The options provided to the constructor.
*/
opts;
/**
* An array of parsed immutable {@link Pattern} objects.
*/
patterns;
/**
* All options are stored as properties on the `Glob` object.
*
* See {@link GlobOptions} for full options descriptions.
*
* Note that a previous `Glob` object can be passed as the
* `GlobOptions` to another `Glob` instantiation to re-use settings
* and caches with a new pattern.
*
* Traversal functions can be called multiple times to run the walk
* again.
*/
constructor(pattern, opts) {
/* c8 ignore start */
if (!opts)
throw new TypeError('glob options required');
/* c8 ignore stop */
this.withFileTypes = !!opts.withFileTypes;
this.signal = opts.signal;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.dotRelative = !!opts.dotRelative;
this.nodir = !!opts.nodir;
this.mark = !!opts.mark;
if (!opts.cwd) {
this.cwd = '';
}
else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
opts.cwd = (0,external_node_url_.fileURLToPath)(opts.cwd);
}
this.cwd = opts.cwd || '';
this.root = opts.root;
this.magicalBraces = !!opts.magicalBraces;
this.nobrace = !!opts.nobrace;
this.noext = !!opts.noext;
this.realpath = !!opts.realpath;
this.absolute = opts.absolute;
this.includeChildMatches = opts.includeChildMatches !== false;
this.noglobstar = !!opts.noglobstar;
this.matchBase = !!opts.matchBase;
this.maxDepth =
typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
this.stat = !!opts.stat;
this.ignore = opts.ignore;
if (this.withFileTypes && this.absolute !== undefined) {
throw new Error('cannot set absolute and withFileTypes:true');
}
if (typeof pattern === 'string') {
pattern = [pattern];
}
this.windowsPathsNoEscape =
!!opts.windowsPathsNoEscape ||
opts.allowWindowsEscape ===
false;
if (this.windowsPathsNoEscape) {
pattern = pattern.map(p => p.replace(/\\/g, '/'));
}
if (this.matchBase) {
if (opts.noglobstar) {
throw new TypeError('base matching requires globstar');
}
pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
}
this.pattern = pattern;
this.platform = opts.platform || glob_defaultPlatform;
this.opts = { ...opts, platform: this.platform };
if (opts.scurry) {
this.scurry = opts.scurry;
if (opts.nocase !== undefined &&
opts.nocase !== opts.scurry.nocase) {
throw new Error('nocase option contradicts provided scurry option');
}
}
else {
const Scurry = opts.platform === 'win32' ? PathScurryWin32
: opts.platform === 'darwin' ? PathScurryDarwin
: opts.platform ? PathScurryPosix
: PathScurry;
this.scurry = new Scurry(this.cwd, {
nocase: opts.nocase,
fs: opts.fs,
});
}
this.nocase = this.scurry.nocase;
// If you do nocase:true on a case-sensitive file system, then
// we need to use regexps instead of strings for non-magic
// path portions, because statting `aBc` won't return results
// for the file `AbC` for example.
const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
const mmo = {
// default nocase based on platform
...opts,
dot: this.dot,
matchBase: this.matchBase,
nobrace: this.nobrace,
nocase: this.nocase,
nocaseMagicOnly,
nocomment: true,
noext: this.noext,
nonegate: true,
optimizationLevel: 2,
platform: this.platform,
windowsPathsNoEscape: this.windowsPathsNoEscape,
debug: !!this.opts.debug,
};
const mms = this.pattern.map(p => new Minimatch(p, mmo));
const [matchSet, globParts] = mms.reduce((set, m) => {
set[0].push(...m.set);
set[1].push(...m.globParts);
return set;
}, [[], []]);
this.patterns = matchSet.map((set, i) => {
const g = globParts[i];
/* c8 ignore start */
if (!g)
throw new Error('invalid pattern object');
/* c8 ignore stop */
return new Pattern(set, g, 0, this.platform);
});
}
async walk() {
// Walkers always return array of Path objects, so we just have to
// coerce them into the right shape. It will have already called
// realpath() if the option was set to do so, so we know that's cached.
// start out knowing the cwd, at least
return [
...(await new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).walk()),
];
}
walkSync() {
return [
...new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).walkSync(),
];
}
stream() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).stream();
}
streamSync() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ?
this.maxDepth + this.scurry.cwd.depth()
: Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches,
}).streamSync();
}
/**
* Default sync iteration function. Returns a Generator that
* iterates over the results.
*/
iterateSync() {
return this.streamSync()[Symbol.iterator]();
}
[Symbol.iterator]() {
return this.iterateSync();
}
/**
* Default async iteration function. Returns an AsyncGenerator that
* iterates over the results.
*/
iterate() {
return this.stream()[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
}
//# sourceMappingURL=glob.js.map
;// ../commons/node_modules/glob/dist/esm/has-magic.js
/**
* Return true if the patterns provided contain any magic glob characters,
* given the options provided.
*
* Brace expansion is not considered "magic" unless the `magicalBraces` option
* is set, as brace expansion just turns one string into an array of strings.
* So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
* `'xby'` both do not contain any magic glob characters, and it's treated the
* same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
* is in the options, brace expansion _is_ treated as a pattern having magic.
*/
const hasMagic = (pattern, options = {}) => {
if (!Array.isArray(pattern)) {
pattern = [pattern];
}
for (const p of pattern) {
if (new Minimatch(p, options).hasMagic())
return true;
}
return false;
};
//# sourceMappingURL=has-magic.js.map
;// ../commons/node_modules/glob/dist/esm/index.js
function globStreamSync(pattern, options = {}) {
return new Glob(pattern, options).streamSync();
}
function globStream(pattern, options = {}) {
return new Glob(pattern, options).stream();
}
function esm_globSync(pattern, options = {}) {
return new Glob(pattern, options).walkSync();
}
async function glob_(pattern, options = {}) {
return new Glob(pattern, options).walk();
}
function globIterateSync(pattern, options = {}) {
return new Glob(pattern, options).iterateSync();
}
function globIterate(pattern, options = {}) {
return new Glob(pattern, options).iterate();
}
// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
const streamSync = globStreamSync;
const stream = Object.assign(globStream, { sync: globStreamSync });
const iterateSync = globIterateSync;
const iterate = Object.assign(globIterate, {
sync: globIterateSync,
});
const sync = Object.assign(esm_globSync, {
stream: globStreamSync,
iterate: globIterateSync,
});
const glob = Object.assign(glob_, {
glob: glob_,
globSync: esm_globSync,
sync,
globStream,
stream,
globStreamSync,
streamSync,
globIterate,
iterate,
globIterateSync,
iterateSync,
Glob: Glob,
hasMagic: hasMagic,
escape: escape_escape,
unescape: unescape_unescape,
});
glob.glob = glob;
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: external "os"
var external_os_ = __webpack_require__(857);
;// ../commons/dist/fs/glob-parent.js
const isWin32 = (0,external_os_.platform)() === 'win32';
const slash = '/';
const backslash = /\\/g;
const escaped = /\\([!*?|[\](){}])/g;
const globParent = (str, opts) => {
const options = { flipBackslashes: true, ...opts };
// flip windows path separators
if (options.flipBackslashes && isWin32 && !str.includes(slash)) {
str = str.replace(backslash, slash);
}
// special case for strings ending in enclosure containing path separator
if (isEnclosure(str)) {
str += slash;
}
// preserves full path in case of trailing path separator
str += 'a';
// remove path parts that are globby
do {
str = external_path_.posix.dirname(str);
} while (isGlobby(str));
// remove escape chars and return result
return str.replace(escaped, '$1');
};
function isEnclosure(str) {
const lastChar = str.slice(-1);
let enclosureStart;
switch (lastChar) {
case '}':
enclosureStart = '{';
break;
case ']':
enclosureStart = '[';
break;
default:
return false;
}
const foundIndex = str.indexOf(enclosureStart);
if (foundIndex < 0) {
return false;
}
return str.slice(foundIndex + 1, -1).includes(slash);
}
function isGlobby(str) {
if (/\([^()]+$/.test(str)) {
return true;
}
if (str[0] === '{' || str[0] === '[') {
return true;
}
if (/[^\\][{[]/.test(str)) {
return true;
}
return hasMagic(str);
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYi1wYXJlbnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZnMvZ2xvYi1wYXJlbnQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLE1BQU0sQ0FBQTtBQUM1QixPQUFPLEVBQUUsUUFBUSxFQUFFLE1BQU0sSUFBSSxDQUFBO0FBQzdCLE9BQU8sRUFBRSxRQUFRLEVBQUUsTUFBTSxNQUFNLENBQUE7QUFFL0IsTUFBTSxPQUFPLEdBQUcsUUFBUSxFQUFFLEtBQUssT0FBTyxDQUFBO0FBRXRDLE1BQU0sS0FBSyxHQUFHLEdBQUcsQ0FBQztBQUNsQixNQUFNLFNBQVMsR0FBRyxLQUFLLENBQUM7QUFDeEIsTUFBTSxPQUFPLEdBQUcsb0JBQW9CLENBQUM7QUFNckMsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHLENBQUMsR0FBVyxFQUFFLElBQWMsRUFBVSxFQUFFO0lBQ2hFLE1BQU0sT0FBTyxHQUFZLEVBQUUsZUFBZSxFQUFFLElBQUksRUFBRSxHQUFHLElBQUksRUFBRSxDQUFDO0lBRTVELCtCQUErQjtJQUMvQixJQUFJLE9BQU8sQ0FBQyxlQUFlLElBQUksT0FBTyxJQUFJLENBQUMsR0FBRyxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsRUFBR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LLENBQUM7SUFDZixDQUFDO0lBRUQsT0FBTyxHQUFHLENBQUMsS0FBSyxDQUFDLFVBQVUsR0FBRyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQyxRQUFRLENBQUMsS0FBSyxDQUFDLENBQUM7QUFDdkQsQ0FBQztBQUVELFNBQVMsUUFBUSxDQUFDLEdBQVc7SUFDM0IsSUFBSSxXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUM7UUFDMUIsT0FBTyxJQUFJLENBQUM7SUFDZCxDQUFDO0lBQ0QsSUFBSSxHQUFHLENBQUMsQ0FBQyxDQUFDLEtBQUssR0FBRyxJQUFJLEdBQUcsQ0FBQyxDQUFDLENBQUMsS0FBSyxHQUFHLEVBQUUsQ0FBQztRQUNyQyxPQUFPLElBQUksQ0FBQztJQUNkLENBQUM7SUFDRCxJQUFJLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQztRQUMxQixPQUFPLElBQUksQ0FBQztJQUNkLENBQUM7SUFDRCxPQUFPLFFBQVEsQ0FBQyxHQUFHLENBQUMsQ0FBQztBQUN2QixDQUFDIn0=
;// ../commons/dist/fs/glob-base.js
/*!
* glob-base
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
function dirname(glob) {
if (glob.slice(-1) === '/')
return glob;
return (0,external_path_.dirname)(glob);
}
const globBase = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('glob-base expects a string.');
}
const res = {
base: globParent(pattern),
isGlob: hasMagic(pattern),
glob: ''
};
if (res.base !== '.') {
res.glob = pattern.substr(res.base.length);
if (res.glob.charAt(0) === '/') {
res.glob = res.glob.substr(1);
}
}
else {
res.glob = pattern;
}
if (!res.isGlob) {
res.base = dirname(pattern);
res.glob = res.base !== '.'
? pattern.substr(res.base.length)
: pattern;
}
if (res.glob.substr(0, 2) === './') {
res.glob = res.glob.substr(2);
}
if (res.glob.char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HQUFHLEdBQUcsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQ2hDLENBQUM7SUFDRCxPQUFPLEdBQUcsQ0FBQztBQUNiLENBQUMsQ0FBQSJ9
;// ../commons/dist/fs/glob-parse.js
/*!
* parse-glob
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
/**
* Expose `cache`
*/
const cache = {};
/**
* Parse a glob pattern into tokens.
*
* When no paths or '**' are in the glob, a different
* strategy is used for parsing the filename, since
* file names can contain braces and other tricky patterns:
*
* - `*.{a,b}`
* - `(**|*.js)`
*/
function parseGlob(glob) {
if (cache.hasOwnProperty(glob)) {
return cache[glob];
}
const tok = {};
tok.orig = glob;
tok.is = {
glob: false,
negated: false,
extglob: false,
braces: false,
brackets: false,
globstar: false,
dotfile: false,
dotdir: false,
};
// Temporarily escape dots and slashes within braces/brackets
glob = escapeSpecial(glob);
const parsed = globBase(glob);
tok.is.glob = parsed.isGlob;
tok.glob = parsed.glob;
tok.base = parsed.base;
const segs = /([^/]*)$/.exec(glob);
tok.path = {
dirname: '',
basename: segs ? segs[1] : '',
filename: '',
extname: '',
ext: '',
};
tok.path.dirname = glob.split(tok.path.basename).join('') || '';
const basenameParts = tok.path.basename.split('.') || [];
tok.path.filename = basenameParts[0] || '';
tok.path.extname = basenameParts.slice(1).join('.') || '';
// If the dirname is a glob and we have no basename, adjust
if (hasMagic(tok.path.dirname) && !tok.path.basename) {
if (!/\/$/.test(tok.glob)) {
tok.path.basename = tok.glob;
}
tok.path.dirname = tok.base;
}
// If glob doesn't contain '/', handle everything as basename
if (!glob.includes('/') && !tok.is.globstar) {
tok.path.dirname = '';
tok.path.basename = tok.orig;
}
const dotIndex = tok.path.basename.indexOf('.');
if (dotIndex !== -1) {
tok.path.filename = tok.path.basename.slice(0, dotIndex);
tok.path.extname = tok.path.basename.slice(dotIndex);
}
if (tok.path.extname.startsWith('.')) {
const exts = tok.path.extname.split('.');
tok.path.ext = exts[exts.length - 1];
}
// Unescape
tok.glob = unescapeSpecial(tok.glob);
tok.path.dirname = unescapeSpecial(tok.path.dirname);
tok.path.basename = unescapeSpecial(tok.path.basename);
tok.path.filename = unescapeSpecial(tok.path.filename);
tok.path.extname = unescapeSpecial(tok.path.extname);
// Booleans
const maybeGlob = !!glob && tok.is.glob;
tok.is.negated = !!glob && glob.charAt(0) === '!';
//tok.is.extglob = !!glob && extglob(glob);
tok.is.braces = has(maybeGlob, glob, '{');
tok.is.brackets = has(maybeGlob, glob, '[:');
tok.is.globstar = has(maybeGlob, glob, '**');
//tok.is.dotfile = dotfile(tok.path.basename) || dotfile(tok.path.filename);
tok.is.dotdir = isDotDir(tok.path.dirname);
cache[glob] = tok;
return tok;
}
/**
* Returns true if the pattern has the given `ch`aracter(s).
*/
function has(is, glob, ch) {
return is && glob.includes(ch);
}
/**
* Returns true if the glob matches dot-directories.
*/
function isDotDir(base) {
if (base.includes('/.')) {
return true;
}
if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
return true;
}
return false;
}
/**
* Escape special characters (dots and slashes) in braces/brackets/parens.
*/
function escapeSpecial(str) {
const re = /\{([^{}]*?)\}|\(([^()]*?)\)|\[([^\[\]]*?)\]/g;
return str.replace(re, (outer, braces, parens, brackets) => {
const inner = braces || parens || brackets;
if (!inner)
return outer;
return outer.split(inner).join(escapeDotsAndSlashes(inner));
});
}
function escapeDotsAndSlashes(str) {
return str
.split('/')
.join('__SLASH__')
.split('.')
.join('__DOT__');
}
/**
* Unescape special placeholders back to dots and slashes.
*/
function unescapeSpecial(str) {
return str
.split('__SLASH__')
.join('/')
.split('__DOT__')
.join('.');
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYi1wYXJzZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9mcy9nbG9iLXBhcnNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ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options || {} });
const filesEx = (cwd, glob, options) => globSync(glob, { ...{ dot: true, cwd, absolute: true, caseSensitiveMatch: false }, ...options || {} });
const GLOB_GROUP_PATTERN = /[!*+?@]\(.*\)/;
const getExtensions = (glob) => {
const match = glob.match(GLOB_GROUP_PATTERN);
if (match) {
return glob.substring((match.index || 0) + 2, glob.lastIndexOf(')')).split('|');
}
else {
return [parseGlob(glob).path.ext];
}
};
const _glob_forward_slash = (path) => {
const isExtendedLengthPath = /^\\\\\?\\/.test(path);
const hasNonAscii = /[^\u0000-\u0080]+/.test(path);
if (isExtendedLengthPath || hasNonAscii) {
return path;
}
return path.replace(/\\/g, '/');
};
const _glob_pathInfoEx = (src, altToken = false, globOptions = {}) => {
const srcParts = external_path_.parse(src);
let variables = {
PATH: src
};
variables.DIR = srcParts.dir;
variables.NAME = srcParts.name;
variables.FILE_NAME = srcParts.base;
variables.FILE_EXT = srcParts.ext.replace('.', '');
variables.PATH = src;
variables.IS_FILE = isFile(src);
variables.IS_FOLDER = isFolder(src);
variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : constants_REGEX_VAR) != null;
variables.IS_GLOB = hasMagic(src);
if (variables.IS_GLOB) {
const glob_base = globBase(src);
variables.DIR = external_path_.resolve(glob_base.base);
variables.FILE_NAME = glob_base.glob;
variables.GLOB = glob_base.glob;
variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob);
globOptions = {
...globOptions,
cwd: globOptions.cwd ? external_path_.join(globOptions.cwd, glob_base.base) : glob_base.base
};
variables.FILES = glob.sync(glob_base.glob, globOptions);
}
else if (variables.IS_FILE && (0,dist_exists/* sync */.OH)(src)) {
variables.FILES = [src];
}
return variables;
};
const pathInfo = (src, altToken = false, cwd = null) => {
const srcParts = external_path_.parse(src);
let variables = {
PATH: src
};
variables.DIR = srcParts.dir;
variables.NAME = srcParts.name;
variables.FILE_NAME = srcParts.base;
variables.FILE_EXT = srcParts.ext.replace('.', '');
variables.PATH = src;
variables.IS_FILE = isFile(src);
variables.IS_FOLDER = isFolder(src);
variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : constants_REGEX_VAR) != null;
if (!variables.IS_FOLDER && !variables.IS_FILE) {
variables.IS_GLOB = hasMagic(srcParts.base);
}
else {
variables.IS_GLOB = false;
}
if (variables.IS_GLOB) {
const glob_base = globBase(src);
variables.DIR = external_path_.resolve(glob_base.base);
variables.FILE_NAME = glob_base.glob;
variables.GLOB = glob_base.glob;
variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob);
variables.FILES = esm_globSync(glob_base.glob, {
dot: true,
cwd: external_path_.resolve(cwd || variables.DIR),
absolute: true
});
}
else if (variables.IS_FILE && (0,dist_exists/* sync */.OH)(src)) {
variables.FILES = [src];
}
return variables;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiX2dsb2IuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZnMvX2dsb2IudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLElBQUksTUFBTSxNQUFNLENBQUE7QUFFNUIsT0FBTyxFQUFFLElBQUksRUFBRSxRQUFRLEVBQWUsUUFBUSxFQUFFLE1BQU0sTUFBTSxDQUFBO0FBQzVELE9BQU8sRUFBRSxTQUFTLEVBQUUsYUFBYSxFQUFFLE1BQU0sMEJBQTBCLENBQUE7QUFDbkUsT0FBTyxFQUFFLElBQUksSUFBSSxNQUFNLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQTtBQUVwRCxNQUFNLENBQUMsTUFBTSxLQUFLLEdBQUcsQ0FBQyxHQUFHLEVBQUUsSUFBSSxFQUFFLE9BQWEsRUFBRSxFQUFFLENBQUMsUUFBUSxDQUFDLElBQUksRUFBRSxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsSUFBSSxFQUFFLEdBQUcsRUFBRSxRQUFRLEVBQUUsSUFBSSxFQUFFLGtCQUFrQixF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HLEVBQUUsSUFBSSxDQUFDLE9BQU8sQ0FBQyxHQUFHLElBQUksU0FBUyxDQUFDLEdBQUcsQ0FBQztZQUN2QyxRQUFRLEVBQUUsSUFBSTtTQUNqQixDQUFDLENBQUE7SUFDTixDQUFDO1NBQU0sSUFBSSxTQUFTLENBQUMsT0FBTyxJQUFJLE1BQU0sQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDO1FBQzFDLFNBQVMsQ0FBQyxLQUFLLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQTtJQUMzQixDQUFDO0lBQ0QsT0FBTyxTQUFTLENBQUE7QUFDcEIsQ0FBQyxDQUFBIn0=
;// ../commons/node_modules/zod/lib/index.mjs
var util;
(function (util) {
util.assertEqual = (val) => val;
function assertIs(_arg) { }
util.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util.assertNever = assertNever;
util.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util.getValidEnumValues = (obj) => {
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util.objectValues(filtered);
};
util.objectValues = (obj) => {
return util.objectKeys(obj).map(function (e) {
return obj[e];
});
};
util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
: (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return undefined;
};
util.isInteger = typeof Number.isInteger === "function"
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
: (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array
.map((val) => (typeof val === "string" ? `'${val}'` : val))
.join(separator);
}
util.joinValues = joinValues;
util.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function (objectUtil) {
objectUtil.mergeShapes = (first, second) => {
return {
...first,
...second, // second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set",
]);
const getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then &&
typeof data.then === "function" &&
data.catch &&
typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite",
]);
const quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
// eslint-disable-next-line ban/ban
Object.setPrototypeOf(this, actualProto);
}
else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper ||
function (issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
}
else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
}
else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
// if (typeof el === "string") {
// curr[el] = curr[el] || { _errors: [] };
// } else if (typeof el === "number") {
// const errorArray: any = [];
// errorArray._errors = [];
// curr[el] = curr[el] || errorArray;
// }
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
}
else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
const errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
}
else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
}
else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
}
else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
}
else {
util.assertNever(issue.validation);
}
}
else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
}
else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact
? `exactly equal to `
: issue.inclusive
? `greater than or equal to `
: `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact
? `exactly equal to `
: issue.inclusive
? `greater than or equal to `
: `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact
? `exactly`
: issue.inclusive
? `less than or equal to`
: `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact
? `exactly`
: issue.inclusive
? `less than or equal to`
: `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact
? `exactly`
: issue.inclusive
? `smaller than or equal to`
: `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
let overrideErrorMap = errorMap;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
const makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...(issueData.path || [])];
const fullIssue = {
...issueData,
path: fullPath,
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message,
};
}
let errorMessage = "";
const maps = errorMaps
.filter((m) => !!m)
.slice()
.reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage,
};
};
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData: issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap, // contextual error map is first priority
ctx.schemaErrorMap, // then schema-bound map if available
overrideMap, // then global override map
overrideMap === errorMap ? undefined : errorMap, // then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" &&
(typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
const INVALID = Object.freeze({
status: "aborted",
});
const DIRTY = (value) => ({ status: "dirty", value });
const OK = (value) => ({ status: "valid", value });
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var errorUtil;
(function (errorUtil) {
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache;
class ParseInputLazyPath {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (this._key instanceof Array) {
this._cachedPath.push(...this._path, ...this._key);
}
else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
}
const handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
}
else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
},
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap, invalid_type_error, required_error, description } = params;
if (errorMap && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap)
return { errorMap: errorMap, description };
const customMap = (iss, ctx) => {
var _a, _b;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
};
return { errorMap: customMap, description };
}
class ZodType {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return (ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent,
});
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent,
},
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a;
const ctx = {
common: {
issues: [],
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
var _a, _b;
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async,
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};
if (!this["~standard"].async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid(result)
? {
value: result.value,
}
: {
issues: ctx.common.issues,
};
}
catch (err) {
if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true,
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
? {
value: result.value,
}
: {
issues: ctx.common.issues,
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
async: true,
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult)
? maybeAsyncResult
: Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
}
else if (typeof message === "function") {
return message(val);
}
else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val),
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
}
else {
return true;
}
});
}
if (!result) {
setError();
return false;
}
else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function"
? refinementData(val, ctx)
: refinementData);
return false;
}
else {
return true;
}
});
}
_refinement(refinement) {
return new lib_ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement },
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
/** Alias of safeParseAsync */
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data),
};
}
optional() {
return lib_ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new lib_ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform },
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new lib_ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault,
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def),
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch,
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description,
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
// const uuidRegex =
// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
// const emailRegex =
// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
// faster, simpler, safer
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
// const ipv6Regex =
// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{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}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
// https://base64.guru/standards/base64url
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
// simple
// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
// no leap year validation
// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
// with leap year validation
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
// let regex = `\\d{2}:\\d{2}:\\d{2}`;
let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
if (args.precision) {
regex = `${regex}\\.\\d{${args.precision}}`;
}
else if (args.precision == null) {
regex = `${regex}(\\.\\d+)?`;
}
return regex;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
// Convert base64url to base64
const base64 = header
.replace(/-/g, "+")
.replace(/_/g, "/")
.padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if (!decoded.typ || !decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
}
catch (_a) {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx.parsedType,
});
return INVALID;
}
const status = new ParseStatus();
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message,
});
}
else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message,
});
}
status.dirty();
}
}
else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "url") {
try {
new URL(input.data);
}
catch (_a) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "trim") {
input.data = input.data.trim();
}
else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
}
else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
}
else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check],
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
base64url(message) {
// base64url encoding is a modification of base64 that can safely be used in URLs and filenames
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message),
});
}
jwt(options) {
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
cidr(options) {
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a, _b;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options,
});
}
return this._addCheck({
kind: "datetime",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options,
});
}
return this._addCheck({
kind: "time",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex: regex,
...errorUtil.errToObj(message),
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value: value,
position: options === null || options === void 0 ? void 0 : options.position,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value: value,
...errorUtil.errToObj(message),
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value: value,
...errorUtil.errToObj(message),
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message),
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message),
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message),
});
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
// base64url encoding is a modification of base64 that can safely be used in URLs and filenames
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodString.create = (params) => {
var _a;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams(params),
});
};
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / Math.pow(10, decCount);
}
class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx.parsedType,
});
return INVALID;
}
let ctx = undefined;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "min") {
const tooSmall = check.inclusive
? input.data < check.value
: input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "max") {
const tooBig = check.inclusive
? input.data > check.value
: input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message,
});
status.dirty();
}
}
else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message),
},
],
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check],
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message),
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message),
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message),
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message),
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message),
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value: value,
message: errorUtil.toString(message),
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message),
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message),
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message),
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" ||
(ch.kind === "multipleOf" && util.isInteger(ch.value)));
}
get isFinite() {
let max = null, min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" ||
ch.kind === "int" ||
ch.kind === "multipleOf") {
return true;
}
else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
}
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params),
});
};
class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
}
catch (_a) {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = undefined;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive
? input.data < check.value
: input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "max") {
const tooBig = check.inclusive
? input.data > check.value
: input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message,
});
status.dirty();
}
}
else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType,
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message),
},
],
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check],
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message),
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message),
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message),
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message),
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message),
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodBigInt.create = (params) => {
var _a;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams(params),
});
};
class ZodBoolean extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
}
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params),
});
};
class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx.parsedType,
});
return INVALID;
}
if (isNaN(input.data.getTime())) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_date,
});
return INVALID;
}
const status = new ParseStatus();
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date",
});
status.dirty();
}
}
else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date",
});
status.dirty();
}
}
else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime()),
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check],
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message),
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message),
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
}
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params),
});
};
class ZodSymbol extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
}
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params),
});
};
class ZodUndefined extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
}
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params),
});
};
class ZodNull extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
}
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params),
});
};
class ZodAny extends ZodType {
constructor() {
super(...arguments);
// to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
this._any = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params),
});
};
class ZodUnknown extends ZodType {
constructor() {
super(...arguments);
// required
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params),
});
};
class ZodNever extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType,
});
return INVALID;
}
}
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params),
});
};
class ZodVoid extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
}
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params),
});
};
class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType,
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: (tooSmall ? def.exactLength.value : undefined),
maximum: (tooBig ? def.exactLength.value : undefined),
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message,
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message,
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message,
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result) => {
return ParseStatus.mergeArray(status, result);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) },
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) },
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) },
});
}
nonempty(message) {
return this.min(1, message);
}
}
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params),
});
};
function deepPartialify(schema) {
if (schema instanceof lib_ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = lib_ZodOptional.create(deepPartialify(fieldSchema));
}
return new lib_ZodObject({
...schema._def,
shape: () => newShape,
});
}
else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element),
});
}
else if (schema instanceof lib_ZodOptional) {
return lib_ZodOptional.create(deepPartialify(schema.unwrap()));
}
else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
}
else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
}
else {
return schema;
}
}
class lib_ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
// extend<
// Augmentation extends ZodRawShape,
// NewOutput extends util.flatten<{
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// }>,
// NewInput extends util.flatten<{
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }>
// >(
// augmentation: Augmentation
// ): ZodObject<
// extendShape,
// UnknownKeys,
// Catchall,
// NewOutput,
// NewInput
// > {
// return new ZodObject({
// ...this._def,
// shape: () => ({
// ...this._def.shape(),
// ...augmentation,
// }),
// }) as any;
// }
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
return (this._cached = { shape, keys });
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType,
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever &&
this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data,
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] },
});
}
}
else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys,
});
status.dirty();
}
}
else if (unknownKeys === "strip") ;
else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
}
else {
// run catchall validation
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data,
});
}
}
if (ctx.common.async) {
return Promise.resolve()
.then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet,
});
}
return syncPairs;
})
.then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
}
else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new lib_ZodObject({
...this._def,
unknownKeys: "strict",
...(message !== undefined
? {
errorMap: (issue, ctx) => {
var _a, _b, _c, _d;
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
};
return {
message: defaultError,
};
},
}
: {}),
});
}
strip() {
return new lib_ZodObject({
...this._def,
unknownKeys: "strip",
});
}
passthrough() {
return new lib_ZodObject({
...this._def,
unknownKeys: "passthrough",
});
}
// const AugmentFactory =
// (def: Def) =>
// (
// augmentation: Augmentation
// ): ZodObject<
// extendShape, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new lib_ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation,
}),
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new lib_ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape(),
}),
typeName: ZodFirstPartyTypeKind.ZodObject,
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge(
// merging: Incoming
// ): //ZodObject = (merging) => {
// ZodObject<
// extendShape>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new lib_ZodObject({
...this._def,
catchall: index,
});
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
});
return new lib_ZodObject({
...this._def,
shape: () => shape,
});
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
shape[key] = this.shape[key];
}
});
return new lib_ZodObject({
...this._def,
shape: () => shape,
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
}
else {
newShape[key] = fieldSchema.optional();
}
});
return new lib_ZodObject({
...this._def,
shape: () => newShape,
});
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
}
else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof lib_ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
});
return new lib_ZodObject({
...this._def,
shape: () => newShape,
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
}
lib_ZodObject.create = (shape, params) => {
return new lib_ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
lib_ZodObject.strictCreate = (shape, params) => {
return new lib_ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
lib_ZodObject.lazycreate = (shape, params) => {
return new lib_ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
class ZodUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
// return first issue-free validation if it exists
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
// add issues from dirty option
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
// return invalid
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors,
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
parent: null,
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx,
}),
ctx: childCtx,
};
})).then(handleResults);
}
else {
let dirty = undefined;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
parent: null,
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx,
});
if (result.status === "valid") {
return result;
}
else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues) => new ZodError(issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors,
});
return INVALID;
}
}
get options() {
return this._def.options;
}
}
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params),
});
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
////////// //////////
////////// ZodDiscriminatedUnion //////////
////////// //////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
const getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
}
else if (type instanceof lib_ZodEffects) {
return getDiscriminator(type.innerType());
}
else if (type instanceof ZodLiteral) {
return [type.value];
}
else if (type instanceof ZodEnum) {
return type.options;
}
else if (type instanceof ZodNativeEnum) {
// eslint-disable-next-line ban/ban
return util.objectValues(type.enum);
}
else if (type instanceof lib_ZodDefault) {
return getDiscriminator(type._def.innerType);
}
else if (type instanceof ZodUndefined) {
return [undefined];
}
else if (type instanceof ZodNull) {
return [null];
}
else if (type instanceof lib_ZodOptional) {
return [undefined, ...getDiscriminator(type.unwrap())];
}
else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
}
else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
}
else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
}
else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
}
else {
return [];
}
};
class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType,
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator],
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
}
else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
// Get all the valid discriminator values
const optionsMap = new Map();
// try {
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params),
});
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
}
else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util
.objectKeys(a)
.filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
}
else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
}
else if (aType === ZodParsedType.date &&
bType === ZodParsedType.date &&
+a === +b) {
return { valid: true, data: a };
}
else {
return { valid: false };
}
}
class ZodIntersection extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types,
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}),
]).then(([left, right]) => handleParsed(left, right));
}
else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}));
}
}
}
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left: left,
right: right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params),
});
};
class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType,
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array",
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array",
});
status.dirty();
}
const items = [...ctx.data]
.map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
})
.filter((x) => !!x); // filter nulls
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
}
else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest,
});
}
}
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params),
});
};
class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType,
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data,
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
}
else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third),
});
}
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second),
});
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType,
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
};
});
if (ctx.common.async) {
const finalMap = new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
}
else {
const finalMap = new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
}
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params),
});
};
class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType,
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message,
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message,
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements) {
const parsedSet = new Set();
for (const element of elements) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements) => finalizeSet(elements));
}
else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) },
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) },
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
}
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params),
});
};
class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType,
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap,
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error,
},
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap,
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error,
},
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(async function (...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args
.parseAsync(args, params)
.catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type
.parseAsync(result, params)
.catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
}
else {
// Would love a way to avoid disabling this rule, but we need
// an alias (using an arrow function was what caused 2651).
// eslint-disable-next-line @typescript-eslint/no-this-alias
const me = this;
return OK(function (...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create()),
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType,
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: (args
? args
: ZodTuple.create([]).rest(ZodUnknown.create())),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params),
});
}
}
class ZodLazy extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
}
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter: getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params),
});
};
class ZodLiteral extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value,
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
}
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value: value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params),
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params),
});
}
class ZodEnum extends ZodType {
constructor() {
super(...arguments);
_ZodEnum_cache.set(this, void 0);
}
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type,
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues,
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef,
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef,
});
}
}
_ZodEnum_cache = new WeakMap();
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
constructor() {
super(...arguments);
_ZodNativeEnum_cache.set(this, void 0);
}
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string &&
ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type,
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues,
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
}
_ZodNativeEnum_cache = new WeakMap();
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values: values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params),
});
};
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise &&
ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType,
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise
? ctx.data
: Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap,
});
}));
}
}
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params),
});
};
class lib_ZodEffects extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
? this._def.schema.sourceType()
: this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
}
else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed,
path: ctx.path,
parent: ctx,
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
}
else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx,
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
// return value is ignored
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
}
else {
return this._def.schema
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
.then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (!isValid(base))
return base;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
}
else {
return this._def.schema
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
.then((base) => {
if (!isValid(base))
return base;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
});
}
}
util.assertNever(effect);
}
}
lib_ZodEffects.create = (schema, effect, params) => {
return new lib_ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params),
});
};
lib_ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new lib_ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params),
});
};
class lib_ZodOptional extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(undefined);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
lib_ZodOptional.create = (type, params) => {
return new lib_ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params),
});
};
class ZodNullable extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params),
});
};
class lib_ZodDefault extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx,
});
}
removeDefault() {
return this._def.innerType;
}
}
lib_ZodDefault.create = (type, params) => {
return new lib_ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function"
? params.default
: () => params.default,
...processCreateParams(params),
});
};
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
// newCtx is used to not collect issues from inner types in ctx
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx,
},
});
if (isAsync(result)) {
return result.then((result) => {
return {
status: "valid",
value: result.status === "valid"
? result.value
: this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data,
}),
};
});
}
else {
return {
status: "valid",
value: result.status === "valid"
? result.value
: this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data,
}),
};
}
}
removeCatch() {
return this._def.innerType;
}
}
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params),
});
};
class ZodNaN extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType,
});
return INVALID;
}
return { status: "valid", value: input.data };
}
}
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params),
});
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx,
});
}
unwrap() {
return this._def.type;
}
}
class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
}
else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx,
});
}
};
return handleAsync();
}
else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value,
};
}
else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx,
});
}
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline,
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result)
? result.then((data) => freeze(data))
: freeze(result);
}
unwrap() {
return this._def.innerType;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params),
});
};
////////////////////////////////////////
////////////////////////////////////////
////////// //////////
////////// z.custom //////////
////////// //////////
////////////////////////////////////////
////////////////////////////////////////
function cleanParams(params, data) {
const p = typeof params === "function"
? params(data)
: typeof params === "string"
? { message: params }
: params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {},
/**
* @deprecated
*
* Pass `fatal` into the params object instead:
*
* ```ts
* z.string().custom((val) => val.length > 5, { fatal: false })
* ```
*
*/
fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
const r = check(data);
if (r instanceof Promise) {
return r.then((r) => {
var _a, _b;
if (!r) {
const params = cleanParams(_params, data);
const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
});
}
if (!r) {
const params = cleanParams(_params, data);
const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
return;
});
return ZodAny.create();
}
const late = {
object: lib_ZodObject.lazycreate,
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (
// const instanceOfType = any>(
cls, params = {
message: `Input not instance of ${cls.name}`,
}) => custom((data) => data instanceof cls, params);
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = lib_ZodObject.create;
const strictObjectType = lib_ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = lib_ZodEffects.create;
const optionalType = lib_ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = lib_ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
const onumber = () => numberType().optional();
const oboolean = () => booleanType().optional();
const coerce = {
string: ((arg) => ZodString.create({ ...arg, coerce: true })),
number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
boolean: ((arg) => ZodBoolean.create({
...arg,
coerce: true,
})),
bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
};
const NEVER = INVALID;
var lib_z = /*#__PURE__*/Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap: setErrorMap,
getErrorMap: getErrorMap,
makeIssue: makeIssue,
EMPTY_PATH: EMPTY_PATH,
addIssueToContext: addIssueToContext,
ParseStatus: ParseStatus,
INVALID: INVALID,
DIRTY: DIRTY,
OK: OK,
isAborted: isAborted,
isDirty: isDirty,
isValid: isValid,
isAsync: isAsync,
get util () { return util; },
get objectUtil () { return objectUtil; },
ZodParsedType: ZodParsedType,
getParsedType: getParsedType,
ZodType: ZodType,
datetimeRegex: datetimeRegex,
ZodString: ZodString,
ZodNumber: ZodNumber,
ZodBigInt: ZodBigInt,
ZodBoolean: ZodBoolean,
ZodDate: ZodDate,
ZodSymbol: ZodSymbol,
ZodUndefined: ZodUndefined,
ZodNull: ZodNull,
ZodAny: ZodAny,
ZodUnknown: ZodUnknown,
ZodNever: ZodNever,
ZodVoid: ZodVoid,
ZodArray: ZodArray,
ZodObject: lib_ZodObject,
ZodUnion: ZodUnion,
ZodDiscriminatedUnion: ZodDiscriminatedUnion,
ZodIntersection: ZodIntersection,
ZodTuple: ZodTuple,
ZodRecord: ZodRecord,
ZodMap: ZodMap,
ZodSet: ZodSet,
ZodFunction: ZodFunction,
ZodLazy: ZodLazy,
ZodLiteral: ZodLiteral,
ZodEnum: ZodEnum,
ZodNativeEnum: ZodNativeEnum,
ZodPromise: ZodPromise,
ZodEffects: lib_ZodEffects,
ZodTransformer: lib_ZodEffects,
ZodOptional: lib_ZodOptional,
ZodNullable: ZodNullable,
ZodDefault: lib_ZodDefault,
ZodCatch: ZodCatch,
ZodNaN: ZodNaN,
BRAND: BRAND,
ZodBranded: ZodBranded,
ZodPipeline: ZodPipeline,
ZodReadonly: ZodReadonly,
custom: custom,
Schema: ZodType,
ZodSchema: ZodType,
late: late,
get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
coerce: coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
'enum': enumType,
'function': functionType,
'instanceof': instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
'null': nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean: oboolean,
onumber: onumber,
optional: optionalType,
ostring: ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
'undefined': undefinedType,
union: unionType,
unknown: unknownType,
'void': voidType,
NEVER: NEVER,
ZodIssueCode: ZodIssueCode,
quotelessJson: quotelessJson,
ZodError: ZodError
});
;// ../commons/node_modules/normalize-url/index.js
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain';
const DATA_URL_DEFAULT_CHARSET = 'us-ascii';
const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);
const supportedProtocols = new Set([
'https:',
'http:',
'file:',
]);
const hasCustomProtocol = urlString => {
try {
const {protocol} = new URL(urlString);
return protocol.endsWith(':')
&& !protocol.includes('.')
&& !supportedProtocols.has(protocol);
} catch {
return false;
}
};
const normalizeDataURL = (urlString, {stripHash}) => {
const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString);
if (!match) {
throw new Error(`Invalid URL: ${urlString}`);
}
let {type, data, hash} = match.groups;
const mediaType = type.split(';');
hash = stripHash ? '' : hash;
let isBase64 = false;
if (mediaType[mediaType.length - 1] === 'base64') {
mediaType.pop();
isBase64 = true;
}
// Lowercase MIME type
const mimeType = mediaType.shift()?.toLowerCase() ?? '';
const attributes = mediaType
.map(attribute => {
let [key, value = ''] = attribute.split('=').map(string => string.trim());
// Lowercase `charset`
if (key === 'charset') {
value = value.toLowerCase();
if (value === DATA_URL_DEFAULT_CHARSET) {
return '';
}
}
return `${key}${value ? `=${value}` : ''}`;
})
.filter(Boolean);
const normalizedMediaType = [
...attributes,
];
if (isBase64) {
normalizedMediaType.push('base64');
}
if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) {
normalizedMediaType.unshift(mimeType);
}
return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`;
};
function normalizeUrl(urlString, options) {
options = {
defaultProtocol: 'http',
normalizeProtocol: true,
forceHttp: false,
forceHttps: false,
stripAuthentication: true,
stripHash: false,
stripTextFragment: true,
stripWWW: true,
removeQueryParameters: [/^utm_\w+/i],
removeTrailingSlash: true,
removeSingleSlash: true,
removeDirectoryIndex: false,
removeExplicitPort: false,
sortQueryParameters: true,
...options,
};
// Legacy: Append `:` to the protocol if missing.
if (typeof options.defaultProtocol === 'string' && !options.defaultProtocol.endsWith(':')) {
options.defaultProtocol = `${options.defaultProtocol}:`;
}
urlString = urlString.trim();
// Data URL
if (/^data:/i.test(urlString)) {
return normalizeDataURL(urlString, options);
}
if (hasCustomProtocol(urlString)) {
return urlString;
}
const hasRelativeProtocol = urlString.startsWith('//');
const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
// Prepend protocol
if (!isRelativeUrl) {
urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
}
const urlObject = new URL(urlString);
if (options.forceHttp && options.forceHttps) {
throw new Error('The `forceHttp` and `forceHttps` options cannot be used together');
}
if (options.forceHttp && urlObject.protocol === 'https:') {
urlObject.protocol = 'http:';
}
if (options.forceHttps && urlObject.protocol === 'http:') {
urlObject.protocol = 'https:';
}
// Remove auth
if (options.stripAuthentication) {
urlObject.username = '';
urlObject.password = '';
}
// Remove hash
if (options.stripHash) {
urlObject.hash = '';
} else if (options.stripTextFragment) {
urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, '');
}
// Remove duplicate slashes if not preceded by a protocol
// NOTE: This could be implemented using a single negative lookbehind
// regex, but we avoid that to maintain compatibility with older js engines
// which do not have support for that feature.
if (urlObject.pathname) {
// TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(? 0) {
let pathComponents = urlObject.pathname.split('/');
const lastComponent = pathComponents[pathComponents.length - 1];
if (testParameter(lastComponent, options.removeDirectoryIndex)) {
pathComponents = pathComponents.slice(0, -1);
urlObject.pathname = pathComponents.slice(1).join('/') + '/';
}
}
if (urlObject.hostname) {
// Remove trailing dot
urlObject.hostname = urlObject.hostname.replace(/\.$/, '');
// Remove `www.`
if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) {
// Each label should be max 63 at length (min: 1).
// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
// Each TLD should be up to 63 characters long (min: 2).
// It is technically possible to have a single character TLD, but none currently exist.
urlObject.hostname = urlObject.hostname.replace(/^www\./, '');
}
}
// Remove query unwanted parameters
if (Array.isArray(options.removeQueryParameters)) {
// eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy.
for (const key of [...urlObject.searchParams.keys()]) {
if (testParameter(key, options.removeQueryParameters)) {
urlObject.searchParams.delete(key);
}
}
}
if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) {
urlObject.search = '';
}
// Keep wanted query parameters
if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) {
// eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy.
for (const key of [...urlObject.searchParams.keys()]) {
if (!testParameter(key, options.keepQueryParameters)) {
urlObject.searchParams.delete(key);
}
}
}
// Sort query parameters
if (options.sortQueryParameters) {
urlObject.searchParams.sort();
// Calling `.sort()` encodes the search parameters, so we need to decode them again.
try {
urlObject.search = decodeURIComponent(urlObject.search);
} catch {}
}
if (options.removeTrailingSlash) {
urlObject.pathname = urlObject.pathname.replace(/\/$/, '');
}
// Remove an explicit port number, excluding a default port number, if applicable
if (options.removeExplicitPort && urlObject.port) {
urlObject.port = '';
}
const oldUrlString = urlString;
// Take advantage of many of the Node `url` normalizations
urlString = urlObject.toString();
if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') {
urlString = urlString.replace(/\/$/, '');
}
// Remove ending `/` unless removeSingleSlash is false
if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) {
urlString = urlString.replace(/\/$/, '');
}
// Restore relative protocol, if applicable
if (hasRelativeProtocol && !options.normalizeProtocol) {
urlString = urlString.replace(/^http:\/\//, '//');
}
// Remove http/https
if (options.stripProtocol) {
urlString = urlString.replace(/^(?:https?:)?\/\//, '');
}
return urlString;
}
;// ../commons/dist/filter.js
//////////////////////////////////////////////////////
//
// NPM related
const isAPIPackage = (_path) => {
const pkg = config_readPackage(_path);
return (pkg.name || '').startsWith(`${API_NAMESPACE}/${API_PREFIX}`) ? pkg : null;
};
const hasDependency = (pkg, dep) => {
pkg = readPackage(pkg);
return Object.keys((pkg.dependencies || {})).
concat(Object.keys(pkg.devDependencies || {})).
find((d) => d === dep);
};
//////////////////////////////////////////////////////
//
// OSR related
const filter_isValidMarketplaceComponent = (_path) => {
const pkg = config_readOSRConfig(_path);
if (!pkg ||
!pkg.name ||
!pkg.slug ||
!pkg.code) {
return false;
}
return true;
};
const filter_isInvalidMarketplaceComponent = (_path) => {
const pkg = readOSRConfig(_path);
if (pkg &&
!pkg.name ||
!pkg.slug ||
!pkg.code) {
return true;
}
return false;
};
const filter_isValidLibraryComponent = (_path) => {
const pkg = config_readOSRConfig(_path);
if (!pkg || !pkg.name) {
return false;
}
const templatePath = external_path_.resolve(`${external_path_.parse(_path).dir}/templates/shared/body.md`);
if (!(0,dist_exists/* sync */.OH)(templatePath)) {
return false;
}
return true;
};
const filter_PFilterInvalid = {
marketplace_component: 'invalid_marketplace_component'
};
const filter_PFilterValid = {
marketplace_component: 'marketplace_component',
library_component: 'library_component',
package: 'package'
};
const FiltersValid = {
'marketplace_component': filter_isValidMarketplaceComponent,
'library_component': filter_isValidLibraryComponent,
'package': isAPIPackage
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmlsdGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2ZpbHRlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssSUFBSSxNQUFNLE1BQU0sQ0FBQTtBQUU1QixPQUFPLEVBQUUsSUFBSSxJQUFJLE1BQU0sRUFBRSxNQUFNLHFCQUFxQixDQUFBO0FBRXBELE9BQU8sRUFDSCxhQUFhLEVBQ2IsVUFBVSxFQUNiLE1BQU0sZ0JBQWdCLENBQUE7QUFFdkIsT0FBTyxFQUNILFdBQVcsRUFDWCxhQUFhLEVBQ2hCLE1BQU0sYUFBYSxDQUFBO0FBRXBCLHNEQUFzRDtBQUN0RCxFQUFFO0FBQ0YsZUFBZTtBQUVmLE1BQU0sQ0FBQyxNQUFNLFlBQVksR0FBRyxDQUFDLEtBQWEsRUFBRSxFQUFFO0lBQzFDLE1BQU0sR0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BTSxZQUFZLEdBQUc7SUFDeEIscUJBQXFCLEVBQUUsdUJBQXVCO0lBQzlDLGlCQUFpQixFQUFFLG1CQUFtQjtJQUN0QyxPQUFPLEVBQUUsU0FBUztDQUNyQixDQUFBO0FBRUQsTUFBTSxDQUFDLE1BQU0sWUFBWSxHQUN6QjtJQUNJLHVCQUF1QixFQUFFLDJCQUEyQjtJQUNwRCxtQkFBbUIsRUFBRSx1QkFBdUI7SUFDNUMsU0FBUyxFQUFHLFlBQVk7Q0FDM0IsQ0FBQSJ9
;// ../commons/dist/component.js
const IMAGES_GLOB = '*.+(JPG|jpg|png|PNG|gif)';
const find_items = (nodes, options) => {
nodes = nodes.filter(options.filter);
return nodes.map((c) => {
const root = resolve(options.root, false, {});
return {
rel: forward_slash(`${path.relative(root, path.parse(c).dir)}`),
path: forward_slash(`${options.root}/${path.relative(root, c)}`),
config: readOSRConfig(c)
};
});
};
const component_get = (src, root, type) => {
const srcInfo = pathInfoEx(src, false, {
absolute: true
});
switch (type) {
case PFilterValid.marketplace_component: {
const options = {
filter: isValidMarketplaceComponent,
root
};
return find_items(srcInfo.FILES, options);
}
case PFilterValid.library_component: {
const options = {
filter: isValidLibraryComponent,
root
};
return find_items(srcInfo.FILES, options);
}
case PFilterInvalid.marketplace_component: {
const options = {
filter: isInvalidMarketplaceComponent,
root
};
return find_items(srcInfo.FILES, options);
}
}
};
const UrlSchema = lib_z.string().url().transform((arg) => normalizeUrl(arg));
const ExifSchema = lib_z.object({
file: lib_z.any(), // Assuming File is another schema or any type
jfif: lib_z.any(), // Assuming Jfif is another schema or any type
exif: lib_z.any(), // Assuming Exif2 is another schema or any type
gps: lib_z.any() // Assuming Gps is another schema or any type
});
const ImageMetaSchema = lib_z.object({
format: lib_z.string(),
width: lib_z.number(),
height: lib_z.number(),
space: lib_z.string(),
channels: lib_z.number(),
depth: lib_z.string(),
density: lib_z.number(),
chromaSubsampling: lib_z.string(),
isProgressive: lib_z.boolean(),
resolutionUnit: lib_z.string(),
hasProfile: lib_z.boolean(),
hasAlpha: lib_z.boolean(),
orientation: lib_z.number(),
exif: lib_z.any() // Assuming Exif is another schema or any type
});
const CADMetaSchema = lib_z.object({
file: lib_z.string(),
name: lib_z.string(),
configuration: lib_z.string(), // solidworks map
step: lib_z.string().optional(),
model: lib_z.string().optional(),
html: lib_z.string().optional(),
});
const ShippingSchema = lib_z.object({
price: lib_z.number().optional(),
transit: lib_z.number().optional(),
handling: lib_z.number().optional()
});
const ManufacturingSchema = lib_z.object({
lead_time: lib_z.number().optional()
});
const ResourceSchema = lib_z.object({
name: lib_z.string(),
url: lib_z.string(),
type: lib_z.string()
});
const AssetImageSchema = lib_z.object({
name: lib_z.string().optional(),
url: lib_z.string(),
thumb: lib_z.string().optional(),
responsive: lib_z.string().optional(),
meta: lib_z.any().optional(),
keywords: lib_z.array(lib_z.string()).optional(),
description: lib_z.string().optional(),
alt: lib_z.string().optional(),
title: lib_z.string().optional(),
height: lib_z.number().optional(),
width: lib_z.number().optional(),
order: lib_z.number().optional(),
exif: ExifSchema.optional(),
});
const GalleryConfig = lib_z.object({
glob: lib_z.array(lib_z.string())
});
const GalleryConfigsSchema = lib_z.record(GalleryConfig);
const AuthorSchema = lib_z.object({
name: lib_z.string(),
url: lib_z.string(),
});
const ContentSchema = lib_z.object({
body: lib_z.string().optional(),
features: lib_z.string().optional(),
highlights: lib_z.string().optional(),
specs: lib_z.string().optional(),
license: lib_z.string().optional(),
resources: lib_z.string().optional(),
readme: lib_z.string().optional(),
shared: lib_z.string().optional()
});
const VersionSchema = lib_z.object({
version: lib_z.string().optional(),
up: lib_z.string().optional(),
down: lib_z.string().optional(),
family: lib_z.string().optional(),
sheet: lib_z.string().optional()
});
const AssetsSchema = lib_z.object({
gallery: lib_z.array(AssetImageSchema).optional(),
renderings: lib_z.array(AssetImageSchema).optional(),
components: lib_z.array(AssetImageSchema).optional(),
configurations: lib_z.array(AssetImageSchema).optional(),
showcase: lib_z.array(AssetImageSchema).optional(),
samples: lib_z.array(AssetImageSchema).optional()
});
const ProductionSchema = lib_z.object({
"fusion-folder": lib_z.string(),
"nc-folder": lib_z.string(),
cam: lib_z.array(AuthorSchema)
});
const ComponentConfigSchema = lib_z.object({
// shop
cart_id: lib_z.string().optional(),
code: lib_z.string(),
price: lib_z.number().optional(),
cscartCats: lib_z.array(lib_z.number()).optional(),
cscartId: lib_z.number().optional(),
vendorId: lib_z.number().optional(),
shipping: ShippingSchema.optional().default({
price: 0,
transit: 12,
handling: 2
}),
// references
replaced_by: lib_z.string().optional(),
alternatives: lib_z.array(ResourceSchema).optional(),
used_by: lib_z.array(ResourceSchema).optional(),
image: AssetImageSchema.optional(),
name: lib_z.string(),
// cad
edrawings: lib_z.string().optional(),
cad: lib_z.array(CADMetaSchema).default([]),
manufacturing: ManufacturingSchema,
// settings
showDimensions: lib_z.boolean().optional(),
showParts: lib_z.boolean().optional(),
Preview3d: lib_z.boolean().optional(),
flags: lib_z.number().optional().default(0),
// meta
slug: lib_z.string(),
keywords: lib_z.string().optional(),
meta_keywords: lib_z.string().optional(),
version: lib_z.string().optional(),
versions: VersionSchema.optional(),
status: lib_z.string().optional(),
authors: lib_z.array(AuthorSchema).optional(),
// content
assets: AssetsSchema.default({
gallery: [],
renderings: [],
components: [],
configurations: [],
showcase: [],
samples: []
}),
resources: lib_z.array(ResourceSchema).default([]),
tests: lib_z.array(ResourceSchema).default([]),
download: lib_z.boolean().optional(),
// galleries
gallery: GalleryConfigsSchema.default({}).default(Object.fromEntries(["renderings", "gallery", "components", "configurations", "showcase", "samples"].map(key => [key, { glob: [IMAGES_GLOB] }]))),
// nesting
components: lib_z.array(lib_z.lazy(() => ComponentConfigSchema)).optional().default([]),
// @deprecated
howto_categories: lib_z.union([lib_z.string(), lib_z.array(lib_z.string())]).optional(),
steps: lib_z.any().optional(),
sourceLanguage: lib_z.string().optional(),
category: lib_z.string(),
product_dimensions: lib_z.string().optional(),
production: ProductionSchema.optional(),
score: lib_z.number().optional()
}).merge(ContentSchema).passthr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yxDQUFDLE1BQU0sRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDLFFBQVEsRUFBRTtJQUN2RSxLQUFLLEVBQUUsQ0FBQyxDQUFDLEdBQUcsRUFBRSxDQUFDLFFBQVEsRUFBRTtJQUN6QixjQUFjLEVBQUUsQ0FBQyxDQUFDLE1BQU0sRUFBRSxDQUFDLFFBQVEsRUFBRTtJQUNyQyxRQUFRLEVBQUUsQ0FBQyxDQUFDLE1BQU0sRUFBRTtJQUNwQixrQkFBa0IsRUFBRSxDQUFDLENBQUMsTUFBTSxFQUFFLENBQUMsUUFBUSxFQUFFO0lBQ3pDLFVBQVUsRUFBRSxnQkFBZ0IsQ0FBQyxRQUFRLEVBQUU7SUFDdkMsS0FBSyxFQUFFLENBQUMsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxRQUFRLEVBQUU7Q0FJL0IsQ0FBQyxDQUFDLEtBQUssQ0FBQyxhQUFhLENBQUMsQ0FBQyxXQUFXLEVBQUUsQ0FBQSJ9
// EXTERNAL MODULE: ../commons/node_modules/source-map-support/source-map-support.js
var source_map_support = __webpack_require__(6966);
// EXTERNAL MODULE: external "util"
var external_util_ = __webpack_require__(9023);
;// ../commons/node_modules/tslog/dist/esm/CallSitesHelper.js
/* Based on https://github.com/watson/error-callsites */
const callsitesSym = Symbol("callsites");
// Lifted from Node.js 0.10.40:
// https://github.com/nodejs/node/blob/0439a28d519fb6efe228074b0588a59452fc1677/deps/v8/src/messages.js#L1053-L1080
function FormatStackTrace(error, frames) {
const lines = [];
try {
lines.push(error.toString());
}
catch (e) {
lines.push("");
}
for (let i = 0; i < frames.length; i++) {
const frame = frames[i];
let line;
try {
line = frame.toString();
}
catch (e) {
line = "";
}
lines.push(" at " + line);
}
return lines.join("\n");
}
const fallback = Error.prepareStackTrace || FormatStackTrace;
let lastPrepareStackTrace = fallback;
function prepareStackTrace(err, callsites) {
var _a;
// If the symbol has already been set it must mean that someone else has also
// overwritten `Error.prepareStackTrace` and retains a reference to this
// function that it's calling every time it's own `prepareStackTrace`
// function is being called. This would create an infinite loop if not
// handled.
if (Object.prototype.hasOwnProperty.call(err, callsitesSym)) {
return fallback(err, callsites);
}
Object.defineProperty(err, callsitesSym, {
enumerable: false,
configurable: true,
writable: false,
value: callsites,
});
return ((_a = (lastPrepareStackTrace && lastPrepareStackTrace(err, callsites))) !== null && _a !== void 0 ? _a : err.toString());
}
Object.defineProperty(Error, "prepareStackTrace", {
configurable: true,
enumerable: true,
get: function () {
return prepareStackTrace;
},
set: function (fn) {
// Don't set `lastPrepareStackTrace` to ourselves. If we did, we'd end up
// throwing a RangeError (Maximum call stack size exceeded).
lastPrepareStackTrace =
fn === prepareStackTrace
? fallback
: fn;
},
});
function getCallSites(err) {
//V8 does not initiate the "stack" property when the Error is constructed.
//However it seems that the "stack" property is a getter that then calls Error.prepareStackTrace.
//So to ensure that the custom "prepareStackTrace" function is executed we must first read the value of "Error.stack" to trigger the getter
// eslint-disable-next-line no-unused-expressions
err.stack;
return err[callsitesSym] || [];
}
//# sourceMappingURL=CallSitesHelper.js.map
;// ../commons/node_modules/tslog/dist/esm/LoggerHelper.js
/** @internal */
class LoggerHelper {
static cleanUpFilePath(fileName) {
return Object.entries(fileName.split(external_path_.sep))
.reduce((cleanFileName, fileNamePart) => fileNamePart[1] !== LoggerHelper.cwdArray[fileNamePart[0]]
? (cleanFileName += external_path_.sep + fileNamePart[1])
: cleanFileName, "")
.substring(1);
}
static isError(e) {
// An error could be an instance of Error while not being a native error
// or could be from a different realm and not be instance of Error but still
// be a native error.
return (external_util_.types === null || external_util_.types === void 0 ? void 0 : external_util_.types.isNativeError) != null
? external_util_.types.isNativeError(e)
: e instanceof Error;
}
static getCallSites(error, cleanUp = true) {
const stack = error == null ? getCallSites(new Error()).slice(1) : getCallSites(error);
return cleanUp === true && (stack === null || stack === void 0 ? void 0 : stack.reduce) != null
? stack.reduce((cleanedUpCallsites, callsite) => {
var _a, _b, _c;
if ((callsite === null || callsite === void 0 ? void 0 : callsite.getFileName()) != null &&
(callsite === null || callsite === void 0 ? void 0 : callsite.getFileName()) !== "" &&
((_a = callsite === null || callsite === void 0 ? void 0 : callsite.getFileName()) === null || _a === void 0 ? void 0 : _a.indexOf("internal/")) !== 0 &&
((_b = callsite === null || callsite === void 0 ? void 0 : callsite.getFileName()) === null || _b === void 0 ? void 0 : _b.indexOf("module.js")) !== 0 &&
((_c = callsite === null || callsite === void 0 ? void 0 : callsite.getFileName()) === null || _c === void 0 ? void 0 : _c.indexOf("bootstrap_node.js")) !== 0) {
cleanedUpCallsites.push(callsite);
}
return cleanedUpCallsites;
}, [])
: stack;
}
static toStackFrameObject(stackFrame) {
var _a, _b, _c, _d, _e, _f;
let filePath = stackFrame.getFileName() || "";
filePath = filePath.replace("file://", "");
return {
filePath: LoggerHelper.cleanUpFilePath(filePath),
fullFilePath: filePath,
fileName: (0,external_path_.basename)(filePath),
lineNumber: (_a = stackFrame.getLineNumber()) !== null && _a !== void 0 ? _a : undefined,
columnNumber: (_b = stackFrame.getColumnNumber()) !== null && _b !== void 0 ? _b : undefined,
isConstructor: (_c = stackFrame.isConstructor()) !== null && _c !== void 0 ? _c : undefined,
functionName: (_d = stackFrame.getFunctionName()) !== null && _d !== void 0 ? _d : undefined,
typeName: (_e = stackFrame.getTypeName()) !== null && _e !== void 0 ? _e : undefined,
methodName: (_f = stackFrame.getMethodName()) !== null && _f !== void 0 ? _f : undefined,
};
}
static initErrorToJsonHelper() {
if (!("toJSON" in Error.prototype))
/* eslint-disable */
Object.defineProperty(Error.prototype, "toJSON", {
/* eslint-enable */
value: function () {
return Object.getOwnPropertyNames(this).reduce((alt, key) => {
alt[key] = this[key];
return alt;
}, {});
},
configurable: true,
writable: true,
});
}
static overwriteConsole($this, handleLog) {
["log", "debug", "info", "warn", "trace", "error"].forEach((name) => {
console[name] = (...args) => {
const loglevelMapping = {
log: "silly",
trace: "trace",
debug: "debug",
info: "info",
warn: "warn",
error: "error",
};
return handleLog.apply($this, [
loglevelMapping[name.toLowerCase()],
args,
]);
};
});
}
static setUtilsInspectStyles(utilsInspectStyles) {
Object.entries(utilsInspectStyles).forEach(([symbol, color]) => {
external_util_.inspect.styles[symbol] = color;
});
}
static styleString(styleTypes, str, colorizePrettyLogs = true) {
return colorizePrettyLogs
? Object.values(styleTypes).reduce((resultStr, styleType) => {
return LoggerHelper._stylizeWithColor(styleType, resultStr);
}, str)
: `${str}`;
}
static _stylizeWithColor(styleType, str) {
var _a;
const color = (_a = external_util_.inspect.colors[styleType]) !== null && _a !== void 0 ? _a : [0, 0];
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
}
/* Async
import { createReadStream, readFileSync } from "fs";
import { createInterface, Interface } from "readline";
public static async _getCodeFrameAsync(
filePath: string,
lineNumber: number | null,
columnNumber: number | null,
linesBeforeAndAfter: number
): Promise {
try {
const fileStream: NodeJS.ReadableStream = createReadStream(filePath, {
encoding: "utf-8",
});
const rl: Interface = createInterface({
input: fileStream,
crlfDelay: Infinity,
});
if (lineNumber != null) {
const linesBefore: string[] = [];
let relevantLine: string | undefined;
const linesAfter: string[] = [];
let i: number = 0;
rl.on("line", (line) => {
if (i < lineNumber && i >= lineNumber - linesBeforeAndAfter) {
linesBefore.push(line);
} else if (i === lineNumber) {
relevantLine = line;
} else if (i > lineNumber && i <= lineNumber + linesBeforeAndAfter) {
linesAfter.push(line);
}
i++;
});
rl.on("close", () => {
const firstLineNumber: number =
lineNumber - linesBeforeAndAfter < 0
? 0
: lineNumber - linesBeforeAndAfter;
return {
firstLineNumber,
lineNumber,
columnNumber,
linesBefore,
relevantLine,
linesAfter,
};
});
}
} catch {
return undefined;
}
}
*/
static _getCodeFrame(filePath, lineNumber, columnNumber, linesBeforeAndAfter) {
var _a;
const lineNumberMinusOne = lineNumber - 1;
try {
const file = (_a = (0,external_fs_.readFileSync)(filePath, {
encoding: "utf-8",
})) === null || _a === void 0 ? void 0 : _a.split("\n");
const startAt = lineNumberMinusOne - linesBeforeAndAfter < 0
? 0
: lineNumberMinusOne - linesBeforeAndAfter;
const endAt = lineNumberMinusOne + linesBeforeAndAfter > file.length
? file.length
: lineNumberMinusOne + linesBeforeAndAfter;
const codeFrame = {
firstLineNumber: startAt + 1,
lineNumber,
columnNumber,
linesBefore: [],
relevantLine: "",
linesAfter: [],
};
for (let i = startAt; i < lineNumberMinusOne; i++) {
if (file[i] != null) {
codeFrame.linesBefore.push(file[i]);
}
}
codeFrame.relevantLine = file[lineNumberMinusOne];
for (let i = lineNumberMinusOne + 1; i <= endAt; i++) {
if (file[i] != null) {
codeFrame.linesAfter.push(file[i]);
}
}
return codeFrame;
}
catch (err) {
// (err) is needed for Node v8 support, remove later
// fail silently
}
}
static lineNumberTo3Char(lineNumber) {
return lineNumber < 10
? `00${lineNumber}`
: lineNumber < 100
? `0${lineNumber}`
: `${lineNumber}`;
}
static cloneObjectRecursively(obj, maskValuesFn, done = [], clonedObject = Object.create(Object.getPrototypeOf(obj))) {
done.push(obj);
// clone array. could potentially be a separate function
if (obj instanceof Date) {
return new Date(obj);
}
else if (Array.isArray(obj)) {
return Object.entries(obj).map(([key, value]) => {
if (value == null || typeof value !== "object") {
return value;
}
else {
return LoggerHelper.cloneObjectRecursively(value, maskValuesFn, done);
}
});
}
else {
Object.getOwnPropertyNames(obj).forEach((currentKey) => {
if (!done.includes(obj[currentKey])) {
if (obj[currentKey] == null) {
clonedObject[currentKey] = obj[currentKey];
}
else if (typeof obj[currentKey] !== "object") {
clonedObject[currentKey] =
maskValuesFn != null
? maskValuesFn(currentKey, obj[currentKey])
: obj[currentKey];
}
else {
clonedObject[currentKey] = LoggerHelper.cloneObjectRecursively(obj[currentKey], maskValuesFn, done, clonedObject[currentKey]);
}
}
else {
// cicrular detected: point to itself to make inspect printout [circular]
clonedObject[currentKey] = clonedObject;
}
});
}
return clonedObject;
}
static logObjectMaskValuesOfKeys(obj, keys, maskPlaceholder) {
if (!Array.isArray(keys) || keys.length === 0) {
return obj;
}
const maskValuesFn = (key, value) => {
const keysLowerCase = keys.map((key) => typeof key === "string" ? key.toLowerCase() : key);
if (keysLowerCase.includes(typeof key === "string" ? key.toLowerCase() : key)) {
return maskPlaceholder;
}
return value;
};
return obj != null
? LoggerHelper.cloneObjectRecursively(obj, maskValuesFn)
: obj;
}
}
LoggerHelper.cwdArray = process.cwd().split(external_path_.sep);
//# sourceMappingURL=LoggerHelper.js.map
;// ../commons/node_modules/tslog/dist/esm/LoggerWithoutCallSite.js
/**
* 📝 Expressive TypeScript Logger for Node.js
* @public
*/
class LoggerWithoutCallSite {
/**
* @param settings - Configuration of the logger instance (all settings are optional with sane defaults)
* @param parentSettings - Used internally to
*/
constructor(settings, parentSettings) {
var _a;
this._logLevels = [
"silly",
"trace",
"debug",
"info",
"warn",
"error",
"fatal",
];
this._minLevelToStdErr = 4;
this._mySettings = {};
this._childLogger = [];
this._callSiteWrapper = (callSite) => callSite;
this._parentOrDefaultSettings = {
type: "pretty",
instanceName: undefined,
hostname: (_a = parentSettings === null || parentSettings === void 0 ? void 0 : parentSettings.hostname) !== null && _a !== void 0 ? _a : (0,external_os_.hostname)(),
name: undefined,
setCallerAsLoggerName: false,
requestId: undefined,
minLevel: "silly",
exposeStack: false,
exposeErrorCodeFrame: true,
exposeErrorCodeFrameLinesBeforeAndAfter: 5,
ignoreStackLevels: 3,
suppressStdOutput: false,
overwriteConsole: false,
colorizePrettyLogs: true,
logLevelsColors: {
0: "whiteBright",
1: "white",
2: "greenBright",
3: "blueBright",
4: "yellowBright",
5: "redBright",
6: "magentaBright",
},
prettyInspectHighlightStyles: {
special: "cyan",
number: "green",
bigint: "green",
boolean: "yellow",
undefined: "red",
null: "red",
string: "red",
symbol: "green",
date: "magenta",
name: "white",
regexp: "red",
module: "underline",
},
prettyInspectOptions: {
colors: true,
compact: false,
depth: Infinity,
},
jsonInspectOptions: {
colors: false,
compact: true,
depth: Infinity,
},
delimiter: " ",
dateTimePattern: undefined,
// local timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
dateTimeTimezone: undefined,
prefix: [],
maskValuesOfKeys: ["password"],
maskAnyRegEx: [],
maskPlaceholder: "[***]",
printLogMessageInNewLine: false,
// display settings
displayDateTime: true,
displayLogLevel: true,
displayInstanceName: false,
displayLoggerName: true,
displayRequestId: true,
displayFilePath: "hideNodeModulesOnly",
displayFunctionName: true,
displayTypes: false,
stdOut: process.stdout,
stdErr: process.stderr,
attachedTransports: [],
};
const mySettings = settings != null ? settings : {};
this.setSettings(mySettings, parentSettings);
LoggerHelper.initErrorToJsonHelper();
}
/** Readonly settings of the current logger instance. Used for testing. */
get settings() {
const myPrefix = this._mySettings.prefix != null ? this._mySettings.prefix : [];
return {
...this._parentOrDefaultSettings,
...this._mySettings,
prefix: [...this._parentOrDefaultSettings.prefix, ...myPrefix],
};
}
/**
* Change settings during runtime
* Changes will be propagated to potential child loggers
*
* @param settings - Settings to overwrite with. Only this settings will be overwritten, rest will remain the same.
* @param parentSettings - INTERNAL USE: Is called by a parent logger to propagate new settings.
*/
setSettings(settings, parentSettings) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
this._mySettings = {
...this._mySettings,
...settings,
};
if (((_a = this.settings.prettyInspectOptions) === null || _a === void 0 ? void 0 : _a.colors) != null ||
((_b = this.settings.prettyInspectOptions) === null || _b === void 0 ? void 0 : _b.colors) === true) {
this.settings.prettyInspectOptions.colors =
this.settings.colorizePrettyLogs;
}
this._mySettings.instanceName =
(_c = this._mySettings.instanceName) !== null && _c !== void 0 ? _c : this._mySettings.hostname;
if (this._mySettings.name == null &&
this._mySettings.setCallerAsLoggerName) {
this._mySettings.name =
(_j = (_f = (_e = (_d = LoggerHelper.getCallSites()) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.getTypeName()) !== null && _f !== void 0 ? _f : (_h = (_g = LoggerHelper.getCallSites()) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.getFunctionName()) !== null && _j !== void 0 ? _j : undefined;
}
if (parentSettings != null) {
this._parentOrDefaultSettings = {
...this._parentOrDefaultSettings,
...parentSettings,
};
}
this._maskAnyRegExp =
((_k = this.settings.maskAnyRegEx) === null || _k === void 0 ? void 0 : _k.length) > 0
? // eslint-disable-next-line @rushstack/security/no-unsafe-regexp
new RegExp(Object.values(this.settings.maskAnyRegEx).join("|"), "g")
: undefined;
LoggerHelper.setUtilsInspectStyles(this.settings.prettyInspectHighlightStyles);
if (this.settings.overwriteConsole) {
LoggerHelper.overwriteConsole(this, this._handleLog);
}
this._childLogger.forEach((childLogger) => {
childLogger.setSettings({}, this.settings);
});
return this.settings;
}
/**
* Returns a child logger based on the current instance with inherited settings
*
* @param settings - Overwrite settings inherited from parent logger
*/
getChildLogger(settings) {
const childSettings = {
...this.settings,
attachedTransports: [...this.settings.attachedTransports],
};
const childLogger = new this.constructor(settings, childSettings);
this._childLogger.push(childLogger);
return childLogger;
}
/**
* Attaches external Loggers, e.g. external log services, file system, database
*
* @param transportLogger - External logger to be attached. Must implement all log methods.
* @param minLevel - Minimum log level to be forwarded to this attached transport logger. (e.g. debug)
*/
attachTransport(transportLogger, minLevel = "silly") {
this.settings.attachedTransports.push({
minLevel,
transportLogger,
});
}
/**
* Logs a silly message.
* @param args - Multiple log attributes that should be logged out.
*/
silly(...args) {
return this._handleLog.apply(this, ["silly", args]);
}
/**
* Logs a trace message.
* @param args - Multiple log attributes that should be logged out.
*/
trace(...args) {
return this._handleLog.apply(this, ["trace", args, true]);
}
/**
* Logs a debug message.
* @param args - Multiple log attributes that should be logged out.
*/
debug(...args) {
return this._handleLog.apply(this, ["debug", args]);
}
/**
* Logs an info message.
* @param args - Multiple log attributes that should be logged out.
*/
info(...args) {
return this._handleLog.apply(this, ["info", args]);
}
/**
* Logs a warn message.
* @param args - Multiple log attributes that should be logged out.
*/
warn(...args) {
return this._handleLog.apply(this, ["warn", args]);
}
/**
* Logs an error message.
* @param args - Multiple log attributes that should be logged out.
*/
error(...args) {
return this._handleLog.apply(this, ["error", args]);
}
/**
* Logs a fatal message.
* @param args - Multiple log attributes that should be logged out.
*/
fatal(...args) {
return this._handleLog.apply(this, ["fatal", args]);
}
/**
* Helper: Pretty print error without logging it
* @param error - Error object
* @param print - Print the error or return only? (default: true)
* @param exposeErrorCodeFrame - Should the code frame be exposed? (default: true)
* @param exposeStackTrace - Should the stack trace be exposed? (default: true)
* @param stackOffset - Offset lines of the stack trace (default: 0)
* @param stackLimit - Limit number of lines of the stack trace (default: Infinity)
* @param std - Which std should the output be printed to? (default: stdErr)
*/
prettyError(error, print = true, exposeErrorCodeFrame = true, exposeStackTrace = true, stackOffset = 0, stackLimit = Infinity, std = this.settings.stdErr) {
const errorObject = this._buildErrorObject(error, exposeErrorCodeFrame, stackOffset, stackLimit);
if (print) {
this._printPrettyError(std, errorObject, exposeStackTrace);
}
return errorObject;
}
_handleLog(logLevel, logArguments, exposeStack = this.settings.exposeStack) {
const logObject = this._buildLogObject(logLevel, logArguments, exposeStack);
if (!this.settings.suppressStdOutput &&
logObject.logLevelId >= this._logLevels.indexOf(this.settings.minLevel)) {
const std = logObject.logLevelId < this._minLevelToStdErr
? this.settings.stdOut
: this.settings.stdErr;
if (this.settings.type === "pretty") {
this.printPrettyLog(std, logObject);
}
else if (this.settings.type === "json") {
this._printJsonLog(std, logObject);
}
else {
// don't print (e.g. "hidden")
}
}
this.settings.attachedTransports.forEach((transport) => {
if (logObject.logLevelId >=
Object.values(this._logLevels).indexOf(transport.minLevel)) {
transport.transportLogger[logLevel](logObject);
}
});
return logObject;
}
_buildLogObject(logLevel, logArguments, exposeStack = true) {
const callSites = LoggerHelper.getCallSites();
const relevantCallSites = callSites.splice(this.settings.ignoreStackLevels);
const stackFrame = relevantCallSites[0] != null
? this._callSiteWrapper(relevantCallSites[0])
: undefined;
const stackFrameObject = stackFrame != null
? LoggerHelper.toStackFrameObject(stackFrame)
: undefined;
const requestId = this.settings.requestId instanceof Function
? this.settings.requestId()
: this.settings.requestId;
const logObject = {
instanceName: this.settings.instanceName,
loggerName: this.settings.name,
hostname: this.settings.hostname,
requestId,
date: new Date(),
logLevel: logLevel,
logLevelId: this._logLevels.indexOf(logLevel),
filePath: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.filePath,
fullFilePath: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.fullFilePath,
fileName: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.fileName,
lineNumber: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.lineNumber,
columnNumber: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.columnNumber,
isConstructor: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.isConstructor,
functionName: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.functionName,
typeName: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.typeName,
methodName: stackFrameObject === null || stackFrameObject === void 0 ? void 0 : stackFrameObject.methodName,
argumentsArray: [],
toJSON: () => this._logObjectToJson(logObject),
};
const logArgumentsWithPrefix = [
...this.settings.prefix,
...logArguments,
];
logArgumentsWithPrefix.forEach((arg) => {
if (arg != null && typeof arg === "object" && LoggerHelper.isError(arg)) {
logObject.argumentsArray.push(this._buildErrorObject(arg, this.settings.exposeErrorCodeFrame));
}
else {
logObject.argumentsArray.push(arg);
}
});
if (exposeStack) {
logObject.stack = this._toStackObjectArray(relevantCallSites);
}
return logObject;
}
_buildErrorObject(error, exposeErrorCodeFrame = true, stackOffset = 0, stackLimit = Infinity) {
var _a, _b;
const errorCallSites = LoggerHelper.getCallSites(error);
stackOffset = stackOffset > -1 ? stackOffset : 0;
const relevantCallSites = (_a = ((errorCallSites === null || errorCallSites === void 0 ? void 0 : errorCallSites.splice) && errorCallSites.splice(stackOffset))) !== null && _a !== void 0 ? _a : [];
stackLimit = stackLimit > -1 ? stackLimit : 0;
if (stackLimit < Infinity) {
relevantCallSites.length = stackLimit;
}
const {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
name: _name, ...errorWithoutName } = error;
const errorObject = {
nativeError: error,
details: { ...errorWithoutName },
name: (_b = error.name) !== null && _b !== void 0 ? _b : "Error",
isError: true,
message: error.message,
stack: this._toStackObjectArray(relevantCallSites),
};
if (errorObject.stack.length > 0) {
const errorCallSite = LoggerHelper.toStackFrameObject(this._callSiteWrapper(relevantCallSites[0]));
if (exposeErrorCodeFrame && errorCallSite.lineNumber != null) {
if (errorCallSite.fullFilePath != null &&
errorCallSite.fullFilePath.indexOf("node_modules") < 0) {
errorObject.codeFrame = LoggerHelper._getCodeFrame(errorCallSite.fullFilePath, errorCallSite.lineNumber, errorCallSite === null || errorCallSite === void 0 ? void 0 : errorCallSite.columnNumber, this.settings.exposeErrorCodeFrameLinesBeforeAndAfter);
}
}
}
return errorObject;
}
_toStackObjectArray(jsStack) {
const stackFrame = Object.values(jsStack).reduce((stackFrameObj, callsite) => {
stackFrameObj.push(LoggerHelper.toStackFrameObject(this._callSiteWrapper(callsite)));
return stackFrameObj;
}, []);
return stackFrame;
}
/**
* Pretty print the log object to the designated output.
*
* @param std - output where to pretty print the object
* @param logObject - object to pretty print
**/
printPrettyLog(std, logObject) {
var _a, _b;
if (this.settings.displayDateTime === true) {
let nowStr = "";
if (this.settings.dateTimePattern != null ||
this.settings.dateTimeTimezone != null) {
const dateTimePattern = (_a = this.settings.dateTimePattern) !== null && _a !== void 0 ? _a : "year-month-day hour:minute:second.millisecond";
const dateTimeTimezone = (_b = this.settings.dateTimeTimezone) !== null && _b !== void 0 ? _b : "utc";
const dateTimeParts = [
...new Intl.DateTimeFormat("en", {
weekday: undefined,
year: "numeric",
month: "2-digit",
day: "2-digit",
hourCycle: "h23",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZone: dateTimeTimezone,
}).formatToParts(logObject.date),
{
type: "millisecond",
value: ("00" + logObject.date.getMilliseconds()).slice(-3),
},
];
nowStr = dateTimeParts.reduce((prevStr, thisStr) => prevStr.replace(thisStr.type, thisStr.value), dateTimePattern);
}
else {
nowStr = new Date().toISOString().replace("T", " ").replace("Z", " ");
}
std.write(LoggerHelper.styleString(["gray"], `${nowStr}${this.settings.delimiter}`, this.settings.colorizePrettyLogs));
}
if (this.settings.displayLogLevel) {
const colorName = this.settings.logLevelsColors[logObject.logLevelId];
std.write(LoggerHelper.styleString([colorName, "bold"], logObject.logLevel.toUpperCase(), this.settings.colorizePrettyLogs) +
(logObject.logLevel === "info"
? this.settings.delimiter.repeat(2)
: this.settings.delimiter));
}
const loggerName = this.settings.displayLoggerName === true && logObject.loggerName != null
? logObject.loggerName
: "";
const instanceName = this.settings.displayInstanceName === true &&
this.settings.instanceName != null
? `@${this.settings.instanceName}`
: "";
const traceId = this.settings.displayRequestId === true && logObject.requestId != null
? `:${logObject.requestId}`
: "";
const name = (loggerName + instanceName + traceId).length > 0
? loggerName + instanceName + traceId
: "";
const functionName = this.settings.displayFunctionName === true
? logObject.isConstructor
? ` ${logObject.typeName}.constructor`
: logObject.methodName != null
? ` ${logObject.typeName}.${logObject.methodName}`
: logObject.functionName != null
? ` ${logObject.functionName}`
: logObject.typeName !== null
? `${logObject.typeName}.`
: ""
: "";
let fileLocation = "";
if (this.settings.displayFilePath === "displayAll" ||
(this.settings.displayFilePath === "hideNodeModulesOnly" &&
logObject.filePath != null &&
logObject.filePath.indexOf("node_modules") < 0)) {
fileLocation = `${logObject.filePath}:${logObject.lineNumber}`;
}
const concatenatedMetaLine = [name, fileLocation, functionName]
.join(" ")
.trim();
if (concatenatedMetaLine.length > 0) {
std.write(LoggerHelper.styleString(["gray"], `[${concatenatedMetaLine}]`, this.settings.colorizePrettyLogs));
if (this.settings.printLogMessageInNewLine === false) {
std.write(`${this.settings.delimiter}`);
}
else {
std.write("\n");
}
}
logObject.argumentsArray.forEach((argument) => {
const typeStr = this.settings.displayTypes === true
? LoggerHelper.styleString(["grey", "bold"], typeof argument + ":", this.settings.colorizePrettyLogs) + this.settings.delimiter
: "";
const errorObject = argument;
if (argument == null) {
std.write(typeStr +
this._inspectAndHideSensitive(argument, this.settings.prettyInspectOptions) +
" ");
}
else if (typeof argument === "object" &&
(errorObject === null || errorObject === void 0 ? void 0 : errorObject.isError) === true) {
this._printPrettyError(std, errorObject);
}
else if (typeof argument === "object" &&
(errorObject === null || errorObject === void 0 ? void 0 : errorObject.isError) !== true) {
std.write("\n" +
typeStr +
this._inspectAndHideSensitive(argument, this.settings.prettyInspectOptions));
}
else {
std.write(typeStr +
this._formatAndHideSensitive(argument, this.settings.prettyInspectOptions) +
this.settings.delimiter);
}
});
std.write("\n");
if (logObject.stack != null) {
std.write(LoggerHelper.styleString(["underline", "bold"], "log stack:\n", this.settings.colorizePrettyLogs));
this._printPrettyStack(std, logObject.stack);
}
}
_printPrettyError(std, errorObject, printStackTrace = true) {
var _a;
std.write("\n" +
LoggerHelper.styleString(["bgRed", "whiteBright", "bold"], ` ${errorObject.name}${this.settings.delimiter}`, this.settings.colorizePrettyLogs) +
(errorObject.message != null
? `${this.settings.delimiter}${this._formatAndHideSensitive(errorObject.message, this.settings.prettyInspectOptions)}`
: ""));
if (Object.values(errorObject.details).length > 0) {
std.write(LoggerHelper.styleString(["underline", "bold"], "\ndetails:", this.settings.colorizePrettyLogs));
std.write("\n" +
this._inspectAndHideSensitive(errorObject.details, this.settings.prettyInspectOptions));
}
if (printStackTrace === true && ((_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject.stack) === null || _a === void 0 ? void 0 : _a.length) > 0) {
std.write(LoggerHelper.styleString(["underline", "bold"], "\nerror stack:", this.settings.colorizePrettyLogs));
this._printPrettyStack(std, errorObject.stack);
}
if (errorObject.codeFrame != null) {
this._printPrettyCodeFrame(std, errorObject.codeFrame);
}
}
_printPrettyStack(std, stackObjectArray) {
std.write("\n");
Object.values(stackObjectArray).forEach((stackObject) => {
var _a;
std.write(LoggerHelper.styleString(["gray"], "• ", this.settings.colorizePrettyLogs));
if (stackObject.fileName != null) {
std.write(LoggerHelper.styleString(["yellowBright"], stackObject.fileName, this.settings.colorizePrettyLogs));
}
if (stackObject.lineNumber != null) {
std.write(LoggerHelper.styleString(["gray"], ":", this.settings.colorizePrettyLogs));
std.write(LoggerHelper.styleString(["yellow"], stackObject.lineNumber, this.settings.colorizePrettyLogs));
}
std.write(LoggerHelper.styleString(["white"], " " + ((_a = stackObject.functionName) !== null && _a !== void 0 ? _a : ""), this.settings.colorizePrettyLogs));
if (stackObject.filePath != null &&
stackObject.lineNumber != null &&
stackObject.columnNumber != null) {
std.write("\n ");
std.write((0,external_path_.normalize)(LoggerHelper.styleString(["gray"], `${stackObject.filePath}:${stackObject.lineNumber}:${stackObject.columnNumber}`, this.settings.colorizePrettyLogs)));
}
std.write("\n\n");
});
}
_printPrettyCodeFrame(std, codeFrame) {
std.write(LoggerHelper.styleString(["underline", "bold"], "code frame:\n", this.settings.colorizePrettyLogs));
let lineNumber = codeFrame.firstLineNumber;
codeFrame.linesBefore.forEach((line) => {
std.write(` ${LoggerHelper.lineNumberTo3Char(lineNumber)} | ${line}\n`);
lineNumber++;
});
std.write(LoggerHelper.styleString(["red"], ">", this.settings.colorizePrettyLogs) +
" " +
LoggerHelper.styleString(["bgRed", "whiteBright"], LoggerHelper.lineNumberTo3Char(lineNumber), this.settings.colorizePrettyLogs) +
" | " +
LoggerHelper.styleString(["yellow"], codeFrame.relevantLine, this.settings.colorizePrettyLogs) +
"\n");
lineNumber++;
if (codeFrame.columnNumber != null) {
const positionMarker = new Array(codeFrame.columnNumber + 8).join(" ") + `^`;
std.write(LoggerHelper.styleString(["red"], positionMarker, this.settings.colorizePrettyLogs) + "\n");
}
codeFrame.linesAfter.forEach((line) => {
std.write(` ${LoggerHelper.lineNumberTo3Char(lineNumber)} | ${line}\n`);
lineNumber++;
});
}
_logObjectToJson(logObject) {
return {
...logObject,
argumentsArray: logObject.argumentsArray.map((argument) => {
const errorObject = argument;
if (typeof argument === "object" && (errorObject === null || errorObject === void 0 ? void 0 : errorObject.isError)) {
return {
...errorObject,
nativeError: undefined,
errorString: this._formatAndHideSensitive(errorObject.nativeError, this.settings.jsonInspectOptions),
};
}
else if (typeof argument === "object") {
return this._inspectAndHideSensitive(argument, this.settings.jsonInspectOptions);
}
else {
return this._formatAndHideSensitive(argument, this.settings.jsonInspectOptions);
}
}),
};
}
_printJsonLog(std, logObject) {
std.write(JSON.stringify(logObject) + "\n");
}
_inspectAndHideSensitive(object, inspectOptions) {
let formatted;
try {
const maskedObject = this._maskValuesOfKeys(object);
formatted = (0,external_util_.inspect)(maskedObject, inspectOptions);
}
catch {
formatted = (0,external_util_.inspect)(object, inspectOptions);
}
return this._maskAny(formatted);
}
_formatAndHideSensitive(formatParam, inspectOptions, ...param) {
return this._maskAny((0,external_util_.formatWithOptions)(inspectOptions, formatParam, ...param));
}
_maskValuesOfKeys(object) {
return LoggerHelper.logObjectMaskValuesOfKeys(object, this.settings.maskValuesOfKeys, this.settings.maskPlaceholder);
}
_maskAny(str) {
const formattedStr = str;
return this._maskAnyRegExp != null
? formattedStr.replace(this._maskAnyRegExp, this.settings.maskPlaceholder)
: formattedStr;
}
}
//# sourceMappingURL=LoggerWithoutCallSite.js.map
;// ../commons/node_modules/tslog/dist/esm/Logger.js
/**
* 📝 Expressive TypeScript Logger for Node.js
* @public
*/
class Logger extends LoggerWithoutCallSite {
/**
* @param settings - Configuration of the logger instance (all settings are optional with sane defaults)
* @param parentSettings - Used internally to
*/
constructor(settings, parentSettings) {
super(settings, parentSettings);
this._callSiteWrapper = source_map_support.wrapCallSite;
}
}
//# sourceMappingURL=Logger.js.map
;// ../commons/dist/logger.js
function createLogger(name, options) {
return new Logger({
name,
type: 'pretty',
...options,
});
}
const defaultLogger = createLogger('DefaultLogger', {
minLevel: 1
});
const logger = createLogger(MODULE_NAME, {});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2xvZ2dlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUcsTUFBTSxFQUFFLE1BQU0sT0FBTyxDQUFBO0FBRS9CLE1BQU0sVUFBVSxZQUFZLENBQUMsSUFBWSxFQUFFLE9BQWE7SUFDcEQsT0FBTyxJQUFJLE1BQU0sQ0FBQztRQUNkLElBQUk7UUFDSixJQUFJLEVBQUUsUUFBUTtRQUNkLEdBQUcsT0FBTztLQUNiLENBQUMsQ0FBQTtBQUNOLENBQUM7QUFDRCxNQUFNLENBQUMsTUFBTSxhQUFhLEdBQUcsWUFBWSxDQUFDLGVBQWUsRUFBRTtJQUN2RCxRQUFRLEVBQUUsQ0FBQztDQUNkLENBQUMsQ0FBQTtBQUVGLE9BQU8sRUFBRSxXQUFXLEVBQUUsTUFBTSxnQkFBZ0IsQ0FBQTtBQUM1QyxPQUFPLEVBQUUsV0FBVyxFQUFFLE1BQU0sZ0JBQWdCLENBQUE7QUFFNUMsTUFBTSxDQUFDLE1BQU0sTUFBTSxHQUFHLFlBQVksQ0FBQyxXQUFXLEVBQUUsRUFBRSxDQUFDLENBQUEifQ==
// EXTERNAL MODULE: ../fs/dist/write.js
var write = __webpack_require__(5682);
// EXTERNAL MODULE: ../commons/node_modules/typescript/lib/typescript.js
var typescript = __webpack_require__(5624);
;// ../commons/node_modules/zod-to-ts/dist/index.js
// src/index.ts
// src/types.ts
var resolveOptions = (raw) => {
const resolved = {
nativeEnums: raw?.resolveNativeEnums ? "resolve" : "identifier"
};
return { ...resolved, ...raw };
};
// src/utils.ts
var { factory: f, SyntaxKind, ScriptKind, ScriptTarget, EmitHint } = typescript;
var maybeIdentifierToTypeReference = (identifier) => {
if (typescript.isIdentifier(identifier)) {
return f.createTypeReferenceNode(identifier);
}
return identifier;
};
var createTypeReferenceFromString = (identifier) => f.createTypeReferenceNode(f.createIdentifier(identifier));
var createUnknownKeywordNode = () => f.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
var createTypeAlias = (node, identifier, comment) => {
const typeAlias = f.createTypeAliasDeclaration(
void 0,
f.createIdentifier(identifier),
void 0,
node
);
if (comment) {
addJsDocComment(typeAlias, comment);
}
return typeAlias;
};
var printNode = (node, printerOptions) => {
const sourceFile = typescript.createSourceFile("print.ts", "", ScriptTarget.Latest, false, ScriptKind.TS);
const printer = typescript.createPrinter(printerOptions);
return printer.printNode(EmitHint.Unspecified, node, sourceFile);
};
var withGetType = (schema, getType) => {
schema._def.getType = getType;
return schema;
};
var identifierRE = /^[$A-Z_a-z][\w$]*$/;
var getIdentifierOrStringLiteral = (string_) => {
if (identifierRE.test(string_)) {
return f.createIdentifier(string_);
}
return f.createStringLiteral(string_);
};
var addJsDocComment = (node, text) => {
typescript.addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, `* ${text} `, true);
};
// src/index.ts
var { factory: f2, SyntaxKind: SyntaxKind2 } = typescript;
var callGetType = (zod, identifier, options) => {
let type;
if (zod._def.getType)
type = zod._def.getType(typescript, identifier, options);
return type;
};
var zodToTs = (zod, identifier, options) => {
const resolvedIdentifier = identifier ?? "Identifier";
const resolvedOptions = resolveOptions(options);
const store = { nativeEnums: [] };
const node = zodToTsNode(zod, resolvedIdentifier, store, resolvedOptions);
return { node, store };
};
var zodToTsNode = (zod, identifier, store, options) => {
const typeName = zod._def.typeName;
const getTypeType = callGetType(zod, identifier, options);
if (getTypeType && typeName !== "ZodNativeEnum") {
return maybeIdentifierToTypeReference(getTypeType);
}
const otherArguments = [identifier, store, options];
switch (typeName) {
case "ZodString": {
return f2.createKeywordTypeNode(SyntaxKind2.StringKeyword);
}
case "ZodNumber": {
return f2.createKeywordTypeNode(SyntaxKind2.NumberKeyword);
}
case "ZodBigInt": {
return f2.createKeywordTypeNode(SyntaxKind2.BigIntKeyword);
}
case "ZodBoolean": {
return f2.createKeywordTypeNode(SyntaxKind2.BooleanKeyword);
}
case "ZodDate": {
return f2.createTypeReferenceNode(f2.createIdentifier("Date"));
}
case "ZodUndefined": {
return f2.createKeywordTypeNode(SyntaxKind2.UndefinedKeyword);
}
case "ZodNull": {
return f2.createLiteralTypeNode(f2.createNull());
}
case "ZodVoid": {
return f2.createUnionTypeNode([
f2.createKeywordTypeNode(SyntaxKind2.VoidKeyword),
f2.createKeywordTypeNode(SyntaxKind2.UndefinedKeyword)
]);
}
case "ZodAny": {
return f2.createKeywordTypeNode(SyntaxKind2.AnyKeyword);
}
case "ZodUnknown": {
return createUnknownKeywordNode();
}
case "ZodNever": {
return f2.createKeywordTypeNode(SyntaxKind2.NeverKeyword);
}
case "ZodLazy": {
if (!getTypeType)
return createTypeReferenceFromString(identifier);
break;
}
case "ZodLiteral": {
let literal;
const literalValue = zod._def.value;
switch (typeof literalValue) {
case "number": {
literal = f2.createNumericLiteral(literalValue);
break;
}
case "boolean": {
literal = literalValue === true ? f2.createTrue() : f2.createFalse();
break;
}
default: {
literal = f2.createStringLiteral(literalValue);
break;
}
}
return f2.createLiteralTypeNode(literal);
}
case "ZodObject": {
const properties = Object.entries(zod._def.shape());
const members = properties.map(([key, value]) => {
const nextZodNode = value;
const type = zodToTsNode(nextZodNode, ...otherArguments);
const { typeName: nextZodNodeTypeName } = nextZodNode._def;
const isOptional = nextZodNodeTypeName === "ZodOptional" || nextZodNode.isOptional();
const propertySignature = f2.createPropertySignature(
void 0,
getIdentifierOrStringLiteral(key),
isOptional ? f2.createToken(SyntaxKind2.QuestionToken) : void 0,
type
);
if (nextZodNode.description) {
addJsDocComment(propertySignature, nextZodNode.description);
}
return propertySignature;
});
return f2.createTypeLiteralNode(members);
}
case "ZodArray": {
const type = zodToTsNode(zod._def.type, ...otherArguments);
const node = f2.createArrayTypeNode(type);
return node;
}
case "ZodEnum": {
const types = zod._def.values.map((value) => f2.createLiteralTypeNode(f2.createStringLiteral(value)));
return f2.createUnionTypeNode(types);
}
case "ZodUnion": {
const options2 = zod._def.options;
const types = options2.map((option) => zodToTsNode(option, ...otherArguments));
return f2.createUnionTypeNode(types);
}
case "ZodDiscriminatedUnion": {
const options2 = [...zod._def.options.values()];
const types = options2.map((option) => zodToTsNode(option, ...otherArguments));
return f2.createUnionTypeNode(types);
}
case "ZodEffects": {
const node = zodToTsNode(zod._def.schema, ...otherArguments);
return node;
}
case "ZodNativeEnum": {
const type = getTypeType;
if (options.nativeEnums === "union") {
if (type)
return maybeIdentifierToTypeReference(type);
const types = Object.values(zod._def.values).map((value) => {
if (typeof value === "number") {
return f2.createLiteralTypeNode(f2.createNumericLiteral(value));
}
return f2.createLiteralTypeNode(f2.createStringLiteral(value));
});
return f2.createUnionTypeNode(types);
}
if (!type)
return createUnknownKeywordNode();
if (options.nativeEnums === "resolve") {
const enumMembers = Object.entries(zod._def.values).map(([key, value]) => {
const literal = typeof value === "number" ? f2.createNumericLiteral(value) : f2.createStringLiteral(value);
return f2.createEnumMember(
getIdentifierOrStringLiteral(key),
literal
);
});
if (typescript.isIdentifier(type)) {
store.nativeEnums.push(
f2.createEnumDeclaration(
void 0,
type,
enumMembers
)
);
} else {
throw new Error('getType on nativeEnum must return an identifier when nativeEnums is "resolve"');
}
}
return maybeIdentifierToTypeReference(type);
}
case "ZodOptional": {
const innerType = zodToTsNode(zod._def.innerType, ...otherArguments);
return f2.createUnionTypeNode([
innerType,
f2.createKeywordTypeNode(SyntaxKind2.UndefinedKeyword)
]);
}
case "ZodNullable": {
const innerType = zodToTsNode(zod._def.innerType, ...otherArguments);
return f2.createUnionTypeNode([
innerType,
f2.createLiteralTypeNode(f2.createNull())
]);
}
case "ZodTuple": {
const types = zod._def.items.map((option) => zodToTsNode(option, ...otherArguments));
return f2.createTupleTypeNode(types);
}
case "ZodRecord": {
const valueType = zodToTsNode(zod._def.valueType, ...otherArguments);
const node = f2.createTypeLiteralNode([f2.createIndexSignature(
void 0,
[f2.createParameterDeclaration(
void 0,
void 0,
f2.createIdentifier("x"),
void 0,
f2.createKeywordTypeNode(SyntaxKind2.StringKeyword)
)],
valueType
)]);
return node;
}
case "ZodMap": {
const valueType = zodToTsNode(zod._def.valueType, ...otherArguments);
const keyType = zodToTsNode(zod._def.keyType, ...otherArguments);
const node = f2.createTypeReferenceNode(
f2.createIdentifier("Map"),
[
keyType,
valueType
]
);
return node;
}
case "ZodSet": {
const type = zodToTsNode(zod._def.valueType, ...otherArguments);
const node = f2.createTypeReferenceNode(
f2.createIdentifier("Set"),
[type]
);
return node;
}
case "ZodIntersection": {
const left = zodToTsNode(zod._def.left, ...otherArguments);
const right = zodToTsNode(zod._def.right, ...otherArguments);
const node = f2.createIntersectionTypeNode([left, right]);
return node;
}
case "ZodPromise": {
const type = zodToTsNode(zod._def.type, ...otherArguments);
const node = f2.createTypeReferenceNode(
f2.createIdentifier("Promise"),
[type]
);
return node;
}
case "ZodFunction": {
const argumentTypes = zod._def.args._def.items.map((argument, index) => {
const argumentType = zodToTsNode(argument, ...otherArguments);
return f2.createParameterDeclaration(
void 0,
void 0,
f2.createIdentifier(`args_${index}`),
void 0,
argumentType
);
});
argumentTypes.push(
f2.createParameterDeclaration(
void 0,
f2.createToken(SyntaxKind2.DotDotDotToken),
f2.createIdentifier(`args_${argumentTypes.length}`),
void 0,
f2.createArrayTypeNode(createUnknownKeywordNode())
)
);
const returnType = zodToTsNode(zod._def.returns, ...otherArguments);
const node = f2.createFunctionTypeNode(
void 0,
argumentTypes,
returnType
);
return node;
}
case "ZodDefault": {
const type = zodToTsNode(zod._def.innerType, ...otherArguments);
const filteredNodes = [];
type.forEachChild((node) => {
if (![SyntaxKind2.UndefinedKeyword].includes(node.kind)) {
filteredNodes.push(node);
}
});
type.types = filteredNodes;
return type;
}
}
return f2.createKeywordTypeNode(SyntaxKind2.AnyKeyword);
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/Options.js
const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
const jsonDescription = (jsonSchema, def) => {
if (def.description) {
try {
return {
...jsonSchema,
...JSON.parse(def.description),
};
}
catch { }
}
return jsonSchema;
};
const defaultOptions = {
name: undefined,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
target: "jsonSchema7",
strictUnions: false,
definitions: {},
errorMessages: false,
markdownDescription: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref",
};
const getDefaultOptions = (options) => (typeof options === "string"
? {
...defaultOptions,
name: options,
}
: {
...defaultOptions,
...options,
});
;// ../commons/node_modules/zod-to-json-schema/dist/esm/Refs.js
const getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== undefined
? [..._options.basePath, _options.definitionPath, _options.name]
: _options.basePath;
return {
..._options,
currentPath: currentPath,
propertyPath: undefined,
seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
def._def,
{
def: def._def,
path: [..._options.basePath, _options.definitionPath, name],
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
jsonSchema: undefined,
},
])),
};
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
function parseAnyDef() {
return {};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
function addErrorMessage(res, key, errorMessage, refs) {
if (!refs?.errorMessages)
return;
if (errorMessage) {
res.errorMessage = {
...res.errorMessage,
[key]: errorMessage,
};
}
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
res[key] = value;
addErrorMessage(res, key, errorMessage, refs);
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
function parseArrayDef(def, refs) {
const res = {
type: "array",
};
if (def.type?._def &&
def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"],
});
}
if (def.minLength) {
setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
}
if (def.maxLength) {
setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
}
if (def.exactLength) {
setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
}
return res;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
function parseBigintDef(def, refs) {
const res = {
type: "integer",
format: "int64",
};
if (!def.checks)
return res;
for (const check of def.checks) {
switch (check.kind) {
case "min":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
else {
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
}
}
else {
if (!check.inclusive) {
res.exclusiveMinimum = true;
}
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
else {
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
}
}
else {
if (!check.inclusive) {
res.exclusiveMaximum = true;
}
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
}
return res;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
function parseBooleanDef() {
return {
type: "boolean",
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
const parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy ?? refs.dateStrategy;
if (Array.isArray(strategy)) {
return {
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),
};
}
switch (strategy) {
case "string":
case "format:date-time":
return {
type: "string",
format: "date-time",
};
case "format:date":
return {
type: "string",
format: "date",
};
case "integer":
return integerDateParser(def, refs);
}
}
const integerDateParser = (def, refs) => {
const res = {
type: "integer",
format: "unix-time",
};
if (refs.target === "openApi3") {
return res;
}
for (const check of def.checks) {
switch (check.kind) {
case "min":
setResponseValueAndErrors(res, "minimum", check.value, // This is in milliseconds
check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maximum", check.value, // This is in milliseconds
check.message, refs);
break;
}
}
return res;
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue(),
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input"
? parseDef(_def.schema._def, refs)
: {};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values),
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
const isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string")
return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [
parseDef(def.left._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"],
}),
parseDef(def.right._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "1"],
}),
].filter((x) => !!x);
let unevaluatedProperties = refs.target === "jsonSchema2019-09"
? { unevaluatedProperties: false }
: undefined;
const mergedAllOf = [];
// If either of the schemas is an allOf, merge them into a single allOf
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) {
mergedAllOf.push(...schema.allOf);
if (schema.unevaluatedProperties === undefined) {
// If one of the schemas has no unevaluatedProperties set,
// the merged schema should also have no unevaluatedProperties set
unevaluatedProperties = undefined;
}
}
else {
let nestedSchema = schema;
if ("additionalProperties" in schema &&
schema.additionalProperties === false) {
const { additionalProperties, ...rest } = schema;
nestedSchema = rest;
}
else {
// As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties
unevaluatedProperties = undefined;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length
? {
allOf: mergedAllOf,
...unevaluatedProperties,
}
: undefined;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
function parseLiteralDef(def, refs) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" &&
parsedType !== "number" &&
parsedType !== "boolean" &&
parsedType !== "string") {
return {
type: Array.isArray(def.value) ? "array" : "object",
};
}
if (refs.target === "openApi3") {
return {
type: parsedType === "bigint" ? "integer" : parsedType,
enum: [def.value],
};
}
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value,
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
let string_emojiRegex = undefined;
/**
* Generated from the regular expressions found here as of 2024-05-22:
* https://github.com/colinhacks/zod/blob/master/src/types.ts.
*
* Expressions with /i flag have been changed accordingly.
*/
const zodPatterns = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (string_emojiRegex === undefined) {
string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
}
return string_emojiRegex;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,
};
function parseStringDef(def, refs) {
const res = {
type: "string",
};
if (def.checks) {
for (const check of def.checks) {
switch (check.kind) {
case "min":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number"
? Math.max(res.minLength, check.value)
: check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number"
? Math.min(res.maxLength, check.value)
: check.value, check.message, refs);
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number"
? Math.max(res.minLength, check.value)
: check.value, check.message, refs);
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number"
? Math.min(res.maxLength, check.value)
: check.value, check.message, refs);
break;
case "includes": {
addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
break;
}
case "ip": {
if (check.version !== "v6") {
addFormat(res, "ipv4", check.message, refs);
}
if (check.version !== "v4") {
addFormat(res, "ipv6", check.message, refs);
}
break;
}
case "base64url":
addPattern(res, zodPatterns.base64url, check.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check.message, refs);
break;
case "cidr": {
if (check.version !== "v6") {
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
}
if (check.version !== "v4") {
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
}
break;
}
case "emoji":
addPattern(res, zodPatterns.emoji(), check.message, refs);
break;
case "ulid": {
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
}
case "base64": {
switch (refs.base64Strategy) {
case "format:binary": {
addFormat(res, "binary", check.message, refs);
break;
}
case "contentEncoding:base64": {
setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
break;
}
case "pattern:zod": {
addPattern(res, zodPatterns.base64, check.message, refs);
break;
}
}
break;
}
case "nanoid": {
addPattern(res, zodPatterns.nanoid, check.message, refs);
}
case "toLowerCase":
case "toUpperCase":
case "trim":
break;
default:
/* c8 ignore next */
((_) => { })(check);
}
}
}
return res;
}
function escapeLiteralCheckValue(literal, refs) {
return refs.patternStrategy === "escape"
? escapeNonAlphaNumeric(literal)
: literal;
}
const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
let result = "";
for (let i = 0; i < source.length; i++) {
if (!ALPHA_NUMERIC.has(source[i])) {
result += "\\";
}
result += source[i];
}
return result;
}
// Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.
function addFormat(schema, value, message, refs) {
if (schema.format || schema.anyOf?.some((x) => x.format)) {
if (!schema.anyOf) {
schema.anyOf = [];
}
if (schema.format) {
schema.anyOf.push({
format: schema.format,
...(schema.errorMessage &&
refs.errorMessages && {
errorMessage: { format: schema.errorMessage.format },
}),
});
delete schema.format;
if (schema.errorMessage) {
delete schema.errorMessage.format;
if (Object.keys(schema.errorMessage).length === 0) {
delete schema.errorMessage;
}
}
}
schema.anyOf.push({
format: value,
...(message &&
refs.errorMessages && { errorMessage: { format: message } }),
});
}
else {
setResponseValueAndErrors(schema, "format", value, message, refs);
}
}
// Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.
function addPattern(schema, regex, message, refs) {
if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
if (!schema.allOf) {
schema.allOf = [];
}
if (schema.pattern) {
schema.allOf.push({
pattern: schema.pattern,
...(schema.errorMessage &&
refs.errorMessages && {
errorMessage: { pattern: schema.errorMessage.pattern },
}),
});
delete schema.pattern;
if (schema.errorMessage) {
delete schema.errorMessage.pattern;
if (Object.keys(schema.errorMessage).length === 0) {
delete schema.errorMessage;
}
}
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...(message &&
refs.errorMessages && { errorMessage: { pattern: message } }),
});
}
else {
setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
}
}
// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true
function stringifyRegExpWithFlags(regex, refs) {
if (!refs.applyRegexFlags || !regex.flags) {
return regex.source;
}
// Currently handled flags
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s"), // `.` matches newlines
};
// The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i = 0; i < source.length; i++) {
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
}
else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
pattern += source[i];
inCharRange = true;
}
else {
pattern += `${source[i]}${source[i].toUpperCase()}`;
}
continue;
}
}
else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i] === "^") {
pattern += `(^|(?<=[\r\n]))`;
continue;
}
else if (source[i] === "$") {
pattern += `($|(?=[\r\n]))`;
continue;
}
}
if (flags.s && source[i] === ".") {
pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
continue;
}
pattern += source[i];
if (source[i] === "\\") {
isEscaped = true;
}
else if (inCharGroup && source[i] === "]") {
inCharGroup = false;
}
else if (!inCharGroup && source[i] === "[") {
inCharGroup = true;
}
}
try {
new RegExp(pattern);
}
catch {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(def, refs) {
if (refs.target === "openAi") {
console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
}
if (refs.target === "openApi3" &&
def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
return {
type: "object",
required: def.keyType._def.values,
properties: def.keyType._def.values.reduce((acc, key) => ({
...acc,
[key]: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "properties", key],
}) ?? {},
}), {}),
additionalProperties: refs.rejectedAdditionalProperties,
};
}
const schema = {
type: "object",
additionalProperties: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"],
}) ?? refs.allowedAdditionalProperties,
};
if (refs.target === "openApi3") {
return schema;
}
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&
def.keyType._def.checks?.length) {
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType,
};
}
else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
return {
...schema,
propertyNames: {
enum: def.keyType._def.values,
},
};
}
else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&
def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&
def.keyType._def.type._def.checks?.length) {
const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType,
};
}
return schema;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") {
return parseRecordDef(def, refs);
}
const keys = parseDef(def.keyType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "0"],
}) || {};
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "1"],
}) || {};
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2,
},
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
function parseNativeEnumDef(def) {
const object = def.values;
const actualKeys = Object.keys(def.values).filter((key) => {
return typeof object[object[key]] !== "number";
});
const actualValues = actualKeys.map((key) => object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1
? parsedTypes[0] === "string"
? "string"
: "number"
: ["string", "number"],
enum: actualValues,
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
function parseNeverDef() {
return {
not: {},
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
function parseNullDef(refs) {
return refs.target === "openApi3"
? {
enum: ["null"],
nullable: true,
}
: {
type: "null",
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
const primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null",
};
function parseUnionDef(def, refs) {
if (refs.target === "openApi3")
return asAnyOf(def, refs);
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
// This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.
if (options.every((x) => x._def.typeName in primitiveMappings &&
(!x._def.checks || !x._def.checks.length))) {
// all types in union are primitive and lack checks, so might as well squash into {type: [...]}
const types = options.reduce((types, x) => {
const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43
return type && !types.includes(type) ? [...types, type] : types;
}, []);
return {
type: types.length > 1 ? types : types[0],
};
}
else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
// all options literals
const types = options.reduce((acc, x) => {
const type = typeof x._def.value;
switch (type) {
case "string":
case "number":
case "boolean":
return [...acc, type];
case "bigint":
return [...acc, "integer"];
case "object":
if (x._def.value === null)
return [...acc, "null"];
case "symbol":
case "undefined":
case "function":
default:
return acc;
}
}, []);
if (types.length === options.length) {
// all the literals are primitive, as far as null can be considered primitive
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x) => {
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
}, []),
};
}
}
else if (options.every((x) => x._def.typeName === "ZodEnum")) {
return {
type: "string",
enum: options.reduce((acc, x) => [
...acc,
...x._def.values.filter((x) => !acc.includes(x)),
], []),
};
}
return asAnyOf(def, refs);
}
const asAnyOf = (def, refs) => {
const anyOf = (def.options instanceof Map
? Array.from(def.options.values())
: def.options)
.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", `${i}`],
}))
.filter((x) => !!x &&
(!refs.strictUnions ||
(typeof x === "object" && Object.keys(x).length > 0)));
return anyOf.length ? { anyOf } : undefined;
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
function parseNullableDef(def, refs) {
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) &&
(!def.innerType._def.checks || !def.innerType._def.checks.length)) {
if (refs.target === "openApi3") {
return {
type: primitiveMappings[def.innerType._def.typeName],
nullable: true,
};
}
return {
type: [
primitiveMappings[def.innerType._def.typeName],
"null",
],
};
}
if (refs.target === "openApi3") {
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath],
});
if (base && "$ref" in base)
return { allOf: [base], nullable: true };
return base && { ...base, nullable: true };
}
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", "0"],
});
return base && { anyOf: [base, { type: "null" }] };
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
function parseNumberDef(def, refs) {
const res = {
type: "number",
};
if (!def.checks)
return res;
for (const check of def.checks) {
switch (check.kind) {
case "int":
res.type = "integer";
addErrorMessage(res, "type", check.message, refs);
break;
case "min":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
else {
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
}
}
else {
if (!check.inclusive) {
res.exclusiveMinimum = true;
}
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if (refs.target === "jsonSchema7") {
if (check.inclusive) {
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
else {
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
}
}
else {
if (!check.inclusive) {
res.exclusiveMaximum = true;
}
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
}
return res;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
function parseObjectDef(def, refs) {
const forceOptionalIntoNullable = refs.target === "openAi";
const result = {
type: "object",
properties: {},
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === undefined || propDef._def === undefined) {
continue;
}
let propOptional = safeIsOptional(propDef);
if (propOptional && forceOptionalIntoNullable) {
if (propDef instanceof lib_ZodOptional) {
propDef = propDef._def.innerType;
}
if (!propDef.isNullable()) {
propDef = propDef.nullable();
}
propOptional = false;
}
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [...refs.currentPath, "properties", propName],
propertyPath: [...refs.currentPath, "properties", propName],
});
if (parsedDef === undefined) {
continue;
}
result.properties[propName] = parsedDef;
if (!propOptional) {
required.push(propName);
}
}
if (required.length) {
result.required = required;
}
const additionalProperties = decideAdditionalProperties(def, refs);
if (additionalProperties !== undefined) {
result.additionalProperties = additionalProperties;
}
return result;
}
function decideAdditionalProperties(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") {
return parseDef(def.catchall._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"],
});
}
switch (def.unknownKeys) {
case "passthrough":
return refs.allowedAdditionalProperties;
case "strict":
return refs.rejectedAdditionalProperties;
case "strip":
return refs.removeAdditionalStrategy === "strict"
? refs.allowedAdditionalProperties
: refs.rejectedAdditionalProperties;
}
}
function safeIsOptional(schema) {
try {
return schema.isOptional();
}
catch {
return true;
}
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
const parseOptionalDef = (def, refs) => {
if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
return parseDef(def.innerType._def, refs);
}
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", "1"],
});
return innerSchema
? {
anyOf: [
{
not: {},
},
innerSchema,
],
}
: {};
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
const parsePipelineDef = (def, refs) => {
if (refs.pipeStrategy === "input") {
return parseDef(def.in._def, refs);
}
else if (refs.pipeStrategy === "output") {
return parseDef(def.out._def, refs);
}
const a = parseDef(def.in._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"],
});
const b = parseDef(def.out._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"],
});
return {
allOf: [a, b].filter((x) => x !== undefined),
};
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
function parseSetDef(def, refs) {
const items = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"],
});
const schema = {
type: "array",
uniqueItems: true,
items,
};
if (def.minSize) {
setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
}
if (def.maxSize) {
setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
}
return schema;
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
function parseTupleDef(def, refs) {
if (def.rest) {
return {
type: "array",
minItems: def.items.length,
items: def.items
.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i}`],
}))
.reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"],
}),
};
}
else {
return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items
.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i}`],
}))
.reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
};
}
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
function parseUndefinedDef() {
return {
not: {},
};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
function parseUnknownDef() {
return {};
}
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
const parseReadonlyDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/selectParser.js
const selectParser = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString:
return parseStringDef(def, refs);
case ZodFirstPartyTypeKind.ZodNumber:
return parseNumberDef(def, refs);
case ZodFirstPartyTypeKind.ZodObject:
return parseObjectDef(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt:
return parseBigintDef(def, refs);
case ZodFirstPartyTypeKind.ZodBoolean:
return parseBooleanDef();
case ZodFirstPartyTypeKind.ZodDate:
return parseDateDef(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined:
return parseUndefinedDef();
case ZodFirstPartyTypeKind.ZodNull:
return parseNullDef(refs);
case ZodFirstPartyTypeKind.ZodArray:
return parseArrayDef(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
return parseUnionDef(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection:
return parseIntersectionDef(def, refs);
case ZodFirstPartyTypeKind.ZodTuple:
return parseTupleDef(def, refs);
case ZodFirstPartyTypeKind.ZodRecord:
return parseRecordDef(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral:
return parseLiteralDef(def, refs);
case ZodFirstPartyTypeKind.ZodEnum:
return parseEnumDef(def);
case ZodFirstPartyTypeKind.ZodNativeEnum:
return parseNativeEnumDef(def);
case ZodFirstPartyTypeKind.ZodNullable:
return parseNullableDef(def, refs);
case ZodFirstPartyTypeKind.ZodOptional:
return parseOptionalDef(def, refs);
case ZodFirstPartyTypeKind.ZodMap:
return parseMapDef(def, refs);
case ZodFirstPartyTypeKind.ZodSet:
return parseSetDef(def, refs);
case ZodFirstPartyTypeKind.ZodLazy:
return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise:
return parsePromiseDef(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever:
return parseNeverDef();
case ZodFirstPartyTypeKind.ZodEffects:
return parseEffectsDef(def, refs);
case ZodFirstPartyTypeKind.ZodAny:
return parseAnyDef();
case ZodFirstPartyTypeKind.ZodUnknown:
return parseUnknownDef();
case ZodFirstPartyTypeKind.ZodDefault:
return parseDefaultDef(def, refs);
case ZodFirstPartyTypeKind.ZodBranded:
return parseBrandedDef(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly:
return parseReadonlyDef(def, refs);
case ZodFirstPartyTypeKind.ZodCatch:
return parseCatchDef(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline:
return parsePipelineDef(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol:
return undefined;
default:
/* c8 ignore next */
return ((_) => undefined)(typeName);
}
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/parseDef.js
function parseDef(def, refs, forceResolution = false) {
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) {
return overrideResult;
}
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== undefined) {
return seenSchema;
}
}
const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
// If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)
const jsonSchema = typeof jsonSchemaOrGetter === "function"
? parseDef(jsonSchemaOrGetter(), refs)
: jsonSchemaOrGetter;
if (jsonSchema) {
addMeta(def, refs, jsonSchema);
}
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema, def, refs);
newItem.jsonSchema = jsonSchema;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema;
return jsonSchema;
}
const get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root":
return { $ref: item.path.join("/") };
case "relative":
return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen": {
if (item.path.length < refs.currentPath.length &&
item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return {};
}
return refs.$refStrategy === "seen" ? {} : undefined;
}
}
};
const getRelativePath = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) {
if (pathA[i] !== pathB[i])
break;
}
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
const addMeta = (def, refs, jsonSchema) => {
if (def.description) {
jsonSchema.description = def.description;
if (refs.markdownDescription) {
jsonSchema.markdownDescription = def.description;
}
}
return jsonSchema;
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
const zodToJsonSchema_zodToJsonSchema = (schema, options) => {
const refs = getRefs(options);
const definitions = typeof options === "object" && options.definitions
? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
...acc,
[name]: parseDef(schema._def, {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name],
}, true) ?? {},
}), {})
: undefined;
const name = typeof options === "string"
? options
: options?.nameStrategy === "title"
? undefined
: options?.name;
const main = parseDef(schema._def, name === undefined
? refs
: {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name],
}, false) ?? {};
const title = typeof options === "object" &&
options.name !== undefined &&
options.nameStrategy === "title"
? options.name
: undefined;
if (title !== undefined) {
main.title = title;
}
const combined = name === undefined
? definitions
? {
...main,
[refs.definitionPath]: definitions,
}
: main
: {
$ref: [
...(refs.$refStrategy === "relative" ? [] : refs.basePath),
refs.definitionPath,
name,
].join("/"),
[refs.definitionPath]: {
...definitions,
[name]: main,
},
};
if (refs.target === "jsonSchema7") {
combined.$schema = "http://json-schema.org/draft-07/schema#";
}
else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
}
if (refs.target === "openAi" &&
("anyOf" in combined ||
"oneOf" in combined ||
"allOf" in combined ||
("type" in combined && Array.isArray(combined.type)))) {
console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
}
return combined;
};
;// ../commons/node_modules/zod-to-json-schema/dist/esm/index.js
/* harmony default export */ const esm = ((/* unused pure expression or super */ null && (zodToJsonSchema)));
;// ../commons/dist/lib/fs.js
const fs_isFile = (src) => {
let srcIsFile = false;
try {
srcIsFile = external_fs_.lstatSync(src).isFile();
}
catch (e) { }
return srcIsFile;
};
const fs_isFolder = (src) => {
let srcIsFolder = false;
try {
srcIsFolder = fs.lstatSync(src).isDirectory();
}
catch (e) { }
return srcIsFolder;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbGliL2ZzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxFQUFFLE1BQU0sSUFBSSxDQUFBO0FBRXhCLE1BQU0sQ0FBQyxNQUFNLE1BQU0sR0FBRyxDQUFDLEdBQVcsRUFBRSxFQUFFO0lBQ2xDLElBQUksU0FBUyxHQUFHLEtBQUssQ0FBQztJQUN0QixJQUFJLENBQUM7UUFDRCxTQUFTLEdBQUcsRUFBRSxDQUFDLFNBQVMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxNQUFNLEVBQUUsQ0FBQTtJQUMxQyxDQUFDO0lBQUMsT0FBTyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUM7SUFDZixPQUFPLFNBQVMsQ0FBQTtBQUNwQixDQUFDLENBQUE7QUFDRCxNQUFNLENBQUMsTUFBTSxRQUFRLEdBQUcsQ0FBQyxHQUFXLEVBQUUsRUFBRTtJQUNwQyxJQUFJLFdBQVcsR0FBRyxLQUFLLENBQUM7SUFDeEIsSUFBSSxDQUFDO1FBQ0QsV0FBVyxHQUFHLEVBQUUsQ0FBQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsV0FBVyxFQUFFLENBQUE7SUFDakQsQ0FBQztJQUFDLE9BQU8sQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDO0lBQ2YsT0FBTyxXQUFXLENBQUM7QUFDdkIsQ0FBQyxDQUFBIn0=
;// ../commons/dist/schemas/path.js
const DefaultPathSchemaBase = lib_z.string().describe('Path to a file or directory');
const PathErrorMessages = {
INVALID_INPUT: 'INVALID_INPUT: ${inputPath}',
PATH_DOES_NOT_EXIST: 'Path does not exist ${inputPath} = ${resolvedPath}',
DIRECTORY_NOT_WRITABLE: 'Directory is not writable ${inputPath} = ${resolvedPath}',
NOT_A_DIRECTORY: 'Path is not a directory or does not exist ${inputPath} = ${resolvedPath}',
NOT_A_JSON_FILE: 'File is not a JSON file or does not exist ${inputPath} = ${resolvedPath}',
PATH_NOT_ABSOLUTE: 'Path is not absolute ${inputPath} = ${resolvedPath}',
PATH_NOT_RELATIVE: 'Path is not relative ${inputPath} = ${resolvedPath}',
};
var E_PATH;
(function (E_PATH) {
E_PATH[E_PATH["ENSURE_PATH_EXISTS"] = 1] = "ENSURE_PATH_EXISTS";
E_PATH[E_PATH["INVALID_INPUT"] = 2] = "INVALID_INPUT";
E_PATH[E_PATH["ENSURE_DIRECTORY_WRITABLE"] = 3] = "ENSURE_DIRECTORY_WRITABLE";
E_PATH[E_PATH["ENSURE_FILE_IS_JSON"] = 4] = "ENSURE_FILE_IS_JSON";
E_PATH[E_PATH["ENSURE_PATH_IS_ABSOLUTE"] = 5] = "ENSURE_PATH_IS_ABSOLUTE";
E_PATH[E_PATH["ENSURE_PATH_IS_RELATIVE"] = 6] = "ENSURE_PATH_IS_RELATIVE";
E_PATH[E_PATH["GET_PATH_INFO"] = 7] = "GET_PATH_INFO";
})(E_PATH || (E_PATH = {}));
const Transformers = {
resolve: (val, variables = {}) => {
if (!val) {
return null;
}
return {
resolved: external_path_.resolve(variables_resolve(val, false, variables)),
source: val
};
},
json: (val, variables = {}) => {
if (!val) {
return null;
}
const resolved = external_path_.resolve(variables_resolve((0,primitives/* isString */.Kg)(val) ? val : val.source, false, variables));
return {
resolved,
source: val,
value: (0,dist_read/* sync */.OH)(resolved, 'json')
};
},
string: (val, variables = {}) => {
if (!val) {
return null;
}
let src = (0,primitives/* isString */.Kg)(val) ? val : val.source;
src = variables_resolve(src, false, variables);
const resolved = external_path_.resolve(src);
if (!(0,dist_exists/* sync */.OH)(resolved) || !fs_isFile(resolved)) {
return {
resolved,
source: val,
value: null
};
}
else {
let value = null;
try {
value = (0,dist_read/* sync */.OH)(resolved, 'string');
}
catch (e) {
logger.error('Failed to read file', { resolved, source: val, error: e.message });
}
return {
resolved,
source: val,
value
};
}
}
};
const TransformersDescription = [
{
description: 'RESOLVE_PATH',
fn: Transformers.resolve
},
{
description: 'READ_JSON',
fn: Transformers.json
},
{
description: 'READ_STRING',
fn: Transformers.string
}
];
const extendType = (type, extend, variables = {}) => {
if (Array.isArray(extend.refine)) {
for (const refine of extend.refine) {
type = type.refine(refine);
}
}
else {
type = type.refine(extend.refine);
}
if (Array.isArray(extend.transform)) {
for (const transform of extend.transform) {
type = type.transform((val) => transform(val, variables));
}
}
else {
type = type.transform(extend.transform);
}
return type;
};
const extendTypeDescription = (type, extension, variables = {}) => {
const description = getDescription(type) || '';
let transformerDescriptions = 'Transformers:\n';
if (Array.isArray(extension.transform)) {
for (const transform of extension.transform) {
transformerDescriptions += transformerDescription(transform) + '\n';
}
}
else {
transformerDescriptions += transformerDescription(extension.transform) + '\n';
}
type = type.describe(description + '\n' + transformerDescriptions);
return type;
};
const transformerDescription = (fn) => {
const description = TransformersDescription.find((t) => t.fn === fn);
return description ? description.description : 'Unknown';
};
const extendSchema = (baseSchema, extend) => {
const baseShape = baseSchema.shape;
const extendedShape = { ...baseShape };
for (const [key, refines] of Object.entries(extend)) {
if (!baseShape[key])
continue;
let fieldSchema = baseShape[key];
if (Array.isArray(refines.refine)) {
for (const refine of refines.refine) {
fieldSchema = fieldSchema.superRefine(refine);
}
}
else {
fieldSchema = fieldSchema.superRefine(refines);
}
if (Array.isArray(refines.transform)) {
for (const transform of refines.transform) {
fieldSchema = fieldSchema.transform((val) => transform(val));
}
}
else {
fieldSchema = fieldSchema.transform(refines.transform);
}
extendedShape[key] = fieldSchema;
}
return z.object(extendedShape);
};
const ENSURE_DIRECTORY_WRITABLE = (inputPath, ctx, variables) => {
const resolvedPath = path.resolve(resolve(inputPath, false, variables));
const parts = path.parse(resolvedPath);
if (resolvedPath && existsSync(parts.dir) && lstatSync(parts.dir).isDirectory()) {
try {
accessSync(resolvedPath, constants.W_OK);
return resolvedPath;
}
catch (e) {
ctx.addIssue({
code: E_PATH.ENSURE_DIRECTORY_WRITABLE,
message: template(PathErrorMessages.DIRECTORY_NOT_WRITABLE, { inputPath, resolvedPath })
});
return z.NEVER;
}
}
else {
ctx.addIssue({
code: E_PATH.ENSURE_DIRECTORY_WRITABLE,
message: template(PathErrorMessages.NOT_A_DIRECTORY, { inputPath, resolvedPath })
});
return z.NEVER;
}
};
const IS_VALID_STRING = (inputPath) => (0,primitives/* isString */.Kg)(inputPath);
const ENSURE_PATH_EXISTS = (inputPath, ctx, variables) => {
if (!inputPath || !ctx) {
return lib_z.NEVER;
}
if (!(0,primitives/* isString */.Kg)(inputPath)) {
ctx.addIssue({
code: E_PATH.INVALID_INPUT,
message: variables_template(PathErrorMessages.INVALID_INPUT, {})
});
return lib_z.NEVER;
}
const resolvedPath = external_path_.resolve(variables_resolve(inputPath, false, variables));
if (!(0,dist_exists/* sync */.OH)(resolvedPath)) {
ctx.addIssue({
code: E_PATH.ENSURE_PATH_EXISTS,
message: variables_template(PathErrorMessages.PATH_DOES_NOT_EXIST, { inputPath, resolvedPath })
});
return lib_z.NEVER;
}
return resolvedPath;
};
const test = () => {
const BaseCompilerOptions = () => z.object({
root: DefaultPathSchemaBase.default(`${process.cwd()}`)
});
const ret = extendSchema(BaseCompilerOptions(), {
root: {
refine: [
(val, ctx) => ENSURE_DIRECTORY_WRITABLE(val, ctx, DEFAULT_VARS({ exampleVar: 'exampleValue' })),
(val, ctx) => ENSURE_PATH_EXISTS(val, ctx, DEFAULT_VARS({ exampleVar: 'exampleValue' }))
],
transform: [
(val) => path.resolve(resolve(val, false, DEFAULT_VARS({ exampleVar: 'exampleValue' })))
]
}
});
return ret;
};
const Templates = {
json: {
refine: [IS_VALID_STRING, ENSURE_PATH_EXISTS],
transform: [Transformers.resolve, Transformers.json]
},
string: {
refine: [ENSURE_PATH_EXISTS],
transform: [Transformers.resolve, Transformers.string]
}
};
const extend = (baseSchema, template, variables = {}) => {
const type = extendType(baseSchema, template, variables);
return extendTypeDescription(type, template, variables);
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGF0aC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zY2hlbWFzL3BhdGgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLENBQUMsRUFBYyxNQUFNLEtBQUssQ0FBQTtBQUNuQyxPQUFPLEtBQUssSUFBSSxNQUFNLE1BQU0sQ0FBQTtBQUM1QixPQUFPLEVBQUUsVUFBVSxFQUFFLFNBQVMsRUFBRSxTQUFTLEVBQUUsVUFBVSxFQUFFLE1BQU0sSUFBSSxDQUFBO0FBRWpFLE9BQU8sRUFBRSxRQUFRLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQTtBQUNwRC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yxDQUFBO0lBQ3hELE9BQU8scUJBQXFCLENBQUMsSUFBSSxFQUFFLFFBQVEsRUFBRSxTQUFTLENBQUMsQ0FBQTtBQUMzRCxDQUFDLENBQUEifQ==
;// ../commons/dist/schemas/zod_map.js
/**
* Manages a collection of Zod schema properties
* and combines them into a single Zod object schema.
*
* @template MetaType The type of metadata you want to store for each field.
* Defaults to Record if not provided.
*/
class ZodMetaMap {
fieldMap = new Map();
/**
* Adds a Zod schema under a specific key (property name),
* optionally attaching typed metadata.
*
* @param key - The name of the property in the root object.
* @param schema - The Zod schema for that property.
* @param metadata - Optional metadata object (type MetaType).
*/
add(key, schema, metadata) {
this.fieldMap.set(key, { schema, metadata });
return this;
}
/**
* Builds and returns a root Zod object
* that combines all properties which were added.
*/
root() {
const shape = {};
for (const [key, { schema }] of this.fieldMap.entries()) {
shape[key] = schema;
}
return lib_z.object(shape);
}
/**
* Retrieves the metadata for a specific key, if any.
*/
getMetadata(key) {
return this.fieldMap.get(key)?.metadata;
}
/**
* Static factory method: creates a SchemaMetaManager
* while letting you optionally specify the MetaType.
*
* Usage:
* const manager = SchemaMetaManager.create();
*/
static create() {
return new ZodMetaMap();
}
/**
* Returns a basic UiSchema object that RJSF can use to render form controls.
*
* - Adds a top-level "ui:submitButtonOptions" (example).
* - For each field, we set `ui:title` (uppercase key),
* `ui:description` (from Zod's .describe() if available),
* and a naive placeholder from the default value (if parse(undefined) succeeds).
*/
getUISchema() {
// Start with some top-level UI schema config (optional)
const uiSchema = {
'ui:submitButtonOptions': {
props: {
disabled: false,
className: 'btn btn-info',
},
norender: false,
submitText: 'Submit',
},
};
for (const [key, { schema }] of this.fieldMap.entries()) {
let fieldUi = {};
// Use the Zod description if available
// (Accessing `._def.description` is private/hacky, but commonly done.)
const sAny = schema;
if (sAny?._def?.description) {
fieldUi['ui:description'] = sAny._def.description;
}
// RJSF usually reads 'title' from JSON schema. But if you want
// to override it in UI schema, you can do so:
fieldUi['ui:title'] = key[0].toUpperCase() + key.substr(1).toLowerCase();
// If the Zod schema allows a default, we can parse(undefined) to get it.
try {
const defaultVal = schema.parse(undefined);
// There's no official 'ui:default' in RJSF, but you could do a placeholder:
fieldUi['ui:placeholder'] = defaultVal;
}
catch {
// no default
}
fieldUi = {
...fieldUi,
...this.getMetadata(key),
};
uiSchema[key] = fieldUi;
}
return uiSchema;
}
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiem9kX21hcC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zY2hlbWFzL3pvZF9tYXAudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLENBQUMsRUFBeUIsTUFBTSxLQUFLLENBQUM7QUFFL0M7Ozs7OztHQU1HO0FBQ0gsTUFBTSxPQUFPLFVBQVU7SUFDWCxRQUFRLEdBQUcsSUFBSSxHQUFHLEVBR3ZCLENBQUM7SUFFSjs7Ozs7OztPQU9HO0lBQ0gsR0FBRyxDQUF1QixHQUFXLEVBQUUsTUFBUyxFQUFFLFFBQW1CO1FBQ2pFLElBQUksQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsRUFBRSxFQUFFLE1BQU0sRUFBRSxRQUFRLEVBQUUsQ0FBQyxDQUFDO1FBQzdDLE9BQU8sSUFBSSxDQUFDO0lBQ2hCLENBQUM7SUFFRDs7O09BR0c7SUFDSCxJQUFJO1FBQ0EsTUFBTSxLQUFLLEdBQStCLEVBQUUsQ0FBQztRQUM3QyxLQUFLLE1BQU0sQ0FBQyxHQUFHLEVBQUUsRUFBRSxNQUFNLEVBQUUsQ0FBQyxJQUFJLElBQUksQ0FBQyxRQUFRLENBQUMsT0FBTyxFQUFFLEVBQUUsQ0FBQztZQUN0RCxLQUFLLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQ3hCLENBQUM7UUFDRCxPQUFPLENBQUMsQ0FBQyxNQ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UMsR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsV0FBVyxFQUFFLEdBQUcsR0FBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxXQUFXLEVBQUUsQ0FBQTtZQUV4RSx5RUFBeUU7WUFDekUsSUFBSSxDQUFDO2dCQUNELE1BQU0sVUFBVSxHQUFHLE1BQU0sQ0FBQyxLQUFLLENBQUMsU0FBUyxDQUFDLENBQUM7Z0JBQzNDLDRFQUE0RTtnQkFDNUUsT0FBTyxDQUFDLGdCQUFnQixDQUFDLEdBQUcsVUFBVSxDQUFDO1lBQzNDLENBQUM7WUFBQyxNQUFNLENBQUM7Z0JBQ0wsYUFBYTtZQUNqQixDQUFDO1lBQ0QsT0FBTyxHQUFHO2dCQUNOLEdBQUcsT0FBTztnQkFDVixHQUFHLElBQUksQ0FBQyxXQUFXLENBQUMsR0FBRyxDQUFDO2FBQzNCLENBQUE7WUFDRCxRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsT0FBTyxDQUFDO1FBQzVCLENBQUM7UUFDRCxPQUFPLFFBQVEsQ0FBQztJQUNwQixDQUFDO0NBQ0oifQ==
;// ../commons/dist/schemas/index.js
const generate_interfaces = (schemas, dst) => {
const types = schemas.map(schema => `export interface ${schema.description || 'IOptions'} ${printNode(zodToTs(schema).node)}`);
(0,write/* sync */.OH)(dst, types.join('\n'));
};
const enumerateHelpStrings = (schema, path = [], logger) => {
if (schema instanceof ZodObject) {
for (const key in schema.shape) {
const nestedSchema = schema.shape[key];
enumerateHelpStrings(nestedSchema, [...path, key], logger);
}
}
else {
const description = schema._def.description;
if (description) {
logger.debug(`\t ${path.join('.')}: ${description}`);
}
}
};
const yargsDefaults = (yargs) => yargs.parserConfiguration({ "camel-case-expansion": false });
const getInnerSchema = (schema) => {
while (schema instanceof lib_ZodEffects) {
schema = schema._def.schema;
}
return schema;
};
const getInnerType = (type) => {
while (type instanceof lib_ZodOptional) {
type = type._def.innerType;
}
while (type._def.typeName === 'ZodDefault' || type._def.typeName === 'ZodOptional') {
type = type._def.innerType;
}
return type._def.typeName;
};
const getDefaultValue = (schema) => {
if (schema instanceof ZodDefault) {
return schema._def.defaultValue();
}
return undefined;
};
const getFieldDefaultValue = (schema) => {
if (!schema) {
return undefined;
}
if (schema._def.typeName === 'ZodDefault') {
return schema._def.defaultValue();
}
if (schema instanceof lib_ZodOptional) {
return getFieldDefaultValue(schema.unwrap());
}
if (schema instanceof lib_ZodEffects) {
return getFieldDefaultValue(schema._def.schema);
}
if (typeof schema._def) {
return getFieldDefaultValue(schema._def.schema);
}
return undefined;
};
const schemas_getDescription = (schema) => {
if (!schema) {
return undefined;
}
if (schema._def.description) {
return schema._def.description;
}
if (schema instanceof ZodOptional) {
return schemas_getDescription(schema.unwrap());
}
if (schema instanceof ZodEffects) {
return schemas_getDescription(schema._def.schema);
}
if (typeof schema._def) {
return schemas_getDescription(schema._def.schema);
}
return undefined;
};
const toYargs = (yargs, zodSchema, options) => {
yargsDefaults(yargs);
try {
const shape = zodSchema.shape;
for (const key in shape) {
const zodField = shape[key];
const innerDef = getInnerSchema(zodField);
if (!innerDef) {
continue;
}
let type;
const inner_type = getInnerType(innerDef);
let descriptionExtra = '';
switch (inner_type) {
case 'ZodString':
type = 'string';
break;
case 'ZodBoolean':
type = 'boolean';
break;
case 'ZodNumber':
type = 'number';
break;
case 'ZodOptional':
case 'ZodEnum':
type = getInnerType(innerDef);
if (innerDef._def.typeName === 'ZodEnum') {
descriptionExtra = `\n\t ${innerDef._def.values.join(' \n\t ')}`;
}
break;
}
const defaultValue = getFieldDefaultValue(zodField);
let handled = false;
const args = {
type,
default: defaultValue,
describe: `${zodField._def.description || ''} ${descriptionExtra}`.trim()
};
if (options?.onKey) {
handled = options.onKey(yargs, key, args);
}
if (!handled) {
yargs.option(key, args);
}
}
return yargs;
}
catch (error) {
logger.error('Error processing schema:', error);
return yargs;
}
};
/////////////////////////////////////////////////////////
//
// Schema Writers
//
const extension = (file) => external_path_.parse(file).ext;
const json = (data, file, name, options) => (0,write/* sync */.OH)(file, data.map((s) => zodToJsonSchema_zodToJsonSchema(s, name)));
const WRITERS = {
'.json': json
};
const writer = (file) => WRITERS[extension(file)];
const schemas_write = (schemas, file, name, options) => {
if (!WRITERS[extension(file)]) {
logger.error(`No writer found for file extension: ${extension(file)} : file: ${file}`);
return;
}
logger.debug(`Writing schema to ${file} : ${name}`);
try {
writer(file)(schemas, file, name, options);
}
catch (e) {
logger.trace(`Error writing schema to ${file} : ${name}`, e, e.stack, e.message);
}
};
////////////////////////////////////////////////////////////////////
//
// Schema Combinators
const combineValidatorsOr = (validators) => {
return z.string().refine((value) => {
const errors = [];
const isValid = validators.some((validator) => {
try {
validator.parse(value);
return true;
}
catch (err) {
errors.push(err.errors);
return false;
}
});
if (!isValid) {
throw new z.ZodError(errors.flat());
}
return true;
}, 'Invalid value for all provided validators');
};
const combineValidatorsOrUsingZod = (validators) => {
return validators.reduce((acc, validator) => acc.or(validator));
};
const combineValidatorsOrUsingZod2 = (validators) => {
return validators.reduce((acc, validator) => {
return acc.or(validator).refine((value) => {
try {
acc.parse(value);
return true;
}
catch (errAcc) {
try {
validator.parse(value);
return true;
}
catch (errValidator) {
throw new z.ZodError([...errAcc.errors, ...errValidator.errors]);
}
}
});
});
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc2NoZW1hcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssSUFBSSxNQUFNLE1BQU0sQ0FBQTtBQUU1QixPQUFPLEVBQUUsQ0FBQyxFQUFjLFNBQVMsRUFBRSxVQUFVLEVBQUUsV0FBVyxFQUFFLFVBQVUsRUFBRSxNQUFNLEtBQUssQ0FBQTtBQUNuRixPQUFPLEVBQUUsSUFBSSxJQUFJLE9BQU8sR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yY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsY0FBYyxTQUFTLENBQUE7QUFDdkIsY0FBYyxhQUFhLENBQUE7QUFDM0IsY0FBYyxTQUFTLENBQUE7QUFDdkIsY0FBYyxZQUFZLENBQUE7QUFDMUIsY0FBYyxnQkFBZ0IsQ0FBQTtBQUM5QixjQUFjLGNBQWMsQ0FBQTtBQUM1QixjQUFjLFlBQVksQ0FBQTtBQUMxQixjQUFjLGdCQUFnQixDQUFBO0FBQzlCLGNBQWMsZUFBZSxDQUFBO0FBQzdCLGNBQWMsZ0JBQWdCLENBQUE7QUFDOUIsY0FBYyxhQUFhLENBQUE7QUFDM0IsY0FBYyxvQkFBb0IsQ0FBQSJ9
/***/ }),
/***/ 3339:
/***/ ((module) => {
"use strict";
module.exports = require("module");
/***/ }),
/***/ 3381:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = __webpack_require__(2208);
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
/***/ }),
/***/ 3425:
/***/ ((module) => {
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};
/***/ }),
/***/ 3468:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(579)
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
/***/ }),
/***/ 3522:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
cq: () => (/* reexport */ ERR_PERM_RETRY_DELAY),
TO: () => (/* reexport */ ERR_PERM_RETRY_MAX),
vF: () => (/* binding */ logger)
});
// UNUSED EXPORTS: GIT_REPO, MODULE_NAME, PACKAGE_NAME
;// ./dist-in/constants.js
const GIT_REPO = 'https://git.osr-plastic.org/osr-plastic/';
const MODULE_NAME = `OSR-MEDIA`;
const PACKAGE_NAME = 'osr-media';
const ERR_PERM_RETRY_DELAY = 500;
const ERR_PERM_RETRY_MAX = 5;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uc3RhbnRzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NvbnN0YW50cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxNQUFNLENBQUMsTUFBTSxRQUFRLEdBQUcsMENBQTBDLENBQUE7QUFDbEUsTUFBTSxDQUFDLE1BQU0sV0FBVyxHQUFHLFdBQVcsQ0FBQztBQUN2QyxNQUFNLENBQUMsTUFBTSxZQUFZLEdBQUcsV0FBVyxDQUFDO0FBRXhDLE1BQU0sQ0FBQyxNQUFNLG9CQUFvQixHQUFHLEdBQUcsQ0FBQTtBQUN2QyxNQUFNLENBQUMsTUFBTSxrQkFBa0IsR0FBRyxDQUFDLENBQUEifQ==
// EXTERNAL MODULE: ../log/dist/index.js + 4 modules
var dist = __webpack_require__(4337);
;// ./dist-in/index.js
const logger = (0,dist/* createLogger */.h)(MODULE_NAME);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsY0FBYyxnQkFBZ0IsQ0FBQTtBQUM5QixjQUFjLFlBQVksQ0FBQTtBQUUxQixPQUFPLEVBQUUsWUFBWSxFQUFFLE1BQU0sZUFBZSxDQUFBO0FBQzVDLE9BQU8sRUFBRSxXQUFXLEVBQUUsTUFBTSxnQkFBZ0IsQ0FBQTtBQUU1QyxNQUFNLENBQUMsTUFBTSxNQUFNLEdBQUcsWUFBWSxDQUFDLFdBQVcsQ0FBK0IsQ0FBQSJ9
/***/ }),
/***/ 3575:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var util = __webpack_require__(2208);
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var context = Promise._getContext();
this._callback = util.contextBind(context, fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
if (util.isArray(promises)) {
for (var i = 0; i < promises.length; ++i) {
var maybePromise = promises[i];
if (maybePromise instanceof Promise) {
maybePromise.suppressUnhandledRejections();
}
}
}
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function() {
this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if (typeof options === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(
new TypeError("'concurrency' must be a number but it is " +
util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError(
"options argument must be an object but it is " +
util.classString(options)));
}
}
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};
/***/ }),
/***/ 3595:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
comp = comp.trim().split(/\s+/).join(' ')
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
options = parseOptions(options)
// Special cases where nothing can possibly be lower
if (options.includePrerelease &&
(this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
return false
}
if (!options.includePrerelease &&
(this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false
}
// Same direction increasing (> or >=)
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
return true
}
// Same direction decreasing (< or <=)
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
return true
}
// same SemVer and both sides are inclusive (<= or >=)
if (
(this.semver.version === comp.semver.version) &&
this.operator.includes('=') && comp.operator.includes('=')) {
return true
}
// opposite directions less than
if (cmp(this.semver, '<', comp.semver, options) &&
this.operator.startsWith('>') && comp.operator.startsWith('<')) {
return true
}
// opposite directions greater than
if (cmp(this.semver, '>', comp.semver, options) &&
this.operator.startsWith('<') && comp.operator.startsWith('>')) {
return true
}
return false
}
}
module.exports = Comparator
const parseOptions = __webpack_require__(9148)
const { safeRe: re, t } = __webpack_require__(439)
const cmp = __webpack_require__(7950)
const debug = __webpack_require__(1967)
const SemVer = __webpack_require__(579)
const Range = __webpack_require__(358)
/***/ }),
/***/ 3610:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
b: () => (/* binding */ iterator_async)
});
// UNUSED EXPORTS: sync
// EXTERNAL MODULE: ../fs/dist/utils/tree_walker.js
var tree_walker = __webpack_require__(5992);
// EXTERNAL MODULE: ../fs/dist/interfaces.js
var interfaces = __webpack_require__(7405);
// EXTERNAL MODULE: ../fs/dist/utils/matcher.js + 6 modules
var utils_matcher = __webpack_require__(7852);
;// ../core/dist/iterator.js
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var Iterable;
(function (Iterable) {
function is(thing) {
return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function';
}
Iterable.is = is;
const _empty = Object.freeze([]);
function empty() {
return _empty;
}
Iterable.empty = empty;
function* single(element) {
yield element;
}
Iterable.single = single;
function wrap(iterableOrElement) {
if (is(iterableOrElement)) {
return iterableOrElement;
}
else {
return single(iterableOrElement);
}
}
Iterable.wrap = wrap;
function from(iterable) {
return iterable || _empty;
}
Iterable.from = from;
function* reverse(array) {
for (let i = array.length - 1; i >= 0; i--) {
yield array[i];
}
}
Iterable.reverse = reverse;
function isEmpty(iterable) {
return !iterable || iterable[Symbol.iterator]().next().done === true;
}
Iterable.isEmpty = isEmpty;
function first(iterable) {
return iterable[Symbol.iterator]().next().value;
}
Iterable.first = first;
function some(iterable, predicate) {
let i = 0;
for (const element of iterable) {
if (predicate(element, i++)) {
return true;
}
}
return false;
}
Iterable.some = some;
function find(iterable, predicate) {
for (const element of iterable) {
if (predicate(element)) {
return element;
}
}
return undefined;
}
Iterable.find = find;
function* filter(iterable, predicate) {
for (const element of iterable) {
if (predicate(element)) {
yield element;
}
}
}
Iterable.filter = filter;
function* map(iterable, fn) {
let index = 0;
for (const element of iterable) {
yield fn(element, index++);
}
}
Iterable.map = map;
function* flatMap(iterable, fn) {
let index = 0;
for (const element of iterable) {
yield* fn(element, index++);
}
}
Iterable.flatMap = flatMap;
function* concat(...iterables) {
for (const iterable of iterables) {
yield* iterable;
}
}
Iterable.concat = concat;
function reduce(iterable, reducer, initialValue) {
let value = initialValue;
for (const element of iterable) {
value = reducer(value, element);
}
return value;
}
Iterable.reduce = reduce;
/**
* Returns an iterable slice of the array, with the same semantics as `array.slice()`.
*/
function* slice(arr, from, to = arr.length) {
if (from < -arr.length) {
from = 0;
}
if (from < 0) {
from += arr.length;
}
if (to < 0) {
to += arr.length;
}
else if (to > arr.length) {
to = arr.length;
}
for (; from < to; from++) {
yield arr[from];
}
}
Iterable.slice = slice;
/**
* Consumes `atMost` elements from iterable and returns the consumed elements,
* and an iterable for the rest of the elements.
*/
function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
const consumed = [];
if (atMost === 0) {
return [consumed, iterable];
}
const iterator = iterable[Symbol.iterator]();
for (let i = 0; i < atMost; i++) {
const next = iterator.next();
if (next.done) {
return [consumed, Iterable.empty()];
}
consumed.push(next.value);
}
return [consumed, { [Symbol.iterator]() { return iterator; } }];
}
Iterable.consume = consume;
async function asyncToArray(iterable) {
const result = [];
for await (const item of iterable) {
result.push(item);
}
return Promise.resolve(result);
}
Iterable.asyncToArray = asyncToArray;
})(Iterable || (Iterable = {}));
class iterator_ArrayIterator {
items;
start;
end;
index;
constructor(items, start = 0, end = items.length) {
this.items = items;
this.start = start;
this.end = end;
this.index = start - 1;
}
first() {
this.index = this.start;
return this.current();
}
next() {
this.index = Math.min(this.index + 1, this.end);
return this.current();
}
current() {
if (this.index === this.start - 1 || this.index === this.end) {
return null;
}
return this.items[this.index];
}
}
class ArrayNavigator extends iterator_ArrayIterator {
constructor(items, start = 0, end = items.length) {
super(items, start, end);
}
current() {
return super.current();
}
previous() {
this.index = Math.max(this.index - 1, this.start - 1);
return this.current();
}
first() {
this.index = this.start;
return this.current();
}
last() {
this.index = this.end - 1;
return this.current();
}
parent() {
return null;
}
}
class MappedIterator {
iterator;
fn;
constructor(iterator, fn) {
this.iterator = iterator;
this.fn = fn;
// noop
}
next() { return this.fn(this.iterator.next()); }
}
class MappedNavigator extends MappedIterator {
navigator;
constructor(navigator, fn) {
super(navigator, fn);
this.navigator = navigator;
}
current() { return this.fn(this.navigator.current()); }
previous() { return this.fn(this.navigator.previous()); }
parent() { return this.fn(this.navigator.parent()); }
first() { return this.fn(this.navigator.first()); }
last() { return this.fn(this.navigator.last()); }
next() { return this.fn(this.navigator.next()); }
}
//# sourceMappingURL=iterator.js.map
;// ../fs/dist/iterator.js
async function iterator_async(from, options) {
if (options && !options.filter) {
if (options.matching) {
options.filter = (0,utils_matcher/* create */.v)(from, options.matching);
}
else {
options.filter = () => true;
}
}
const collectorSync = function (path, item) {
if (!item) {
return;
}
if (options.filter(path)) {
nodes.push({
path: path,
item: item,
status: interfaces/* ENodeOperationStatus */.x5.COLLECTED
});
}
};
const nodes = [];
return new Promise((resolve, reject) => {
(0,tree_walker/* sync */.O)(from, {
inspectOptions: {
mode: options ? options.flags & interfaces/* EInspectFlags */.Zd.MODE ? true : false : false,
times: options ? options.flags & interfaces/* EInspectFlags */.Zd.TIMES ? true : false : false,
checksum: options ? options.flags & interfaces/* EInspectFlags */.Zd.CHECKSUM ? 'md5' : null : null,
symlinks: options ? options.flags & interfaces/* EInspectFlags */.Zd.SYMLINKS ? false : true : true,
mime: options ? options.flags & interfaces/* EInspectFlags */.Zd.MIME ? true : false : false
}
}, collectorSync);
resolve(new iterator_ArrayIterator(nodes));
});
}
function sync(from, options) {
if (options && !options.filter) {
if (options.matching) {
options.filter = matcher(from, options.matching);
}
else {
options.filter = () => true;
}
}
const nodes = [];
const collectorSync = function (path, item) {
if (!item) {
return;
}
if (options.filter(path)) {
nodes.push({
path: path,
item: item,
status: ENodeOperationStatus.COLLECTED
});
}
};
treeWalkerSync(from, {
inspectOptions: {
mode: options ? options.flags & EInspectFlags.MODE ? true : false : false,
times: options ? options.flags & EInspectFlags.TIMES ? true : false : false,
checksum: options ? options.flags & EInspectFlags.CHECKSUM ? 'md5' : null : null,
symlinks: options ? options.flags & EInspectFlags.SYMLINKS ? false : true : true,
mime: options ? options.flags & EInspectFlags.MIME ? true : false : false
}
}, collectorSync);
return new ArrayIterator(nodes);
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaXRlcmF0b3Iu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QyxDQUFDO0FBQ2xELENBQUMifQ==
/***/ }),
/***/ 3657:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Minipass = exports.isWritable = exports.isReadable = exports.isStream = void 0;
const proc = typeof process === 'object' && process
? process
: {
stdout: null,
stderr: null,
};
const node_events_1 = __webpack_require__(8474);
const node_stream_1 = __importDefault(__webpack_require__(7075));
const node_string_decoder_1 = __webpack_require__(6193);
/**
* Return true if the argument is a Minipass stream, Node stream, or something
* else that Minipass can interact with.
*/
const isStream = (s) => !!s &&
typeof s === 'object' &&
(s instanceof Minipass ||
s instanceof node_stream_1.default ||
(0, exports.isReadable)(s) ||
(0, exports.isWritable)(s));
exports.isStream = isStream;
/**
* Return true if the argument is a valid {@link Minipass.Readable}
*/
const isReadable = (s) => !!s &&
typeof s === 'object' &&
s instanceof node_events_1.EventEmitter &&
typeof s.pipe === 'function' &&
// node core Writable streams have a pipe() method, but it throws
s.pipe !== node_stream_1.default.Writable.prototype.pipe;
exports.isReadable = isReadable;
/**
* Return true if the argument is a valid {@link Minipass.Writable}
*/
const isWritable = (s) => !!s &&
typeof s === 'object' &&
s instanceof node_events_1.EventEmitter &&
typeof s.write === 'function' &&
typeof s.end === 'function';
exports.isWritable = isWritable;
const EOF = Symbol('EOF');
const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
const EMITTED_END = Symbol('emittedEnd');
const EMITTING_END = Symbol('emittingEnd');
const EMITTED_ERROR = Symbol('emittedError');
const CLOSED = Symbol('closed');
const READ = Symbol('read');
const FLUSH = Symbol('flush');
const FLUSHCHUNK = Symbol('flushChunk');
const ENCODING = Symbol('encoding');
const DECODER = Symbol('decoder');
const FLOWING = Symbol('flowing');
const PAUSED = Symbol('paused');
const RESUME = Symbol('resume');
const BUFFER = Symbol('buffer');
const PIPES = Symbol('pipes');
const BUFFERLENGTH = Symbol('bufferLength');
const BUFFERPUSH = Symbol('bufferPush');
const BUFFERSHIFT = Symbol('bufferShift');
const OBJECTMODE = Symbol('objectMode');
// internal event when stream is destroyed
const DESTROYED = Symbol('destroyed');
// internal event when stream has an error
const ERROR = Symbol('error');
const EMITDATA = Symbol('emitData');
const EMITEND = Symbol('emitEnd');
const EMITEND2 = Symbol('emitEnd2');
const ASYNC = Symbol('async');
const ABORT = Symbol('abort');
const ABORTED = Symbol('aborted');
const SIGNAL = Symbol('signal');
const DATALISTENERS = Symbol('dataListeners');
const DISCARDED = Symbol('discarded');
const defer = (fn) => Promise.resolve().then(fn);
const nodefer = (fn) => fn();
const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
(!!b &&
typeof b === 'object' &&
b.constructor &&
b.constructor.name === 'ArrayBuffer' &&
b.byteLength >= 0);
const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
/**
* Internal class representing a pipe to a destination stream.
*
* @internal
*/
class Pipe {
src;
dest;
opts;
ondrain;
constructor(src, dest, opts) {
this.src = src;
this.dest = dest;
this.opts = opts;
this.ondrain = () => src[RESUME]();
this.dest.on('drain', this.ondrain);
}
unpipe() {
this.dest.removeListener('drain', this.ondrain);
}
// only here for the prototype
/* c8 ignore start */
proxyErrors(_er) { }
/* c8 ignore stop */
end() {
this.unpipe();
if (this.opts.end)
this.dest.end();
}
}
/**
* Internal class representing a pipe to a destination stream where
* errors are proxied.
*
* @internal
*/
class PipeProxyErrors extends Pipe {
unpipe() {
this.src.removeListener('error', this.proxyErrors);
super.unpipe();
}
constructor(src, dest, opts) {
super(src, dest, opts);
this.proxyErrors = er => dest.emit('error', er);
src.on('error', this.proxyErrors);
}
}
const isObjectModeOptions = (o) => !!o.objectMode;
const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
/**
* Main export, the Minipass class
*
* `RType` is the type of data emitted, defaults to Buffer
*
* `WType` is the type of data to be written, if RType is buffer or string,
* then any {@link Minipass.ContiguousData} is allowed.
*
* `Events` is the set of event handler signatures that this object
* will emit, see {@link Minipass.Events}
*/
class Minipass extends node_events_1.EventEmitter {
[FLOWING] = false;
[PAUSED] = false;
[PIPES] = [];
[BUFFER] = [];
[OBJECTMODE];
[ENCODING];
[ASYNC];
[DECODER];
[EOF] = false;
[EMITTED_END] = false;
[EMITTING_END] = false;
[CLOSED] = false;
[EMITTED_ERROR] = null;
[BUFFERLENGTH] = 0;
[DESTROYED] = false;
[SIGNAL];
[ABORTED] = false;
[DATALISTENERS] = 0;
[DISCARDED] = false;
/**
* true if the stream can be written
*/
writable = true;
/**
* true if the stream can be read
*/
readable = true;
/**
* If `RType` is Buffer, then options do not need to be provided.
* Otherwise, an options object must be provided to specify either
* {@link Minipass.SharedOptions.objectMode} or
* {@link Minipass.SharedOptions.encoding}, as appropriate.
*/
constructor(...args) {
const options = (args[0] ||
{});
super();
if (options.objectMode && typeof options.encoding === 'string') {
throw new TypeError('Encoding and objectMode may not be used together');
}
if (isObjectModeOptions(options)) {
this[OBJECTMODE] = true;
this[ENCODING] = null;
}
else if (isEncodingOptions(options)) {
this[ENCODING] = options.encoding;
this[OBJECTMODE] = false;
}
else {
this[OBJECTMODE] = false;
this[ENCODING] = null;
}
this[ASYNC] = !!options.async;
this[DECODER] = this[ENCODING]
? new node_string_decoder_1.StringDecoder(this[ENCODING])
: null;
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposeBuffer === true) {
Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
}
//@ts-ignore - private option for debugging and testing
if (options && options.debugExposePipes === true) {
Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
}
const { signal } = options;
if (signal) {
this[SIGNAL] = signal;
if (signal.aborted) {
this[ABORT]();
}
else {
signal.addEventListener('abort', () => this[ABORT]());
}
}
}
/**
* The amount of data stored in the buffer waiting to be read.
*
* For Buffer strings, this will be the total byte length.
* For string encoding streams, this will be the string character length,
* according to JavaScript's `string.length` logic.
* For objectMode streams, this is a count of the items waiting to be
* emitted.
*/
get bufferLength() {
return this[BUFFERLENGTH];
}
/**
* The `BufferEncoding` currently in use, or `null`
*/
get encoding() {
return this[ENCODING];
}
/**
* @deprecated - This is a read only property
*/
set encoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* @deprecated - Encoding may only be set at instantiation time
*/
setEncoding(_enc) {
throw new Error('Encoding must be set at instantiation time');
}
/**
* True if this is an objectMode stream
*/
get objectMode() {
return this[OBJECTMODE];
}
/**
* @deprecated - This is a read-only property
*/
set objectMode(_om) {
throw new Error('objectMode must be set at instantiation time');
}
/**
* true if this is an async stream
*/
get ['async']() {
return this[ASYNC];
}
/**
* Set to true to make this stream async.
*
* Once set, it cannot be unset, as this would potentially cause incorrect
* behavior. Ie, a sync stream can be made async, but an async stream
* cannot be safely made sync.
*/
set ['async'](a) {
this[ASYNC] = this[ASYNC] || !!a;
}
// drop everything and get out of the flow completely
[ABORT]() {
this[ABORTED] = true;
this.emit('abort', this[SIGNAL]?.reason);
this.destroy(this[SIGNAL]?.reason);
}
/**
* True if the stream has been aborted.
*/
get aborted() {
return this[ABORTED];
}
/**
* No-op setter. Stream aborted status is set via the AbortSignal provided
* in the constructor options.
*/
set aborted(_) { }
write(chunk, encoding, cb) {
if (this[ABORTED])
return false;
if (this[EOF])
throw new Error('write after end');
if (this[DESTROYED]) {
this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
return true;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (!encoding)
encoding = 'utf8';
const fn = this[ASYNC] ? defer : nodefer;
// convert array buffers and typed array views into buffers
// at some point in the future, we may want to do the opposite!
// leave strings and buffers as-is
// anything is only allowed if in object mode, so throw
if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
if (isArrayBufferView(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
else if (isArrayBufferLike(chunk)) {
//@ts-ignore - sinful unsafe type changing
chunk = Buffer.from(chunk);
}
else if (typeof chunk !== 'string') {
throw new Error('Non-contiguous data written to non-objectMode stream');
}
}
// handle object mode up front, since it's simpler
// this yields better performance, fewer checks later.
if (this[OBJECTMODE]) {
// maybe impossible?
/* c8 ignore start */
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
/* c8 ignore stop */
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// at this point the chunk is a buffer or string
// don't buffer it up or send it to the decoder
if (!chunk.length) {
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
// fast-path writing strings of same encoding to a stream with
// an empty buffer, skipping the buffer/decoder dance
if (typeof chunk === 'string' &&
// unless it is a string already ready for us to use
!(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
//@ts-ignore - sinful unsafe type change
chunk = Buffer.from(chunk, encoding);
}
if (Buffer.isBuffer(chunk) && this[ENCODING]) {
//@ts-ignore - sinful unsafe type change
chunk = this[DECODER].write(chunk);
}
// Note: flushing CAN potentially switch us into not-flowing mode
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
if (this[FLOWING])
this.emit('data', chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit('readable');
if (cb)
fn(cb);
return this[FLOWING];
}
/**
* Low-level explicit read method.
*
* In objectMode, the argument is ignored, and one item is returned if
* available.
*
* `n` is the number of bytes (or in the case of encoding streams,
* characters) to consume. If `n` is not provided, then the entire buffer
* is returned, or `null` is returned if no data is available.
*
* If `n` is greater that the amount of data in the internal buffer,
* then `null` is returned.
*/
read(n) {
if (this[DESTROYED])
return null;
this[DISCARDED] = false;
if (this[BUFFERLENGTH] === 0 ||
n === 0 ||
(n && n > this[BUFFERLENGTH])) {
this[MAYBE_EMIT_END]();
return null;
}
if (this[OBJECTMODE])
n = null;
if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
// not object mode, so if we have an encoding, then RType is string
// otherwise, must be Buffer
this[BUFFER] = [
(this[ENCODING]
? this[BUFFER].join('')
: Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
];
}
const ret = this[READ](n || null, this[BUFFER][0]);
this[MAYBE_EMIT_END]();
return ret;
}
[READ](n, chunk) {
if (this[OBJECTMODE])
this[BUFFERSHIFT]();
else {
const c = chunk;
if (n === c.length || n === null)
this[BUFFERSHIFT]();
else if (typeof c === 'string') {
this[BUFFER][0] = c.slice(n);
chunk = c.slice(0, n);
this[BUFFERLENGTH] -= n;
}
else {
this[BUFFER][0] = c.subarray(n);
chunk = c.subarray(0, n);
this[BUFFERLENGTH] -= n;
}
}
this.emit('data', chunk);
if (!this[BUFFER].length && !this[EOF])
this.emit('drain');
return chunk;
}
end(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = undefined;
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = 'utf8';
}
if (chunk !== undefined)
this.write(chunk, encoding);
if (cb)
this.once('end', cb);
this[EOF] = true;
this.writable = false;
// if we haven't written anything, then go ahead and emit,
// even if we're not reading.
// we'll re-emit if a new 'end' listener is added anyway.
// This makes MP more suitable to write-only use cases.
if (this[FLOWING] || !this[PAUSED])
this[MAYBE_EMIT_END]();
return this;
}
// don't let the internal resume be overwritten
[RESUME]() {
if (this[DESTROYED])
return;
if (!this[DATALISTENERS] && !this[PIPES].length) {
this[DISCARDED] = true;
}
this[PAUSED] = false;
this[FLOWING] = true;
this.emit('resume');
if (this[BUFFER].length)
this[FLUSH]();
else if (this[EOF])
this[MAYBE_EMIT_END]();
else
this.emit('drain');
}
/**
* Resume the stream if it is currently in a paused state
*
* If called when there are no pipe destinations or `data` event listeners,
* this will place the stream in a "discarded" state, where all data will
* be thrown away. The discarded state is removed if a pipe destination or
* data handler is added, if pause() is called, or if any synchronous or
* asynchronous iteration is started.
*/
resume() {
return this[RESUME]();
}
/**
* Pause the stream
*/
pause() {
this[FLOWING] = false;
this[PAUSED] = true;
this[DISCARDED] = false;
}
/**
* true if the stream has been forcibly destroyed
*/
get destroyed() {
return this[DESTROYED];
}
/**
* true if the stream is currently in a flowing state, meaning that
* any writes will be immediately emitted.
*/
get flowing() {
return this[FLOWING];
}
/**
* true if the stream is currently in a paused state
*/
get paused() {
return this[PAUSED];
}
[BUFFERPUSH](chunk) {
if (this[OBJECTMODE])
this[BUFFERLENGTH] += 1;
else
this[BUFFERLENGTH] += chunk.length;
this[BUFFER].push(chunk);
}
[BUFFERSHIFT]() {
if (this[OBJECTMODE])
this[BUFFERLENGTH] -= 1;
else
this[BUFFERLENGTH] -= this[BUFFER][0].length;
return this[BUFFER].shift();
}
[FLUSH](noDrain = false) {
do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
this[BUFFER].length);
if (!noDrain && !this[BUFFER].length && !this[EOF])
this.emit('drain');
}
[FLUSHCHUNK](chunk) {
this.emit('data', chunk);
return this[FLOWING];
}
/**
* Pipe all data emitted by this stream into the destination provided.
*
* Triggers the flow of data.
*/
pipe(dest, opts) {
if (this[DESTROYED])
return dest;
this[DISCARDED] = false;
const ended = this[EMITTED_END];
opts = opts || {};
if (dest === proc.stdout || dest === proc.stderr)
opts.end = false;
else
opts.end = opts.end !== false;
opts.proxyErrors = !!opts.proxyErrors;
// piping an ended stream ends immediately
if (ended) {
if (opts.end)
dest.end();
}
else {
// "as" here just ignores the WType, which pipes don't care about,
// since they're only consuming from us, and writing to the dest
this[PIPES].push(!opts.proxyErrors
? new Pipe(this, dest, opts)
: new PipeProxyErrors(this, dest, opts));
if (this[ASYNC])
defer(() => this[RESUME]());
else
this[RESUME]();
}
return dest;
}
/**
* Fully unhook a piped destination stream.
*
* If the destination stream was the only consumer of this stream (ie,
* there are no other piped destinations or `'data'` event listeners)
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
unpipe(dest) {
const p = this[PIPES].find(p => p.dest === dest);
if (p) {
if (this[PIPES].length === 1) {
if (this[FLOWING] && this[DATALISTENERS] === 0) {
this[FLOWING] = false;
}
this[PIPES] = [];
}
else
this[PIPES].splice(this[PIPES].indexOf(p), 1);
p.unpipe();
}
}
/**
* Alias for {@link Minipass#on}
*/
addListener(ev, handler) {
return this.on(ev, handler);
}
/**
* Mostly identical to `EventEmitter.on`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* - Adding a 'data' event handler will trigger the flow of data
*
* - Adding a 'readable' event handler when there is data waiting to be read
* will cause 'readable' to be emitted immediately.
*
* - Adding an 'endish' event handler ('end', 'finish', etc.) which has
* already passed will cause the event to be emitted immediately and all
* handlers removed.
*
* - Adding an 'error' event handler after an error has been emitted will
* cause the event to be re-emitted immediately with the error previously
* raised.
*/
on(ev, handler) {
const ret = super.on(ev, handler);
if (ev === 'data') {
this[DISCARDED] = false;
this[DATALISTENERS]++;
if (!this[PIPES].length && !this[FLOWING]) {
this[RESUME]();
}
}
else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
super.emit('readable');
}
else if (isEndish(ev) && this[EMITTED_END]) {
super.emit(ev);
this.removeAllListeners(ev);
}
else if (ev === 'error' && this[EMITTED_ERROR]) {
const h = handler;
if (this[ASYNC])
defer(() => h.call(this, this[EMITTED_ERROR]));
else
h.call(this, this[EMITTED_ERROR]);
}
return ret;
}
/**
* Alias for {@link Minipass#off}
*/
removeListener(ev, handler) {
return this.off(ev, handler);
}
/**
* Mostly identical to `EventEmitter.off`
*
* If a 'data' event handler is removed, and it was the last consumer
* (ie, there are no pipe destinations or other 'data' event listeners),
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
off(ev, handler) {
const ret = super.off(ev, handler);
// if we previously had listeners, and now we don't, and we don't
// have any pipes, then stop the flow, unless it's been explicitly
// put in a discarded flowing state via stream.resume().
if (ev === 'data') {
this[DATALISTENERS] = this.listeners('data').length;
if (this[DATALISTENERS] === 0 &&
!this[DISCARDED] &&
!this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* Mostly identical to `EventEmitter.removeAllListeners`
*
* If all 'data' event handlers are removed, and they were the last consumer
* (ie, there are no pipe destinations), then the flow of data will stop
* until there is another consumer or {@link Minipass#resume} is explicitly
* called.
*/
removeAllListeners(ev) {
const ret = super.removeAllListeners(ev);
if (ev === 'data' || ev === undefined) {
this[DATALISTENERS] = 0;
if (!this[DISCARDED] && !this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* true if the 'end' event has been emitted
*/
get emittedEnd() {
return this[EMITTED_END];
}
[MAYBE_EMIT_END]() {
if (!this[EMITTING_END] &&
!this[EMITTED_END] &&
!this[DESTROYED] &&
this[BUFFER].length === 0 &&
this[EOF]) {
this[EMITTING_END] = true;
this.emit('end');
this.emit('prefinish');
this.emit('finish');
if (this[CLOSED])
this.emit('close');
this[EMITTING_END] = false;
}
}
/**
* Mostly identical to `EventEmitter.emit`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* If the stream has been destroyed, and the event is something other
* than 'close' or 'error', then `false` is returned and no handlers
* are called.
*
* If the event is 'end', and has already been emitted, then the event
* is ignored. If the stream is in a paused or non-flowing state, then
* the event will be deferred until data flow resumes. If the stream is
* async, then handlers will be called on the next tick rather than
* immediately.
*
* If the event is 'close', and 'end' has not yet been emitted, then
* the event will be deferred until after 'end' is emitted.
*
* If the event is 'error', and an AbortSignal was provided for the stream,
* and there are no listeners, then the event is ignored, matching the
* behavior of node core streams in the presense of an AbortSignal.
*
* If the event is 'finish' or 'prefinish', then all listeners will be
* removed after emitting the event, to prevent double-firing.
*/
emit(ev, ...args) {
const data = args[0];
// error and close are only events allowed after calling destroy()
if (ev !== 'error' &&
ev !== 'close' &&
ev !== DESTROYED &&
this[DESTROYED]) {
return false;
}
else if (ev === 'data') {
return !this[OBJECTMODE] && !data
? false
: this[ASYNC]
? (defer(() => this[EMITDATA](data)), true)
: this[EMITDATA](data);
}
else if (ev === 'end') {
return this[EMITEND]();
}
else if (ev === 'close') {
this[CLOSED] = true;
// don't emit close before 'end' and 'finish'
if (!this[EMITTED_END] && !this[DESTROYED])
return false;
const ret = super.emit('close');
this.removeAllListeners('close');
return ret;
}
else if (ev === 'error') {
this[EMITTED_ERROR] = data;
super.emit(ERROR, data);
const ret = !this[SIGNAL] || this.listeners('error').length
? super.emit('error', data)
: false;
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'resume') {
const ret = super.emit('resume');
this[MAYBE_EMIT_END]();
return ret;
}
else if (ev === 'finish' || ev === 'prefinish') {
const ret = super.emit(ev);
this.removeAllListeners(ev);
return ret;
}
// Some other unknown event
const ret = super.emit(ev, ...args);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITDATA](data) {
for (const p of this[PIPES]) {
if (p.dest.write(data) === false)
this.pause();
}
const ret = this[DISCARDED] ? false : super.emit('data', data);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITEND]() {
if (this[EMITTED_END])
return false;
this[EMITTED_END] = true;
this.readable = false;
return this[ASYNC]
? (defer(() => this[EMITEND2]()), true)
: this[EMITEND2]();
}
[EMITEND2]() {
if (this[DECODER]) {
const data = this[DECODER].end();
if (data) {
for (const p of this[PIPES]) {
p.dest.write(data);
}
if (!this[DISCARDED])
super.emit('data', data);
}
}
for (const p of this[PIPES]) {
p.end();
}
const ret = super.emit('end');
this.removeAllListeners('end');
return ret;
}
/**
* Return a Promise that resolves to an array of all emitted data once
* the stream ends.
*/
async collect() {
const buf = Object.assign([], {
dataLength: 0,
});
if (!this[OBJECTMODE])
buf.dataLength = 0;
// set the promise first, in case an error is raised
// by triggering the flow here.
const p = this.promise();
this.on('data', c => {
buf.push(c);
if (!this[OBJECTMODE])
buf.dataLength += c.length;
});
await p;
return buf;
}
/**
* Return a Promise that resolves to the concatenation of all emitted data
* once the stream ends.
*
* Not allowed on objectMode streams.
*/
async concat() {
if (this[OBJECTMODE]) {
throw new Error('cannot concat in objectMode');
}
const buf = await this.collect();
return (this[ENCODING]
? buf.join('')
: Buffer.concat(buf, buf.dataLength));
}
/**
* Return a void Promise that resolves once the stream ends.
*/
async promise() {
return new Promise((resolve, reject) => {
this.on(DESTROYED, () => reject(new Error('stream destroyed')));
this.on('error', er => reject(er));
this.on('end', () => resolve());
});
}
/**
* Asynchronous `for await of` iteration.
*
* This will continue emitting all chunks until the stream terminates.
*/
[Symbol.asyncIterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = async () => {
this.pause();
stopped = true;
return { value: undefined, done: true };
};
const next = () => {
if (stopped)
return stop();
const res = this.read();
if (res !== null)
return Promise.resolve({ done: false, value: res });
if (this[EOF])
return stop();
let resolve;
let reject;
const onerr = (er) => {
this.off('data', ondata);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
stop();
reject(er);
};
const ondata = (value) => {
this.off('error', onerr);
this.off('end', onend);
this.off(DESTROYED, ondestroy);
this.pause();
resolve({ value, done: !!this[EOF] });
};
const onend = () => {
this.off('error', onerr);
this.off('data', ondata);
this.off(DESTROYED, ondestroy);
stop();
resolve({ done: true, value: undefined });
};
const ondestroy = () => onerr(new Error('stream destroyed'));
return new Promise((res, rej) => {
reject = rej;
resolve = res;
this.once(DESTROYED, ondestroy);
this.once('error', onerr);
this.once('end', onend);
this.once('data', ondata);
});
};
return {
next,
throw: stop,
return: stop,
[Symbol.asyncIterator]() {
return this;
},
};
}
/**
* Synchronous `for of` iteration.
*
* The iteration will terminate when the internal buffer runs out, even
* if the stream has not yet terminated.
*/
[Symbol.iterator]() {
// set this up front, in case the consumer doesn't call next()
// right away.
this[DISCARDED] = false;
let stopped = false;
const stop = () => {
this.pause();
this.off(ERROR, stop);
this.off(DESTROYED, stop);
this.off('end', stop);
stopped = true;
return { done: true, value: undefined };
};
const next = () => {
if (stopped)
return stop();
const value = this.read();
return value === null ? stop() : { done: false, value };
};
this.once('end', stop);
this.once(ERROR, stop);
this.once(DESTROYED, stop);
return {
next,
throw: stop,
return: stop,
[Symbol.iterator]() {
return this;
},
};
}
/**
* Destroy a stream, preventing it from being used for any further purpose.
*
* If the stream has a `close()` method, then it will be called on
* destruction.
*
* After destruction, any attempt to write data, read data, or emit most
* events will be ignored.
*
* If an error argument is provided, then it will be emitted in an
* 'error' event.
*/
destroy(er) {
if (this[DESTROYED]) {
if (er)
this.emit('error', er);
else
this.emit(DESTROYED);
return this;
}
this[DESTROYED] = true;
this[DISCARDED] = true;
// throw away all buffered data, it's never coming out
this[BUFFER].length = 0;
this[BUFFERLENGTH] = 0;
const wc = this;
if (typeof wc.close === 'function' && !this[CLOSED])
wc.close();
if (er)
this.emit('error', er);
// if no error to emit, still reject pending promises
else
this.emit(DESTROYED);
return this;
}
/**
* Alias for {@link isStream}
*
* Former export location, maintained for backwards compatibility.
*
* @deprecated
*/
static get isStream() {
return exports.isStream;
}
}
exports.Minipass = Minipass;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 3706:
/***/ ((module) => {
"use strict";
module.exports = function asFloat (value) {
const n = parseFloat(value)
// Some values are parsed as valid floats despite being obviously invalid, e.g. "1.o" or "192.168.1.1".
// In these cases we would want to throw an error.
if (isNaN(n) || isNaN(value)) {
throw new Error('should be a valid float')
}
return n
}
/***/ }),
/***/ 3723:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const { dirname, join, resolve, relative, isAbsolute } = __webpack_require__(6928)
const fs = __webpack_require__(1943)
const pathExists = async path => {
try {
await fs.access(path)
return true
} catch (er) {
return er.code !== 'ENOENT'
}
}
const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => {
if (!source || !destination) {
throw new TypeError('`source` and `destination` file required')
}
options = {
overwrite: true,
...options,
}
if (!options.overwrite && await pathExists(destination)) {
throw new Error(`The destination file exists: ${destination}`)
}
await fs.mkdir(dirname(destination), { recursive: true })
try {
await fs.rename(source, destination)
} catch (error) {
if (error.code === 'EXDEV' || error.code === 'EPERM') {
const sourceStat = await fs.lstat(source)
if (sourceStat.isDirectory()) {
const files = await fs.readdir(source)
await Promise.all(files.map((file) =>
moveFile(join(source, file), join(destination, file), options, false, symlinks)
))
} else if (sourceStat.isSymbolicLink()) {
symlinks.push({ source, destination })
} else {
await fs.copyFile(source, destination)
}
} else {
throw error
}
}
if (root) {
await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => {
let target = await fs.readlink(symSource)
// junction symlinks in windows will be absolute paths, so we need to
// make sure they point to the symlink destination
if (isAbsolute(target)) {
target = resolve(symDestination, relative(symSource, target))
}
// try to determine what the actual file is so we can create the correct
// type of symlink in windows
let targetStat = 'file'
try {
targetStat = await fs.stat(resolve(dirname(symSource), target))
if (targetStat.isDirectory()) {
targetStat = 'junction'
}
} catch {
// targetStat remains 'file'
}
await fs.symlink(
target,
symDestination,
targetStat
)
}))
await fs.rm(source, { recursive: true, force: true })
}
}
module.exports = moveFile
/***/ }),
/***/ 3728:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseClass = void 0;
// { : [, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length
? '(' + sranges + '|' + snegs + ')'
: ranges.length
? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
exports.parseClass = parseClass;
//# sourceMappingURL=brace-expressions.js.map
/***/ }),
/***/ 3858:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(5469)
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
/***/ }),
/***/ 3859:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const asString = __webpack_require__(6411)
module.exports = function asEnum (value, validValues) {
const valueString = asString(value)
if (validValues.indexOf(valueString) < 0) {
throw new Error(`should be one of [${validValues.join(', ')}]`)
}
return valueString
}
/***/ }),
/***/ 3925:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ gK: () => (/* binding */ types),
/* harmony export */ jo: () => (/* binding */ schemas),
/* harmony export */ pw: () => (/* binding */ watermark),
/* harmony export */ yb: () => (/* binding */ WatermarkOptionsSchema)
/* harmony export */ });
/* unused harmony exports addLogoWatermark, addTextWatermark */
/* harmony import */ var sharp__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9288);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6928);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var p_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4459);
/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9476);
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3522);
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7403);
/* harmony import */ var _polymech_fs_dir__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(3235);
/* harmony import */ var _polymech_commons__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3250);
// Zod Schema for watermark options
let schemaMap;
const WatermarkOptionsSchema = (opts) => {
schemaMap = _polymech_commons__WEBPACK_IMPORTED_MODULE_8__/* .ZodMetaMap */ .p7.create();
schemaMap.add('src', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.min(1)
.describe('FILE|FOLDER|GLOB - Source file(s) to add watermark to'))
.add('dst', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.optional()
.describe('FILE|FOLDER|GLOB - Destination for watermarked files'))
.add('debug', zod__WEBPACK_IMPORTED_MODULE_4__/* .boolean */ .zM()
.default(false)
.describe('Enable internal debug messages'))
.add('alt', zod__WEBPACK_IMPORTED_MODULE_4__/* .boolean */ .zM()
.default(false)
.describe('Use alternate tokenizer, & instead of $'))
.add('dry', zod__WEBPACK_IMPORTED_MODULE_4__/* .boolean */ .zM()
.default(false)
.describe('Run without conversion'))
.add('verbose', zod__WEBPACK_IMPORTED_MODULE_4__/* .boolean */ .zM()
.default(false)
.describe('Show internal messages'))
.add('logLevel', zod__WEBPACK_IMPORTED_MODULE_4__/* ["enum"] */ .k5(['warn', 'info', 'debug', 'error'])
.default('info')
.describe('Log level: warn, info, debug, error'))
.add('cache', zod__WEBPACK_IMPORTED_MODULE_4__/* .boolean */ .zM()
.default(true)
.describe('Skip processing if target file already exists'))
.add('watermark', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.min(1)
.describe('Watermark content: text string or path to image file (PNG, JPG, SVG)'))
.add('position', zod__WEBPACK_IMPORTED_MODULE_4__/* ["enum"] */ .k5(['top-left', 'top-right', 'bottom-left', 'bottom-right', 'center'])
.default('bottom-right')
.describe('Position of watermark'))
.add('margin', zod__WEBPACK_IMPORTED_MODULE_4__/* .number */ .ai()
.int()
.min(0)
.default(24)
.describe('Margin from edges in pixels'))
.add('opacity', zod__WEBPACK_IMPORTED_MODULE_4__/* .number */ .ai()
.min(0)
.max(1)
.default(0.85)
.describe('Opacity of watermark (0-1)'))
.add('sizePct', zod__WEBPACK_IMPORTED_MODULE_4__/* .number */ .ai()
.min(0)
.max(1)
.default(0.2)
.describe('Size of image watermark as percentage of base image width (0-1)'))
.add('fontSize', zod__WEBPACK_IMPORTED_MODULE_4__/* .number */ .ai()
.int()
.positive()
.default(48)
.describe('Font size for text watermark in pixels'))
.add('color', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.regex(/^#[0-9a-fA-F]{6}$/)
.default('#ffffff')
.describe('Text color (hex format, e.g., #ffffff)'))
.add('fontFamily', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.default('Arial')
.describe('Font family for text watermark'))
.add('strokeColor', zod__WEBPACK_IMPORTED_MODULE_4__/* .string */ .Yj()
.regex(/^#[0-9a-fA-F]{6}$/)
.default('#000000')
.describe('Text stroke color (hex format, e.g., #000000)'))
.add('strokeWidth', zod__WEBPACK_IMPORTED_MODULE_4__/* .number */ .ai()
.int()
.min(0)
.default(2)
.describe('Text stroke width in pixels'));
return schemaMap.root()
.passthrough()
.describe('IWatermarkOptions');
};
const types = () => {
(0,_polymech_commons__WEBPACK_IMPORTED_MODULE_8__/* .generate_interfaces */ .BR)([WatermarkOptionsSchema()], 'src/zod_types_watermark.ts');
schemas();
};
const schemas = () => {
const schema = WatermarkOptionsSchema();
(0,_polymech_commons__WEBPACK_IMPORTED_MODULE_8__/* .write */ .M9)([schema], 'schemas_watermark.json', 'watermark', {});
// Note: schema_ui.json would need ZodMetaMap.getUISchema() implementation
if (schemaMap && typeof schemaMap.getUISchema === 'function') {
Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 9896, 19)).then(fs => {
fs.writeFileSync('schema_ui_watermark.json', JSON.stringify(schemaMap.getUISchema(), null, 2));
}).catch(err => {
console.warn('Could not write UI schema:', err.message);
});
}
};
async function addLogoWatermark(inputPath, logoPath, outputPath, opts = {}) {
const { position = "bottom-right", margin = 24, sizePct = 0.2, opacity = 0.85, blend = "over", } = opts;
const base = sharp__WEBPACK_IMPORTED_MODULE_0__(inputPath);
const { width: W = 0, height: H = 0 } = await base.metadata();
if (!W || !H)
throw new Error("Could not read base image size");
// Resize logo to sizePct of base width
const logoWidth = Math.max(1, Math.round(W * sizePct));
// Handle SVG files specially
let logoSharp;
const logoExt = path__WEBPACK_IMPORTED_MODULE_1__.extname(logoPath).toLowerCase();
if (logoExt === '.svg') {
// For SVG files, specify density for better quality
logoSharp = sharp__WEBPACK_IMPORTED_MODULE_0__(logoPath, {
density: 300 // High DPI for crisp SVG rendering
}).resize({ width: logoWidth });
}
else {
// For other image formats
logoSharp = sharp__WEBPACK_IMPORTED_MODULE_0__(logoPath).resize({ width: logoWidth });
}
const logoBuf = await logoSharp.toBuffer();
const { width: w = 0, height: h = 0 } = await sharp__WEBPACK_IMPORTED_MODULE_0__(logoBuf).metadata();
// Compute pixel placement
const pos = (() => {
switch (position) {
case "top-left": return { left: margin, top: margin };
case "top-right": return { left: W - w - margin, top: margin };
case "bottom-left": return { left: margin, top: H - h - margin };
case "center": return { left: Math.round((W - w) / 2), top: Math.round((H - h) / 2) };
case "bottom-right":
default: return { left: W - w - margin, top: H - h - margin };
}
})();
(0,_polymech_fs_dir__WEBPACK_IMPORTED_MODULE_7__/* .sync */ .OH)(path__WEBPACK_IMPORTED_MODULE_1__.dirname(outputPath));
await base
.composite([{
input: logoBuf,
left: pos.left,
top: pos.top,
blend,
...(opacity < 1 ? { blend: 'multiply' } : {}),
}])
.toFile(outputPath);
}
async function addTextWatermark(inputPath, text, outputPath, opts = {}) {
const { position = "bottom-right", margin = 24, fontSize = 48, opacity = 0.8, color = '#ffffff', fontFamily = 'Arial', strokeColor = '#000000', strokeWidth = 2, } = opts;
const base = sharp__WEBPACK_IMPORTED_MODULE_0__(inputPath);
const { width: W = 0, height: H = 0 } = await base.metadata();
if (!W || !H)
throw new Error("Could not read base image size");
// Create SVG text element
const svgText = `