// -> /\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '')\n continue;\n if (p === '.' || p === '') {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')) {\n didSomething = true;\n parts.pop();\n }\n }\n // //../
-> /\n let dd = 0;\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1];\n if (p &&\n p !== '.' &&\n p !== '..' &&\n p !== '**' &&\n !(this.isWindows && /^[a-z]:$/i.test(p))) {\n didSomething = true;\n parts.splice(dd - 1, 2);\n dd -= 2;\n }\n }\n } while (didSomething);\n return parts.length === 0 ? [''] : parts;\n }\n // First phase: single-pattern processing\n // is 1 or more portions\n //is 1 or more portions\n // is any portion other than ., .., '', or **\n //
is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n // /**/..//
/
-> { /..//
/
, /**//
/
}\n // // -> /\n // //../
-> /\n // **/**/ -> **/ \n //\n // **/*/ -> */**/ <== not valid because ** doesn't follow\n // this WOULD be allowed if ** did follow symlinks, or * didn't\n firstPhasePreProcess(globParts) {\n let didSomething = false;\n do {\n didSomething = false;\n // /**/..//
/
-> { /..//
/
, /**//
/
}\n for (let parts of globParts) {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss = gs;\n while (parts[gss + 1] === '**') {\n // /**/**/-> /**/\n gss++;\n }\n // eg, if gs is 2 and gss is 4, that means we have 3 **\n // parts, and can remove 2 of them.\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs);\n }\n let next = parts[gs + 1];\n const p = parts[gs + 2];\n const p2 = parts[gs + 3];\n if (next !== '..')\n continue;\n if (!p ||\n p === '.' ||\n p === '..' ||\n !p2 ||\n p2 === '.' ||\n p2 === '..') {\n continue;\n }\n didSomething = true;\n // edit parts in place, and push the new one\n parts.splice(gs, 1);\n const other = parts.slice(0);\n other[gs] = '**';\n globParts.push(other);\n gs--;\n }\n // // -> /\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '')\n continue;\n if (p === '.' || p === '') {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')) {\n didSomething = true;\n parts.pop();\n }\n }\n // //../
-> /\n let dd = 0;\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true;\n const needDot = dd === 1 && parts[dd + 1] === '**';\n const splin = needDot ? ['.'] : [];\n parts.splice(dd - 1, 2, ...splin);\n if (parts.length === 0)\n parts.push('');\n dd -= 2;\n }\n }\n }\n } while (didSomething);\n return globParts;\n }\n // second phase: multi-pattern dedupes\n // { /*/, //
} -> /*/\n // { /, /} -> /\n // { /**/, /} -> /**/\n //\n // { /**/, /**//
} -> /**/\n // ^-- not valid because ** doens't follow symlinks\n secondPhasePreProcess(globParts) {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);\n if (matched) {\n globParts[i] = [];\n globParts[j] = matched;\n break;\n }\n }\n }\n return globParts.filter(gs => gs.length);\n }\n partsMatch(a, b, emptyGSMatch = false) {\n let ai = 0;\n let bi = 0;\n let result = [];\n let which = '';\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === 'b' ? b[bi] : a[ai]);\n ai++;\n bi++;\n }\n else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n result.push(a[ai]);\n ai++;\n }\n else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n result.push(b[bi]);\n bi++;\n }\n else if (a[ai] === '*' &&\n b[bi] &&\n (this.options.dot || !b[bi].startsWith('.')) &&\n b[bi] !== '**') {\n if (which === 'b')\n return false;\n which = 'a';\n result.push(a[ai]);\n ai++;\n bi++;\n }\n else if (b[bi] === '*' &&\n a[ai] &&\n (this.options.dot || !a[ai].startsWith('.')) &&\n a[ai] !== '**') {\n if (which === 'a')\n return false;\n which = 'b';\n result.push(b[bi]);\n ai++;\n bi++;\n }\n else {\n return false;\n }\n }\n // if we fall out of the loop, it means they two are identical\n // as long as their lengths match\n return a.length === b.length && result;\n }\n parseNegate() {\n if (this.nonegate)\n return;\n const pattern = this.pattern;\n let negate = false;\n let negateOffset = 0;\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate;\n negateOffset++;\n }\n if (negateOffset)\n this.pattern = pattern.slice(negateOffset);\n this.negate = negate;\n }\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne(file, pattern, partial = false) {\n let fileStartIndex = 0;\n let patternStartIndex = 0;\n // UNC paths like //?/X:/... can match X:/... and vice versa\n // Drive letters in absolute drive or unc paths are always compared\n // case-insensitively.\n if (this.isWindows) {\n const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);\n const fileUNC = !fileDrive &&\n file[0] === '' &&\n file[1] === '' &&\n file[2] === '?' &&\n /^[a-z]:$/i.test(file[3]);\n const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);\n const patternUNC = !patternDrive &&\n pattern[0] === '' &&\n pattern[1] === '' &&\n pattern[2] === '?' &&\n typeof pattern[3] === 'string' &&\n /^[a-z]:$/i.test(pattern[3]);\n const fdi = fileUNC ? 3\n : fileDrive ? 0\n : undefined;\n const pdi = patternUNC ? 3\n : patternDrive ? 0\n : undefined;\n if (typeof fdi === 'number' && typeof pdi === 'number') {\n const [fd, pd] = [\n file[fdi],\n pattern[pdi],\n ];\n // start matching at the drive letter index of each\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd;\n patternStartIndex = pdi;\n fileStartIndex = fdi;\n }\n }\n }\n // resolve and reduce . and .. portions in the file as well.\n // don't need to do the second phase, because it's only one string[]\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file);\n }\n if (pattern.includes(GLOBSTAR)) {\n return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {\n // split the pattern into head, tail, and middle of ** delimited parts\n const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);\n const lastgs = pattern.lastIndexOf(GLOBSTAR);\n // split the pattern up into globstar-delimited sections\n // the tail has to be at the end, and the others just have\n // to be found in order from the head.\n const [head, body, tail] = partial ?\n [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1),\n [],\n ]\n : [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1, lastgs),\n pattern.slice(lastgs + 1),\n ];\n // check the head, from the current file/pattern index.\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length);\n if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n return false;\n }\n fileIndex += head.length;\n patternIndex += head.length;\n }\n // now we know the head matches!\n // if the last portion is not empty, it MUST match the end\n // check the tail\n let fileTailMatch = 0;\n if (tail.length) {\n // if head + tail > file, then we cannot possibly match\n if (tail.length + fileIndex > file.length)\n return false;\n // try to match the tail\n let tailStart = file.length - tail.length;\n if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length;\n }\n else {\n // affordance for stuff like a/**/* matching a/b/\n // if the last file portion is '', and there's more to the pattern\n // then try without the '' bit.\n if (file[file.length - 1] !== '' ||\n fileIndex + tail.length === file.length) {\n return false;\n }\n tailStart--;\n if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n return false;\n }\n fileTailMatch = tail.length + 1;\n }\n }\n // now we know the tail matches!\n // the middle is zero or more portions wrapped in **, possibly\n // containing more ** sections.\n // so a/**/b/**/c/**/d has become **/b/**/c/**\n // if it's empty, it means a/**/b, just verify we have no bad dots\n // if there's no tail, so it ends on /**, then we must have *something*\n // after the head, or it's not a matc\n if (!body.length) {\n let sawSome = !!fileTailMatch;\n for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n const f = String(file[i]);\n sawSome = true;\n if (f === '.' ||\n f === '..' ||\n (!this.options.dot && f.startsWith('.'))) {\n return false;\n }\n }\n // in partial mode, we just need to get past all file parts\n return partial || sawSome;\n }\n // now we know that there's one or more body sections, which can\n // be matched anywhere from the 0 index (because the head was pruned)\n // through to the length-fileTailMatch index.\n // split the body up into sections, and note the minimum index it can\n // be found at (start with the length of all previous segments)\n // [section, before, after]\n const bodySegments = [[[], 0]];\n let currentBody = bodySegments[0];\n let nonGsParts = 0;\n const nonGsPartsSums = [0];\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts);\n currentBody = [[], 0];\n bodySegments.push(currentBody);\n }\n else {\n currentBody[0].push(b);\n nonGsParts++;\n }\n }\n let i = bodySegments.length - 1;\n const fileLength = file.length - fileTailMatch;\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);\n }\n return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);\n }\n // return false for \"nope, not matching\"\n // return null for \"not matching, cannot keep trying\"\n #matchGlobStarBodySections(file, \n // pattern section, last possible position for it\n bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {\n // take the first body segment, and walk from fileIndex to its \"after\"\n // value at the end\n // If it doesn't match at that position, we increment, until we hit\n // that final possible position, and give up.\n // If it does match, then advance and try to rest.\n // If any of them fail we keep walking forward.\n // this is still a bit recursively painful, but it's more constrained\n // than previous implementations, because we never test something that\n // can't possibly be a valid matching condition.\n const bs = bodySegments[bodyIndex];\n if (!bs) {\n // just make sure that there's no bad dots\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true;\n const f = file[i];\n if (f === '.' ||\n f === '..' ||\n (!this.options.dot && f.startsWith('.'))) {\n return false;\n }\n }\n return sawTail;\n }\n // have a non-globstar body section to test\n const [body, after] = bs;\n while (fileIndex <= after) {\n const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);\n // if limit exceeded, no match. intentional false negative,\n // acceptable break in correctness for security.\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n // match! see if the rest match. if so, we're done!\n const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);\n if (sub !== false) {\n return sub;\n }\n }\n const f = file[fileIndex];\n if (f === '.' ||\n f === '..' ||\n (!this.options.dot && f.startsWith('.'))) {\n return false;\n }\n fileIndex++;\n }\n // walked off. no point continuing\n return partial || null;\n }\n #matchOne(file, pattern, partial, fileIndex, patternIndex) {\n let fi;\n let pi;\n let pl;\n let fl;\n for (fi = fileIndex,\n pi = patternIndex,\n fl = file.length,\n pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {\n this.debug('matchOne loop');\n let p = pattern[pi];\n let f = file[fi];\n this.debug(pattern, p, f);\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* c8 ignore start */\n if (p === false || p === GLOBSTAR) {\n return false;\n }\n /* c8 ignore stop */\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit;\n if (typeof p === 'string') {\n hit = f === p;\n this.debug('string match', p, f, hit);\n }\n else {\n hit = p.test(f);\n this.debug('pattern match', p, f, hit);\n }\n if (!hit)\n return false;\n }\n // Note: ending in / means that we'll get a final \"\"\n // at the end of the pattern. This can only match a\n // corresponding \"\" at the end of the file.\n // If the file ends in /, then it can only match a\n // a pattern that ends in /, unless the pattern just\n // doesn't have any more for it. But, a/b/ should *not*\n // match \"a/b/*\", even though \"\" matches against the\n // [^/]*? pattern, except in partial mode, where it might\n // simply not be reached yet.\n // However, a/b/ should still satisfy a/*\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true;\n }\n else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial;\n }\n else if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return fi === fl - 1 && file[fi] === '';\n /* c8 ignore start */\n }\n else {\n // should be unreachable.\n throw new Error('wtf?');\n }\n /* c8 ignore stop */\n }\n braceExpand() {\n return braceExpand(this.pattern, this.options);\n }\n parse(pattern) {\n assertValidPattern(pattern);\n const options = this.options;\n // shortcuts\n if (pattern === '**')\n return GLOBSTAR;\n if (pattern === '')\n return '';\n // far and away, the most common glob pattern parts are\n // *, *.*, and *. Add a fast check method for those.\n let m;\n let fastTest = null;\n if ((m = pattern.match(starRE))) {\n fastTest = options.dot ? starTestDot : starTest;\n }\n else if ((m = pattern.match(starDotExtRE))) {\n fastTest = (options.nocase ?\n options.dot ?\n starDotExtTestNocaseDot\n : starDotExtTestNocase\n : options.dot ? starDotExtTestDot\n : starDotExtTest)(m[1]);\n }\n else if ((m = pattern.match(qmarksRE))) {\n fastTest = (options.nocase ?\n options.dot ?\n qmarksTestNocaseDot\n : qmarksTestNocase\n : options.dot ? qmarksTestDot\n : qmarksTest)(m);\n }\n else if ((m = pattern.match(starDotStarRE))) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest;\n }\n else if ((m = pattern.match(dotStarRE))) {\n fastTest = dotStarTest;\n }\n const re = AST.fromGlob(pattern, this.options).toMMPattern();\n if (fastTest && typeof re === 'object') {\n // Avoids overriding in frozen environments\n Reflect.defineProperty(re, 'test', { value: fastTest });\n }\n return re;\n }\n makeRe() {\n if (this.regexp || this.regexp === false)\n return this.regexp;\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set;\n if (!set.length) {\n this.regexp = false;\n return this.regexp;\n }\n const options = this.options;\n const twoStar = options.noglobstar ? star\n : options.dot ? twoStarDot\n : twoStarNoDot;\n const flags = new Set(options.nocase ? ['i'] : []);\n // regexpify non-globstar patterns\n // if ** is only item, then we just do one twoStar\n // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if ** is last, append (\\/twoStar|) to previous\n // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set\n .map(pattern => {\n const pp = pattern.map(p => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split(''))\n flags.add(f);\n }\n return (typeof p === 'string' ? regExpEscape(p)\n : p === GLOBSTAR ? GLOBSTAR\n : p._src);\n });\n pp.forEach((p, i) => {\n const next = pp[i + 1];\n const prev = pp[i - 1];\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return;\n }\n if (prev === undefined) {\n if (next !== undefined && next !== GLOBSTAR) {\n pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next;\n }\n else {\n pp[i] = twoStar;\n }\n }\n else if (next === undefined) {\n pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + ')?';\n }\n else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next;\n pp[i + 1] = GLOBSTAR;\n }\n });\n const filtered = pp.filter(p => p !== GLOBSTAR);\n // For partial matches, we need to make the pattern match\n // any prefix of the full path. We do this by generating\n // alternative patterns that match progressively longer prefixes.\n if (this.partial && filtered.length >= 1) {\n const prefixes = [];\n for (let i = 1; i <= filtered.length; i++) {\n prefixes.push(filtered.slice(0, i).join('/'));\n }\n return '(?:' + prefixes.join('|') + ')';\n }\n return filtered.join('/');\n })\n .join('|');\n // need to wrap in parens if we had more than one thing with |,\n // otherwise only the first will be anchored to ^ and the last to $\n const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^' + open + re + close + '$';\n // In partial mode, '/' should always match as it's a valid prefix for any pattern\n if (this.partial) {\n re = '^(?:\\\\/|' + open + re.slice(1, -1) + close + ')$';\n }\n // can match anything, as long as it's not this.\n if (this.negate)\n re = '^(?!' + re + ').+$';\n try {\n this.regexp = new RegExp(re, [...flags].join(''));\n /* c8 ignore start */\n }\n catch {\n // should be impossible\n this.regexp = false;\n }\n /* c8 ignore stop */\n return this.regexp;\n }\n slashSplit(p) {\n // if p starts with // on windows, we preserve that\n // so that UNC paths aren't broken. Otherwise, any number of\n // / characters are coalesced into one, unless\n // preserveMultipleSlashes is set to true.\n if (this.preserveMultipleSlashes) {\n return p.split('/');\n }\n else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n // add an extra '' for the one we lose\n return ['', ...p.split(/\\/+/)];\n }\n else {\n return p.split(/\\/+/);\n }\n }\n match(f, partial = this.partial) {\n this.debug('match', f, this.pattern);\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) {\n return false;\n }\n if (this.empty) {\n return f === '';\n }\n if (f === '/' && partial) {\n return true;\n }\n const options = this.options;\n // windows: need to use /, not \\\n if (this.isWindows) {\n f = f.split('\\\\').join('/');\n }\n // treat the test path as a set of pathparts.\n const ff = this.slashSplit(f);\n this.debug(this.pattern, 'split', ff);\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n const set = this.set;\n this.debug(this.pattern, 'set', set);\n // Find the basename of the path by looking for the last non-empty segment\n let filename = ff[ff.length - 1];\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i];\n }\n }\n for (const pattern of set) {\n let file = ff;\n if (options.matchBase && pattern.length === 1) {\n file = [filename];\n }\n const hit = this.matchOne(file, pattern, partial);\n if (hit) {\n if (options.flipNegate) {\n return true;\n }\n return !this.negate;\n }\n }\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) {\n return false;\n }\n return this.negate;\n }\n static defaults(def) {\n return minimatch.defaults(def).Minimatch;\n }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js';\nexport { escape } from './escape.js';\nexport { unescape } from './unescape.js';\n/* c8 ignore stop */\nminimatch.AST = AST;\nminimatch.Minimatch = Minimatch;\nminimatch.escape = escape;\nminimatch.unescape = unescape;\n//# sourceMappingURL=index.js.map","import * as path from 'path';\nimport * as pathHelper from './internal-path-helper.js';\nimport assert from 'assert';\nconst IS_WINDOWS = process.platform === 'win32';\n/**\n * Helper class for parsing paths into segments\n */\nexport class Path {\n /**\n * Constructs a Path\n * @param itemPath Path or array of segments\n */\n constructor(itemPath) {\n this.segments = [];\n // String\n if (typeof itemPath === 'string') {\n assert(itemPath, `Parameter 'itemPath' must not be empty`);\n // Normalize slashes and trim unnecessary trailing slash\n itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);\n // Not rooted\n if (!pathHelper.hasRoot(itemPath)) {\n this.segments = itemPath.split(path.sep);\n }\n // Rooted\n else {\n // Add all segments, while not at the root\n let remaining = itemPath;\n let dir = pathHelper.dirname(remaining);\n while (dir !== remaining) {\n // Add the segment\n const basename = path.basename(remaining);\n this.segments.unshift(basename);\n // Truncate the last segment\n remaining = dir;\n dir = pathHelper.dirname(remaining);\n }\n // Remainder is the root\n this.segments.unshift(remaining);\n }\n }\n // Array\n else {\n // Must not be empty\n assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`);\n // Each segment\n for (let i = 0; i < itemPath.length; i++) {\n let segment = itemPath[i];\n // Must not be empty\n assert(segment, `Parameter 'itemPath' must not contain any empty segments`);\n // Normalize slashes\n segment = pathHelper.normalizeSeparators(itemPath[i]);\n // Root segment\n if (i === 0 && pathHelper.hasRoot(segment)) {\n segment = pathHelper.safeTrimTrailingSeparator(segment);\n assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`);\n this.segments.push(segment);\n }\n // All other segments\n else {\n // Must not contain slash\n assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`);\n this.segments.push(segment);\n }\n }\n }\n }\n /**\n * Converts the path to it's string representation\n */\n toString() {\n // First segment\n let result = this.segments[0];\n // All others\n let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result));\n for (let i = 1; i < this.segments.length; i++) {\n if (skipSlash) {\n skipSlash = false;\n }\n else {\n result += path.sep;\n }\n result += this.segments[i];\n }\n return result;\n }\n}\n//# sourceMappingURL=internal-path.js.map","import * as os from 'os';\nimport * as path from 'path';\nimport * as pathHelper from './internal-path-helper.js';\nimport assert from 'assert';\nimport { Minimatch } from 'minimatch';\nimport { MatchKind } from './internal-match-kind.js';\nimport { Path } from './internal-path.js';\nconst IS_WINDOWS = process.platform === 'win32';\nexport class Pattern {\n constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) {\n /**\n * Indicates whether matches should be excluded from the result set\n */\n this.negate = false;\n // Pattern overload\n let pattern;\n if (typeof patternOrNegate === 'string') {\n pattern = patternOrNegate.trim();\n }\n // Segments overload\n else {\n // Convert to pattern\n segments = segments || [];\n assert(segments.length, `Parameter 'segments' must not empty`);\n const root = Pattern.getLiteral(segments[0]);\n assert(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`);\n pattern = new Path(segments).toString().trim();\n if (patternOrNegate) {\n pattern = `!${pattern}`;\n }\n }\n // Negate\n while (pattern.startsWith('!')) {\n this.negate = !this.negate;\n pattern = pattern.substr(1).trim();\n }\n // Normalize slashes and ensures absolute root\n pattern = Pattern.fixupPattern(pattern, homedir);\n // Segments\n this.segments = new Path(pattern).segments;\n // Trailing slash indicates the pattern should only match directories, not regular files\n this.trailingSeparator = pathHelper\n .normalizeSeparators(pattern)\n .endsWith(path.sep);\n pattern = pathHelper.safeTrimTrailingSeparator(pattern);\n // Search path (literal path prior to the first glob segment)\n let foundGlob = false;\n const searchSegments = this.segments\n .map(x => Pattern.getLiteral(x))\n .filter(x => !foundGlob && !(foundGlob = x === ''));\n this.searchPath = new Path(searchSegments).toString();\n // Root RegExp (required when determining partial match)\n this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : '');\n this.isImplicitPattern = isImplicitPattern;\n // Create minimatch\n const minimatchOptions = {\n dot: true,\n nobrace: true,\n nocase: IS_WINDOWS,\n nocomment: true,\n noext: true,\n nonegate: true\n };\n pattern = IS_WINDOWS ? pattern.replace(/\\\\/g, '/') : pattern;\n this.minimatch = new Minimatch(pattern, minimatchOptions);\n }\n /**\n * Matches the pattern against the specified path\n */\n match(itemPath) {\n // Last segment is globstar?\n if (this.segments[this.segments.length - 1] === '**') {\n // Normalize slashes\n itemPath = pathHelper.normalizeSeparators(itemPath);\n // Append a trailing slash. Otherwise Minimatch will not match the directory immediately\n // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns\n // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk.\n if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) {\n // Note, this is safe because the constructor ensures the pattern has an absolute root.\n // For example, formats like C: and C:foo on Windows are resolved to an absolute root.\n itemPath = `${itemPath}${path.sep}`;\n }\n }\n else {\n // Normalize slashes and trim unnecessary trailing slash\n itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);\n }\n // Match\n if (this.minimatch.match(itemPath)) {\n return this.trailingSeparator ? MatchKind.Directory : MatchKind.All;\n }\n return MatchKind.None;\n }\n /**\n * Indicates whether the pattern may match descendants of the specified path\n */\n partialMatch(itemPath) {\n // Normalize slashes and trim unnecessary trailing slash\n itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);\n // matchOne does not handle root path correctly\n if (pathHelper.dirname(itemPath) === itemPath) {\n return this.rootRegExp.test(itemPath);\n }\n return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\\\+/ : /\\/+/), this.minimatch.set[0], true);\n }\n /**\n * Escapes glob patterns within a path\n */\n static globEscape(s) {\n return (IS_WINDOWS ? s : s.replace(/\\\\/g, '\\\\\\\\')) // escape '\\' on Linux/macOS\n .replace(/(\\[)(?=[^/]+\\])/g, '[[]') // escape '[' when ']' follows within the path segment\n .replace(/\\?/g, '[?]') // escape '?'\n .replace(/\\*/g, '[*]'); // escape '*'\n }\n /**\n * Normalizes slashes and ensures absolute root\n */\n static fixupPattern(pattern, homedir) {\n // Empty\n assert(pattern, 'pattern cannot be empty');\n // Must not contain `.` segment, unless first segment\n // Must not contain `..` segment\n const literalSegments = new Path(pattern).segments.map(x => Pattern.getLiteral(x));\n assert(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`);\n // Must not contain globs in root, e.g. Windows UNC path \\\\foo\\b*r\n assert(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`);\n // Normalize slashes\n pattern = pathHelper.normalizeSeparators(pattern);\n // Replace leading `.` segment\n if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) {\n pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1);\n }\n // Replace leading `~` segment\n else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) {\n homedir = homedir || os.homedir();\n assert(homedir, 'Unable to determine HOME directory');\n assert(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`);\n pattern = Pattern.globEscape(homedir) + pattern.substr(1);\n }\n // Replace relative drive root, e.g. pattern is C: or C:foo\n else if (IS_WINDOWS &&\n (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\\\]/i))) {\n let root = pathHelper.ensureAbsoluteRoot('C:\\\\dummy-root', pattern.substr(0, 2));\n if (pattern.length > 2 && !root.endsWith('\\\\')) {\n root += '\\\\';\n }\n pattern = Pattern.globEscape(root) + pattern.substr(2);\n }\n // Replace relative root, e.g. pattern is \\ or \\foo\n else if (IS_WINDOWS && (pattern === '\\\\' || pattern.match(/^\\\\[^\\\\]/))) {\n let root = pathHelper.ensureAbsoluteRoot('C:\\\\dummy-root', '\\\\');\n if (!root.endsWith('\\\\')) {\n root += '\\\\';\n }\n pattern = Pattern.globEscape(root) + pattern.substr(1);\n }\n // Otherwise ensure absolute root\n else {\n pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern);\n }\n return pathHelper.normalizeSeparators(pattern);\n }\n /**\n * Attempts to unescape a pattern segment to create a literal path segment.\n * Otherwise returns empty string.\n */\n static getLiteral(segment) {\n let literal = '';\n for (let i = 0; i < segment.length; i++) {\n const c = segment[i];\n // Escape\n if (c === '\\\\' && !IS_WINDOWS && i + 1 < segment.length) {\n literal += segment[++i];\n continue;\n }\n // Wildcard\n else if (c === '*' || c === '?') {\n return '';\n }\n // Character set\n else if (c === '[' && i + 1 < segment.length) {\n let set = '';\n let closed = -1;\n for (let i2 = i + 1; i2 < segment.length; i2++) {\n const c2 = segment[i2];\n // Escape\n if (c2 === '\\\\' && !IS_WINDOWS && i2 + 1 < segment.length) {\n set += segment[++i2];\n continue;\n }\n // Closed\n else if (c2 === ']') {\n closed = i2;\n break;\n }\n // Otherwise\n else {\n set += c2;\n }\n }\n // Closed?\n if (closed >= 0) {\n // Cannot convert\n if (set.length > 1) {\n return '';\n }\n // Convert to literal\n if (set) {\n literal += set;\n i = closed;\n continue;\n }\n }\n // Otherwise fall thru\n }\n // Append\n literal += c;\n }\n return literal;\n }\n /**\n * Escapes regexp special characters\n * https://javascript.info/regexp-escaping\n */\n static regExpEscape(s) {\n return s.replace(/[[\\\\^$.|?*+()]/g, '\\\\$&');\n }\n}\n//# sourceMappingURL=internal-pattern.js.map","export class SearchState {\n constructor(path, level) {\n this.path = path;\n this.level = level;\n }\n}\n//# sourceMappingURL=internal-search-state.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport * as core from '@actions/core';\nimport * as fs from 'fs';\nimport * as globOptionsHelper from './internal-glob-options-helper.js';\nimport * as path from 'path';\nimport * as patternHelper from './internal-pattern-helper.js';\nimport { MatchKind } from './internal-match-kind.js';\nimport { Pattern } from './internal-pattern.js';\nimport { SearchState } from './internal-search-state.js';\nconst IS_WINDOWS = process.platform === 'win32';\nexport class DefaultGlobber {\n constructor(options) {\n this.patterns = [];\n this.searchPaths = [];\n this.options = globOptionsHelper.getOptions(options);\n }\n getSearchPaths() {\n // Return a copy\n return this.searchPaths.slice();\n }\n glob() {\n return __awaiter(this, void 0, void 0, function* () {\n var _a, e_1, _b, _c;\n const result = [];\n try {\n for (var _d = true, _e = __asyncValues(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {\n _c = _f.value;\n _d = false;\n const itemPath = _c;\n result.push(itemPath);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return result;\n });\n }\n globGenerator() {\n return __asyncGenerator(this, arguments, function* globGenerator_1() {\n // Fill in defaults options\n const options = globOptionsHelper.getOptions(this.options);\n // Implicit descendants?\n const patterns = [];\n for (const pattern of this.patterns) {\n patterns.push(pattern);\n if (options.implicitDescendants &&\n (pattern.trailingSeparator ||\n pattern.segments[pattern.segments.length - 1] !== '**')) {\n patterns.push(new Pattern(pattern.negate, true, pattern.segments.concat('**')));\n }\n }\n // Push the search paths\n const stack = [];\n for (const searchPath of patternHelper.getSearchPaths(patterns)) {\n core.debug(`Search path '${searchPath}'`);\n // Exists?\n try {\n // Intentionally using lstat. Detection for broken symlink\n // will be performed later (if following symlinks).\n yield __await(fs.promises.lstat(searchPath));\n }\n catch (err) {\n if (err.code === 'ENOENT') {\n continue;\n }\n throw err;\n }\n stack.unshift(new SearchState(searchPath, 1));\n }\n // Search\n const traversalChain = []; // used to detect cycles\n while (stack.length) {\n // Pop\n const item = stack.pop();\n // Match?\n const match = patternHelper.match(patterns, item.path);\n const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path);\n if (!match && !partialMatch) {\n continue;\n }\n // Stat\n const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain)\n // Broken symlink, or symlink cycle detected, or no longer exists\n );\n // Broken symlink, or symlink cycle detected, or no longer exists\n if (!stats) {\n continue;\n }\n // Hidden file or directory?\n if (options.excludeHiddenFiles && path.basename(item.path).match(/^\\./)) {\n continue;\n }\n // Directory\n if (stats.isDirectory()) {\n // Matched\n if (match & MatchKind.Directory && options.matchDirectories) {\n yield yield __await(item.path);\n }\n // Descend?\n else if (!partialMatch) {\n continue;\n }\n // Push the child items in reverse\n const childLevel = item.level + 1;\n const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new SearchState(path.join(item.path, x), childLevel));\n stack.push(...childItems.reverse());\n }\n // File\n else if (match & MatchKind.File) {\n yield yield __await(item.path);\n }\n }\n });\n }\n /**\n * Constructs a DefaultGlobber\n */\n static create(patterns, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const result = new DefaultGlobber(options);\n if (IS_WINDOWS) {\n patterns = patterns.replace(/\\r\\n/g, '\\n');\n patterns = patterns.replace(/\\r/g, '\\n');\n }\n const lines = patterns.split('\\n').map(x => x.trim());\n for (const line of lines) {\n // Empty or comment\n if (!line || line.startsWith('#')) {\n continue;\n }\n // Pattern\n else {\n result.patterns.push(new Pattern(line));\n }\n }\n result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns));\n return result;\n });\n }\n static stat(item, options, traversalChain) {\n return __awaiter(this, void 0, void 0, function* () {\n // Note:\n // `stat` returns info about the target of a symlink (or symlink chain)\n // `lstat` returns info about a symlink itself\n let stats;\n if (options.followSymbolicLinks) {\n try {\n // Use `stat` (following symlinks)\n stats = yield fs.promises.stat(item.path);\n }\n catch (err) {\n if (err.code === 'ENOENT') {\n if (options.omitBrokenSymbolicLinks) {\n core.debug(`Broken symlink '${item.path}'`);\n return undefined;\n }\n throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`);\n }\n throw err;\n }\n }\n else {\n // Use `lstat` (not following symlinks)\n stats = yield fs.promises.lstat(item.path);\n }\n // Note, isDirectory() returns false for the lstat of a symlink\n if (stats.isDirectory() && options.followSymbolicLinks) {\n // Get the realpath\n const realPath = yield fs.promises.realpath(item.path);\n // Fixup the traversal chain to match the item level\n while (traversalChain.length >= item.level) {\n traversalChain.pop();\n }\n // Test for a cycle\n if (traversalChain.some((x) => x === realPath)) {\n core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`);\n return undefined;\n }\n // Update the traversal chain\n traversalChain.push(realPath);\n }\n return stats;\n });\n }\n}\n//# sourceMappingURL=internal-globber.js.map","const __WEBPACK_NAMESPACE_OBJECT__ = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"stream\");","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nimport * as crypto from 'crypto';\nimport * as core from '@actions/core';\nimport * as fs from 'fs';\nimport * as stream from 'stream';\nimport * as util from 'util';\nimport * as path from 'path';\nexport function hashFiles(globber_1, currentWorkspace_1) {\n return __awaiter(this, arguments, void 0, function* (globber, currentWorkspace, verbose = false) {\n var _a, e_1, _b, _c;\n var _d;\n const writeDelegate = verbose ? core.info : core.debug;\n let hasMatch = false;\n const githubWorkspace = currentWorkspace\n ? currentWorkspace\n : ((_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd());\n const result = crypto.createHash('sha256');\n let count = 0;\n try {\n for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {\n _c = _g.value;\n _e = false;\n const file = _c;\n writeDelegate(file);\n if (!file.startsWith(`${githubWorkspace}${path.sep}`)) {\n writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`);\n continue;\n }\n if (fs.statSync(file).isDirectory()) {\n writeDelegate(`Skip directory '${file}'.`);\n continue;\n }\n const hash = crypto.createHash('sha256');\n const pipeline = util.promisify(stream.pipeline);\n yield pipeline(fs.createReadStream(file), hash);\n result.write(hash.digest());\n count++;\n if (!hasMatch) {\n hasMatch = true;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);\n }\n finally { if (e_1) throw e_1.error; }\n }\n result.end();\n if (hasMatch) {\n writeDelegate(`Found ${count} files to hash.`);\n return result.digest('hex');\n }\n else {\n writeDelegate(`No matches found for glob`);\n return '';\n }\n });\n}\n//# sourceMappingURL=internal-hash-files.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nimport { DefaultGlobber } from './internal-globber.js';\nimport { hashFiles as _hashFiles } from './internal-hash-files.js';\n/**\n * Constructs a globber\n *\n * @param patterns Patterns separated by newlines\n * @param options Glob options\n */\nexport function create(patterns, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield DefaultGlobber.create(patterns, options);\n });\n}\n/**\n * Computes the sha256 hash of a glob\n *\n * @param patterns Patterns separated by newlines\n * @param currentWorkspace Workspace used when matching files\n * @param options Glob options\n * @param verbose Enables verbose logging\n */\nexport function hashFiles(patterns_1) {\n return __awaiter(this, arguments, void 0, function* (patterns, currentWorkspace = '', options, verbose = false) {\n let followSymbolicLinks = true;\n if (options && typeof options.followSymbolicLinks === 'boolean') {\n followSymbolicLinks = options.followSymbolicLinks;\n }\n const globber = yield create(patterns, { followSymbolicLinks });\n return _hashFiles(globber, currentWorkspace, verbose);\n });\n}\n//# sourceMappingURL=glob.js.map","import { createReadStream } from 'node:fs'\nimport { basename, posix, relative, resolve, sep } from 'node:path'\nimport { Readable } from 'node:stream'\nimport * as core from '@actions/core'\nimport * as glob from '@actions/glob'\nimport type { Bucket } from '@backblaze-labs/b2-sdk'\nimport { StreamSource } from '@backblaze-labs/b2-sdk/streams'\nimport { tryStat } from '../fs.ts'\nimport {\n type ParsedInputs,\n requireSource,\n uploadFileInfoTotalMaxBytes,\n validateFileInfo,\n} from '../inputs.ts'\nimport { makeProgressListener } from '../progress.ts'\n\n/** One entry in {@link UploadResult.files}. */\nexport interface UploadedFile {\n /** Absolute path on the runner that was uploaded. */\n localPath: string\n /** B2 file name (the key) the upload landed under. */\n fileName: string\n /** B2 file ID assigned by the server. */\n fileId: string\n /** Byte size of the upload. */\n size: number\n /** Whole-file SHA-1, or `null` when the file was multipart-uploaded. */\n contentSha1: string | null\n /**\n * B2 fileInfo metadata for the uploaded object. This is the SDK-returned\n * metadata when available; otherwise it falls back to the canonical metadata\n * submitted in the upload request.\n */\n fileInfo: Record \n}\n\n/** Result of {@link uploadCommand}. */\nexport interface UploadResult {\n /** One entry per uploaded file. Single-file mode returns a one-element array. */\n files: UploadedFile[]\n /** Total bytes uploaded across all files. */\n bytesTransferred: number\n}\n\n/**\n * Upload one or more files to B2.\n *\n * Mode selection:\n * - If `source` is a plain file path (no glob metacharacters and the path\n * exists as a regular file), upload that single file. The B2 file name is\n * `destination` if set; otherwise `basename(source)`.\n * - Otherwise treat `source` (plus any `include` patterns) as glob(s). Each\n * matched file is uploaded preserving its path relative to the glob root,\n * prefixed by `destination` (default empty).\n *\n * Large files are streamed (StreamSource over a fs ReadStream-as-Web-Stream)\n * so we don't buffer the whole payload in RAM. The SDK's `Bucket.upload`\n * routes to multipart automatically when size exceeds the recommended part\n * size and parallelizes parts up to `concurrency`.\n */\nexport async function uploadCommand(\n bucket: Bucket,\n inputs: ParsedInputs,\n signal?: AbortSignal,\n): Promise {\n const source = requireSource(inputs.source, 'upload')\n\n const { files, isSingleExplicitFile } = await resolveFiles(source, inputs.include, inputs.exclude)\n if (files.length === 0) {\n if (inputs.failOnEmpty) {\n throw new Error(`No files matched: ${source}`)\n }\n core.warning(`No files matched: ${source}`)\n return { files: [], bytesTransferred: 0 }\n }\n\n const fileConcurrency = isSingleExplicitFile ? 1 : inputs.concurrency\n // Multi-file uploads spend the concurrency budget across files and keep each\n // file's multipart upload sequential so total in-flight B2 requests remain\n // bounded by the user-supplied `concurrency` value.\n const partConcurrency = isSingleExplicitFile || files.length === 1 ? inputs.concurrency : 1\n\n const uploadPlans = await mapWithConcurrency(files, fileConcurrency, async (f) => {\n signal?.throwIfAborted()\n return await prepareUploadPlan(f, inputs, isSingleExplicitFile)\n })\n\n const uploaded = await mapWithConcurrency(uploadPlans, fileConcurrency, async (plan) => {\n signal?.throwIfAborted()\n const uploadLabel = `upload ${plan.localPath} → b2://${bucket.name}/${plan.fileName}`\n const groupedLog = uploadPlans.length === 1 || fileConcurrency === 1\n if (groupedLog) {\n core.startGroup(uploadLabel)\n } else {\n core.info(uploadLabel)\n }\n try {\n return await uploadOne(bucket, plan, inputs, partConcurrency, groupedLog, signal)\n } finally {\n if (groupedLog) core.endGroup()\n }\n })\n const totalBytes = uploaded.reduce((sum, file) => sum + file.size, 0)\n\n return { files: uploaded, bytesTransferred: totalBytes }\n}\n\nasync function mapWithConcurrency (\n items: T[],\n concurrency: number,\n mapper: (item: T) => Promise,\n): Promise {\n const results = new Array(items.length)\n let next = 0\n let firstError: unknown\n let failed = false\n\n async function worker(): Promise {\n while (true) {\n if (failed) return\n const index = next++\n if (index >= items.length) return\n try {\n results[index] = await mapper(items[index] as T)\n } catch (error) {\n if (!failed) {\n failed = true\n firstError = error\n }\n return\n }\n }\n }\n\n const workerCount = Math.min(concurrency, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n if (failed) throw firstError\n return results\n}\n\ninterface ResolvedFiles {\n files: ResolvedFile[]\n isSingleExplicitFile: boolean\n}\n\n/**\n * Local file resolved from an upload source.\n *\n * @internal\n */\nexport interface ResolvedFile {\n localPath: string\n /** Path relative to the glob root, used when computing the B2 key. */\n fileName: string\n /** Byte size captured while resolving the upload source. */\n size: number\n /** Modification time captured while resolving the upload source. */\n mtimeMs: number\n}\n\ninterface UploadPlan {\n localPath: string\n fileName: string\n size: number\n lastModifiedMillis: number | undefined\n fileInfo: Record \n}\n\nasync function resolveFiles(\n source: string,\n include: string[],\n exclude: string[],\n): Promise {\n const explicitFile = await tryStat(source)\n const looksLikeGlob = /[*?[\\]]/.test(source)\n\n if (explicitFile?.isFile() && !looksLikeGlob && include.length === 0) {\n return {\n files: [\n {\n localPath: resolve(source),\n fileName: basename(source),\n size: explicitFile.size,\n mtimeMs: explicitFile.mtimeMs,\n },\n ],\n isSingleExplicitFile: true,\n }\n }\n\n const patterns: string[] = []\n if (explicitFile?.isDirectory()) {\n patterns.push(`${resolve(source)}/**`)\n } else {\n patterns.push(source)\n }\n for (const p of include) patterns.push(p)\n for (const p of exclude) patterns.push(`!${p}`)\n\n const globber = await glob.create(patterns.join('\\n'), {\n followSymbolicLinks: false,\n matchDirectories: false,\n })\n const matches = await globber.glob()\n const root = explicitFile?.isDirectory() ? resolve(source) : process.cwd()\n\n const out: ResolvedFile[] = []\n for (const m of matches) {\n const s = await tryStat(m)\n // Filesystem boundary: skip entries that aren't readable files (broken\n // symlinks, races where a file is unlinked between glob and stat, etc.).\n if (!s?.isFile()) continue\n const rel = relative(root, m).split(sep).join(posix.sep)\n out.push({ localPath: m, fileName: rel, size: s.size, mtimeMs: s.mtimeMs })\n }\n out.sort(compareResolvedFiles)\n return { files: out, isSingleExplicitFile: false }\n}\n\nfunction compareResolvedFiles(a: ResolvedFile, b: ResolvedFile): number {\n return compareStrings(a.fileName, b.fileName) || compareStrings(a.localPath, b.localPath)\n}\n\nfunction compareStrings(a: string, b: string): number {\n if (a < b) return -1\n if (a > b) return 1\n return 0\n}\n\n/**\n * Map a local source file to its B2 file name under the requested destination.\n *\n * @internal\n */\nexport function remapFileName(\n file: ResolvedFile,\n destination: string | undefined,\n isSingleExplicitFile: boolean,\n): string {\n if (destination === undefined || destination === '') return file.fileName\n const dest = destination.replace(/\\/+$/, '')\n if (isSingleExplicitFile && !destination.endsWith('/')) return dest\n return `${dest}/${file.fileName}`\n}\n\nasync function prepareUploadPlan(\n file: ResolvedFile,\n inputs: ParsedInputs,\n isSingleExplicitFile: boolean,\n): Promise {\n const size = file.size\n const lastModifiedMillis = inputs.preserveMtime ? Math.trunc(file.mtimeMs) : undefined\n const fileInfo = buildUploadFileInfo(inputs.fileInfo, lastModifiedMillis)\n validateFileInfo(fileInfo, uploadFileInfoTotalMaxBytes(inputs.encryption))\n\n return {\n localPath: file.localPath,\n fileName: remapFileName(file, inputs.destination, isSingleExplicitFile),\n size,\n lastModifiedMillis,\n fileInfo,\n }\n}\n\nasync function uploadOne(\n bucket: Bucket,\n plan: UploadPlan,\n inputs: ParsedInputs,\n partConcurrency: number,\n groupedLog: boolean,\n signal?: AbortSignal,\n): Promise {\n const { fileInfo, fileName, lastModifiedMillis, localPath, size } = plan\n\n // Stream the file from disk. The SDK's `bucket.upload` routes files larger\n // than the recommended part size through `uploadLargeFile`, which now\n // detects non-sliceable sources (StreamSource) and reads the stream once,\n // shipping one part at a time. Peak memory ≈ partSize regardless of file\n // size, so multi-GB uploads stay bounded.\n const nodeStream = createReadStream(localPath)\n const webStream = Readable.toWeb(nodeStream) as ReadableStream \n const source = new StreamSource(webStream, size)\n\n const onProgress = makeProgressListener(`upload[${fileName}]`)\n\n // `inputs.resume` is parsed but deliberately NOT forwarded to the SDK.\n // The SDK's resume implementation requires a sliceable source so it can\n // re-upload specific part offsets after a crash. The action uses\n // `StreamSource` (memory-bounded streaming from disk), which is read-once-\n // sequential and not sliceable; passing `resume: true` here would throw\n // `\"resume is not supported on non-sliceable sources\"`. The input is\n // kept in the action surface so this can be re-enabled if the action\n // ever offers a `BufferSource` fallback for users willing to trade RAM\n // for resumability.\n const result = await bucket.upload({\n fileName,\n source,\n concurrency: partConcurrency,\n ...(inputs.partSize !== undefined ? { partSize: inputs.partSize } : {}),\n ...(inputs.contentType !== undefined ? { contentType: inputs.contentType } : {}),\n ...(Object.keys(fileInfo).length > 0 ? { fileInfo } : {}),\n ...(lastModifiedMillis !== undefined ? { lastModifiedMillis } : {}),\n ...(inputs.encryption !== undefined ? { serverSideEncryption: inputs.encryption } : {}),\n ...(signal !== undefined ? { signal } : {}),\n onProgress,\n })\n\n // SDK now normalizes multipart `'none'` to `null` at the boundary, so\n // `result.contentSha1` is `string | null` directly.\n const sha1 = result.contentSha1\n const detailPrefix = groupedLog ? ' ' : ''\n core.info(`${detailPrefix}fileId=${result.fileId} sha1=${sha1 ?? 'multipart'}`)\n const resultFileInfo = Object.keys(result.fileInfo).length > 0 ? result.fileInfo : fileInfo\n\n return {\n localPath,\n fileName: result.fileName,\n fileId: result.fileId,\n size,\n contentSha1: sha1,\n fileInfo: resultFileInfo,\n }\n}\n\nfunction buildUploadFileInfo(\n inputFileInfo: Record ,\n lastModifiedMillis: number | undefined,\n): Record {\n const fileInfo: Record = {}\n for (const [key, value] of Object.entries(inputFileInfo)) {\n const canonicalKey = key.toLowerCase()\n if (Object.hasOwn(fileInfo, canonicalKey)) {\n throw new Error(`Duplicate fileInfo key \"${key}\" from upload metadata`)\n }\n fileInfo[canonicalKey] = value\n }\n if (lastModifiedMillis !== undefined) {\n if (Object.hasOwn(fileInfo, 'src_last_modified_millis')) {\n throw new Error(\n `Duplicate fileInfo key \"src_last_modified_millis\" from 'preserve-mtime' input`,\n )\n }\n fileInfo.src_last_modified_millis = String(lastModifiedMillis)\n }\n return fileInfo\n}\n","import { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport * as core from '@actions/core'\nimport type { Bucket } from '@backblaze-labs/b2-sdk'\nimport { IncrementalSha1 } from '@backblaze-labs/b2-sdk/streams'\nimport { type ParsedInputs, requireSource } from '../inputs.ts'\n\n/** Result of {@link verifyCommand}. */\nexport interface VerifyResult {\n /** B2 file name that was checked. */\n fileName: string\n /** Server-reported byte size of the remote object. */\n remoteSize: number\n /**\n * Remote SHA-1 result: normalized lowercase digest when comparable, raw B2\n * value for non-comparable headers such as `none` or `unverified: `,\n * or `null` when B2 does not expose one.\n */\n remoteSha1: string | null\n /** Locally-computed SHA-1, or `null` if no local file was provided. */\n localSha1: string | null\n /** True when remote SHA-1 matches the expected value. */\n verified: boolean\n /** Human-readable failure reason; `undefined` on success. */\n reason: string | undefined\n}\n\n/**\n * Verify that a B2 object matches a local file (or an expected SHA-1) without\n * transferring the body.\n *\n * Three modes, in priority order:\n * 1. `expected-sha1` input set → compare the remote object's SHA-1 to that\n * literal value. No local read.\n * 2. `destination` input is an existing local file → compute that file's\n * SHA-1 locally and compare to the remote.\n * 3. Neither → fail.\n *\n * In all modes, the remote SHA-1 is fetched via a HEAD request (header\n * `x-bz-content-sha1`). Large files uploaded via multipart return `null` from\n * B2 here because B2 stores the per-part SHA-1s but not a whole-file SHA-1;\n * HEAD-only verification cannot validate those objects, even when\n * `expected-sha1` is supplied.\n */\nexport async function verifyCommand(bucket: Bucket, inputs: ParsedInputs): Promise {\n const source = requireSource(inputs.source, 'verify', 'the B2 file name')\n\n core.startGroup(`verify b2://${bucket.name}/${source}`)\n try {\n // `bucket.head` returns only the parsed response headers; no body to\n // drain. The SDK normalizes multipart `'none'` to `null` at the boundary.\n const { headers } = await bucket.head(source)\n const remoteSize = headers.contentLength\n const remoteSha1 = headers.contentSha1\n\n let localSha1: string | null = null\n let expected: string | null =\n inputs.expectedSha1 !== undefined ? normalizeSha1(inputs.expectedSha1, 'expected-sha1') : null\n\n if (expected === null && inputs.destination !== undefined && inputs.destination !== '') {\n localSha1 = await sha1OfFile(inputs.destination)\n expected = normalizeSha1(localSha1, 'destination')\n }\n\n if (expected === null) {\n throw new Error(\n \"verify needs either 'expected-sha1' (literal) or 'destination' (local file path) to compare against\",\n )\n }\n\n const normalizedRemoteSha1 = remoteSha1 === null ? null : normalizeRemoteSha1(remoteSha1)\n if (normalizedRemoteSha1 === null) {\n const reason = unavailableRemoteSha1Reason(remoteSha1)\n core.warning(` ${reason}`)\n return {\n fileName: source,\n remoteSize,\n remoteSha1,\n localSha1,\n verified: false,\n reason,\n }\n }\n\n const verified = normalizedRemoteSha1 === expected\n const reason = verified\n ? undefined\n : `SHA-1 mismatch: remote=${normalizedRemoteSha1} expected=${expected}`\n if (verified) {\n core.info(` ✓ SHA-1 matches (${normalizedRemoteSha1}), size=${remoteSize}B`)\n } else {\n core.warning(` ${reason}`)\n }\n\n return {\n fileName: source,\n remoteSize,\n remoteSha1: normalizedRemoteSha1,\n localSha1,\n verified,\n reason,\n }\n } finally {\n core.endGroup()\n }\n}\n\n/**\n * Normalize and validate a SHA-1 digest for case-insensitive comparison.\n *\n * @internal\n */\nexport function normalizeSha1(raw: string, label = 'SHA-1'): string {\n const normalized = raw.trim().toLowerCase()\n if (!/^[a-f0-9]{40}$/.test(normalized)) {\n throw new Error(`Invalid ${label}: expected a 40-character hexadecimal SHA-1 digest`)\n }\n return normalized\n}\n\nfunction normalizeRemoteSha1(raw: string): string | null {\n const normalized = raw.trim().toLowerCase()\n return /^[a-f0-9]{40}$/.test(normalized) ? normalized : null\n}\n\nfunction unavailableRemoteSha1Reason(remoteSha1: string | null): string {\n if (remoteSha1 === null) {\n return 'remote SHA-1 is unavailable because B2 does not expose a whole-file SHA-1 for multipart-uploaded files; HEAD-only verify cannot validate this object, even with expected-sha1'\n }\n return `remote SHA-1 is unavailable because B2 reported ${JSON.stringify(remoteSha1)} instead of a verified 40-character whole-file SHA-1; HEAD-only verify cannot validate this object, even with expected-sha1`\n}\n\nasync function sha1OfFile(path: string): Promise