diff --git a/dist/index.js b/dist/index.js index fd169b7..be67d1e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2498,7 +2498,11 @@ function slug(name) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -2511,7 +2515,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -2573,13 +2577,13 @@ class Command { } } function escapeData(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -2597,7 +2601,11 @@ function escapeProperty(s) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -2610,7 +2618,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -2624,7 +2632,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(7351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); @@ -2644,7 +2652,7 @@ var ExitCode; * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +})(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- @@ -2655,13 +2663,13 @@ var ExitCode; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); + const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } - command_1.issueCommand('set-env', { name }, convertedVal); + (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -2669,7 +2677,7 @@ exports.exportVariable = exportVariable; * @param secret value of the secret */ function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); + (0, command_1.issueCommand)('add-mask', {}, secret); } exports.setSecret = setSecret; /** @@ -2679,10 +2687,10 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); + (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { - command_1.issueCommand('add-path', {}, inputPath); + (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } @@ -2757,10 +2765,10 @@ exports.getBooleanInput = getBooleanInput; function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** @@ -2769,7 +2777,7 @@ exports.setOutput = setOutput; * */ function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- @@ -2800,7 +2808,7 @@ exports.isDebug = isDebug; * @param message debug message */ function debug(message) { - command_1.issueCommand('debug', {}, message); + (0, command_1.issueCommand)('debug', {}, message); } exports.debug = debug; /** @@ -2809,7 +2817,7 @@ exports.debug = debug; * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** @@ -2818,7 +2826,7 @@ exports.error = error; * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** @@ -2827,7 +2835,7 @@ exports.warning = warning; * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** @@ -2846,14 +2854,14 @@ exports.info = info; * @param name The name of the output group */ function startGroup(name) { - command_1.issue('group', name); + (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { - command_1.issue('endgroup'); + (0, command_1.issue)('endgroup'); } exports.endGroup = endGroup; /** @@ -2891,9 +2899,9 @@ exports.group = group; function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** @@ -2929,6 +2937,10 @@ var path_utils_1 = __nccwpck_require__(2981); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(5243)); //# sourceMappingURL=core.js.map /***/ }), @@ -2941,7 +2953,11 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -2954,7 +2970,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -2962,9 +2978,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ +const crypto = __importStar(__nccwpck_require__(6113)); const fs = __importStar(__nccwpck_require__(7147)); const os = __importStar(__nccwpck_require__(2037)); -const uuid_1 = __nccwpck_require__(5840); const utils_1 = __nccwpck_require__(5278); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -2974,14 +2990,14 @@ function issueFileCommand(command, message) { if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. @@ -3066,9 +3082,9 @@ class OidcClient { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - core_1.debug(`ID token url is ${id_token_url}`); + (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); + (0, core_1.setSecret)(id_token); return id_token; } catch (error) { @@ -3089,7 +3105,11 @@ exports.OidcClient = OidcClient; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -3102,7 +3122,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -3147,6 +3167,107 @@ exports.toPlatformPath = toPlatformPath; /***/ }), +/***/ 5243: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(2037)); +const exec = __importStar(__nccwpck_require__(1514)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + /***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -10938,8 +11059,9 @@ const pth = __nccwpck_require__(1017); const ZipEntry = __nccwpck_require__(4057); const ZipFile = __nccwpck_require__(7744); -const get_Bool = (val, def) => (typeof val === "boolean" ? val : def); -const get_Str = (val, def) => (typeof val === "string" ? val : def); +const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean"); +const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string"); +const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function"); const defaultOptions = { // option "noSort" : if true it disables files sorting @@ -10981,6 +11103,10 @@ module.exports = function (/**String*/ input, /** object */ options) { // instanciate utils filesystem const filetools = new Utils(opts); + if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") { + opts.decoder = Utils.decoder; + } + // if input is file name we retrieve its content if (input && "string" === typeof input) { // load zip file @@ -10989,20 +11115,20 @@ module.exports = function (/**String*/ input, /** object */ options) { opts.filename = input; inBuffer = filetools.fs.readFileSync(input); } else { - throw new Error(Utils.Errors.INVALID_FILENAME); + throw Utils.Errors.INVALID_FILENAME(); } } // create variable const _zip = new ZipFile(inBuffer, opts); - const { canonical, sanitize } = Utils; + const { canonical, sanitize, zipnamefix } = Utils; function getEntry(/**Object*/ entry) { if (entry && _zip) { var item; // If entry was given as a file name - if (typeof entry === "string") item = _zip.getEntry(entry); + if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry)); // if entry was given as a ZipEntry object if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName); @@ -11019,26 +11145,60 @@ module.exports = function (/**String*/ input, /** object */ options) { return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep)); } + function filenameFilter(filterfn) { + if (filterfn instanceof RegExp) { + // if filter is RegExp wrap it + return (function (rx) { + return function (filename) { + return rx.test(filename); + }; + })(filterfn); + } else if ("function" !== typeof filterfn) { + // if filter is not function we will replace it + return () => true; + } + return filterfn; + } + + // keep last character on folders + const relativePath = (local, entry) => { + let lastChar = entry.slice(-1); + lastChar = lastChar === filetools.sep ? filetools.sep : ""; + return pth.relative(local, entry) + lastChar; + }; + return { /** * Extracts the given entry from the archive and returns the content as a Buffer object - * @param entry ZipEntry object or String with the full path of the entry - * + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {Buffer|string} [pass] - password * @return Buffer or Null in case of error */ - readFile: function (/**Object*/ entry, /*String, Buffer*/ pass) { + readFile: function (entry, pass) { var item = getEntry(entry); return (item && item.getData(pass)) || null; }, + /** + * Returns how many child elements has on entry (directories) on files it is always 0 + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @returns {integer} + */ + childCount: function (entry) { + const item = getEntry(entry); + if (item) { + return _zip.getChildCount(item); + } + }, + /** * Asynchronous readFile - * @param entry ZipEntry object or String with the full path of the entry - * @param callback + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {callback} callback * * @return Buffer or Null in case of error */ - readFileAsync: function (/**Object*/ entry, /**Function*/ callback) { + readFileAsync: function (entry, callback) { var item = getEntry(entry); if (item) { item.getDataAsync(callback); @@ -11049,12 +11209,12 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Extracts the given entry from the archive and returns the content as plain text in the given encoding - * @param entry ZipEntry object or String with the full path of the entry - * @param encoding Optional. If no encoding is specified utf8 is used + * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry + * @param {string} encoding - Optional. If no encoding is specified utf8 is used * * @return String */ - readAsText: function (/**Object*/ entry, /**String=*/ encoding) { + readAsText: function (entry, encoding) { var item = getEntry(entry); if (item) { var data = item.getData(); @@ -11067,13 +11227,13 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Asynchronous readAsText - * @param entry ZipEntry object or String with the full path of the entry - * @param callback - * @param encoding Optional. If no encoding is specified utf8 is used + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {callback} callback + * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used * * @return String */ - readAsTextAsync: function (/**Object*/ entry, /**Function*/ callback, /**String=*/ encoding) { + readAsTextAsync: function (entry, callback, encoding) { var item = getEntry(entry); if (item) { item.getDataAsync(function (data, err) { @@ -11096,11 +11256,26 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory * - * @param entry + * @param {ZipEntry|string} entry + * @returns {void} */ - deleteFile: function (/**Object*/ entry) { + deleteFile: function (entry, withsubfolders = true) { // @TODO: test deleteFile var item = getEntry(entry); + if (item) { + _zip.deleteFile(item.entryName, withsubfolders); + } + }, + + /** + * Remove the entry from the file or directory without affecting any nested entries + * + * @param {ZipEntry|string} entry + * @returns {void} + */ + deleteEntry: function (entry) { + // @TODO: test deleteEntry + var item = getEntry(entry); if (item) { _zip.deleteEntry(item.entryName); } @@ -11109,9 +11284,9 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Adds a comment to the zip. The zip must be rewritten after adding the comment. * - * @param comment + * @param {string} comment */ - addZipComment: function (/**String*/ comment) { + addZipComment: function (comment) { // @TODO: test addZipComment _zip.comment = comment; }, @@ -11129,10 +11304,10 @@ module.exports = function (/**String*/ input, /** object */ options) { * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment * The comment cannot exceed 65535 characters in length * - * @param entry - * @param comment + * @param {ZipEntry} entry + * @param {string} comment */ - addZipEntryComment: function (/**Object*/ entry, /**String*/ comment) { + addZipEntryComment: function (entry, comment) { var item = getEntry(entry); if (item) { item.comment = comment; @@ -11142,10 +11317,10 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Returns the comment of the specified entry * - * @param entry + * @param {ZipEntry} entry * @return String */ - getZipEntryComment: function (/**Object*/ entry) { + getZipEntryComment: function (entry) { var item = getEntry(entry); if (item) { return item.comment || ""; @@ -11156,10 +11331,10 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content * - * @param entry - * @param content + * @param {ZipEntry} entry + * @param {Buffer} content */ - updateFile: function (/**Object*/ entry, /**Buffer*/ content) { + updateFile: function (entry, content) { var item = getEntry(entry); if (item) { item.setData(content); @@ -11169,17 +11344,18 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Adds a file from the disk to the archive * - * @param localPath File to add to zip - * @param zipPath Optional path inside the zip - * @param zipName Optional name for the file + * @param {string} localPath File to add to zip + * @param {string} [zipPath] Optional path inside the zip + * @param {string} [zipName] Optional name for the file + * @param {string} [comment] Optional file comment */ - addLocalFile: function (/**String*/ localPath, /**String=*/ zipPath, /**String=*/ zipName, /**String*/ comment) { + addLocalFile: function (localPath, zipPath, zipName, comment) { if (filetools.fs.existsSync(localPath)) { // fix ZipPath zipPath = zipPath ? fixPath(zipPath) : ""; // p - local file name - var p = localPath.split("\\").join("/").split("/").pop(); + const p = pth.win32.basename(pth.win32.normalize(localPath)); // add file name into zippath zipPath += zipName ? zipName : p; @@ -11187,37 +11363,77 @@ module.exports = function (/**String*/ input, /** object */ options) { // read file attributes const _attr = filetools.fs.statSync(localPath); + // get file content + const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0); + + // if folder + if (_attr.isDirectory()) zipPath += filetools.sep; + // add file into zip file - this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr); + this.addFile(zipPath, data, comment, _attr); } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + throw Utils.Errors.FILE_NOT_FOUND(localPath); } }, + /** + * Callback for showing if everything was done. + * + * @callback doneCallback + * @param {Error} err - Error object + * @param {boolean} done - was request fully completed + */ + + /** + * Adds a file from the disk to the archive + * + * @param {(object|string)} options - options object, if it is string it us used as localPath. + * @param {string} options.localPath - Local path to the file. + * @param {string} [options.comment] - Optional file comment. + * @param {string} [options.zipPath] - Optional path inside the zip + * @param {string} [options.zipName] - Optional name for the file + * @param {doneCallback} callback - The callback that handles the response. + */ + addLocalFileAsync: function (options, callback) { + options = typeof options === "object" ? options : { localPath: options }; + const localPath = pth.resolve(options.localPath); + const { comment } = options; + let { zipPath, zipName } = options; + const self = this; + + filetools.fs.stat(localPath, function (err, stats) { + if (err) return callback(err, false); + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; + // p - local file name + const p = pth.win32.basename(pth.win32.normalize(localPath)); + // add file name into zippath + zipPath += zipName ? zipName : p; + + if (stats.isFile()) { + filetools.fs.readFile(localPath, function (err, data) { + if (err) return callback(err, false); + self.addFile(zipPath, data, comment, stats); + return setImmediate(callback, undefined, true); + }); + } else if (stats.isDirectory()) { + zipPath += filetools.sep; + self.addFile(zipPath, Buffer.alloc(0), comment, stats); + return setImmediate(callback, undefined, true); + } + }); + }, + /** * Adds a local directory and all its nested files and directories to the archive * - * @param localPath - * @param zipPath optional path inside zip - * @param filter optional RegExp or Function if files match will - * be included. - * @param {number | object} attr - number as unix file permissions, object as filesystem Stats object + * @param {string} localPath - local path to the folder + * @param {string} [zipPath] - optional path inside zip + * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included. */ - addLocalFolder: function (/**String*/ localPath, /**String=*/ zipPath, /**=RegExp|Function*/ filter, /**=number|object*/ attr) { + addLocalFolder: function (localPath, zipPath, filter) { // Prepare filter - if (filter instanceof RegExp) { - // if filter is RegExp wrap it - filter = (function (rx) { - return function (filename) { - return rx.test(filename); - }; - })(filter); - } else if ("function" !== typeof filter) { - // if filter is not function we will replace it - filter = function () { - return true; - }; - } + filter = filenameFilter(filter); // fix ZipPath zipPath = zipPath ? fixPath(zipPath) : ""; @@ -11230,43 +11446,29 @@ module.exports = function (/**String*/ input, /** object */ options) { const self = this; if (items.length) { - items.forEach(function (filepath) { - var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix + for (const filepath of items) { + const p = pth.join(zipPath, relativePath(localPath, filepath)); if (filter(p)) { - var stats = filetools.fs.statSync(filepath); - if (stats.isFile()) { - self.addFile(zipPath + p, filetools.fs.readFileSync(filepath), "", attr ? attr : stats); - } else { - self.addFile(zipPath + p + "/", Buffer.alloc(0), "", attr ? attr : stats); - } + self.addLocalFile(filepath, pth.dirname(p)); } - }); + } } } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + throw Utils.Errors.FILE_NOT_FOUND(localPath); } }, /** - * Asynchronous addLocalFile - * @param localPath - * @param callback - * @param zipPath optional path inside zip - * @param filter optional RegExp or Function if files match will + * Asynchronous addLocalFolder + * @param {string} localPath + * @param {callback} callback + * @param {string} [zipPath] optional path inside zip + * @param {RegExp|function} [filter] optional RegExp or Function if files match will * be included. */ - addLocalFolderAsync: function (/*String*/ localPath, /*Function*/ callback, /*String*/ zipPath, /*RegExp|Function*/ filter) { - if (filter instanceof RegExp) { - filter = (function (rx) { - return function (filename) { - return rx.test(filename); - }; - })(filter); - } else if ("function" !== typeof filter) { - filter = function () { - return true; - }; - } + addLocalFolderAsync: function (localPath, callback, zipPath, filter) { + // Prepare filter + filter = filenameFilter(filter); // fix ZipPath zipPath = zipPath ? fixPath(zipPath) : ""; @@ -11277,7 +11479,7 @@ module.exports = function (/**String*/ input, /** object */ options) { var self = this; filetools.fs.open(localPath, "r", function (err) { if (err && err.code === "ENOENT") { - callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); } else if (err) { callback(undefined, err); } else { @@ -11288,7 +11490,7 @@ module.exports = function (/**String*/ input, /** object */ options) { i += 1; if (i < items.length) { var filepath = items[i]; - var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix + var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix p = p .normalize("NFD") .replace(/[\u0300-\u036f]/g, "") @@ -11326,24 +11528,99 @@ module.exports = function (/**String*/ input, /** object */ options) { }, /** + * Adds a local directory and all its nested files and directories to the archive + * + * @param {object | string} options - options object, if it is string it us used as localPath. + * @param {string} options.localPath - Local path to the folder. + * @param {string} [options.zipPath] - optional path inside zip. + * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included. + * @param {function|string} [options.namefix] - optional function to help fix filename + * @param {doneCallback} callback - The callback that handles the response. + * + */ + addLocalFolderAsync2: function (options, callback) { + const self = this; + options = typeof options === "object" ? options : { localPath: options }; + localPath = pth.resolve(fixPath(options.localPath)); + let { zipPath, filter, namefix } = options; + + if (filter instanceof RegExp) { + filter = (function (rx) { + return function (filename) { + return rx.test(filename); + }; + })(filter); + } else if ("function" !== typeof filter) { + filter = function () { + return true; + }; + } + + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; + + // Check Namefix function + if (namefix == "latin1") { + namefix = (str) => + str + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only) + } + + if (typeof namefix !== "function") namefix = (str) => str; + + // internal, create relative path + fix the name + const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry))); + const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry))); + + filetools.fs.open(localPath, "r", function (err) { + if (err && err.code === "ENOENT") { + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); + } else if (err) { + callback(undefined, err); + } else { + filetools.findFilesAsync(localPath, function (err, fileEntries) { + if (err) return callback(err); + fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir))); + if (!fileEntries.length) callback(undefined, false); + + setImmediate( + fileEntries.reverse().reduce(function (next, entry) { + return function (err, done) { + if (err || done === false) return setImmediate(next, err, false); + + self.addLocalFileAsync( + { + localPath: entry, + zipPath: pth.dirname(relPathFix(entry)), + zipName: fileNameFix(entry) + }, + next + ); + }; + }, callback) + ); + }); + } + }); + }, + + /** + * Adds a local directory and all its nested files and directories to the archive * * @param {string} localPath - path where files will be extracted * @param {object} props - optional properties - * @param {string} props.zipPath - optional path inside zip - * @param {regexp, function} props.filter - RegExp or Function if files match will be included. + * @param {string} [props.zipPath] - optional path inside zip + * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included. + * @param {function|string} [props.namefix] - optional function to help fix filename */ - addLocalFolderPromise: function (/*String*/ localPath, /* object */ props) { + addLocalFolderPromise: function (localPath, props) { return new Promise((resolve, reject) => { - const { filter, zipPath } = Object.assign({}, props); - this.addLocalFolderAsync( - localPath, - (done, err) => { - if (err) reject(err); - if (done) resolve(this); - }, - zipPath, - filter - ); + this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => { + if (err) reject(err); + if (done) resolve(this); + }); }); }, @@ -11354,17 +11631,18 @@ module.exports = function (/**String*/ input, /** object */ options) { * * @param {string} entryName * @param {Buffer | string} content - file content as buffer or utf8 coded string - * @param {string} comment - file comment - * @param {number | object} attr - number as unix file permissions, object as filesystem Stats object + * @param {string} [comment] - file comment + * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object */ - addFile: function (/**String*/ entryName, /**Buffer*/ content, /**String*/ comment, /**Number*/ attr) { + addFile: function (entryName, content, comment, attr) { + entryName = zipnamefix(entryName); let entry = getEntry(entryName); const update = entry != null; // prepare new entry if (!update) { - entry = new ZipEntry(); - entry.entryName = Utils.canonical(entryName); + entry = new ZipEntry(opts); + entry.entryName = entryName; } entry.comment = comment || ""; @@ -11406,9 +11684,10 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Returns an array of ZipEntry objects representing the files and folders inside the archive * - * @return Array + * @param {string} [password] + * @returns Array */ - getEntries: function (/**String*/ password) { + getEntries: function (password) { _zip.password = password; return _zip ? _zip.entries : []; }, @@ -11416,7 +11695,7 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Returns a ZipEntry object representing the file or folder specified by ``name``. * - * @param name + * @param {string} name * @return ZipEntry */ getEntry: function (/**String*/ name) { @@ -11435,34 +11714,24 @@ module.exports = function (/**String*/ input, /** object */ options) { * Extracts the given entry to the given targetPath * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted * - * @param entry ZipEntry object or String with the full path of the entry - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder - * will be created in targetPath as well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - * @param keepOriginalPermission The file will be set as the permission from the entry if this is true. - * Default is FALSE - * @param outFileName String If set will override the filename of the extracted file (Only works if the entry is a file) + * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry + * @param {string} targetPath - Target folder where to write the file + * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE + * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true. + * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true. + * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file) * * @return Boolean */ - extractEntryTo: function ( - /**Object*/ entry, - /**String*/ targetPath, - /**Boolean*/ maintainEntryPath, - /**Boolean*/ overwrite, - /**Boolean*/ keepOriginalPermission, - /**String**/ outFileName - ) { - overwrite = get_Bool(overwrite, false); - keepOriginalPermission = get_Bool(keepOriginalPermission, false); - maintainEntryPath = get_Bool(maintainEntryPath, true); - outFileName = get_Str(outFileName, get_Str(keepOriginalPermission, undefined)); + extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) { + overwrite = get_Bool(false, overwrite); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + maintainEntryPath = get_Bool(true, maintainEntryPath); + outFileName = get_Str(keepOriginalPermission, outFileName); var item = getEntry(entry); if (!item) { - throw new Error(Utils.Errors.NO_ENTRY); + throw Utils.Errors.NO_ENTRY(); } var entryName = canonical(item.entryName); @@ -11475,7 +11744,7 @@ module.exports = function (/**String*/ input, /** object */ options) { if (child.isDirectory) return; var content = child.getData(); if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } var name = canonical(child.entryName); var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); @@ -11487,10 +11756,10 @@ module.exports = function (/**String*/ input, /** object */ options) { } var content = item.getData(_zip.password); - if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + if (!content) throw Utils.Errors.CANT_EXTRACT_FILE(); if (filetools.fs.existsSync(target) && !overwrite) { - throw new Error(Utils.Errors.CANT_OVERRIDE); + throw Utils.Errors.CANT_OVERRIDE(); } // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; @@ -11501,7 +11770,7 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Test the archive - * + * @param {string} [pass] */ test: function (pass) { if (!_zip) { @@ -11527,28 +11796,28 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Extracts the entire archive to the given location * - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. + * @param {string} targetPath Target location + * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. * Default is FALSE - * @param keepOriginalPermission The file will be set as the permission from the entry if this is true. + * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. * Default is FALSE + * @param {string|Buffer} [pass] password */ - extractAllTo: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /*String, Buffer*/ pass) { - overwrite = get_Bool(overwrite, false); + extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) { + keepOriginalPermission = get_Bool(false, keepOriginalPermission); pass = get_Str(keepOriginalPermission, pass); - keepOriginalPermission = get_Bool(keepOriginalPermission, false); - if (!_zip) { - throw new Error(Utils.Errors.NO_ZIP); - } + overwrite = get_Bool(false, overwrite); + if (!_zip) throw Utils.Errors.NO_ZIP(); + _zip.entries.forEach(function (entry) { - var entryName = sanitize(targetPath, canonical(entry.entryName.toString())); + var entryName = sanitize(targetPath, canonical(entry.entryName)); if (entry.isDirectory) { filetools.makeDir(entryName); return; } var content = entry.getData(pass); if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; @@ -11556,7 +11825,7 @@ module.exports = function (/**String*/ input, /** object */ options) { try { filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); } catch (err) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } }); }, @@ -11564,18 +11833,17 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Asynchronous extractAllTo * - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. + * @param {string} targetPath Target location + * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. * Default is FALSE - * @param keepOriginalPermission The file will be set as the permission from the entry if this is true. + * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. * Default is FALSE - * @param callback The callback will be executed when all entries are extracted successfully or any error is thrown. + * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown. */ - extractAllToAsync: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /**Function*/ callback) { - if (typeof overwrite === "function" && !callback) callback = overwrite; - overwrite = get_Bool(overwrite, false); - if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission; - keepOriginalPermission = get_Bool(keepOriginalPermission, false); + extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) { + callback = get_Fun(overwrite, keepOriginalPermission, callback); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + overwrite = get_Bool(false, overwrite); if (!callback) { return new Promise((resolve, reject) => { this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) { @@ -11588,13 +11856,13 @@ module.exports = function (/**String*/ input, /** object */ options) { }); } if (!_zip) { - callback(new Error(Utils.Errors.NO_ZIP)); + callback(Utils.Errors.NO_ZIP()); return; } targetPath = pth.resolve(targetPath); // convert entryName to - const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString()))); + const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName))); const getError = (msg, file) => new Error(msg + ': "' + file + '"'); // separate directories from files @@ -11629,13 +11897,13 @@ module.exports = function (/**String*/ input, /** object */ options) { if (err) { next(err); } else { - const entryName = pth.normalize(canonical(entry.entryName.toString())); + const entryName = pth.normalize(canonical(entry.entryName)); const filePath = sanitize(targetPath, entryName); entry.getDataAsync(function (content, err_1) { if (err_1) { - next(new Error(err_1)); + next(err_1); } else if (!content) { - next(new Error(Utils.Errors.CANT_EXTRACT_FILE)); + next(Utils.Errors.CANT_EXTRACT_FILE()); } else { // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; @@ -11661,10 +11929,10 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip * - * @param targetFileName - * @param callback + * @param {string} targetFileName + * @param {function} callback */ - writeZip: function (/**String*/ targetFileName, /**Function*/ callback) { + writeZip: function (targetFileName, callback) { if (arguments.length === 1) { if (typeof targetFileName === "function") { callback = targetFileName; @@ -11684,6 +11952,15 @@ module.exports = function (/**String*/ input, /** object */ options) { } }, + /** + * + * @param {string} targetFileName + * @param {object} [props] + * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true. + * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true. + + * @returns {Promise} + */ writeZipPromise: function (/**String*/ targetFileName, /* object */ props) { const { overwrite, perm } = Object.assign({ overwrite: true }, props); @@ -11699,6 +11976,9 @@ module.exports = function (/**String*/ input, /** object */ options) { }); }, + /** + * @returns {Promise} A promise to the Buffer. + */ toBufferPromise: function () { return new Promise((resolve, reject) => { _zip.toAsyncBuffer(resolve, reject); @@ -11708,10 +11988,13 @@ module.exports = function (/**String*/ input, /** object */ options) { /** * Returns the content of the entire zip file as a Buffer object * - * @return Buffer + * @prop {function} [onSuccess] + * @prop {function} [onFail] + * @prop {function} [onItemStart] + * @prop {function} [onItemEnd] + * @returns {Buffer} */ - toBuffer: function (/**Function=*/ onSuccess, /**Function=*/ onFail, /**Function=*/ onItemStart, /**Function=*/ onItemEnd) { - this.valueOf = 2; + toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) { if (typeof onSuccess === "function") { _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); return null; @@ -11754,21 +12037,16 @@ module.exports = function () { // Without it file names may be corrupted for other apps when file names use unicode chars _flags |= Constants.FLG_EFS; - var _localHeader = {}; + const _localHeader = { + extraLen: 0 + }; - function setTime(val) { - val = new Date(val); - _time = - (((val.getFullYear() - 1980) & 0x7f) << 25) | // b09-16 years from 1980 - ((val.getMonth() + 1) << 21) | // b05-08 month - (val.getDate() << 16) | // b00-04 hour - // 2 bytes time - (val.getHours() << 11) | // b11-15 hour - (val.getMinutes() << 5) | // b05-10 minute - (val.getSeconds() >> 1); // b00-04 seconds divided by 2 - } + // casting + const uint32 = (val) => Math.max(0, val) >>> 0; + const uint16 = (val) => Math.max(0, val) & 0xffff; + const uint8 = (val) => Math.max(0, val) & 0xff; - setTime(+new Date()); + _time = Utils.fromDate2DOS(new Date()); return { get made() { @@ -11792,6 +12070,28 @@ module.exports = function () { _flags = val; }, + get flags_efs() { + return (_flags & Constants.FLG_EFS) > 0; + }, + set flags_efs(val) { + if (val) { + _flags |= Constants.FLG_EFS; + } else { + _flags &= ~Constants.FLG_EFS; + } + }, + + get flags_desc() { + return (_flags & Constants.FLG_DESC) > 0; + }, + set flags_desc(val) { + if (val) { + _flags |= Constants.FLG_DESC; + } else { + _flags &= ~Constants.FLG_DESC; + } + }, + get method() { return _method; }, @@ -11807,33 +12107,41 @@ module.exports = function () { }, get time() { - return new Date(((_time >> 25) & 0x7f) + 1980, ((_time >> 21) & 0x0f) - 1, (_time >> 16) & 0x1f, (_time >> 11) & 0x1f, (_time >> 5) & 0x3f, (_time & 0x1f) << 1); + return Utils.fromDOS2Date(this.timeval); }, set time(val) { - setTime(val); + this.timeval = Utils.fromDate2DOS(val); + }, + + get timeval() { + return _time; + }, + set timeval(val) { + _time = uint32(val); }, + get timeHighByte() { - return (_time >>> 8) & 0xff; + return uint8(_time >>> 8); }, get crc() { return _crc; }, set crc(val) { - _crc = Math.max(0, val) >>> 0; + _crc = uint32(val); }, get compressedSize() { return _compressedSize; }, set compressedSize(val) { - _compressedSize = Math.max(0, val) >>> 0; + _compressedSize = uint32(val); }, get size() { return _size; }, set size(val) { - _size = Math.max(0, val) >>> 0; + _size = uint32(val); }, get fileNameLength() { @@ -11850,6 +12158,13 @@ module.exports = function () { _extraLen = val; }, + get extraLocalLength() { + return _localHeader.extraLen; + }, + set extraLocalLength(val) { + _localHeader.extraLen = val; + }, + get commentLength() { return _comLen; }, @@ -11861,37 +12176,37 @@ module.exports = function () { return _diskStart; }, set diskNumStart(val) { - _diskStart = Math.max(0, val) >>> 0; + _diskStart = uint32(val); }, get inAttr() { return _inattr; }, set inAttr(val) { - _inattr = Math.max(0, val) >>> 0; + _inattr = uint32(val); }, get attr() { return _attr; }, set attr(val) { - _attr = Math.max(0, val) >>> 0; + _attr = uint32(val); }, // get Unix file permissions get fileAttr() { - return _attr ? (((_attr >>> 0) | 0) >> 16) & 0xfff : 0; + return (_attr || 0) >> 16 & 0xfff; }, get offset() { return _offset; }, set offset(val) { - _offset = Math.max(0, val) >>> 0; + _offset = uint32(val); }, get encrypted() { - return (_flags & 1) === 1; + return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC; }, get centralHeaderSize() { @@ -11910,34 +12225,38 @@ module.exports = function () { var data = input.slice(_offset, _offset + Constants.LOCHDR); // 30 bytes and should start with "PK\003\004" if (data.readUInt32LE(0) !== Constants.LOCSIG) { - throw new Error(Utils.Errors.INVALID_LOC); - } - _localHeader = { - // version needed to extract - version: data.readUInt16LE(Constants.LOCVER), - // general purpose bit flag - flags: data.readUInt16LE(Constants.LOCFLG), - // compression method - method: data.readUInt16LE(Constants.LOCHOW), - // modification time (2 bytes time, 2 bytes date) - time: data.readUInt32LE(Constants.LOCTIM), - // uncompressed file crc-32 value - crc: data.readUInt32LE(Constants.LOCCRC), - // compressed size - compressedSize: data.readUInt32LE(Constants.LOCSIZ), - // uncompressed size - size: data.readUInt32LE(Constants.LOCLEN), - // filename length - fnameLen: data.readUInt16LE(Constants.LOCNAM), - // extra field length - extraLen: data.readUInt16LE(Constants.LOCEXT) - }; + throw Utils.Errors.INVALID_LOC(); + } + + // version needed to extract + _localHeader.version = data.readUInt16LE(Constants.LOCVER); + // general purpose bit flag + _localHeader.flags = data.readUInt16LE(Constants.LOCFLG); + // compression method + _localHeader.method = data.readUInt16LE(Constants.LOCHOW); + // modification time (2 bytes time, 2 bytes date) + _localHeader.time = data.readUInt32LE(Constants.LOCTIM); + // uncompressed file crc-32 valu + _localHeader.crc = data.readUInt32LE(Constants.LOCCRC); + // compressed size + _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ); + // uncompressed size + _localHeader.size = data.readUInt32LE(Constants.LOCLEN); + // filename length + _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM); + // extra field length + _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT); + + // read extra data + const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen; + const extraEnd = extraStart + _localHeader.extraLen; + return input.slice(extraStart, extraEnd); }, loadFromBinary: function (/*Buffer*/ data) { // data should be 46 bytes and start with "PK 01 02" if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { - throw new Error(Utils.Errors.INVALID_CEN); + throw Utils.Errors.INVALID_CEN(); } // version made by _verMade = data.readUInt16LE(Constants.CENVEM); @@ -11993,7 +12312,7 @@ module.exports = function () { // filename length data.writeUInt16LE(_fnameLen, Constants.LOCNAM); // extra field length - data.writeUInt16LE(_extraLen, Constants.LOCEXT); + data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT); return data; }, @@ -12032,8 +12351,6 @@ module.exports = function () { data.writeUInt32LE(_attr, Constants.CENATX); // LOC header offset data.writeUInt32LE(_offset, Constants.CENOFF); - // fill all with - data.fill(0x00, Constants.CENHDR); return data; }, @@ -12141,7 +12458,7 @@ module.exports = function () { (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG) ) { - throw new Error(Utils.Errors.INVALID_END); + throw Utils.Errors.INVALID_END(); } if (data.readUInt32LE(0) === Constants.ENDSIG) { @@ -12317,6 +12634,7 @@ module.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) { // node crypt, we use it for generate salt // eslint-disable-next-line node/no-unsupported-features/node-builtins const { randomFillSync } = __nccwpck_require__(6113); +const Errors = __nccwpck_require__(1255); // generate CRC32 lookup table const crctable = new Uint32Array(256).map((t, crc) => { @@ -12438,7 +12756,7 @@ function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) { //3. does password meet expectations if (salt[11] !== verifyByte) { - throw "ADM-ZIP: Wrong Password"; + throw Errors.WRONG_PASSWORD(); } // 4. decode content @@ -12639,19 +12957,36 @@ module.exports = { /***/ }), -/***/ 1255: +/***/ 7396: /***/ ((module) => { module.exports = { + efs: true, + encode: (data) => Buffer.from(data, "utf8"), + decode: (data) => data.toString("utf8") +}; + + +/***/ }), + +/***/ 1255: +/***/ ((__unused_webpack_module, exports) => { + +const errors = { /* Header error messages */ INVALID_LOC: "Invalid LOC header (bad signature)", INVALID_CEN: "Invalid CEN header (bad signature)", INVALID_END: "Invalid END header (bad signature)", + /* Descriptor */ + DESCRIPTOR_NOT_EXIST: "No descriptor present", + DESCRIPTOR_UNKNOWN: "Unknown descriptor format", + DESCRIPTOR_FAULTY: "Descriptor data is malformed", + /* ZipEntry error messages*/ NO_DATA: "Nothing to decompress", - BAD_CRC: "CRC32 checksum failed", - FILE_IN_THE_WAY: "There is a file in the way: %s", + BAD_CRC: "CRC32 checksum failed {0}", + FILE_IN_THE_WAY: "There is a file in the way: {0}", UNKNOWN_METHOD: "Invalid/unsupported compression method", /* Inflater error messages */ @@ -12673,24 +13008,43 @@ module.exports = { NO_ZIP: "No zip file was loaded", NO_ENTRY: "Entry doesn't exist", DIRECTORY_CONTENT_ERROR: "A directory cannot have content", - FILE_NOT_FOUND: "File not found: %s", + FILE_NOT_FOUND: 'File not found: "{0}"', NOT_IMPLEMENTED: "Not implemented", INVALID_FILENAME: "Invalid filename", - INVALID_FORMAT: "Invalid or unsupported zip format. No END header found" + INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", + INVALID_PASS_PARAM: "Incompatible password parameter", + WRONG_PASSWORD: "Wrong Password", + + /* ADM-ZIP */ + COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space) + EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" }; +// template +function E(message) { + return function (...args) { + if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number + message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ''); + } + + return new Error('ADM-ZIP: ' + message); + }; +} + +// Init errors with template +for (const msg of Object.keys(errors)) { + exports[msg] = E(errors[msg]); +} + /***/ }), /***/ 8321: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const fs = (__nccwpck_require__(2895).require)(); const pth = __nccwpck_require__(1017); -fs.existsSync = fs.existsSync || pth.existsSync; - -module.exports = function (/*String*/ path) { +module.exports = function (/*String*/ path, /*Utils object*/ { fs }) { var _path = path || "", _obj = newAttr(), _stat = null; @@ -12766,24 +13120,6 @@ module.exports = function (/*String*/ path) { }; -/***/ }), - -/***/ 2895: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -exports.require = function () { - if (typeof process === "object" && process.versions && process.versions["electron"]) { - try { - const originalFs = __nccwpck_require__(2941); - if (Object.keys(originalFs).length > 0) { - return originalFs; - } - } catch (e) {} - } - return __nccwpck_require__(7147); -}; - - /***/ }), /***/ 5182: @@ -12793,6 +13129,7 @@ module.exports = __nccwpck_require__(1291); module.exports.Constants = __nccwpck_require__(4522); module.exports.Errors = __nccwpck_require__(1255); module.exports.FileAttr = __nccwpck_require__(8321); +module.exports.decoder = __nccwpck_require__(7396); /***/ }), @@ -12800,13 +13137,13 @@ module.exports.FileAttr = __nccwpck_require__(8321); /***/ 1291: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const fsystem = (__nccwpck_require__(2895).require)(); +const fsystem = __nccwpck_require__(7147); const pth = __nccwpck_require__(1017); const Constants = __nccwpck_require__(4522); const Errors = __nccwpck_require__(1255); const isWin = typeof process === "object" && "win32" === process.platform; -const is_Obj = (obj) => obj && typeof obj === "object"; +const is_Obj = (obj) => typeof obj === "object" && obj !== null; // generate CRC32 lookup table const crcTable = new Uint32Array(256).map((t, c) => { @@ -12836,7 +13173,7 @@ function Utils(opts) { module.exports = Utils; -// INSTANCED functions +// INSTANTIABLE functions Utils.prototype.makeDir = function (/*String*/ folder) { const self = this; @@ -12853,7 +13190,7 @@ Utils.prototype.makeDir = function (/*String*/ folder) { } catch (e) { self.fs.mkdirSync(resolvedPath); } - if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath); + if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); }); } @@ -12877,10 +13214,10 @@ Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*B var fd; try { - fd = self.fs.openSync(path, "w", 438); // 0666 + fd = self.fs.openSync(path, "w", 0o666); // 0666 } catch (e) { - self.fs.chmodSync(path, 438); - fd = self.fs.openSync(path, "w", 438); + self.fs.chmodSync(path, 0o666); + fd = self.fs.openSync(path, "w", 0o666); } if (fd) { try { @@ -12889,7 +13226,7 @@ Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*B self.fs.closeSync(fd); } } - self.fs.chmodSync(path, attr || 438); + self.fs.chmodSync(path, attr || 0o666); return true; }; @@ -12913,13 +13250,13 @@ Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content self.fs.exists(folder, function (exists) { if (!exists) self.makeDir(folder); - self.fs.open(path, "w", 438, function (err, fd) { + self.fs.open(path, "w", 0o666, function (err, fd) { if (err) { - self.fs.chmod(path, 438, function () { - self.fs.open(path, "w", 438, function (err, fd) { + self.fs.chmod(path, 0o666, function () { + self.fs.open(path, "w", 0o666, function (err, fd) { self.fs.write(fd, content, 0, content.length, 0, function () { self.fs.close(fd, function () { - self.fs.chmod(path, attr || 438, function () { + self.fs.chmod(path, attr || 0o666, function () { callback(true); }); }); @@ -12929,13 +13266,13 @@ Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content } else if (fd) { self.fs.write(fd, content, 0, content.length, 0, function () { self.fs.close(fd, function () { - self.fs.chmod(path, attr || 438, function () { + self.fs.chmod(path, attr || 0o666, function () { callback(true); }); }); }); } else { - self.fs.chmod(path, attr || 438, function () { + self.fs.chmod(path, attr || 0o666, function () { callback(true); }); } @@ -12955,13 +13292,14 @@ Utils.prototype.findFiles = function (/*String*/ path) { } let files = []; self.fs.readdirSync(dir).forEach(function (file) { - var path = pth.join(dir, file); - - if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); + const path = pth.join(dir, file); + const stat = self.fs.statSync(path); if (!pattern || pattern.test(path)) { - files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : "")); + files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : "")); } + + if (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); }); return files; } @@ -12969,6 +13307,47 @@ Utils.prototype.findFiles = function (/*String*/ path) { return findSync(path, undefined, true); }; +/** + * Callback for showing if everything was done. + * + * @callback filelistCallback + * @param {Error} err - Error object + * @param {string[]} list - was request fully completed + */ + +/** + * + * @param {string} dir + * @param {filelistCallback} cb + */ +Utils.prototype.findFilesAsync = function (dir, cb) { + const self = this; + let results = []; + self.fs.readdir(dir, function (err, list) { + if (err) return cb(err); + let list_length = list.length; + if (!list_length) return cb(null, results); + list.forEach(function (file) { + file = pth.join(dir, file); + self.fs.stat(file, function (err, stat) { + if (err) return cb(err); + if (stat) { + results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : "")); + if (stat.isDirectory()) { + self.findFilesAsync(file, function (err, res) { + if (err) return cb(err); + results = results.concat(res); + if (!--list_length) cb(null, results); + }); + } else { + if (!--list_length) cb(null, results); + } + } + }); + }); + }); +}; + Utils.prototype.getAttributes = function () {}; Utils.prototype.setAttributes = function () {}; @@ -12984,8 +13363,6 @@ Utils.crc32 = function (buf) { if (typeof buf === "string") { buf = Buffer.from(buf, "utf8"); } - // Generate crcTable - if (!crcTable.length) genCRCTable(); let len = buf.length; let crc = ~0; @@ -13005,14 +13382,49 @@ Utils.methodToString = function (/*Number*/ method) { } }; -// removes ".." style path elements +/** + * removes ".." style path elements + * @param {string} path - fixable path + * @returns string - fixed filepath + */ Utils.canonical = function (/*string*/ path) { if (!path) return ""; // trick normalize think path is absolute - var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); return pth.join(".", safeSuffix); }; +/** + * fix file names in achive + * @param {string} path - fixable path + * @returns string - fixed filepath + */ + +Utils.zipnamefix = function (path) { + if (!path) return ""; + // trick normalize think path is absolute + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + return pth.posix.join(".", safeSuffix); +}; + +/** + * + * @param {Array} arr + * @param {function} callback + * @returns + */ +Utils.findLast = function (arr, callback) { + if (!Array.isArray(arr)) throw new TypeError("arr is not array"); + + const len = arr.length >>> 0; + for (let i = len - 1; i >= 0; i--) { + if (callback(arr[i], i, arr)) { + return arr[i]; + } + } + return void 0; +}; + // make abolute paths taking prefix as root folder Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { prefix = pth.resolve(pth.normalize(prefix)); @@ -13027,14 +13439,14 @@ Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { }; // converts buffer, Uint8Array, string types to buffer -Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) { +Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) { if (Buffer.isBuffer(input)) { return input; } else if (input instanceof Uint8Array) { return Buffer.from(input); } else { // expect string all other values are invalid and return empty buffer - return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0); + return typeof input === "string" ? encoder(input) : Buffer.alloc(0); } }; @@ -13045,6 +13457,20 @@ Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) { return parseInt(`0x${slice.toString("hex")}`); }; +Utils.fromDOS2Date = function (val) { + return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1); +}; + +Utils.fromDate2DOS = function (val) { + let date = 0; + let time = 0; + if (val.getFullYear() > 1979) { + date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate(); + time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1); + } + return (date << 16) | time; +}; + Utils.isWin = isWin; // Do we have windows system Utils.crcTable = crcTable; @@ -13059,33 +13485,72 @@ var Utils = __nccwpck_require__(5182), Constants = Utils.Constants, Methods = __nccwpck_require__(3928); -module.exports = function (/*Buffer*/ input) { +module.exports = function (/** object */ options, /*Buffer*/ input) { var _centralHeader = new Headers.EntryHeader(), _entryName = Buffer.alloc(0), _comment = Buffer.alloc(0), _isDirectory = false, uncompressedData = null, - _extra = Buffer.alloc(0); + _extra = Buffer.alloc(0), + _extralocal = Buffer.alloc(0), + _efs = true; + + // assign options + const opts = options; + + const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder; + _efs = decoder.hasOwnProperty("efs") ? decoder.efs : false; function getCompressedDataFromZip() { //if (!input || !Buffer.isBuffer(input)) { if (!input || !(input instanceof Uint8Array)) { return Buffer.alloc(0); } - _centralHeader.loadLocalHeaderFromBinary(input); + _extralocal = _centralHeader.loadLocalHeaderFromBinary(input); return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); } function crc32OK(data) { - // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written - if ((_centralHeader.flags & 0x8) !== 0x8) { + // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written + if (!_centralHeader.flags_desc) { if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { return false; } } else { - // @TODO: load and check data descriptor header - // The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure - // (optionally preceded by a 4-byte signature) immediately after the compressed data: + const descriptor = {}; + const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; + // no descriptor after compressed data, instead new local header + if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { + throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); + } + + // get decriptor data + if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) { + // descriptor with signature + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN); + } else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) { + // descriptor without signature (we check is new header starting where we expect) + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); + } else { + throw Utils.Errors.DESCRIPTOR_UNKNOWN(); + } + + // check data integrity + if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { + throw Utils.Errors.DESCRIPTOR_FAULTY(); + } + if (Utils.crc32(data) !== descriptor.crc) { + return false; + } + + // @TODO: zip64 bit descriptor fields + // if bit 3 is set and any value in local header "zip64 Extended information" extra field are set 0 (place holder) + // then 64-bit descriptor format is used instead of 32-bit + // central header - "zip64 Extended information" extra field should store real values and not place holders } return true; } @@ -13097,7 +13562,7 @@ module.exports = function (/*Buffer*/ input) { } if (_isDirectory) { if (async && callback) { - callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error. + callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error. } return Buffer.alloc(0); } @@ -13112,7 +13577,7 @@ module.exports = function (/*Buffer*/ input) { if (_centralHeader.encrypted) { if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { - throw new Error("ADM-ZIP: Incompatible password parameter"); + throw Utils.Errors.INVALID_PASS_PARAM(); } compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); } @@ -13123,8 +13588,8 @@ module.exports = function (/*Buffer*/ input) { case Utils.Constants.STORED: compressedData.copy(data); if (!crc32OK(data)) { - if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error - throw new Error(Utils.Errors.BAD_CRC); + if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error + throw Utils.Errors.BAD_CRC(); } else { //si added otherwise did not seem to return data. if (async && callback) callback(data); @@ -13136,7 +13601,7 @@ module.exports = function (/*Buffer*/ input) { const result = inflater.inflate(data); result.copy(data, 0); if (!crc32OK(data)) { - throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString()); + throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); } return data; } else { @@ -13144,7 +13609,7 @@ module.exports = function (/*Buffer*/ input) { result.copy(result, 0); if (callback) { if (!crc32OK(result)) { - callback(result, Utils.Errors.BAD_CRC); //si added error + callback(result, Utils.Errors.BAD_CRC()); //si added error } else { callback(result); } @@ -13153,8 +13618,8 @@ module.exports = function (/*Buffer*/ input) { } break; default: - if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD); - throw new Error(Utils.Errors.UNKNOWN_METHOD); + if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); + throw Utils.Errors.UNKNOWN_METHOD(); } } @@ -13207,18 +13672,22 @@ module.exports = function (/*Buffer*/ input) { } function parseExtra(data) { - var offset = 0; - var signature, size, part; - while (offset < data.length) { - signature = data.readUInt16LE(offset); - offset += 2; - size = data.readUInt16LE(offset); - offset += 2; - part = data.slice(offset, offset + size); - offset += size; - if (Constants.ID_ZIP64 === signature) { - parseZip64ExtendedInformation(part); + try { + var offset = 0; + var signature, size, part; + while (offset + 4 < data.length) { + signature = data.readUInt16LE(offset); + offset += 2; + size = data.readUInt16LE(offset); + offset += 2; + part = data.slice(offset, offset + size); + offset += size; + if (Constants.ID_ZIP64 === signature) { + parseZip64ExtendedInformation(part); + } } + } catch (error) { + throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); } } @@ -13254,18 +13723,26 @@ module.exports = function (/*Buffer*/ input) { return { get entryName() { - return _entryName.toString(); + return decoder.decode(_entryName); }, get rawEntryName() { return _entryName; }, set entryName(val) { - _entryName = Utils.toBuffer(val); + _entryName = Utils.toBuffer(val, decoder.encode); var lastChar = _entryName[_entryName.length - 1]; _isDirectory = lastChar === 47 || lastChar === 92; _centralHeader.fileNameLength = _entryName.length; }, + get efs() { + if (typeof _efs === "function") { + return _efs(this.entryName); + } else { + return _efs; + } + }, + get extra() { return _extra; }, @@ -13276,15 +13753,16 @@ module.exports = function (/*Buffer*/ input) { }, get comment() { - return _comment.toString(); + return decoder.decode(_comment); }, set comment(val) { - _comment = Utils.toBuffer(val); + _comment = Utils.toBuffer(val, decoder.encode); _centralHeader.commentLength = _comment.length; + if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG(); }, get name() { - var n = _entryName.toString(); + var n = decoder.decode(_entryName); return _isDirectory ? n .substr(n.length - 1) @@ -13305,7 +13783,7 @@ module.exports = function (/*Buffer*/ input) { }, setData: function (value) { - uncompressedData = Utils.toBuffer(value); + uncompressedData = Utils.toBuffer(value, Utils.decoder.encode); if (!_isDirectory && uncompressedData.length) { _centralHeader.size = uncompressedData.length; _centralHeader.method = Utils.Constants.DEFLATED; @@ -13349,6 +13827,8 @@ module.exports = function (/*Buffer*/ input) { }, packCentralHeader: function () { + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLength = _extra.length; // 1. create header (buffer) var header = _centralHeader.centralHeaderToBinary(); var addpos = Utils.Constants.CENHDR; @@ -13356,24 +13836,21 @@ module.exports = function (/*Buffer*/ input) { _entryName.copy(header, addpos); addpos += _entryName.length; // 3. add extra data - if (_centralHeader.extraLength) { - _extra.copy(header, addpos); - addpos += _centralHeader.extraLength; - } + _extra.copy(header, addpos); + addpos += _centralHeader.extraLength; // 4. add file comment - if (_centralHeader.commentLength) { - _comment.copy(header, addpos); - } + _comment.copy(header, addpos); return header; }, packLocalHeader: function () { let addpos = 0; - + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLocalLength = _extralocal.length; // 1. construct local header Buffer const localHeaderBuf = _centralHeader.localHeaderToBinary(); // 2. localHeader - crate header buffer - const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _extra.length); + const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength); // 2.1 add localheader localHeaderBuf.copy(localHeader, addpos); addpos += localHeaderBuf.length; @@ -13381,8 +13858,8 @@ module.exports = function (/*Buffer*/ input) { _entryName.copy(localHeader, addpos); addpos += _entryName.length; // 2.3 add extra field - _extra.copy(localHeader, addpos); - addpos += _extra.length; + _extralocal.copy(localHeader, addpos); + addpos += _extralocal.length; return localHeader; }, @@ -13426,11 +13903,12 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { mainHeader = new Headers.MainHeader(), loadedEntries = false; var password = null; + const temporary = new Set(); // assign options - const opts = Object.assign(Object.create(null), options); + const opts = options; - const { noSort } = opts; + const { noSort, decoder } = opts; if (inBuffer) { // is a memory buffer @@ -13440,20 +13918,31 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { loadedEntries = true; } - function iterateEntries(callback) { - const totalEntries = mainHeader.diskEntries; // total number of entries - let index = mainHeader.offset; // offset of first CEN header - - for (let i = 0; i < totalEntries; i++) { - let tmp = index; - const entry = new ZipEntry(inBuffer); + function makeTemporaryFolders() { + const foldersList = new Set(); - entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); - entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength)); - - index += entry.header.centralHeaderSize; + // Make list of all folders in file + for (const elem of Object.keys(entryTable)) { + const elements = elem.split("/"); + elements.pop(); // filename + if (!elements.length) continue; // no folders + for (let i = 0; i < elements.length; i++) { + const sub = elements.slice(0, i + 1).join("/") + "/"; + foldersList.add(sub); + } + } - callback(entry); + // create missing folders as temporary + for (const elem of foldersList) { + if (!(elem in entryTable)) { + const tempfolder = new ZipEntry(opts); + tempfolder.entryName = elem; + tempfolder.attr = 0x10; + tempfolder.temporary = true; + entryList.push(tempfolder); + entryTable[tempfolder.entryName] = tempfolder; + temporary.add(tempfolder); + } } } @@ -13461,13 +13950,13 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { loadedEntries = true; entryTable = {}; if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { - throw new Error(Utils.Errors.DISK_ENTRY_TOO_LARGE); + throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); } entryList = new Array(mainHeader.diskEntries); // total number of entries var index = mainHeader.offset; // offset of first CEN header for (var i = 0; i < entryList.length; i++) { var tmp = index, - entry = new ZipEntry(inBuffer); + entry = new ZipEntry(opts, inBuffer); entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength)); @@ -13483,6 +13972,8 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { entryList[i] = entry; entryTable[entry.entryName] = entry; } + temporary.clear(); + makeTemporaryFolders(); } function readMainHeader(/*Boolean*/ readNow) { @@ -13493,6 +13984,10 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { endOffset = -1, // Start offset of the END header commentEnd = 0; + // option to search header form entire file + const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false; + if (trailingSpace) max = 0; + for (i; i >= n; i--) { if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P' if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) { @@ -13519,7 +14014,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { } } - if (!~endOffset) throw new Error(Utils.Errors.INVALID_FORMAT); + if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT(); mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); if (mainHeader.commentLength) { @@ -13543,7 +14038,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { if (!loadedEntries) { readEntries(); } - return entryList; + return entryList.filter((e) => !temporary.has(e)); }, /** @@ -13551,10 +14046,10 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { * @return {String} */ get comment() { - return _comment.toString(); + return decoder.decode(_comment); }, set comment(val) { - _comment = Utils.toBuffer(val); + _comment = Utils.toBuffer(val, decoder.encode); mainHeader.commentLength = _comment.length; }, @@ -13567,12 +14062,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { }, forEach: function (callback) { - if (!loadedEntries) { - iterateEntries(callback); - return; - } - - entryList.forEach(callback); + this.entries.forEach(callback); }, /** @@ -13603,27 +14093,39 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { }, /** - * Removes the entry with the given name from the entry list. + * Removes the file with the given name from the entry list. * * If the entry is a directory, then all nested files and directories will be removed * @param entryName + * @returns {void} + */ + deleteFile: function (/*String*/ entryName, withsubfolders = true) { + if (!loadedEntries) { + readEntries(); + } + const entry = entryTable[entryName]; + const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName); + + list.forEach(this.deleteEntry); + }, + + /** + * Removes the entry with the given name from the entry list. + * + * @param {string} entryName + * @returns {void} */ deleteEntry: function (/*String*/ entryName) { if (!loadedEntries) { readEntries(); } - var entry = entryTable[entryName]; - if (entry && entry.isDirectory) { - var _self = this; - this.getEntryChildren(entry).forEach(function (child) { - if (child.entryName !== entryName) { - _self.deleteEntry(child.entryName); - } - }); + const entry = entryTable[entryName]; + const index = entryList.indexOf(entry); + if (index >= 0) { + entryList.splice(index, 1); + delete entryTable[entryName]; + mainHeader.totalEntries = entryList.length; } - entryList.splice(entryList.indexOf(entry), 1); - delete entryTable[entryName]; - mainHeader.totalEntries = entryList.length; }, /** @@ -13632,25 +14134,42 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { * @param entry * @return Array */ - getEntryChildren: function (/*ZipEntry*/ entry) { + getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) { if (!loadedEntries) { readEntries(); } - if (entry && entry.isDirectory) { - const list = []; - const name = entry.entryName; - const len = name.length; + if (typeof entry === "object") { + if (entry.isDirectory && subfolders) { + const list = []; + const name = entry.entryName; - entryList.forEach(function (zipEntry) { - if (zipEntry.entryName.substr(0, len) === name) { - list.push(zipEntry); + for (const zipEntry of entryList) { + if (zipEntry.entryName.startsWith(name)) { + list.push(zipEntry); + } } - }); - return list; + return list; + } else { + return [entry]; + } } return []; }, + /** + * How many child elements entry has + * + * @param {ZipEntry} entry + * @return {integer} + */ + getChildCount: function (entry) { + if (entry && entry.isDirectory) { + const list = this.getEntryChildren(entry); + return list.includes(entry) ? list.length - 1 : list.length; + } + return 0; + }, + /** * Returns the zip file * @@ -13669,8 +14188,9 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { mainHeader.size = 0; mainHeader.offset = 0; + let totalEntries = 0; - for (const entry of entryList) { + for (const entry of this.entries) { // compress data and set local and entry header accordingly. Reason why is called first const compressedData = entry.getCompressedData(); entry.header.offset = dindex; @@ -13692,11 +14212,13 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { // 5. update main header mainHeader.size += centralHeader.length; totalSize += dataLength + centralHeader.length; + totalEntries++; } totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length // point to end of data and beginning of central directory first record mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; dindex = 0; const outBuffer = Buffer.alloc(totalSize); @@ -13719,6 +14241,13 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { } mh.copy(outBuffer, dindex); + // Since we update entry and main header offsets, + // they are no longer valid and we have to reset content + // (Issue 64) + + inBuffer = outBuffer; + loadedEntries = false; + return outBuffer; }, @@ -13733,6 +14262,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { const centralHeaders = []; let totalSize = 0; let dindex = 0; + let totalEntries = 0; mainHeader.size = 0; mainHeader.offset = 0; @@ -13762,6 +14292,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { centralHeaders.push(centalHeader); mainHeader.size += centalHeader.length; totalSize += dataLength + centalHeader.length; + totalEntries++; compress2Buffer(entryLists); }); @@ -13769,6 +14300,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length // point to end of data and beginning of central directory first record mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; dindex = 0; const outBuffer = Buffer.alloc(totalSize); @@ -13788,11 +14320,18 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { mh.copy(outBuffer, dindex); // write main header + // Since we update entry and main header offsets, they are no + // longer valid and we have to reset content using our new buffer + // (Issue 64) + + inBuffer = outBuffer; + loadedEntries = false; + onSuccess(outBuffer); } }; - compress2Buffer(Array.from(entryList)); + compress2Buffer(Array.from(this.entries)); } catch (e) { onFail(e); } @@ -14013,8 +14552,8 @@ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { - for (let pattern of input) { - let result = braces.create(pattern, options); + for (const pattern of input) { + const result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { @@ -14148,7 +14687,7 @@ braces.create = (input, options = {}) => { return [input]; } - return options.expand !== true + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; @@ -14172,30 +14711,32 @@ const fill = __nccwpck_require__(6330); const utils = __nccwpck_require__(5207); const compile = (ast, options = {}) => { - let walk = (node, parent = {}) => { - let invalidBlock = utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let invalid = invalidBlock === true || invalidNode === true; - let prefix = options.escapeInvalid === true ? '\\' : ''; + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { - return invalid ? (prefix + node.value) : '('; + return invalid ? prefix + node.value : '('; } if (node.type === 'close') { - return invalid ? (prefix + node.value) : ')'; + return invalid ? prefix + node.value : ')'; } if (node.type === 'comma') { - return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } if (node.value) { @@ -14203,8 +14744,8 @@ const compile = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); - let range = fill(...args, { ...options, wrap: false, toRegex: true }); + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; @@ -14212,10 +14753,11 @@ const compile = (ast, options = {}) => { } if (node.nodes) { - for (let child of node.nodes) { + for (const child of node.nodes) { output += walk(child, node); } } + return output; }; @@ -14234,7 +14776,7 @@ module.exports = compile; module.exports = { - MAX_LENGTH: 1024 * 64, + MAX_LENGTH: 10000, // Digits CHAR_0: '0', /* 0 */ @@ -14303,7 +14845,7 @@ const stringify = __nccwpck_require__(8750); const utils = __nccwpck_require__(5207); const append = (queue = '', stash = '', enclose = false) => { - let result = []; + const result = []; queue = [].concat(queue); stash = [].concat(stash); @@ -14313,15 +14855,15 @@ const append = (queue = '', stash = '', enclose = false) => { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } - for (let item of queue) { + for (const item of queue) { if (Array.isArray(item)) { - for (let value of item) { + for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } @@ -14329,9 +14871,9 @@ const append = (queue = '', stash = '', enclose = false) => { }; const expand = (ast, options = {}) => { - let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; - let walk = (node, parent = {}) => { + const walk = (node, parent = {}) => { node.queue = []; let p = parent; @@ -14353,7 +14895,7 @@ const expand = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); + const args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); @@ -14369,7 +14911,7 @@ const expand = (ast, options = {}) => { return; } - let enclose = utils.encloseBrace(node); + const enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; @@ -14379,7 +14921,7 @@ const expand = (ast, options = {}) => { } for (let i = 0; i < node.nodes.length; i++) { - let child = node.nodes[i]; + const child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); @@ -14452,22 +14994,21 @@ const parse = (input, options = {}) => { throw new TypeError('Expected a string'); } - let opts = options || {}; - let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } - let ast = { type: 'root', input, nodes: [] }; - let stack = [ast]; + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; - let length = input.length; + const length = input.length; let index = 0; let depth = 0; let value; - let memo = {}; /** * Helpers @@ -14530,7 +15071,6 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; - let closed = true; let next; while (index < length && (next = advance())) { @@ -14586,7 +15126,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - let open = value; + const open = value; let next; if (options.keepQuotes !== true) { @@ -14618,8 +15158,8 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_CURLY_BRACE) { depth++; - let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; - let brace = { + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { type: 'brace', open: true, close: false, @@ -14646,7 +15186,7 @@ const parse = (input, options = {}) => { continue; } - let type = 'close'; + const type = 'close'; block = stack.pop(); block.close = true; @@ -14664,7 +15204,7 @@ const parse = (input, options = {}) => { if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; - let open = block.nodes.shift(); + const open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } @@ -14678,7 +15218,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { - let siblings = block.nodes; + const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); @@ -14705,7 +15245,7 @@ const parse = (input, options = {}) => { if (prev.type === 'range') { siblings.pop(); - let before = siblings[siblings.length - 1]; + const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; @@ -14738,8 +15278,8 @@ const parse = (input, options = {}) => { }); // get the location of the block on parent.nodes (block's siblings) - let parent = stack[stack.length - 1]; - let index = parent.nodes.indexOf(block); + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } @@ -14763,9 +15303,9 @@ module.exports = parse; const utils = __nccwpck_require__(5207); module.exports = (ast, options = {}) => { - let stringify = (node, parent = {}) => { - let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { @@ -14780,7 +15320,7 @@ module.exports = (ast, options = {}) => { } if (node.nodes) { - for (let child of node.nodes) { + for (const child of node.nodes) { output += stringify(child); } } @@ -14831,7 +15371,7 @@ exports.exceedsLimit = (min, max, step = 1, limit) => { */ exports.escapeNode = (block, n = 0, type) => { - let node = block.nodes[n]; + const node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { @@ -14900,13 +15440,23 @@ exports.reduce = nodes => nodes.reduce((acc, node) => { exports.flatten = (...args) => { const result = []; + const flat = arr => { for (let i = 0; i < arr.length; i++) { - let ele = arr[i]; - Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } } return result; }; + flat(args); return result; }; @@ -16498,11 +17048,19 @@ class EntryFilter { this.index = new Map(); } getFilter(positive, negative) { - const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); - return (entry) => this._filter(entry, positiveRe, negativeRe); + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); } - _filter(entry, positiveRe, negativeRe) { + _filter(entry, patterns) { const filepath = utils.path.removeLeadingDotSegment(entry.path); if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; @@ -16510,11 +17068,7 @@ class EntryFilter { if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } - if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { - return false; - } - const isDirectory = entry.dirent.isDirectory(); - const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); if (this._settings.unique && isMatched) { this._createIndexRecord(filepath); } @@ -16532,14 +17086,32 @@ class EntryFilter { _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } - _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { - if (!this._settings.absolute) { + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { + return false; + } + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { return false; } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); - return utils.pattern.matchAny(fullpath, patternsRe); + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; + } + return true; + } + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); } _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } // Trying to match files and directories by patterns. const isMatched = utils.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. @@ -17281,7 +17853,7 @@ exports.convertPosixPathToPattern = convertPosixPathToPattern; "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; const path = __nccwpck_require__(1017); const globParent = __nccwpck_require__(4460); const micromatch = __nccwpck_require__(6228); @@ -17467,6 +18039,24 @@ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE, '/'); } exports.removeDuplicateSlashes = removeDuplicateSlashes; +function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) { + if (isAbsolute(pattern)) { + absolute.push(pattern); + } + else { + relative.push(pattern); + } + } + return [absolute, relative]; +} +exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; +function isAbsolute(pattern) { + return path.isAbsolute(pattern); +} +exports.isAbsolute = isAbsolute; /***/ }), @@ -17878,7 +18468,7 @@ const toMaxLen = (input, maxLength) => { return negative ? ('-' + input) : input; }; -const toSequence = (parts, options) => { +const toSequence = (parts, options, maxLen) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); @@ -17888,11 +18478,11 @@ const toSequence = (parts, options) => { let result; if (parts.positives.length) { - positives = parts.positives.join('|'); + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); } if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.join('|')})`; + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; } if (positives && negatives) { @@ -17990,7 +18580,7 @@ const fillNumbers = (start, end, step = 1, options = {}) => { if (options.toRegex === true) { return step > 1 - ? toSequence(parts, options) + ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } @@ -18002,7 +18592,6 @@ const fillLetters = (start, end, step = 1, options = {}) => { return invalidRange(start, end, options); } - let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); @@ -23836,7 +24425,12 @@ const util = __nccwpck_require__(3837); const braces = __nccwpck_require__(610); const picomatch = __nccwpck_require__(2864); const utils = __nccwpck_require__(7426); -const isEmptyString = val => val === '' || val === './'; + +const isEmptyString = v => v === '' || v === './'; +const hasBraces = v => { + const index = v.indexOf('{'); + return index > -1 && v.indexOf('}', index) > -1; +}; /** * Returns an array of strings that match one or more glob patterns. @@ -24277,7 +24871,7 @@ micromatch.parse = (patterns, options) => { micromatch.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + if ((options && options.nobrace === true) || !hasBraces(pattern)) { return [pattern]; } return braces(pattern, options); @@ -24296,6 +24890,8 @@ micromatch.braceExpand = (pattern, options) => { * Expose micromatch */ +// exposed for tests +micromatch.hasBraces = hasBraces; module.exports = micromatch; @@ -53526,652 +54122,6 @@ exports.getUserAgent = getUserAgent; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 5840: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "NIL", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "stringify", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); - -var _v = _interopRequireDefault(__nccwpck_require__(8628)); - -var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); - -var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); - -var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); - -var _nil = _interopRequireDefault(__nccwpck_require__(5332)); - -var _version = _interopRequireDefault(__nccwpck_require__(1595)); - -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); - -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/***/ }), - -/***/ 4569: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('md5').update(bytes).digest(); -} - -var _default = md5; -exports["default"] = _default; - -/***/ }), - -/***/ 5332: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; - -/***/ }), - -/***/ 2746: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -var _default = parse; -exports["default"] = _default; - -/***/ }), - -/***/ 814: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports["default"] = _default; - -/***/ }), - -/***/ 807: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - -let poolPtr = rnds8Pool.length; - -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); - - poolPtr = 0; - } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 5274: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('sha1').update(bytes).digest(); -} - -var _default = sha1; -exports["default"] = _default; - -/***/ }), - -/***/ 8950: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; - -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} - -function stringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -var _default = stringify; -exports["default"] = _default; - -/***/ }), - -/***/ 8628: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(807)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; - -let _clockseq; // Previous uuid creation time - - -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf || (0, _stringify.default)(b); -} - -var _default = v1; -exports["default"] = _default; - -/***/ }), - -/***/ 6409: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _v = _interopRequireDefault(__nccwpck_require__(5998)); - -var _md = _interopRequireDefault(__nccwpck_require__(4569)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; - -/***/ }), - -/***/ 5998: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = _default; -exports.URL = exports.DNS = void 0; - -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); - -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function _default(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return (0, _stringify.default)(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 5122: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(807)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function v4(options, buf, offset) { - options = options || {}; - - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return (0, _stringify.default)(rnds); -} - -var _default = v4; -exports["default"] = _default; - -/***/ }), - -/***/ 9120: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _v = _interopRequireDefault(__nccwpck_require__(5998)); - -var _sha = _interopRequireDefault(__nccwpck_require__(5274)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; - -/***/ }), - -/***/ 6900: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _regex = _interopRequireDefault(__nccwpck_require__(814)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} - -var _default = validate; -exports["default"] = _default; - -/***/ }), - -/***/ 1595: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.substr(14, 1), 16); -} - -var _default = version; -exports["default"] = _default; - /***/ }), /***/ 2940: @@ -59229,14 +59179,6 @@ function wrappy (fn, cb) { }).call(this); -/***/ }), - -/***/ 2941: -/***/ ((module) => { - -module.exports = eval("require")("original-fs"); - - /***/ }), /***/ 9491: diff --git a/dist/licenses.txt b/dist/licenses.txt index 0eeea04..96443af 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -378,16 +378,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@vercel/ncc -MIT -Copyright 2018 ZEIT, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - adm-zip MIT MIT License @@ -622,7 +612,7 @@ braces MIT The MIT License (MIT) -Copyright (c) 2014-2018, Jon Schlinkert. +Copyright (c) 2014-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -1490,19 +1480,6 @@ Permission to use, copy, modify, and/or distribute this software for any purpose 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. -uuid -MIT -The MIT License (MIT) - -Copyright (c) 2010-2020 Robert Kieffer and other contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - wrappy ISC The ISC License diff --git a/package-lock.json b/package-lock.json index 60cdb82..0b59b86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,11 +9,11 @@ "version": "2.0.0-preview", "license": "MIT", "dependencies": { - "@actions/core": "^1.10.1", + "@actions/core": "^1.11.1", "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", - "adm-zip": "^0.5.14", - "fast-glob": "^3.3.2", + "adm-zip": "^0.5.16", + "fast-glob": "^3.3.3", "got": "^11.8.6", "picomatch": "^4.0.2", "xml2js": "^0.6.2" @@ -57,12 +57,13 @@ } }, "node_modules/@actions/core": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.1.tgz", - "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.11.1.tgz", + "integrity": "sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==", + "license": "MIT", "dependencies": { - "@actions/http-client": "^2.0.1", - "uuid": "^8.3.2" + "@actions/exec": "^1.1.1", + "@actions/http-client": "^2.0.1" } }, "node_modules/@actions/exec": { @@ -1944,9 +1945,10 @@ } }, "node_modules/adm-zip": { - "version": "0.5.14", - "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.14.tgz", - "integrity": "sha512-DnyqqifT4Jrcvb8USYjp6FHtBpEIz1mnXu6pTRHZ0RL69LbQYiO+0lDFg5+OKA7U29oWSs3a/i8fhn8ZcceIWg==", + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz", + "integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==", + "license": "MIT", "engines": { "node": ">=12.0" } @@ -2349,11 +2351,12 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" @@ -3604,15 +3607,16 @@ "dev": true }, "node_modules/fast-glob": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", - "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", - "micromatch": "^4.0.4" + "micromatch": "^4.0.8" }, "engines": { "node": ">=8.6.0" @@ -3671,9 +3675,10 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -4342,6 +4347,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -5380,11 +5386,12 @@ } }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { @@ -6546,6 +6553,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -6843,6 +6851,7 @@ "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, "bin": { "uuid": "dist/bin/uuid" } diff --git a/package.json b/package.json index 69f2515..ee6f467 100644 --- a/package.json +++ b/package.json @@ -33,11 +33,11 @@ "author": "Michal Dorner ", "license": "MIT", "dependencies": { - "@actions/core": "^1.10.1", + "@actions/core": "^1.11.1", "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", - "adm-zip": "^0.5.14", - "fast-glob": "^3.3.2", + "adm-zip": "^0.5.16", + "fast-glob": "^3.3.3", "got": "^11.8.6", "picomatch": "^4.0.2", "xml2js": "^0.6.2"