From b5f58b2abc5763ade55e4e9d0fe52cd1ff7979ca Mon Sep 17 00:00:00 2001 From: Kevin Stillhammer Date: Thu, 16 Jan 2025 16:38:18 +0100 Subject: [PATCH] Support toml spec 1.0.0 (#245) iarna/toml is unmaintained. Replaced by smol-toml which is maintained and has the same api Fixes: #242 --- .../pyproject-toml-project/pyproject.toml | 9 + dist/save-cache/index.js | 325 +- dist/setup/index.js | 3641 ++++++----------- dist/update-known-checksums/index.js | 116 +- package-lock.json | 30 +- package.json | 2 +- src/utils/pyproject.ts | 2 +- tsconfig.json | 2 +- 8 files changed, 1350 insertions(+), 2777 deletions(-) diff --git a/__tests__/fixtures/pyproject-toml-project/pyproject.toml b/__tests__/fixtures/pyproject-toml-project/pyproject.toml index 55ad9ab..5bacb75 100644 --- a/__tests__/fixtures/pyproject-toml-project/pyproject.toml +++ b/__tests__/fixtures/pyproject-toml-project/pyproject.toml @@ -6,5 +6,14 @@ readme = "README.md" requires-python = ">=3.11" dependencies = [] +[dependency-groups] +dev = [ + "reuse==5.0.2", + {include-group = "lint"}, +] +lint = [ + "flake8==4.0.1", +] + [tool.uv] required-version = "==0.5.14" diff --git a/dist/save-cache/index.js b/dist/save-cache/index.js index 5f7403d..098a2d6 100644 --- a/dist/save-cache/index.js +++ b/dist/save-cache/index.js @@ -91444,15 +91444,6 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STATE_CACHE_MATCHED_KEY = exports.STATE_CACHE_KEY = void 0; exports.restoreCache = restoreCache; @@ -91465,71 +91456,65 @@ const exec = __importStar(__nccwpck_require__(5236)); exports.STATE_CACHE_KEY = "cache-key"; exports.STATE_CACHE_MATCHED_KEY = "cache-matched-key"; const CACHE_VERSION = "1"; -function restoreCache() { - return __awaiter(this, void 0, void 0, function* () { - const cacheKey = yield computeKeys(); - let matchedKey; - core.info(`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`); - try { - matchedKey = yield cache.restoreCache([inputs_1.cacheLocalPath], cacheKey); - } - catch (err) { - const message = err.message; - core.warning(message); - core.setOutput("cache-hit", false); - return; - } - core.saveState(exports.STATE_CACHE_KEY, cacheKey); - handleMatchResult(matchedKey, cacheKey); - }); +async function restoreCache() { + const cacheKey = await computeKeys(); + let matchedKey; + core.info(`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`); + try { + matchedKey = await cache.restoreCache([inputs_1.cacheLocalPath], cacheKey); + } + catch (err) { + const message = err.message; + core.warning(message); + core.setOutput("cache-hit", false); + return; + } + core.saveState(exports.STATE_CACHE_KEY, cacheKey); + handleMatchResult(matchedKey, cacheKey); } -function computeKeys() { - return __awaiter(this, void 0, void 0, function* () { - let cacheDependencyPathHash = "-"; - if (inputs_1.cacheDependencyGlob !== "") { - core.info(`Searching files using cache dependency glob: ${inputs_1.cacheDependencyGlob.split("\n").join(",")}`); - cacheDependencyPathHash += yield (0, hash_files_1.hashFiles)(inputs_1.cacheDependencyGlob, true); - if (cacheDependencyPathHash === "-") { - core.warning(`No file matched to [${inputs_1.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`); - } - } +async function computeKeys() { + let cacheDependencyPathHash = "-"; + if (inputs_1.cacheDependencyGlob !== "") { + core.info(`Searching files using cache dependency glob: ${inputs_1.cacheDependencyGlob.split("\n").join(",")}`); + cacheDependencyPathHash += await (0, hash_files_1.hashFiles)(inputs_1.cacheDependencyGlob, true); if (cacheDependencyPathHash === "-") { - cacheDependencyPathHash = "-no-dependency-glob"; + core.warning(`No file matched to [${inputs_1.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`); } - const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : ""; - const pythonVersion = yield getPythonVersion(); - return `setup-uv-${CACHE_VERSION}-${(0, platforms_1.getArch)()}-${(0, platforms_1.getPlatform)()}-${pythonVersion}${cacheDependencyPathHash}${suffix}`; - }); + } + if (cacheDependencyPathHash === "-") { + cacheDependencyPathHash = "-no-dependency-glob"; + } + const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : ""; + const pythonVersion = await getPythonVersion(); + return `setup-uv-${CACHE_VERSION}-${(0, platforms_1.getArch)()}-${(0, platforms_1.getPlatform)()}-${pythonVersion}${cacheDependencyPathHash}${suffix}`; } -function getPythonVersion() { - return __awaiter(this, void 0, void 0, function* () { - if (inputs_1.pythonVersion !== "") { - return inputs_1.pythonVersion; - } - let output = ""; - const options = { - silent: !core.isDebug(), - listeners: { - stdout: (data) => { - output += data.toString(); - }, +async function getPythonVersion() { + if (inputs_1.pythonVersion !== "") { + return inputs_1.pythonVersion; + } + let output = ""; + const options = { + silent: !core.isDebug(), + listeners: { + stdout: (data) => { + output += data.toString(); }, - }; - try { - const execArgs = ["python", "find"]; - yield exec.exec("uv", execArgs, options); - const pythonPath = output.trim(); - output = ""; - yield exec.exec(pythonPath, ["--version"], options); - // output is like "Python 3.8.10" - return output.split(" ")[1].trim(); - } - catch (error) { - const err = error; - core.debug(`Failed to get python version from uv. Error: ${err.message}`); - return "unknown"; - } - }); + }, + }; + try { + const execArgs = ["python", "find"]; + await exec.exec("uv", execArgs, options); + const pythonPath = output.trim(); + output = ""; + await exec.exec(pythonPath, ["--version"], options); + // output is like "Python 3.8.10" + return output.split(" ")[1].trim(); + } + catch (error) { + const err = error; + core.debug(`Failed to get python version from uv. Error: ${err.message}`); + return "unknown"; + } } function handleMatchResult(matchedKey, primaryKey) { if (!matchedKey) { @@ -91583,22 +91568,6 @@ var __importStar = (this && this.__importStar) || (function () { 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 __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.hashFiles = hashFiles; const crypto = __importStar(__nccwpck_require__(7598)); @@ -91615,49 +91584,34 @@ const glob_1 = __nccwpck_require__(7206); * @param pattern The glob pattern to match files. * @param verbose Whether to log the files being hashed. */ -function hashFiles(pattern_1) { - return __awaiter(this, arguments, void 0, function* (pattern, verbose = false) { - var _a, e_1, _b, _c; - const globber = yield (0, glob_1.create)(pattern); - let hasMatch = false; - const writeDelegate = verbose ? core.info : core.debug; - const result = crypto.createHash("sha256"); - let count = 0; - try { - for (var _d = true, _e = __asyncValues(globber.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const file = _c; - writeDelegate(file); - if (fs.statSync(file).isDirectory()) { - writeDelegate(`Skip directory '${file}'.`); - continue; - } - const hash = crypto.createHash("sha256"); - const pipeline = util.promisify(stream.pipeline); - yield pipeline(fs.createReadStream(file), hash); - result.write(hash.digest()); - count++; - if (!hasMatch) { - hasMatch = true; - } - } +async function hashFiles(pattern, verbose = false) { + const globber = await (0, glob_1.create)(pattern); + let hasMatch = false; + const writeDelegate = verbose ? core.info : core.debug; + const result = crypto.createHash("sha256"); + let count = 0; + for await (const file of globber.globGenerator()) { + writeDelegate(file); + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); - } - finally { if (e_1) throw e_1.error; } + const hash = crypto.createHash("sha256"); + const pipeline = util.promisify(stream.pipeline); + await pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; } - result.end(); - if (hasMatch) { - writeDelegate(`Found ${count} files to hash.`); - return result.digest("hex"); - } - writeDelegate("No matches found for glob"); - return ""; - }); + } + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest("hex"); + } + writeDelegate("No matches found for glob"); + return ""; } @@ -91701,15 +91655,6 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.run = run; const cache = __importStar(__nccwpck_require__(5116)); @@ -91718,69 +91663,63 @@ const exec = __importStar(__nccwpck_require__(5236)); const fs = __importStar(__nccwpck_require__(3024)); const restore_cache_1 = __nccwpck_require__(5391); const inputs_1 = __nccwpck_require__(9612); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - if (inputs_1.enableCache) { - yield saveCache(); - // node will stay alive if any promises are not resolved, - // which is a possibility if HTTP requests are dangling - // due to retries or timeouts. We know that if we got here - // that all promises that we care about have successfully - // resolved, so simply exit with success. - process.exit(0); - } +async function run() { + try { + if (inputs_1.enableCache) { + await saveCache(); + // node will stay alive if any promises are not resolved, + // which is a possibility if HTTP requests are dangling + // due to retries or timeouts. We know that if we got here + // that all promises that we care about have successfully + // resolved, so simply exit with success. + process.exit(0); } - catch (error) { - const err = error; - core.setFailed(err.message); - } - }); + } + catch (error) { + const err = error; + core.setFailed(err.message); + } } -function saveCache() { - return __awaiter(this, void 0, void 0, function* () { - const cacheKey = core.getState(restore_cache_1.STATE_CACHE_KEY); - const matchedKey = core.getState(restore_cache_1.STATE_CACHE_MATCHED_KEY); - if (!cacheKey) { - core.warning("Error retrieving cache key from state."); - return; +async function saveCache() { + const cacheKey = core.getState(restore_cache_1.STATE_CACHE_KEY); + const matchedKey = core.getState(restore_cache_1.STATE_CACHE_MATCHED_KEY); + if (!cacheKey) { + core.warning("Error retrieving cache key from state."); + return; + } + if (matchedKey === cacheKey) { + core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`); + return; + } + if (inputs_1.pruneCache) { + await pruneCache(); + } + core.info(`Saving cache path: ${inputs_1.cacheLocalPath}`); + if (!fs.existsSync(inputs_1.cacheLocalPath) && !inputs_1.ignoreNothingToCache) { + throw new Error(`Cache path ${inputs_1.cacheLocalPath} does not exist on disk. This likely indicates that there are no dependencies to cache. Consider disabling the cache input if it is not needed.`); + } + try { + await cache.saveCache([inputs_1.cacheLocalPath], cacheKey); + core.info(`cache saved with the key: ${cacheKey}`); + } + catch (e) { + if (e instanceof Error && + e.message === + "Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.") { + core.info("No cacheable paths were found. Ignoring because ignore-nothing-to-save is enabled."); } - if (matchedKey === cacheKey) { - core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`); - return; + else { + throw e; } - if (inputs_1.pruneCache) { - yield pruneCache(); - } - core.info(`Saving cache path: ${inputs_1.cacheLocalPath}`); - if (!fs.existsSync(inputs_1.cacheLocalPath) && !inputs_1.ignoreNothingToCache) { - throw new Error(`Cache path ${inputs_1.cacheLocalPath} does not exist on disk. This likely indicates that there are no dependencies to cache. Consider disabling the cache input if it is not needed.`); - } - try { - yield cache.saveCache([inputs_1.cacheLocalPath], cacheKey); - core.info(`cache saved with the key: ${cacheKey}`); - } - catch (e) { - if (e instanceof Error && - e.message === - "Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.") { - core.info("No cacheable paths were found. Ignoring because ignore-nothing-to-save is enabled."); - } - else { - throw e; - } - } - }); + } } -function pruneCache() { - return __awaiter(this, void 0, void 0, function* () { - const options = { - silent: !core.isDebug(), - }; - const execArgs = ["cache", "prune", "--ci"]; - core.info("Pruning cache..."); - yield exec.exec("uv", execArgs, options); - }); +async function pruneCache() { + const options = { + silent: !core.isDebug(), + }; + const execArgs = ["cache", "prune", "--ci"]; + core.info("Pruning cache..."); + await exec.exec("uv", execArgs, options); } run(); diff --git a/dist/setup/index.js b/dist/setup/index.js index f22218c..64098a3 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -48107,2174 +48107,6 @@ var __disposeResources; }); -/***/ }), - -/***/ 8557: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const f = __nccwpck_require__(9470) -const DateTime = global.Date - -class Date extends DateTime { - constructor (value) { - super(value) - this.isDate = true - } - toISOString () { - return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` - } -} - -module.exports = value => { - const date = new Date(value) - /* istanbul ignore if */ - if (isNaN(date)) { - throw new TypeError('Invalid Datetime') - } else { - return date - } -} - - -/***/ }), - -/***/ 9487: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const f = __nccwpck_require__(9470) - -class FloatingDateTime extends Date { - constructor (value) { - super(value + 'Z') - this.isFloating = true - } - toISOString () { - const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}` - const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` - return `${date}T${time}` - } -} - -module.exports = value => { - const date = new FloatingDateTime(value) - /* istanbul ignore if */ - if (isNaN(date)) { - throw new TypeError('Invalid Datetime') - } else { - return date - } -} - - -/***/ }), - -/***/ 6376: -/***/ ((module) => { - -"use strict"; - -module.exports = value => { - const date = new Date(value) - /* istanbul ignore if */ - if (isNaN(date)) { - throw new TypeError('Invalid Datetime') - } else { - return date - } -} - - -/***/ }), - -/***/ 420: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const f = __nccwpck_require__(9470) - -class Time extends Date { - constructor (value) { - super(`0000-01-01T${value}Z`) - this.isTime = true - } - toISOString () { - return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}` - } -} - -module.exports = value => { - const date = new Time(value) - /* istanbul ignore if */ - if (isNaN(date)) { - throw new TypeError('Invalid Datetime') - } else { - return date - } -} - - -/***/ }), - -/***/ 9470: -/***/ ((module) => { - -"use strict"; - -module.exports = (d, num) => { - num = String(num) - while (num.length < d) num = '0' + num - return num -} - - -/***/ }), - -/***/ 5991: -/***/ ((module) => { - -"use strict"; - -const ParserEND = 0x110000 -class ParserError extends Error { - /* istanbul ignore next */ - constructor (msg, filename, linenumber) { - super('[ParserError] ' + msg, filename, linenumber) - this.name = 'ParserError' - this.code = 'ParserError' - if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError) - } -} -class State { - constructor (parser) { - this.parser = parser - this.buf = '' - this.returned = null - this.result = null - this.resultTable = null - this.resultArr = null - } -} -class Parser { - constructor () { - this.pos = 0 - this.col = 0 - this.line = 0 - this.obj = {} - this.ctx = this.obj - this.stack = [] - this._buf = '' - this.char = null - this.ii = 0 - this.state = new State(this.parseStart) - } - - parse (str) { - /* istanbul ignore next */ - if (str.length === 0 || str.length == null) return - - this._buf = String(str) - this.ii = -1 - this.char = -1 - let getNext - while (getNext === false || this.nextChar()) { - getNext = this.runOne() - } - this._buf = null - } - nextChar () { - if (this.char === 0x0A) { - ++this.line - this.col = -1 - } - ++this.ii - this.char = this._buf.codePointAt(this.ii) - ++this.pos - ++this.col - return this.haveBuffer() - } - haveBuffer () { - return this.ii < this._buf.length - } - runOne () { - return this.state.parser.call(this, this.state.returned) - } - finish () { - this.char = ParserEND - let last - do { - last = this.state.parser - this.runOne() - } while (this.state.parser !== last) - - this.ctx = null - this.state = null - this._buf = null - - return this.obj - } - next (fn) { - /* istanbul ignore next */ - if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn)) - this.state.parser = fn - } - goto (fn) { - this.next(fn) - return this.runOne() - } - call (fn, returnWith) { - if (returnWith) this.next(returnWith) - this.stack.push(this.state) - this.state = new State(fn) - } - callNow (fn, returnWith) { - this.call(fn, returnWith) - return this.runOne() - } - return (value) { - /* istanbul ignore next */ - if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow')) - if (value === undefined) value = this.state.buf - this.state = this.stack.pop() - this.state.returned = value - } - returnNow (value) { - this.return(value) - return this.runOne() - } - consume () { - /* istanbul ignore next */ - if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer')) - this.state.buf += this._buf[this.ii] - } - error (err) { - err.line = this.line - err.col = this.col - err.pos = this.pos - return err - } - /* istanbul ignore next */ - parseStart () { - throw new ParserError('Must declare a parseStart method') - } -} -Parser.END = ParserEND -Parser.Error = ParserError -module.exports = Parser - - -/***/ }), - -/***/ 2862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */ -module.exports = makeParserClass(__nccwpck_require__(5991)) -module.exports.makeParserClass = makeParserClass - -class TomlError extends Error { - constructor (msg) { - super(msg) - this.name = 'TomlError' - /* istanbul ignore next */ - if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError) - this.fromTOML = true - this.wrapped = null - } -} -TomlError.wrap = err => { - const terr = new TomlError(err.message) - terr.code = err.code - terr.wrapped = err - return terr -} -module.exports.TomlError = TomlError - -const createDateTime = __nccwpck_require__(6376) -const createDateTimeFloat = __nccwpck_require__(9487) -const createDate = __nccwpck_require__(8557) -const createTime = __nccwpck_require__(420) - -const CTRL_I = 0x09 -const CTRL_J = 0x0A -const CTRL_M = 0x0D -const CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL -const CHAR_SP = 0x20 -const CHAR_QUOT = 0x22 -const CHAR_NUM = 0x23 -const CHAR_APOS = 0x27 -const CHAR_PLUS = 0x2B -const CHAR_COMMA = 0x2C -const CHAR_HYPHEN = 0x2D -const CHAR_PERIOD = 0x2E -const CHAR_0 = 0x30 -const CHAR_1 = 0x31 -const CHAR_7 = 0x37 -const CHAR_9 = 0x39 -const CHAR_COLON = 0x3A -const CHAR_EQUALS = 0x3D -const CHAR_A = 0x41 -const CHAR_E = 0x45 -const CHAR_F = 0x46 -const CHAR_T = 0x54 -const CHAR_U = 0x55 -const CHAR_Z = 0x5A -const CHAR_LOWBAR = 0x5F -const CHAR_a = 0x61 -const CHAR_b = 0x62 -const CHAR_e = 0x65 -const CHAR_f = 0x66 -const CHAR_i = 0x69 -const CHAR_l = 0x6C -const CHAR_n = 0x6E -const CHAR_o = 0x6F -const CHAR_r = 0x72 -const CHAR_s = 0x73 -const CHAR_t = 0x74 -const CHAR_u = 0x75 -const CHAR_x = 0x78 -const CHAR_z = 0x7A -const CHAR_LCUB = 0x7B -const CHAR_RCUB = 0x7D -const CHAR_LSQB = 0x5B -const CHAR_BSOL = 0x5C -const CHAR_RSQB = 0x5D -const CHAR_DEL = 0x7F -const SURROGATE_FIRST = 0xD800 -const SURROGATE_LAST = 0xDFFF - -const escapes = { - [CHAR_b]: '\u0008', - [CHAR_t]: '\u0009', - [CHAR_n]: '\u000A', - [CHAR_f]: '\u000C', - [CHAR_r]: '\u000D', - [CHAR_QUOT]: '\u0022', - [CHAR_BSOL]: '\u005C' -} - -function isDigit (cp) { - return cp >= CHAR_0 && cp <= CHAR_9 -} -function isHexit (cp) { - return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9) -} -function isBit (cp) { - return cp === CHAR_1 || cp === CHAR_0 -} -function isOctit (cp) { - return (cp >= CHAR_0 && cp <= CHAR_7) -} -function isAlphaNumQuoteHyphen (cp) { - return (cp >= CHAR_A && cp <= CHAR_Z) - || (cp >= CHAR_a && cp <= CHAR_z) - || (cp >= CHAR_0 && cp <= CHAR_9) - || cp === CHAR_APOS - || cp === CHAR_QUOT - || cp === CHAR_LOWBAR - || cp === CHAR_HYPHEN -} -function isAlphaNumHyphen (cp) { - return (cp >= CHAR_A && cp <= CHAR_Z) - || (cp >= CHAR_a && cp <= CHAR_z) - || (cp >= CHAR_0 && cp <= CHAR_9) - || cp === CHAR_LOWBAR - || cp === CHAR_HYPHEN -} -const _type = Symbol('type') -const _declared = Symbol('declared') - -const hasOwnProperty = Object.prototype.hasOwnProperty -const defineProperty = Object.defineProperty -const descriptor = {configurable: true, enumerable: true, writable: true, value: undefined} - -function hasKey (obj, key) { - if (hasOwnProperty.call(obj, key)) return true - if (key === '__proto__') defineProperty(obj, '__proto__', descriptor) - return false -} - -const INLINE_TABLE = Symbol('inline-table') -function InlineTable () { - return Object.defineProperties({}, { - [_type]: {value: INLINE_TABLE} - }) -} -function isInlineTable (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === INLINE_TABLE -} - -const TABLE = Symbol('table') -function Table () { - return Object.defineProperties({}, { - [_type]: {value: TABLE}, - [_declared]: {value: false, writable: true} - }) -} -function isTable (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === TABLE -} - -const _contentType = Symbol('content-type') -const INLINE_LIST = Symbol('inline-list') -function InlineList (type) { - return Object.defineProperties([], { - [_type]: {value: INLINE_LIST}, - [_contentType]: {value: type} - }) -} -function isInlineList (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === INLINE_LIST -} - -const LIST = Symbol('list') -function List () { - return Object.defineProperties([], { - [_type]: {value: LIST} - }) -} -function isList (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === LIST -} - -// in an eval, to let bundlers not slurp in a util proxy -let _custom -try { - const utilInspect = eval("require('util').inspect") - _custom = utilInspect.custom -} catch (_) { - /* eval require not available in transpiled bundle */ -} -/* istanbul ignore next */ -const _inspect = _custom || 'inspect' - -class BoxedBigInt { - constructor (value) { - try { - this.value = global.BigInt.asIntN(64, value) - } catch (_) { - /* istanbul ignore next */ - this.value = null - } - Object.defineProperty(this, _type, {value: INTEGER}) - } - isNaN () { - return this.value === null - } - /* istanbul ignore next */ - toString () { - return String(this.value) - } - /* istanbul ignore next */ - [_inspect] () { - return `[BigInt: ${this.toString()}]}` - } - valueOf () { - return this.value - } -} - -const INTEGER = Symbol('integer') -function Integer (value) { - let num = Number(value) - // -0 is a float thing, not an int thing - if (Object.is(num, -0)) num = 0 - /* istanbul ignore else */ - if (global.BigInt && !Number.isSafeInteger(num)) { - return new BoxedBigInt(value) - } else { - /* istanbul ignore next */ - return Object.defineProperties(new Number(num), { - isNaN: {value: function () { return isNaN(this) }}, - [_type]: {value: INTEGER}, - [_inspect]: {value: () => `[Integer: ${value}]`} - }) - } -} -function isInteger (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === INTEGER -} - -const FLOAT = Symbol('float') -function Float (value) { - /* istanbul ignore next */ - return Object.defineProperties(new Number(value), { - [_type]: {value: FLOAT}, - [_inspect]: {value: () => `[Float: ${value}]`} - }) -} -function isFloat (obj) { - if (obj === null || typeof (obj) !== 'object') return false - return obj[_type] === FLOAT -} - -function tomlType (value) { - const type = typeof value - if (type === 'object') { - /* istanbul ignore if */ - if (value === null) return 'null' - if (value instanceof Date) return 'datetime' - /* istanbul ignore else */ - if (_type in value) { - switch (value[_type]) { - case INLINE_TABLE: return 'inline-table' - case INLINE_LIST: return 'inline-list' - /* istanbul ignore next */ - case TABLE: return 'table' - /* istanbul ignore next */ - case LIST: return 'list' - case FLOAT: return 'float' - case INTEGER: return 'integer' - } - } - } - return type -} - -function makeParserClass (Parser) { - class TOMLParser extends Parser { - constructor () { - super() - this.ctx = this.obj = Table() - } - - /* MATCH HELPER */ - atEndOfWord () { - return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine() - } - atEndOfLine () { - return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M - } - - parseStart () { - if (this.char === Parser.END) { - return null - } else if (this.char === CHAR_LSQB) { - return this.call(this.parseTableOrList) - } else if (this.char === CHAR_NUM) { - return this.call(this.parseComment) - } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { - return null - } else if (isAlphaNumQuoteHyphen(this.char)) { - return this.callNow(this.parseAssignStatement) - } else { - throw this.error(new TomlError(`Unknown character "${this.char}"`)) - } - } - - // HELPER, this strips any whitespace and comments to the end of the line - // then RETURNS. Last state in a production. - parseWhitespaceToEOL () { - if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { - return null - } else if (this.char === CHAR_NUM) { - return this.goto(this.parseComment) - } else if (this.char === Parser.END || this.char === CTRL_J) { - return this.return() - } else { - throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line')) - } - } - - /* ASSIGNMENT: key = value */ - parseAssignStatement () { - return this.callNow(this.parseAssign, this.recordAssignStatement) - } - recordAssignStatement (kv) { - let target = this.ctx - let finalKey = kv.key.pop() - for (let kw of kv.key) { - if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { - throw this.error(new TomlError("Can't redefine existing key")) - } - target = target[kw] = target[kw] || Table() - } - if (hasKey(target, finalKey)) { - throw this.error(new TomlError("Can't redefine existing key")) - } - // unbox our numbers - if (isInteger(kv.value) || isFloat(kv.value)) { - target[finalKey] = kv.value.valueOf() - } else { - target[finalKey] = kv.value - } - return this.goto(this.parseWhitespaceToEOL) - } - - /* ASSSIGNMENT expression, key = value possibly inside an inline table */ - parseAssign () { - return this.callNow(this.parseKeyword, this.recordAssignKeyword) - } - recordAssignKeyword (key) { - if (this.state.resultTable) { - this.state.resultTable.push(key) - } else { - this.state.resultTable = [key] - } - return this.goto(this.parseAssignKeywordPreDot) - } - parseAssignKeywordPreDot () { - if (this.char === CHAR_PERIOD) { - return this.next(this.parseAssignKeywordPostDot) - } else if (this.char !== CHAR_SP && this.char !== CTRL_I) { - return this.goto(this.parseAssignEqual) - } - } - parseAssignKeywordPostDot () { - if (this.char !== CHAR_SP && this.char !== CTRL_I) { - return this.callNow(this.parseKeyword, this.recordAssignKeyword) - } - } - - parseAssignEqual () { - if (this.char === CHAR_EQUALS) { - return this.next(this.parseAssignPreValue) - } else { - throw this.error(new TomlError('Invalid character, expected "="')) - } - } - parseAssignPreValue () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else { - return this.callNow(this.parseValue, this.recordAssignValue) - } - } - recordAssignValue (value) { - return this.returnNow({key: this.state.resultTable, value: value}) - } - - /* COMMENTS: #...eol */ - parseComment () { - do { - if (this.char === Parser.END || this.char === CTRL_J) { - return this.return() - } - } while (this.nextChar()) - } - - /* TABLES AND LISTS, [foo] and [[foo]] */ - parseTableOrList () { - if (this.char === CHAR_LSQB) { - this.next(this.parseList) - } else { - return this.goto(this.parseTable) - } - } - - /* TABLE [foo.bar.baz] */ - parseTable () { - this.ctx = this.obj - return this.goto(this.parseTableNext) - } - parseTableNext () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else { - return this.callNow(this.parseKeyword, this.parseTableMore) - } - } - parseTableMore (keyword) { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else if (this.char === CHAR_RSQB) { - if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) { - throw this.error(new TomlError("Can't redefine existing key")) - } else { - this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table() - this.ctx[_declared] = true - } - return this.next(this.parseWhitespaceToEOL) - } else if (this.char === CHAR_PERIOD) { - if (!hasKey(this.ctx, keyword)) { - this.ctx = this.ctx[keyword] = Table() - } else if (isTable(this.ctx[keyword])) { - this.ctx = this.ctx[keyword] - } else if (isList(this.ctx[keyword])) { - this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] - } else { - throw this.error(new TomlError("Can't redefine existing key")) - } - return this.next(this.parseTableNext) - } else { - throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) - } - } - - /* LIST [[a.b.c]] */ - parseList () { - this.ctx = this.obj - return this.goto(this.parseListNext) - } - parseListNext () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else { - return this.callNow(this.parseKeyword, this.parseListMore) - } - } - parseListMore (keyword) { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else if (this.char === CHAR_RSQB) { - if (!hasKey(this.ctx, keyword)) { - this.ctx[keyword] = List() - } - if (isInlineList(this.ctx[keyword])) { - throw this.error(new TomlError("Can't extend an inline array")) - } else if (isList(this.ctx[keyword])) { - const next = Table() - this.ctx[keyword].push(next) - this.ctx = next - } else { - throw this.error(new TomlError("Can't redefine an existing key")) - } - return this.next(this.parseListEnd) - } else if (this.char === CHAR_PERIOD) { - if (!hasKey(this.ctx, keyword)) { - this.ctx = this.ctx[keyword] = Table() - } else if (isInlineList(this.ctx[keyword])) { - throw this.error(new TomlError("Can't extend an inline array")) - } else if (isInlineTable(this.ctx[keyword])) { - throw this.error(new TomlError("Can't extend an inline table")) - } else if (isList(this.ctx[keyword])) { - this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1] - } else if (isTable(this.ctx[keyword])) { - this.ctx = this.ctx[keyword] - } else { - throw this.error(new TomlError("Can't redefine an existing key")) - } - return this.next(this.parseListNext) - } else { - throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) - } - } - parseListEnd (keyword) { - if (this.char === CHAR_RSQB) { - return this.next(this.parseWhitespaceToEOL) - } else { - throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')) - } - } - - /* VALUE string, number, boolean, inline list, inline object */ - parseValue () { - if (this.char === Parser.END) { - throw this.error(new TomlError('Key without value')) - } else if (this.char === CHAR_QUOT) { - return this.next(this.parseDoubleString) - } if (this.char === CHAR_APOS) { - return this.next(this.parseSingleString) - } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { - return this.goto(this.parseNumberSign) - } else if (this.char === CHAR_i) { - return this.next(this.parseInf) - } else if (this.char === CHAR_n) { - return this.next(this.parseNan) - } else if (isDigit(this.char)) { - return this.goto(this.parseNumberOrDateTime) - } else if (this.char === CHAR_t || this.char === CHAR_f) { - return this.goto(this.parseBoolean) - } else if (this.char === CHAR_LSQB) { - return this.call(this.parseInlineList, this.recordValue) - } else if (this.char === CHAR_LCUB) { - return this.call(this.parseInlineTable, this.recordValue) - } else { - throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table')) - } - } - recordValue (value) { - return this.returnNow(value) - } - - parseInf () { - if (this.char === CHAR_n) { - return this.next(this.parseInf2) - } else { - throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) - } - } - parseInf2 () { - if (this.char === CHAR_f) { - if (this.state.buf === '-') { - return this.return(-Infinity) - } else { - return this.return(Infinity) - } - } else { - throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')) - } - } - - parseNan () { - if (this.char === CHAR_a) { - return this.next(this.parseNan2) - } else { - throw this.error(new TomlError('Unexpected character, expected "nan"')) - } - } - parseNan2 () { - if (this.char === CHAR_n) { - return this.return(NaN) - } else { - throw this.error(new TomlError('Unexpected character, expected "nan"')) - } - } - - /* KEYS, barewords or basic, literal, or dotted */ - parseKeyword () { - if (this.char === CHAR_QUOT) { - return this.next(this.parseBasicString) - } else if (this.char === CHAR_APOS) { - return this.next(this.parseLiteralString) - } else { - return this.goto(this.parseBareKey) - } - } - - /* KEYS: barewords */ - parseBareKey () { - do { - if (this.char === Parser.END) { - throw this.error(new TomlError('Key ended without value')) - } else if (isAlphaNumHyphen(this.char)) { - this.consume() - } else if (this.state.buf.length === 0) { - throw this.error(new TomlError('Empty bare keys are not allowed')) - } else { - return this.returnNow() - } - } while (this.nextChar()) - } - - /* STRINGS, single quoted (literal) */ - parseSingleString () { - if (this.char === CHAR_APOS) { - return this.next(this.parseLiteralMultiStringMaybe) - } else { - return this.goto(this.parseLiteralString) - } - } - parseLiteralString () { - do { - if (this.char === CHAR_APOS) { - return this.return() - } else if (this.atEndOfLine()) { - throw this.error(new TomlError('Unterminated string')) - } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { - throw this.errorControlCharInString() - } else { - this.consume() - } - } while (this.nextChar()) - } - parseLiteralMultiStringMaybe () { - if (this.char === CHAR_APOS) { - return this.next(this.parseLiteralMultiString) - } else { - return this.returnNow() - } - } - parseLiteralMultiString () { - if (this.char === CTRL_M) { - return null - } else if (this.char === CTRL_J) { - return this.next(this.parseLiteralMultiStringContent) - } else { - return this.goto(this.parseLiteralMultiStringContent) - } - } - parseLiteralMultiStringContent () { - do { - if (this.char === CHAR_APOS) { - return this.next(this.parseLiteralMultiEnd) - } else if (this.char === Parser.END) { - throw this.error(new TomlError('Unterminated multi-line string')) - } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { - throw this.errorControlCharInString() - } else { - this.consume() - } - } while (this.nextChar()) - } - parseLiteralMultiEnd () { - if (this.char === CHAR_APOS) { - return this.next(this.parseLiteralMultiEnd2) - } else { - this.state.buf += "'" - return this.goto(this.parseLiteralMultiStringContent) - } - } - parseLiteralMultiEnd2 () { - if (this.char === CHAR_APOS) { - return this.return() - } else { - this.state.buf += "''" - return this.goto(this.parseLiteralMultiStringContent) - } - } - - /* STRINGS double quoted */ - parseDoubleString () { - if (this.char === CHAR_QUOT) { - return this.next(this.parseMultiStringMaybe) - } else { - return this.goto(this.parseBasicString) - } - } - parseBasicString () { - do { - if (this.char === CHAR_BSOL) { - return this.call(this.parseEscape, this.recordEscapeReplacement) - } else if (this.char === CHAR_QUOT) { - return this.return() - } else if (this.atEndOfLine()) { - throw this.error(new TomlError('Unterminated string')) - } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) { - throw this.errorControlCharInString() - } else { - this.consume() - } - } while (this.nextChar()) - } - recordEscapeReplacement (replacement) { - this.state.buf += replacement - return this.goto(this.parseBasicString) - } - parseMultiStringMaybe () { - if (this.char === CHAR_QUOT) { - return this.next(this.parseMultiString) - } else { - return this.returnNow() - } - } - parseMultiString () { - if (this.char === CTRL_M) { - return null - } else if (this.char === CTRL_J) { - return this.next(this.parseMultiStringContent) - } else { - return this.goto(this.parseMultiStringContent) - } - } - parseMultiStringContent () { - do { - if (this.char === CHAR_BSOL) { - return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement) - } else if (this.char === CHAR_QUOT) { - return this.next(this.parseMultiEnd) - } else if (this.char === Parser.END) { - throw this.error(new TomlError('Unterminated multi-line string')) - } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) { - throw this.errorControlCharInString() - } else { - this.consume() - } - } while (this.nextChar()) - } - errorControlCharInString () { - let displayCode = '\\u00' - if (this.char < 16) { - displayCode += '0' - } - displayCode += this.char.toString(16) - - return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`)) - } - recordMultiEscapeReplacement (replacement) { - this.state.buf += replacement - return this.goto(this.parseMultiStringContent) - } - parseMultiEnd () { - if (this.char === CHAR_QUOT) { - return this.next(this.parseMultiEnd2) - } else { - this.state.buf += '"' - return this.goto(this.parseMultiStringContent) - } - } - parseMultiEnd2 () { - if (this.char === CHAR_QUOT) { - return this.return() - } else { - this.state.buf += '""' - return this.goto(this.parseMultiStringContent) - } - } - parseMultiEscape () { - if (this.char === CTRL_M || this.char === CTRL_J) { - return this.next(this.parseMultiTrim) - } else if (this.char === CHAR_SP || this.char === CTRL_I) { - return this.next(this.parsePreMultiTrim) - } else { - return this.goto(this.parseEscape) - } - } - parsePreMultiTrim () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else if (this.char === CTRL_M || this.char === CTRL_J) { - return this.next(this.parseMultiTrim) - } else { - throw this.error(new TomlError("Can't escape whitespace")) - } - } - parseMultiTrim () { - // explicitly whitespace here, END should follow the same path as chars - if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { - return null - } else { - return this.returnNow() - } - } - parseEscape () { - if (this.char in escapes) { - return this.return(escapes[this.char]) - } else if (this.char === CHAR_u) { - return this.call(this.parseSmallUnicode, this.parseUnicodeReturn) - } else if (this.char === CHAR_U) { - return this.call(this.parseLargeUnicode, this.parseUnicodeReturn) - } else { - throw this.error(new TomlError('Unknown escape character: ' + this.char)) - } - } - parseUnicodeReturn (char) { - try { - const codePoint = parseInt(char, 16) - if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) { - throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved')) - } - return this.returnNow(String.fromCodePoint(codePoint)) - } catch (err) { - throw this.error(TomlError.wrap(err)) - } - } - parseSmallUnicode () { - if (!isHexit(this.char)) { - throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) - } else { - this.consume() - if (this.state.buf.length >= 4) return this.return() - } - } - parseLargeUnicode () { - if (!isHexit(this.char)) { - throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')) - } else { - this.consume() - if (this.state.buf.length >= 8) return this.return() - } - } - - /* NUMBERS */ - parseNumberSign () { - this.consume() - return this.next(this.parseMaybeSignedInfOrNan) - } - parseMaybeSignedInfOrNan () { - if (this.char === CHAR_i) { - return this.next(this.parseInf) - } else if (this.char === CHAR_n) { - return this.next(this.parseNan) - } else { - return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart) - } - } - parseNumberIntegerStart () { - if (this.char === CHAR_0) { - this.consume() - return this.next(this.parseNumberIntegerExponentOrDecimal) - } else { - return this.goto(this.parseNumberInteger) - } - } - parseNumberIntegerExponentOrDecimal () { - if (this.char === CHAR_PERIOD) { - this.consume() - return this.call(this.parseNoUnder, this.parseNumberFloat) - } else if (this.char === CHAR_E || this.char === CHAR_e) { - this.consume() - return this.next(this.parseNumberExponentSign) - } else { - return this.returnNow(Integer(this.state.buf)) - } - } - parseNumberInteger () { - if (isDigit(this.char)) { - this.consume() - } else if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnder) - } else if (this.char === CHAR_E || this.char === CHAR_e) { - this.consume() - return this.next(this.parseNumberExponentSign) - } else if (this.char === CHAR_PERIOD) { - this.consume() - return this.call(this.parseNoUnder, this.parseNumberFloat) - } else { - const result = Integer(this.state.buf) - /* istanbul ignore if */ - if (result.isNaN()) { - throw this.error(new TomlError('Invalid number')) - } else { - return this.returnNow(result) - } - } - } - parseNoUnder () { - if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) { - throw this.error(new TomlError('Unexpected character, expected digit')) - } else if (this.atEndOfWord()) { - throw this.error(new TomlError('Incomplete number')) - } - return this.returnNow() - } - parseNoUnderHexOctBinLiteral () { - if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) { - throw this.error(new TomlError('Unexpected character, expected digit')) - } else if (this.atEndOfWord()) { - throw this.error(new TomlError('Incomplete number')) - } - return this.returnNow() - } - parseNumberFloat () { - if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnder, this.parseNumberFloat) - } else if (isDigit(this.char)) { - this.consume() - } else if (this.char === CHAR_E || this.char === CHAR_e) { - this.consume() - return this.next(this.parseNumberExponentSign) - } else { - return this.returnNow(Float(this.state.buf)) - } - } - parseNumberExponentSign () { - if (isDigit(this.char)) { - return this.goto(this.parseNumberExponent) - } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { - this.consume() - this.call(this.parseNoUnder, this.parseNumberExponent) - } else { - throw this.error(new TomlError('Unexpected character, expected -, + or digit')) - } - } - parseNumberExponent () { - if (isDigit(this.char)) { - this.consume() - } else if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnder) - } else { - return this.returnNow(Float(this.state.buf)) - } - } - - /* NUMBERS or DATETIMES */ - parseNumberOrDateTime () { - if (this.char === CHAR_0) { - this.consume() - return this.next(this.parseNumberBaseOrDateTime) - } else { - return this.goto(this.parseNumberOrDateTimeOnly) - } - } - parseNumberOrDateTimeOnly () { - // note, if two zeros are in a row then it MUST be a date - if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnder, this.parseNumberInteger) - } else if (isDigit(this.char)) { - this.consume() - if (this.state.buf.length > 4) this.next(this.parseNumberInteger) - } else if (this.char === CHAR_E || this.char === CHAR_e) { - this.consume() - return this.next(this.parseNumberExponentSign) - } else if (this.char === CHAR_PERIOD) { - this.consume() - return this.call(this.parseNoUnder, this.parseNumberFloat) - } else if (this.char === CHAR_HYPHEN) { - return this.goto(this.parseDateTime) - } else if (this.char === CHAR_COLON) { - return this.goto(this.parseOnlyTimeHour) - } else { - return this.returnNow(Integer(this.state.buf)) - } - } - parseDateTimeOnly () { - if (this.state.buf.length < 4) { - if (isDigit(this.char)) { - return this.consume() - } else if (this.char === CHAR_COLON) { - return this.goto(this.parseOnlyTimeHour) - } else { - throw this.error(new TomlError('Expected digit while parsing year part of a date')) - } - } else { - if (this.char === CHAR_HYPHEN) { - return this.goto(this.parseDateTime) - } else { - throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date')) - } - } - } - parseNumberBaseOrDateTime () { - if (this.char === CHAR_b) { - this.consume() - return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin) - } else if (this.char === CHAR_o) { - this.consume() - return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct) - } else if (this.char === CHAR_x) { - this.consume() - return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex) - } else if (this.char === CHAR_PERIOD) { - return this.goto(this.parseNumberInteger) - } else if (isDigit(this.char)) { - return this.goto(this.parseDateTimeOnly) - } else { - return this.returnNow(Integer(this.state.buf)) - } - } - parseIntegerHex () { - if (isHexit(this.char)) { - this.consume() - } else if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnderHexOctBinLiteral) - } else { - const result = Integer(this.state.buf) - /* istanbul ignore if */ - if (result.isNaN()) { - throw this.error(new TomlError('Invalid number')) - } else { - return this.returnNow(result) - } - } - } - parseIntegerOct () { - if (isOctit(this.char)) { - this.consume() - } else if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnderHexOctBinLiteral) - } else { - const result = Integer(this.state.buf) - /* istanbul ignore if */ - if (result.isNaN()) { - throw this.error(new TomlError('Invalid number')) - } else { - return this.returnNow(result) - } - } - } - parseIntegerBin () { - if (isBit(this.char)) { - this.consume() - } else if (this.char === CHAR_LOWBAR) { - return this.call(this.parseNoUnderHexOctBinLiteral) - } else { - const result = Integer(this.state.buf) - /* istanbul ignore if */ - if (result.isNaN()) { - throw this.error(new TomlError('Invalid number')) - } else { - return this.returnNow(result) - } - } - } - - /* DATETIME */ - parseDateTime () { - // we enter here having just consumed the year and about to consume the hyphen - if (this.state.buf.length < 4) { - throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters')) - } - this.state.result = this.state.buf - this.state.buf = '' - return this.next(this.parseDateMonth) - } - parseDateMonth () { - if (this.char === CHAR_HYPHEN) { - if (this.state.buf.length < 2) { - throw this.error(new TomlError('Months less than 10 must be zero padded to two characters')) - } - this.state.result += '-' + this.state.buf - this.state.buf = '' - return this.next(this.parseDateDay) - } else if (isDigit(this.char)) { - this.consume() - } else { - throw this.error(new TomlError('Incomplete datetime')) - } - } - parseDateDay () { - if (this.char === CHAR_T || this.char === CHAR_SP) { - if (this.state.buf.length < 2) { - throw this.error(new TomlError('Days less than 10 must be zero padded to two characters')) - } - this.state.result += '-' + this.state.buf - this.state.buf = '' - return this.next(this.parseStartTimeHour) - } else if (this.atEndOfWord()) { - return this.returnNow(createDate(this.state.result + '-' + this.state.buf)) - } else if (isDigit(this.char)) { - this.consume() - } else { - throw this.error(new TomlError('Incomplete datetime')) - } - } - parseStartTimeHour () { - if (this.atEndOfWord()) { - return this.returnNow(createDate(this.state.result)) - } else { - return this.goto(this.parseTimeHour) - } - } - parseTimeHour () { - if (this.char === CHAR_COLON) { - if (this.state.buf.length < 2) { - throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) - } - this.state.result += 'T' + this.state.buf - this.state.buf = '' - return this.next(this.parseTimeMin) - } else if (isDigit(this.char)) { - this.consume() - } else { - throw this.error(new TomlError('Incomplete datetime')) - } - } - parseTimeMin () { - if (this.state.buf.length < 2 && isDigit(this.char)) { - this.consume() - } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { - this.state.result += ':' + this.state.buf - this.state.buf = '' - return this.next(this.parseTimeSec) - } else { - throw this.error(new TomlError('Incomplete datetime')) - } - } - parseTimeSec () { - if (isDigit(this.char)) { - this.consume() - if (this.state.buf.length === 2) { - this.state.result += ':' + this.state.buf - this.state.buf = '' - return this.next(this.parseTimeZoneOrFraction) - } - } else { - throw this.error(new TomlError('Incomplete datetime')) - } - } - - parseOnlyTimeHour () { - /* istanbul ignore else */ - if (this.char === CHAR_COLON) { - if (this.state.buf.length < 2) { - throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')) - } - this.state.result = this.state.buf - this.state.buf = '' - return this.next(this.parseOnlyTimeMin) - } else { - throw this.error(new TomlError('Incomplete time')) - } - } - parseOnlyTimeMin () { - if (this.state.buf.length < 2 && isDigit(this.char)) { - this.consume() - } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { - this.state.result += ':' + this.state.buf - this.state.buf = '' - return this.next(this.parseOnlyTimeSec) - } else { - throw this.error(new TomlError('Incomplete time')) - } - } - parseOnlyTimeSec () { - if (isDigit(this.char)) { - this.consume() - if (this.state.buf.length === 2) { - return this.next(this.parseOnlyTimeFractionMaybe) - } - } else { - throw this.error(new TomlError('Incomplete time')) - } - } - parseOnlyTimeFractionMaybe () { - this.state.result += ':' + this.state.buf - if (this.char === CHAR_PERIOD) { - this.state.buf = '' - this.next(this.parseOnlyTimeFraction) - } else { - return this.return(createTime(this.state.result)) - } - } - parseOnlyTimeFraction () { - if (isDigit(this.char)) { - this.consume() - } else if (this.atEndOfWord()) { - if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds')) - return this.returnNow(createTime(this.state.result + '.' + this.state.buf)) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) - } - } - - parseTimeZoneOrFraction () { - if (this.char === CHAR_PERIOD) { - this.consume() - this.next(this.parseDateTimeFraction) - } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { - this.consume() - this.next(this.parseTimeZoneHour) - } else if (this.char === CHAR_Z) { - this.consume() - return this.return(createDateTime(this.state.result + this.state.buf)) - } else if (this.atEndOfWord()) { - return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) - } - } - parseDateTimeFraction () { - if (isDigit(this.char)) { - this.consume() - } else if (this.state.buf.length === 1) { - throw this.error(new TomlError('Expected digit in milliseconds')) - } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { - this.consume() - this.next(this.parseTimeZoneHour) - } else if (this.char === CHAR_Z) { - this.consume() - return this.return(createDateTime(this.state.result + this.state.buf)) - } else if (this.atEndOfWord()) { - return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf)) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')) - } - } - parseTimeZoneHour () { - if (isDigit(this.char)) { - this.consume() - // FIXME: No more regexps - if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected digit')) - } - } - parseTimeZoneSep () { - if (this.char === CHAR_COLON) { - this.consume() - this.next(this.parseTimeZoneMin) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected colon')) - } - } - parseTimeZoneMin () { - if (isDigit(this.char)) { - this.consume() - if (/\d\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf)) - } else { - throw this.error(new TomlError('Unexpected character in datetime, expected digit')) - } - } - - /* BOOLEAN */ - parseBoolean () { - /* istanbul ignore else */ - if (this.char === CHAR_t) { - this.consume() - return this.next(this.parseTrue_r) - } else if (this.char === CHAR_f) { - this.consume() - return this.next(this.parseFalse_a) - } - } - parseTrue_r () { - if (this.char === CHAR_r) { - this.consume() - return this.next(this.parseTrue_u) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - parseTrue_u () { - if (this.char === CHAR_u) { - this.consume() - return this.next(this.parseTrue_e) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - parseTrue_e () { - if (this.char === CHAR_e) { - return this.return(true) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - - parseFalse_a () { - if (this.char === CHAR_a) { - this.consume() - return this.next(this.parseFalse_l) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - - parseFalse_l () { - if (this.char === CHAR_l) { - this.consume() - return this.next(this.parseFalse_s) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - - parseFalse_s () { - if (this.char === CHAR_s) { - this.consume() - return this.next(this.parseFalse_e) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - - parseFalse_e () { - if (this.char === CHAR_e) { - return this.return(false) - } else { - throw this.error(new TomlError('Invalid boolean, expected true or false')) - } - } - - /* INLINE LISTS */ - parseInlineList () { - if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { - return null - } else if (this.char === Parser.END) { - throw this.error(new TomlError('Unterminated inline array')) - } else if (this.char === CHAR_NUM) { - return this.call(this.parseComment) - } else if (this.char === CHAR_RSQB) { - return this.return(this.state.resultArr || InlineList()) - } else { - return this.callNow(this.parseValue, this.recordInlineListValue) - } - } - recordInlineListValue (value) { - if (this.state.resultArr) { - const listType = this.state.resultArr[_contentType] - const valueType = tomlType(value) - if (listType !== valueType) { - throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`)) - } - } else { - this.state.resultArr = InlineList(tomlType(value)) - } - if (isFloat(value) || isInteger(value)) { - // unbox now that we've verified they're ok - this.state.resultArr.push(value.valueOf()) - } else { - this.state.resultArr.push(value) - } - return this.goto(this.parseInlineListNext) - } - parseInlineListNext () { - if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { - return null - } else if (this.char === CHAR_NUM) { - return this.call(this.parseComment) - } else if (this.char === CHAR_COMMA) { - return this.next(this.parseInlineList) - } else if (this.char === CHAR_RSQB) { - return this.goto(this.parseInlineList) - } else { - throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) - } - } - - /* INLINE TABLE */ - parseInlineTable () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { - throw this.error(new TomlError('Unterminated inline array')) - } else if (this.char === CHAR_RCUB) { - return this.return(this.state.resultTable || InlineTable()) - } else { - if (!this.state.resultTable) this.state.resultTable = InlineTable() - return this.callNow(this.parseAssign, this.recordInlineTableValue) - } - } - recordInlineTableValue (kv) { - let target = this.state.resultTable - let finalKey = kv.key.pop() - for (let kw of kv.key) { - if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { - throw this.error(new TomlError("Can't redefine existing key")) - } - target = target[kw] = target[kw] || Table() - } - if (hasKey(target, finalKey)) { - throw this.error(new TomlError("Can't redefine existing key")) - } - if (isInteger(kv.value) || isFloat(kv.value)) { - target[finalKey] = kv.value.valueOf() - } else { - target[finalKey] = kv.value - } - return this.goto(this.parseInlineTableNext) - } - parseInlineTableNext () { - if (this.char === CHAR_SP || this.char === CTRL_I) { - return null - } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { - throw this.error(new TomlError('Unterminated inline array')) - } else if (this.char === CHAR_COMMA) { - return this.next(this.parseInlineTable) - } else if (this.char === CHAR_RCUB) { - return this.goto(this.parseInlineTable) - } else { - throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')) - } - } - } - return TOMLParser -} - - -/***/ }), - -/***/ 7072: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = parseAsync - -const TOMLParser = __nccwpck_require__(2862) -const prettyError = __nccwpck_require__(7349) - -function parseAsync (str, opts) { - if (!opts) opts = {} - const index = 0 - const blocksize = opts.blocksize || 40960 - const parser = new TOMLParser() - return new Promise((resolve, reject) => { - setImmediate(parseAsyncNext, index, blocksize, resolve, reject) - }) - function parseAsyncNext (index, blocksize, resolve, reject) { - if (index >= str.length) { - try { - return resolve(parser.finish()) - } catch (err) { - return reject(prettyError(err, str)) - } - } - try { - parser.parse(str.slice(index, index + blocksize)) - setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject) - } catch (err) { - reject(prettyError(err, str)) - } - } -} - - -/***/ }), - -/***/ 7349: -/***/ ((module) => { - -"use strict"; - -module.exports = prettyError - -function prettyError (err, buf) { - /* istanbul ignore if */ - if (err.pos == null || err.line == null) return err - let msg = err.message - msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n` - - /* istanbul ignore else */ - if (buf && buf.split) { - const lines = buf.split(/\n/) - const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length - let linePadding = ' ' - while (linePadding.length < lineNumWidth) linePadding += ' ' - for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) { - let lineNum = String(ii + 1) - if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum - if (err.line === ii) { - msg += lineNum + '> ' + lines[ii] + '\n' - msg += linePadding + ' ' - for (let hh = 0; hh < err.col; ++hh) { - msg += ' ' - } - msg += '^\n' - } else { - msg += lineNum + ': ' + lines[ii] + '\n' - } - } - } - err.message = msg + '\n' - return err -} - - -/***/ }), - -/***/ 6874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = parseStream - -const stream = __nccwpck_require__(2203) -const TOMLParser = __nccwpck_require__(2862) - -function parseStream (stm) { - if (stm) { - return parseReadable(stm) - } else { - return parseTransform(stm) - } -} - -function parseReadable (stm) { - const parser = new TOMLParser() - stm.setEncoding('utf8') - return new Promise((resolve, reject) => { - let readable - let ended = false - let errored = false - function finish () { - ended = true - if (readable) return - try { - resolve(parser.finish()) - } catch (err) { - reject(err) - } - } - function error (err) { - errored = true - reject(err) - } - stm.once('end', finish) - stm.once('error', error) - readNext() - - function readNext () { - readable = true - let data - while ((data = stm.read()) !== null) { - try { - parser.parse(data) - } catch (err) { - return error(err) - } - } - readable = false - /* istanbul ignore if */ - if (ended) return finish() - /* istanbul ignore if */ - if (errored) return - stm.once('readable', readNext) - } - }) -} - -function parseTransform () { - const parser = new TOMLParser() - return new stream.Transform({ - objectMode: true, - transform (chunk, encoding, cb) { - try { - parser.parse(chunk.toString(encoding)) - } catch (err) { - this.emit('error', err) - } - cb() - }, - flush (cb) { - try { - this.push(parser.finish()) - } catch (err) { - this.emit('error', err) - } - cb() - } - }) -} - - -/***/ }), - -/***/ 4171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = parseString - -const TOMLParser = __nccwpck_require__(2862) -const prettyError = __nccwpck_require__(7349) - -function parseString (str) { - if (global.Buffer && global.Buffer.isBuffer(str)) { - str = str.toString('utf8') - } - const parser = new TOMLParser() - try { - parser.parse(str) - return parser.finish() - } catch (err) { - throw prettyError(err, str) - } -} - - -/***/ }), - -/***/ 9185: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = __nccwpck_require__(4171) -module.exports.async = __nccwpck_require__(7072) -module.exports.stream = __nccwpck_require__(6874) -module.exports.prettyError = __nccwpck_require__(7349) - - -/***/ }), - -/***/ 3887: -/***/ ((module) => { - -"use strict"; - -module.exports = stringify -module.exports.value = stringifyInline - -function stringify (obj) { - if (obj === null) throw typeError('null') - if (obj === void (0)) throw typeError('undefined') - if (typeof obj !== 'object') throw typeError(typeof obj) - - if (typeof obj.toJSON === 'function') obj = obj.toJSON() - if (obj == null) return null - const type = tomlType(obj) - if (type !== 'table') throw typeError(type) - return stringifyObject('', '', obj) -} - -function typeError (type) { - return new Error('Can only stringify objects, not ' + type) -} - -function arrayOneTypeError () { - return new Error("Array values can't have mixed types") -} - -function getInlineKeys (obj) { - return Object.keys(obj).filter(key => isInline(obj[key])) -} -function getComplexKeys (obj) { - return Object.keys(obj).filter(key => !isInline(obj[key])) -} - -function toJSON (obj) { - let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {} - for (let prop of Object.keys(obj)) { - if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) { - nobj[prop] = obj[prop].toJSON() - } else { - nobj[prop] = obj[prop] - } - } - return nobj -} - -function stringifyObject (prefix, indent, obj) { - obj = toJSON(obj) - var inlineKeys - var complexKeys - inlineKeys = getInlineKeys(obj) - complexKeys = getComplexKeys(obj) - var result = [] - var inlineIndent = indent || '' - inlineKeys.forEach(key => { - var type = tomlType(obj[key]) - if (type !== 'undefined' && type !== 'null') { - result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true)) - } - }) - if (result.length > 0) result.push('') - var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : '' - complexKeys.forEach(key => { - result.push(stringifyComplex(prefix, complexIndent, key, obj[key])) - }) - return result.join('\n') -} - -function isInline (value) { - switch (tomlType(value)) { - case 'undefined': - case 'null': - case 'integer': - case 'nan': - case 'float': - case 'boolean': - case 'string': - case 'datetime': - return true - case 'array': - return value.length === 0 || tomlType(value[0]) !== 'table' - case 'table': - return Object.keys(value).length === 0 - /* istanbul ignore next */ - default: - return false - } -} - -function tomlType (value) { - if (value === undefined) { - return 'undefined' - } else if (value === null) { - return 'null' - /* eslint-disable valid-typeof */ - } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) { - return 'integer' - } else if (typeof value === 'number') { - return 'float' - } else if (typeof value === 'boolean') { - return 'boolean' - } else if (typeof value === 'string') { - return 'string' - } else if ('toISOString' in value) { - return isNaN(value) ? 'undefined' : 'datetime' - } else if (Array.isArray(value)) { - return 'array' - } else { - return 'table' - } -} - -function stringifyKey (key) { - var keyStr = String(key) - if (/^[-A-Za-z0-9_]+$/.test(keyStr)) { - return keyStr - } else { - return stringifyBasicString(keyStr) - } -} - -function stringifyBasicString (str) { - return '"' + escapeString(str).replace(/"/g, '\\"') + '"' -} - -function stringifyLiteralString (str) { - return "'" + str + "'" -} - -function numpad (num, str) { - while (str.length < num) str = '0' + str - return str -} - -function escapeString (str) { - return str.replace(/\\/g, '\\\\') - .replace(/[\b]/g, '\\b') - .replace(/\t/g, '\\t') - .replace(/\n/g, '\\n') - .replace(/\f/g, '\\f') - .replace(/\r/g, '\\r') - /* eslint-disable no-control-regex */ - .replace(/([\u0000-\u001f\u007f])/, c => '\\u' + numpad(4, c.codePointAt(0).toString(16))) - /* eslint-enable no-control-regex */ -} - -function stringifyMultilineString (str) { - let escaped = str.split(/\n/).map(str => { - return escapeString(str).replace(/"(?="")/g, '\\"') - }).join('\n') - if (escaped.slice(-1) === '"') escaped += '\\\n' - return '"""\n' + escaped + '"""' -} - -function stringifyAnyInline (value, multilineOk) { - let type = tomlType(value) - if (type === 'string') { - if (multilineOk && /\n/.test(value)) { - type = 'string-multiline' - } else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) { - type = 'string-literal' - } - } - return stringifyInline(value, type) -} - -function stringifyInline (value, type) { - /* istanbul ignore if */ - if (!type) type = tomlType(value) - switch (type) { - case 'string-multiline': - return stringifyMultilineString(value) - case 'string': - return stringifyBasicString(value) - case 'string-literal': - return stringifyLiteralString(value) - case 'integer': - return stringifyInteger(value) - case 'float': - return stringifyFloat(value) - case 'boolean': - return stringifyBoolean(value) - case 'datetime': - return stringifyDatetime(value) - case 'array': - return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan')) - case 'table': - return stringifyInlineTable(value) - /* istanbul ignore next */ - default: - throw typeError(type) - } -} - -function stringifyInteger (value) { - /* eslint-disable security/detect-unsafe-regex */ - return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '_') -} - -function stringifyFloat (value) { - if (value === Infinity) { - return 'inf' - } else if (value === -Infinity) { - return '-inf' - } else if (Object.is(value, NaN)) { - return 'nan' - } else if (Object.is(value, -0)) { - return '-0.0' - } - var chunks = String(value).split('.') - var int = chunks[0] - var dec = chunks[1] || 0 - return stringifyInteger(int) + '.' + dec -} - -function stringifyBoolean (value) { - return String(value) -} - -function stringifyDatetime (value) { - return value.toISOString() -} - -function isNumber (type) { - return type === 'float' || type === 'integer' -} -function arrayType (values) { - var contentType = tomlType(values[0]) - if (values.every(_ => tomlType(_) === contentType)) return contentType - // mixed integer/float, emit as floats - if (values.every(_ => isNumber(tomlType(_)))) return 'float' - return 'mixed' -} -function validateArray (values) { - const type = arrayType(values) - if (type === 'mixed') { - throw arrayOneTypeError() - } - return type -} - -function stringifyInlineArray (values) { - values = toJSON(values) - const type = validateArray(values) - var result = '[' - var stringified = values.map(_ => stringifyInline(_, type)) - if (stringified.join(', ').length > 60 || /\n/.test(stringified)) { - result += '\n ' + stringified.join(',\n ') + '\n' - } else { - result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '') - } - return result + ']' -} - -function stringifyInlineTable (value) { - value = toJSON(value) - var result = [] - Object.keys(value).forEach(key => { - result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false)) - }) - return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}' -} - -function stringifyComplex (prefix, indent, key, value) { - var valueType = tomlType(value) - /* istanbul ignore else */ - if (valueType === 'array') { - return stringifyArrayOfTables(prefix, indent, key, value) - } else if (valueType === 'table') { - return stringifyComplexTable(prefix, indent, key, value) - } else { - throw typeError(valueType) - } -} - -function stringifyArrayOfTables (prefix, indent, key, values) { - values = toJSON(values) - validateArray(values) - var firstValueType = tomlType(values[0]) - /* istanbul ignore if */ - if (firstValueType !== 'table') throw typeError(firstValueType) - var fullKey = prefix + stringifyKey(key) - var result = '' - values.forEach(table => { - if (result.length > 0) result += '\n' - result += indent + '[[' + fullKey + ']]\n' - result += stringifyObject(fullKey + '.', indent, table) - }) - return result -} - -function stringifyComplexTable (prefix, indent, key, value) { - var fullKey = prefix + stringifyKey(key) - var result = '' - if (getInlineKeys(value).length > 0) { - result += indent + '[' + fullKey + ']\n' - } - return result + stringifyObject(fullKey + '.', indent, value) -} - - -/***/ }), - -/***/ 4572: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -exports.parse = __nccwpck_require__(9185) -exports.stringify = __nccwpck_require__(3887) - - /***/ }), /***/ 7864: @@ -98695,15 +96527,6 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STATE_CACHE_MATCHED_KEY = exports.STATE_CACHE_KEY = void 0; exports.restoreCache = restoreCache; @@ -98716,71 +96539,65 @@ const exec = __importStar(__nccwpck_require__(5236)); exports.STATE_CACHE_KEY = "cache-key"; exports.STATE_CACHE_MATCHED_KEY = "cache-matched-key"; const CACHE_VERSION = "1"; -function restoreCache() { - return __awaiter(this, void 0, void 0, function* () { - const cacheKey = yield computeKeys(); - let matchedKey; - core.info(`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`); - try { - matchedKey = yield cache.restoreCache([inputs_1.cacheLocalPath], cacheKey); - } - catch (err) { - const message = err.message; - core.warning(message); - core.setOutput("cache-hit", false); - return; - } - core.saveState(exports.STATE_CACHE_KEY, cacheKey); - handleMatchResult(matchedKey, cacheKey); - }); +async function restoreCache() { + const cacheKey = await computeKeys(); + let matchedKey; + core.info(`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`); + try { + matchedKey = await cache.restoreCache([inputs_1.cacheLocalPath], cacheKey); + } + catch (err) { + const message = err.message; + core.warning(message); + core.setOutput("cache-hit", false); + return; + } + core.saveState(exports.STATE_CACHE_KEY, cacheKey); + handleMatchResult(matchedKey, cacheKey); } -function computeKeys() { - return __awaiter(this, void 0, void 0, function* () { - let cacheDependencyPathHash = "-"; - if (inputs_1.cacheDependencyGlob !== "") { - core.info(`Searching files using cache dependency glob: ${inputs_1.cacheDependencyGlob.split("\n").join(",")}`); - cacheDependencyPathHash += yield (0, hash_files_1.hashFiles)(inputs_1.cacheDependencyGlob, true); - if (cacheDependencyPathHash === "-") { - core.warning(`No file matched to [${inputs_1.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`); - } - } +async function computeKeys() { + let cacheDependencyPathHash = "-"; + if (inputs_1.cacheDependencyGlob !== "") { + core.info(`Searching files using cache dependency glob: ${inputs_1.cacheDependencyGlob.split("\n").join(",")}`); + cacheDependencyPathHash += await (0, hash_files_1.hashFiles)(inputs_1.cacheDependencyGlob, true); if (cacheDependencyPathHash === "-") { - cacheDependencyPathHash = "-no-dependency-glob"; + core.warning(`No file matched to [${inputs_1.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`); } - const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : ""; - const pythonVersion = yield getPythonVersion(); - return `setup-uv-${CACHE_VERSION}-${(0, platforms_1.getArch)()}-${(0, platforms_1.getPlatform)()}-${pythonVersion}${cacheDependencyPathHash}${suffix}`; - }); + } + if (cacheDependencyPathHash === "-") { + cacheDependencyPathHash = "-no-dependency-glob"; + } + const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : ""; + const pythonVersion = await getPythonVersion(); + return `setup-uv-${CACHE_VERSION}-${(0, platforms_1.getArch)()}-${(0, platforms_1.getPlatform)()}-${pythonVersion}${cacheDependencyPathHash}${suffix}`; } -function getPythonVersion() { - return __awaiter(this, void 0, void 0, function* () { - if (inputs_1.pythonVersion !== "") { - return inputs_1.pythonVersion; - } - let output = ""; - const options = { - silent: !core.isDebug(), - listeners: { - stdout: (data) => { - output += data.toString(); - }, +async function getPythonVersion() { + if (inputs_1.pythonVersion !== "") { + return inputs_1.pythonVersion; + } + let output = ""; + const options = { + silent: !core.isDebug(), + listeners: { + stdout: (data) => { + output += data.toString(); }, - }; - try { - const execArgs = ["python", "find"]; - yield exec.exec("uv", execArgs, options); - const pythonPath = output.trim(); - output = ""; - yield exec.exec(pythonPath, ["--version"], options); - // output is like "Python 3.8.10" - return output.split(" ")[1].trim(); - } - catch (error) { - const err = error; - core.debug(`Failed to get python version from uv. Error: ${err.message}`); - return "unknown"; - } - }); + }, + }; + try { + const execArgs = ["python", "find"]; + await exec.exec("uv", execArgs, options); + const pythonPath = output.trim(); + output = ""; + await exec.exec(pythonPath, ["--version"], options); + // output is like "Python 3.8.10" + return output.split(" ")[1].trim(); + } + catch (error) { + const err = error; + core.debug(`Failed to get python version from uv. Error: ${err.message}`); + return "unknown"; + } } function handleMatchResult(matchedKey, primaryKey) { if (!matchedKey) { @@ -98834,15 +96651,6 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateChecksum = validateChecksum; exports.isknownVersion = isknownVersion; @@ -98850,43 +96658,39 @@ const fs = __importStar(__nccwpck_require__(3024)); const crypto = __importStar(__nccwpck_require__(7598)); const core = __importStar(__nccwpck_require__(7484)); const known_checksums_1 = __nccwpck_require__(2764); -function validateChecksum(checkSum, downloadPath, arch, platform, version) { - return __awaiter(this, void 0, void 0, function* () { - let isValid = undefined; - if (checkSum !== undefined && checkSum !== "") { - isValid = yield validateFileCheckSum(downloadPath, checkSum); +async function validateChecksum(checkSum, downloadPath, arch, platform, version) { + let isValid = undefined; + if (checkSum !== undefined && checkSum !== "") { + isValid = await validateFileCheckSum(downloadPath, checkSum); + } + else { + core.debug("Checksum not provided. Checking known checksums."); + const key = `${arch}-${platform}-${version}`; + if (key in known_checksums_1.KNOWN_CHECKSUMS) { + const knownChecksum = known_checksums_1.KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`]; + core.debug(`Checking checksum for ${arch}-${platform}-${version}.`); + isValid = await validateFileCheckSum(downloadPath, knownChecksum); } else { - core.debug("Checksum not provided. Checking known checksums."); - const key = `${arch}-${platform}-${version}`; - if (key in known_checksums_1.KNOWN_CHECKSUMS) { - const knownChecksum = known_checksums_1.KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`]; - core.debug(`Checking checksum for ${arch}-${platform}-${version}.`); - isValid = yield validateFileCheckSum(downloadPath, knownChecksum); - } - else { - core.debug(`No known checksum found for ${key}.`); - } + core.debug(`No known checksum found for ${key}.`); } - if (isValid === false) { - throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`); - } - if (isValid === true) { - core.debug(`Checksum for ${downloadPath} is valid.`); - } - }); + } + if (isValid === false) { + throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`); + } + if (isValid === true) { + core.debug(`Checksum for ${downloadPath} is valid.`); + } } -function validateFileCheckSum(filePath, expected) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const hash = crypto.createHash("sha256"); - const stream = fs.createReadStream(filePath); - stream.on("error", (err) => reject(err)); - stream.on("data", (chunk) => hash.update(chunk)); - stream.on("end", () => { - const actual = hash.digest("hex"); - resolve(actual === expected); - }); +async function validateFileCheckSum(filePath, expected) { + return new Promise((resolve, reject) => { + const hash = crypto.createHash("sha256"); + const stream = fs.createReadStream(filePath); + stream.on("error", (err) => reject(err)); + stream.on("data", (chunk) => hash.update(chunk)); + stream.on("end", () => { + const actual = hash.digest("hex"); + resolve(actual === expected); }); }); } @@ -101290,15 +99094,6 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tryGetFromToolCache = tryGetFromToolCache; exports.downloadVersion = downloadVersion; @@ -101321,72 +99116,64 @@ function tryGetFromToolCache(arch, version) { const installedPath = tc.find(constants_1.TOOL_CACHE_NAME, resolvedVersion, arch); return { version: resolvedVersion, installedPath }; } -function downloadVersion(platform, arch, version, checkSum, githubToken) { - return __awaiter(this, void 0, void 0, function* () { - const resolvedVersion = yield resolveVersion(version, githubToken); - const artifact = `uv-${arch}-${platform}`; - let extension = ".tar.gz"; - if (platform === "pc-windows-msvc") { - extension = ".zip"; - } - const downloadUrl = `https://github.com/${constants_1.OWNER}/${constants_1.REPO}/releases/download/${resolvedVersion}/${artifact}${extension}`; - core.info(`Downloading uv from "${downloadUrl}" ...`); - const downloadPath = yield tc.downloadTool(downloadUrl, undefined, githubToken); - yield (0, checksum_1.validateChecksum)(checkSum, downloadPath, arch, platform, resolvedVersion); - let uvDir; - if (platform === "pc-windows-msvc") { - const fullPathWithExtension = `${downloadPath}${extension}`; - yield node_fs_1.promises.copyFile(downloadPath, fullPathWithExtension); - uvDir = yield tc.extractZip(fullPathWithExtension); - // On windows extracting the zip does not create an intermediate directory - } - else { - const extractedDir = yield tc.extractTar(downloadPath); - uvDir = path.join(extractedDir, artifact); - } - const cachedToolDir = yield tc.cacheDir(uvDir, constants_1.TOOL_CACHE_NAME, resolvedVersion, arch); - return { version: resolvedVersion, cachedToolDir }; - }); +async function downloadVersion(platform, arch, version, checkSum, githubToken) { + const resolvedVersion = await resolveVersion(version, githubToken); + const artifact = `uv-${arch}-${platform}`; + let extension = ".tar.gz"; + if (platform === "pc-windows-msvc") { + extension = ".zip"; + } + const downloadUrl = `https://github.com/${constants_1.OWNER}/${constants_1.REPO}/releases/download/${resolvedVersion}/${artifact}${extension}`; + core.info(`Downloading uv from "${downloadUrl}" ...`); + const downloadPath = await tc.downloadTool(downloadUrl, undefined, githubToken); + await (0, checksum_1.validateChecksum)(checkSum, downloadPath, arch, platform, resolvedVersion); + let uvDir; + if (platform === "pc-windows-msvc") { + const fullPathWithExtension = `${downloadPath}${extension}`; + await node_fs_1.promises.copyFile(downloadPath, fullPathWithExtension); + uvDir = await tc.extractZip(fullPathWithExtension); + // On windows extracting the zip does not create an intermediate directory + } + else { + const extractedDir = await tc.extractTar(downloadPath); + uvDir = path.join(extractedDir, artifact); + } + const cachedToolDir = await tc.cacheDir(uvDir, constants_1.TOOL_CACHE_NAME, resolvedVersion, arch); + return { version: resolvedVersion, cachedToolDir }; } -function resolveVersion(versionInput, githubToken) { - return __awaiter(this, void 0, void 0, function* () { - const version = versionInput === "latest" - ? yield getLatestVersion(githubToken) - : versionInput; - if (tc.isExplicitVersion(version)) { - core.debug(`Version ${version} is an explicit version.`); - return version; - } - const availableVersions = yield getAvailableVersions(githubToken); - const resolvedVersion = tc.evaluateVersions(availableVersions, version); - if (resolvedVersion === "") { - throw new Error(`No version found for ${version}`); - } - return resolvedVersion; - }); +async function resolveVersion(versionInput, githubToken) { + const version = versionInput === "latest" + ? await getLatestVersion(githubToken) + : versionInput; + if (tc.isExplicitVersion(version)) { + core.debug(`Version ${version} is an explicit version.`); + return version; + } + const availableVersions = await getAvailableVersions(githubToken); + const resolvedVersion = tc.evaluateVersions(availableVersions, version); + if (resolvedVersion === "") { + throw new Error(`No version found for ${version}`); + } + return resolvedVersion; } -function getAvailableVersions(githubToken) { - return __awaiter(this, void 0, void 0, function* () { - const octokit = github.getOctokit(githubToken, { baseUrl: constants_1.GITHUB_COM_API }); - const response = yield octokit.paginate(octokit.rest.repos.listReleases, { - owner: constants_1.OWNER, - repo: constants_1.REPO, - }); - return response.map((release) => release.tag_name); +async function getAvailableVersions(githubToken) { + const octokit = github.getOctokit(githubToken, { baseUrl: constants_1.GITHUB_COM_API }); + const response = await octokit.paginate(octokit.rest.repos.listReleases, { + owner: constants_1.OWNER, + repo: constants_1.REPO, }); + return response.map((release) => release.tag_name); } -function getLatestVersion(githubToken) { - return __awaiter(this, void 0, void 0, function* () { - const octokit = github.getOctokit(githubToken, { baseUrl: constants_1.GITHUB_COM_API }); - const { data: latestRelease } = yield octokit.rest.repos.getLatestRelease({ - owner: constants_1.OWNER, - repo: constants_1.REPO, - }); - if (!latestRelease) { - throw new Error("Could not determine latest release."); - } - return latestRelease.tag_name; +async function getLatestVersion(githubToken) { + const octokit = github.getOctokit(githubToken, { baseUrl: constants_1.GITHUB_COM_API }); + const { data: latestRelease } = await octokit.rest.repos.getLatestRelease({ + owner: constants_1.OWNER, + repo: constants_1.REPO, }); + if (!latestRelease) { + throw new Error("Could not determine latest release."); + } + return latestRelease.tag_name; } @@ -101430,22 +99217,6 @@ var __importStar = (this && this.__importStar) || (function () { 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 __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.hashFiles = hashFiles; const crypto = __importStar(__nccwpck_require__(7598)); @@ -101462,49 +99233,34 @@ const glob_1 = __nccwpck_require__(7206); * @param pattern The glob pattern to match files. * @param verbose Whether to log the files being hashed. */ -function hashFiles(pattern_1) { - return __awaiter(this, arguments, void 0, function* (pattern, verbose = false) { - var _a, e_1, _b, _c; - const globber = yield (0, glob_1.create)(pattern); - let hasMatch = false; - const writeDelegate = verbose ? core.info : core.debug; - const result = crypto.createHash("sha256"); - let count = 0; - try { - for (var _d = true, _e = __asyncValues(globber.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const file = _c; - writeDelegate(file); - if (fs.statSync(file).isDirectory()) { - writeDelegate(`Skip directory '${file}'.`); - continue; - } - const hash = crypto.createHash("sha256"); - const pipeline = util.promisify(stream.pipeline); - yield pipeline(fs.createReadStream(file), hash); - result.write(hash.digest()); - count++; - if (!hasMatch) { - hasMatch = true; - } - } +async function hashFiles(pattern, verbose = false) { + const globber = await (0, glob_1.create)(pattern); + let hasMatch = false; + const writeDelegate = verbose ? core.info : core.debug; + const result = crypto.createHash("sha256"); + let count = 0; + for await (const file of globber.globGenerator()) { + writeDelegate(file); + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); - } - finally { if (e_1) throw e_1.error; } + const hash = crypto.createHash("sha256"); + const pipeline = util.promisify(stream.pipeline); + await pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; } - result.end(); - if (hasMatch) { - writeDelegate(`Found ${count} files to hash.`); - return result.digest("hex"); - } - writeDelegate("No matches found for glob"); - return ""; - }); + } + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest("hex"); + } + writeDelegate("No matches found for glob"); + return ""; } @@ -101548,15 +99304,6 @@ var __importStar = (this && this.__importStar) || (function () { 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 }; }; @@ -101570,74 +99317,68 @@ const inputs_1 = __nccwpck_require__(9612); const exec = __importStar(__nccwpck_require__(5236)); const node_fs_1 = __importDefault(__nccwpck_require__(3024)); const pyproject_1 = __nccwpck_require__(3929); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const platform = (0, platforms_1.getPlatform)(); - const arch = (0, platforms_1.getArch)(); - try { - if (platform === undefined) { - throw new Error(`Unsupported platform: ${process.platform}`); - } - if (arch === undefined) { - throw new Error(`Unsupported architecture: ${process.arch}`); - } - const setupResult = yield setupUv(platform, arch, inputs_1.checkSum, inputs_1.githubToken); - addUvToPath(setupResult.uvDir); - addToolBinToPath(); - setToolDir(); - yield setupPython(); - addMatchers(); - setCacheDir(inputs_1.cacheLocalPath); - core.setOutput("uv-version", setupResult.version); - core.info(`Successfully installed uv version ${setupResult.version}`); - if (inputs_1.enableCache) { - yield (0, restore_cache_1.restoreCache)(); - } - process.exit(0); +async function run() { + const platform = (0, platforms_1.getPlatform)(); + const arch = (0, platforms_1.getArch)(); + try { + if (platform === undefined) { + throw new Error(`Unsupported platform: ${process.platform}`); } - catch (err) { - core.setFailed(err.message); + if (arch === undefined) { + throw new Error(`Unsupported architecture: ${process.arch}`); } - }); + const setupResult = await setupUv(platform, arch, inputs_1.checkSum, inputs_1.githubToken); + addUvToPath(setupResult.uvDir); + addToolBinToPath(); + setToolDir(); + await setupPython(); + addMatchers(); + setCacheDir(inputs_1.cacheLocalPath); + core.setOutput("uv-version", setupResult.version); + core.info(`Successfully installed uv version ${setupResult.version}`); + if (inputs_1.enableCache) { + await (0, restore_cache_1.restoreCache)(); + } + process.exit(0); + } + catch (err) { + core.setFailed(err.message); + } } -function setupUv(platform, arch, checkSum, githubToken) { - return __awaiter(this, void 0, void 0, function* () { - const resolvedVersion = yield determineVersion(); - const toolCacheResult = (0, download_version_1.tryGetFromToolCache)(arch, resolvedVersion); - if (toolCacheResult.installedPath) { - core.info(`Found uv in tool-cache for ${toolCacheResult.version}`); - return { - uvDir: toolCacheResult.installedPath, - version: toolCacheResult.version, - }; - } - const downloadVersionResult = yield (0, download_version_1.downloadVersion)(platform, arch, resolvedVersion, checkSum, githubToken); +async function setupUv(platform, arch, checkSum, githubToken) { + const resolvedVersion = await determineVersion(); + const toolCacheResult = (0, download_version_1.tryGetFromToolCache)(arch, resolvedVersion); + if (toolCacheResult.installedPath) { + core.info(`Found uv in tool-cache for ${toolCacheResult.version}`); return { - uvDir: downloadVersionResult.cachedToolDir, - version: downloadVersionResult.version, + uvDir: toolCacheResult.installedPath, + version: toolCacheResult.version, }; - }); + } + const downloadVersionResult = await (0, download_version_1.downloadVersion)(platform, arch, resolvedVersion, checkSum, githubToken); + return { + uvDir: downloadVersionResult.cachedToolDir, + version: downloadVersionResult.version, + }; } -function determineVersion() { - return __awaiter(this, void 0, void 0, function* () { - if (inputs_1.version !== "") { - return yield (0, download_version_1.resolveVersion)(inputs_1.version, inputs_1.githubToken); +async function determineVersion() { + if (inputs_1.version !== "") { + return await (0, download_version_1.resolveVersion)(inputs_1.version, inputs_1.githubToken); + } + const configFile = inputs_1.uvFile !== "" ? inputs_1.uvFile : inputs_1.pyProjectFile; + if (configFile !== "") { + const versionFromConfigFile = (0, pyproject_1.getUvVersionFromConfigFile)(configFile); + if (versionFromConfigFile === undefined) { + core.warning(`Could not find required-version under [tool.uv] in ${configFile}. Falling back to latest`); } - const configFile = inputs_1.uvFile !== "" ? inputs_1.uvFile : inputs_1.pyProjectFile; - if (configFile !== "") { - const versionFromConfigFile = (0, pyproject_1.getUvVersionFromConfigFile)(configFile); - if (versionFromConfigFile === undefined) { - core.warning(`Could not find required-version under [tool.uv] in ${configFile}. Falling back to latest`); - } - return yield (0, download_version_1.resolveVersion)(versionFromConfigFile || "latest", inputs_1.githubToken); - } - if (!node_fs_1.default.existsSync("uv.toml") && !node_fs_1.default.existsSync("pyproject.toml")) { - return yield (0, download_version_1.resolveVersion)("latest", inputs_1.githubToken); - } - const versionFile = node_fs_1.default.existsSync("uv.toml") ? "uv.toml" : "pyproject.toml"; - const versionFromConfigFile = (0, pyproject_1.getUvVersionFromConfigFile)(versionFile); - return yield (0, download_version_1.resolveVersion)(versionFromConfigFile || "latest", inputs_1.githubToken); - }); + return await (0, download_version_1.resolveVersion)(versionFromConfigFile || "latest", inputs_1.githubToken); + } + if (!node_fs_1.default.existsSync("uv.toml") && !node_fs_1.default.existsSync("pyproject.toml")) { + return await (0, download_version_1.resolveVersion)("latest", inputs_1.githubToken); + } + const versionFile = node_fs_1.default.existsSync("uv.toml") ? "uv.toml" : "pyproject.toml"; + const versionFromConfigFile = (0, pyproject_1.getUvVersionFromConfigFile)(versionFile); + return await (0, download_version_1.resolveVersion)(versionFromConfigFile || "latest", inputs_1.githubToken); } function addUvToPath(cachedPath) { core.addPath(cachedPath); @@ -101671,25 +99412,23 @@ function setToolDir() { core.info(`Set UV_TOOL_DIR to ${inputs_1.toolDir}`); } } -function setupPython() { - return __awaiter(this, void 0, void 0, function* () { - if (inputs_1.pythonVersion !== "") { - core.exportVariable("UV_PYTHON", inputs_1.pythonVersion); - core.info(`Set UV_PYTHON to ${inputs_1.pythonVersion}`); - const options = { - silent: !core.isDebug(), - }; - const execArgs = ["venv", "--python", inputs_1.pythonVersion]; - core.info("Activating python venv..."); - yield exec.exec("uv", execArgs, options); - let venvBinPath = ".venv/bin"; - if (process.platform === "win32") { - venvBinPath = ".venv/Scripts"; - } - core.addPath(path.resolve(venvBinPath)); - core.exportVariable("VIRTUAL_ENV", path.resolve(".venv")); +async function setupPython() { + if (inputs_1.pythonVersion !== "") { + core.exportVariable("UV_PYTHON", inputs_1.pythonVersion); + core.info(`Set UV_PYTHON to ${inputs_1.pythonVersion}`); + const options = { + silent: !core.isDebug(), + }; + const execArgs = ["venv", "--python", inputs_1.pythonVersion]; + core.info("Activating python venv..."); + await exec.exec("uv", execArgs, options); + let venvBinPath = ".venv/bin"; + if (process.platform === "win32") { + venvBinPath = ".venv/Scripts"; } - }); + core.addPath(path.resolve(venvBinPath)); + core.exportVariable("VIRTUAL_ENV", path.resolve(".venv")); + } } function setCacheDir(cacheLocalPath) { core.exportVariable("UV_CACHE_DIR", cacheLocalPath); @@ -101910,14 +99649,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUvVersionFromConfigFile = getUvVersionFromConfigFile; const node_fs_1 = __importDefault(__nccwpck_require__(3024)); const core = __importStar(__nccwpck_require__(7484)); -const toml = __importStar(__nccwpck_require__(4572)); +const toml = __importStar(__nccwpck_require__(7106)); function getUvVersionFromConfigFile(filePath) { if (!node_fs_1.default.existsSync(filePath)) { core.warning(`Could not find file: ${filePath}`); return undefined; } let requiredVersion = getRequiredVersion(filePath); - if (requiredVersion === null || requiredVersion === void 0 ? void 0 : requiredVersion.startsWith("==")) { + if (requiredVersion?.startsWith("==")) { requiredVersion = requiredVersion.slice(2); } if (requiredVersion !== undefined) { @@ -101926,11 +99665,10 @@ function getUvVersionFromConfigFile(filePath) { return requiredVersion; } function getRequiredVersion(filePath) { - var _a, _b; const fileContent = node_fs_1.default.readFileSync(filePath, "utf-8"); if (filePath.endsWith("pyproject.toml")) { const tomlContent = toml.parse(fileContent); - return (_b = (_a = tomlContent === null || tomlContent === void 0 ? void 0 : tomlContent.tool) === null || _a === void 0 ? void 0 : _a.uv) === null || _b === void 0 ? void 0 : _b["required-version"]; + return tomlContent?.tool?.uv?.["required-version"]; } const tomlContent = toml.parse(fileContent); return tomlContent["required-version"]; @@ -103836,6 +101574,913 @@ function parseParams (str) { module.exports = parseParams +/***/ }), + +/***/ 7106: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// dist/index.js +var dist_exports = {}; +__export(dist_exports, { + TomlDate: () => TomlDate, + TomlError: () => TomlError, + default: () => dist_default, + parse: () => parse, + stringify: () => stringify +}); +module.exports = __toCommonJS(dist_exports); + +// dist/error.js +function getLineColFromPtr(string, ptr) { + let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g); + return [lines.length, lines.pop().length + 1]; +} +function makeCodeBlock(string, line, column) { + let lines = string.split(/\r\n|\n|\r/g); + let codeblock = ""; + let numberLen = (Math.log10(line + 1) | 0) + 1; + for (let i = line - 1; i <= line + 1; i++) { + let l = lines[i - 1]; + if (!l) + continue; + codeblock += i.toString().padEnd(numberLen, " "); + codeblock += ": "; + codeblock += l; + codeblock += "\n"; + if (i === line) { + codeblock += " ".repeat(numberLen + column + 2); + codeblock += "^\n"; + } + } + return codeblock; +} +var TomlError = class extends Error { + line; + column; + codeblock; + constructor(message, options) { + const [line, column] = getLineColFromPtr(options.toml, options.ptr); + const codeblock = makeCodeBlock(options.toml, line, column); + super(`Invalid TOML document: ${message} + +${codeblock}`, options); + this.line = line; + this.column = column; + this.codeblock = codeblock; + } +}; + +// dist/util.js +function indexOfNewline(str, start = 0, end = str.length) { + let idx = str.indexOf("\n", start); + if (str[idx - 1] === "\r") + idx--; + return idx <= end ? idx : -1; +} +function skipComment(str, ptr) { + for (let i = ptr; i < str.length; i++) { + let c = str[i]; + if (c === "\n") + return i; + if (c === "\r" && str[i + 1] === "\n") + return i + 1; + if (c < " " && c !== " " || c === "\x7F") { + throw new TomlError("control characters are not allowed in comments", { + toml: str, + ptr + }); + } + } + return str.length; +} +function skipVoid(str, ptr, banNewLines, banComments) { + let c; + while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n")) + ptr++; + return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines); +} +function skipUntil(str, ptr, sep, end, banNewLines = false) { + if (!end) { + ptr = indexOfNewline(str, ptr); + return ptr < 0 ? str.length : ptr; + } + for (let i = ptr; i < str.length; i++) { + let c = str[i]; + if (c === "#") { + i = indexOfNewline(str, i); + } else if (c === sep) { + return i + 1; + } else if (c === end) { + return i; + } else if (banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) { + return i; + } + } + throw new TomlError("cannot find end of structure", { + toml: str, + ptr + }); +} +function getStringEnd(str, seek) { + let first = str[seek]; + let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first; + seek += target.length - 1; + do + seek = str.indexOf(target, ++seek); + while (seek > -1 && first !== "'" && str[seek - 1] === "\\" && str[seek - 2] !== "\\"); + if (seek > -1) { + seek += target.length; + if (target.length > 1) { + if (str[seek] === first) + seek++; + if (str[seek] === first) + seek++; + } + } + return seek; +} + +// dist/date.js +var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i; +var TomlDate = class _TomlDate extends Date { + #hasDate = false; + #hasTime = false; + #offset = null; + constructor(date) { + let hasDate = true; + let hasTime = true; + let offset = "Z"; + if (typeof date === "string") { + let match = date.match(DATE_TIME_RE); + if (match) { + if (!match[1]) { + hasDate = false; + date = `0000-01-01T${date}`; + } + hasTime = !!match[2]; + if (match[2] && +match[2] > 23) { + date = ""; + } else { + offset = match[3] || null; + date = date.toUpperCase(); + if (!offset && hasTime) + date += "Z"; + } + } else { + date = ""; + } + } + super(date); + if (!isNaN(this.getTime())) { + this.#hasDate = hasDate; + this.#hasTime = hasTime; + this.#offset = offset; + } + } + isDateTime() { + return this.#hasDate && this.#hasTime; + } + isLocal() { + return !this.#hasDate || !this.#hasTime || !this.#offset; + } + isDate() { + return this.#hasDate && !this.#hasTime; + } + isTime() { + return this.#hasTime && !this.#hasDate; + } + isValid() { + return this.#hasDate || this.#hasTime; + } + toISOString() { + let iso = super.toISOString(); + if (this.isDate()) + return iso.slice(0, 10); + if (this.isTime()) + return iso.slice(11, 23); + if (this.#offset === null) + return iso.slice(0, -1); + if (this.#offset === "Z") + return iso; + let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6); + offset = this.#offset[0] === "-" ? offset : -offset; + let offsetDate = new Date(this.getTime() - offset * 6e4); + return offsetDate.toISOString().slice(0, -1) + this.#offset; + } + static wrapAsOffsetDateTime(jsDate, offset = "Z") { + let date = new _TomlDate(jsDate); + date.#offset = offset; + return date; + } + static wrapAsLocalDateTime(jsDate) { + let date = new _TomlDate(jsDate); + date.#offset = null; + return date; + } + static wrapAsLocalDate(jsDate) { + let date = new _TomlDate(jsDate); + date.#hasTime = false; + date.#offset = null; + return date; + } + static wrapAsLocalTime(jsDate) { + let date = new _TomlDate(jsDate); + date.#hasDate = false; + date.#offset = null; + return date; + } +}; + +// dist/primitive.js +var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/; +var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/; +var LEADING_ZERO = /^[+-]?0[0-9_]/; +var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i; +var ESC_MAP = { + b: "\b", + t: " ", + n: "\n", + f: "\f", + r: "\r", + '"': '"', + "\\": "\\" +}; +function parseString(str, ptr = 0, endPtr = str.length) { + let isLiteral = str[ptr] === "'"; + let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1]; + if (isMultiline) { + endPtr -= 2; + if (str[ptr += 2] === "\r") + ptr++; + if (str[ptr] === "\n") + ptr++; + } + let tmp = 0; + let isEscape; + let parsed = ""; + let sliceStart = ptr; + while (ptr < endPtr - 1) { + let c = str[ptr++]; + if (c === "\n" || c === "\r" && str[ptr] === "\n") { + if (!isMultiline) { + throw new TomlError("newlines are not allowed in strings", { + toml: str, + ptr: ptr - 1 + }); + } + } else if (c < " " && c !== " " || c === "\x7F") { + throw new TomlError("control characters are not allowed in strings", { + toml: str, + ptr: ptr - 1 + }); + } + if (isEscape) { + isEscape = false; + if (c === "u" || c === "U") { + let code = str.slice(ptr, ptr += c === "u" ? 4 : 8); + if (!ESCAPE_REGEX.test(code)) { + throw new TomlError("invalid unicode escape", { + toml: str, + ptr: tmp + }); + } + try { + parsed += String.fromCodePoint(parseInt(code, 16)); + } catch { + throw new TomlError("invalid unicode escape", { + toml: str, + ptr: tmp + }); + } + } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) { + ptr = skipVoid(str, ptr - 1, true); + if (str[ptr] !== "\n" && str[ptr] !== "\r") { + throw new TomlError("invalid escape: only line-ending whitespace may be escaped", { + toml: str, + ptr: tmp + }); + } + ptr = skipVoid(str, ptr); + } else if (c in ESC_MAP) { + parsed += ESC_MAP[c]; + } else { + throw new TomlError("unrecognized escape sequence", { + toml: str, + ptr: tmp + }); + } + sliceStart = ptr; + } else if (!isLiteral && c === "\\") { + tmp = ptr - 1; + isEscape = true; + parsed += str.slice(sliceStart, tmp); + } + } + return parsed + str.slice(sliceStart, endPtr - 1); +} +function parseValue(value, toml, ptr) { + if (value === "true") + return true; + if (value === "false") + return false; + if (value === "-inf") + return -Infinity; + if (value === "inf" || value === "+inf") + return Infinity; + if (value === "nan" || value === "+nan" || value === "-nan") + return NaN; + if (value === "-0") + return 0; + let isInt; + if ((isInt = INT_REGEX.test(value)) || FLOAT_REGEX.test(value)) { + if (LEADING_ZERO.test(value)) { + throw new TomlError("leading zeroes are not allowed", { + toml, + ptr + }); + } + let numeric = +value.replace(/_/g, ""); + if (isNaN(numeric)) { + throw new TomlError("invalid number", { + toml, + ptr + }); + } + if (isInt && !Number.isSafeInteger(numeric)) { + throw new TomlError("integer value cannot be represented losslessly", { + toml, + ptr + }); + } + return numeric; + } + let date = new TomlDate(value); + if (!date.isValid()) { + throw new TomlError("invalid value", { + toml, + ptr + }); + } + return date; +} + +// dist/extract.js +function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) { + let value = str.slice(startPtr, endPtr); + let commentIdx = value.indexOf("#"); + if (commentIdx > -1) { + skipComment(str, commentIdx); + value = value.slice(0, commentIdx); + } + let trimmed = value.trimEnd(); + if (!allowNewLines) { + let newlineIdx = value.indexOf("\n", trimmed.length); + if (newlineIdx > -1) { + throw new TomlError("newlines are not allowed in inline tables", { + toml: str, + ptr: startPtr + newlineIdx + }); + } + } + return [trimmed, commentIdx]; +} +function extractValue(str, ptr, end, depth) { + if (depth === 0) { + throw new TomlError("document contains excessively nested structures. aborting.", { + toml: str, + ptr + }); + } + let c = str[ptr]; + if (c === "[" || c === "{") { + let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth) : parseInlineTable(str, ptr, depth); + let newPtr = skipUntil(str, endPtr2, ",", end); + if (end === "}") { + let nextNewLine = indexOfNewline(str, endPtr2, newPtr); + if (nextNewLine > -1) { + throw new TomlError("newlines are not allowed in inline tables", { + toml: str, + ptr: nextNewLine + }); + } + } + return [value, newPtr]; + } + let endPtr; + if (c === '"' || c === "'") { + endPtr = getStringEnd(str, ptr); + let parsed = parseString(str, ptr, endPtr); + if (end) { + endPtr = skipVoid(str, endPtr, end !== "]"); + if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") { + throw new TomlError("unexpected character encountered", { + toml: str, + ptr: endPtr + }); + } + endPtr += +(str[endPtr] === ","); + } + return [parsed, endPtr]; + } + endPtr = skipUntil(str, ptr, ",", end); + let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]"); + if (!slice[0]) { + throw new TomlError("incomplete key-value declaration: no value specified", { + toml: str, + ptr + }); + } + if (end && slice[1] > -1) { + endPtr = skipVoid(str, ptr + slice[1]); + endPtr += +(str[endPtr] === ","); + } + return [ + parseValue(slice[0], str, ptr), + endPtr + ]; +} + +// dist/struct.js +var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/; +function parseKey(str, ptr, end = "=") { + let dot = ptr - 1; + let parsed = []; + let endPtr = str.indexOf(end, ptr); + if (endPtr < 0) { + throw new TomlError("incomplete key-value: cannot find end of key", { + toml: str, + ptr + }); + } + do { + let c = str[ptr = ++dot]; + if (c !== " " && c !== " ") { + if (c === '"' || c === "'") { + if (c === str[ptr + 1] && c === str[ptr + 2]) { + throw new TomlError("multiline strings are not allowed in keys", { + toml: str, + ptr + }); + } + let eos = getStringEnd(str, ptr); + if (eos < 0) { + throw new TomlError("unfinished string encountered", { + toml: str, + ptr + }); + } + dot = str.indexOf(".", eos); + let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot); + let newLine = indexOfNewline(strEnd); + if (newLine > -1) { + throw new TomlError("newlines are not allowed in keys", { + toml: str, + ptr: ptr + dot + newLine + }); + } + if (strEnd.trimStart()) { + throw new TomlError("found extra tokens after the string part", { + toml: str, + ptr: eos + }); + } + if (endPtr < eos) { + endPtr = str.indexOf(end, eos); + if (endPtr < 0) { + throw new TomlError("incomplete key-value: cannot find end of key", { + toml: str, + ptr + }); + } + } + parsed.push(parseString(str, ptr, eos)); + } else { + dot = str.indexOf(".", ptr); + let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot); + if (!KEY_PART_RE.test(part)) { + throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", { + toml: str, + ptr + }); + } + parsed.push(part.trimEnd()); + } + } + } while (dot + 1 && dot < endPtr); + return [parsed, skipVoid(str, endPtr + 1, true, true)]; +} +function parseInlineTable(str, ptr, depth) { + let res = {}; + let seen = /* @__PURE__ */ new Set(); + let c; + let comma = 0; + ptr++; + while ((c = str[ptr++]) !== "}" && c) { + if (c === "\n") { + throw new TomlError("newlines are not allowed in inline tables", { + toml: str, + ptr: ptr - 1 + }); + } else if (c === "#") { + throw new TomlError("inline tables cannot contain comments", { + toml: str, + ptr: ptr - 1 + }); + } else if (c === ",") { + throw new TomlError("expected key-value, found comma", { + toml: str, + ptr: ptr - 1 + }); + } else if (c !== " " && c !== " ") { + let k; + let t = res; + let hasOwn = false; + let [key, keyEndPtr] = parseKey(str, ptr - 1); + for (let i = 0; i < key.length; i++) { + if (i) + t = hasOwn ? t[k] : t[k] = {}; + k = key[i]; + if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) { + throw new TomlError("trying to redefine an already defined value", { + toml: str, + ptr + }); + } + if (!hasOwn && k === "__proto__") { + Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true }); + } + } + if (hasOwn) { + throw new TomlError("trying to redefine an already defined value", { + toml: str, + ptr + }); + } + let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1); + seen.add(value); + t[k] = value; + ptr = valueEndPtr; + comma = str[ptr - 1] === "," ? ptr - 1 : 0; + } + } + if (comma) { + throw new TomlError("trailing commas are not allowed in inline tables", { + toml: str, + ptr: comma + }); + } + if (!c) { + throw new TomlError("unfinished table encountered", { + toml: str, + ptr + }); + } + return [res, ptr]; +} +function parseArray(str, ptr, depth) { + let res = []; + let c; + ptr++; + while ((c = str[ptr++]) !== "]" && c) { + if (c === ",") { + throw new TomlError("expected value, found comma", { + toml: str, + ptr: ptr - 1 + }); + } else if (c === "#") + ptr = skipComment(str, ptr); + else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") { + let e = extractValue(str, ptr - 1, "]", depth - 1); + res.push(e[0]); + ptr = e[1]; + } + } + if (!c) { + throw new TomlError("unfinished array encountered", { + toml: str, + ptr + }); + } + return [res, ptr]; +} + +// dist/parse.js +function peekTable(key, table, meta, type) { + let t = table; + let m = meta; + let k; + let hasOwn = false; + let state; + for (let i = 0; i < key.length; i++) { + if (i) { + t = hasOwn ? t[k] : t[k] = {}; + m = (state = m[k]).c; + if (type === 0 && (state.t === 1 || state.t === 2)) { + return null; + } + if (state.t === 2) { + let l = t.length - 1; + t = t[l]; + m = m[l].c; + } + } + k = key[i]; + if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) { + return null; + } + if (!hasOwn) { + if (k === "__proto__") { + Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true }); + Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true }); + } + m[k] = { + t: i < key.length - 1 && type === 2 ? 3 : type, + d: false, + i: 0, + c: {} + }; + } + } + state = m[k]; + if (state.t !== type && !(type === 1 && state.t === 3)) { + return null; + } + if (type === 2) { + if (!state.d) { + state.d = true; + t[k] = []; + } + t[k].push(t = {}); + state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} }; + } + if (state.d) { + return null; + } + state.d = true; + if (type === 1) { + t = hasOwn ? t[k] : t[k] = {}; + } else if (type === 0 && hasOwn) { + return null; + } + return [k, t, state.c]; +} +function parse(toml, opts) { + let maxDepth = opts?.maxDepth ?? 1e3; + let res = {}; + let meta = {}; + let tbl = res; + let m = meta; + for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) { + if (toml[ptr] === "[") { + let isTableArray = toml[++ptr] === "["; + let k = parseKey(toml, ptr += +isTableArray, "]"); + if (isTableArray) { + if (toml[k[1] - 1] !== "]") { + throw new TomlError("expected end of table declaration", { + toml, + ptr: k[1] - 1 + }); + } + k[1]++; + } + let p = peekTable( + k[0], + res, + meta, + isTableArray ? 2 : 1 + /* Type.EXPLICIT */ + ); + if (!p) { + throw new TomlError("trying to redefine an already defined table or value", { + toml, + ptr + }); + } + m = p[2]; + tbl = p[1]; + ptr = k[1]; + } else { + let k = parseKey(toml, ptr); + let p = peekTable( + k[0], + tbl, + m, + 0 + /* Type.DOTTED */ + ); + if (!p) { + throw new TomlError("trying to redefine an already defined table or value", { + toml, + ptr + }); + } + let v = extractValue(toml, k[1], void 0, maxDepth); + p[1][p[0]] = v[0]; + ptr = v[1]; + } + ptr = skipVoid(toml, ptr, true); + if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") { + throw new TomlError("each key-value declaration must be followed by an end-of-line", { + toml, + ptr + }); + } + ptr = skipVoid(toml, ptr); + } + return res; +} + +// dist/stringify.js +var BARE_KEY = /^[a-z0-9-_]+$/i; +function extendedTypeOf(obj) { + let type = typeof obj; + if (type === "object") { + if (Array.isArray(obj)) + return "array"; + if (obj instanceof Date) + return "date"; + } + return type; +} +function isArrayOfTables(obj) { + for (let i = 0; i < obj.length; i++) { + if (extendedTypeOf(obj[i]) !== "object") + return false; + } + return obj.length != 0; +} +function formatString(s) { + return JSON.stringify(s).replace(/\x7f/g, "\\u007f"); +} +function stringifyValue(val, type, depth) { + if (depth === 0) { + throw new Error("Could not stringify the object: maximum object depth exceeded"); + } + if (type === "number") { + if (isNaN(val)) + return "nan"; + if (val === Infinity) + return "inf"; + if (val === -Infinity) + return "-inf"; + return val.toString(); + } + if (type === "bigint" || type === "boolean") { + return val.toString(); + } + if (type === "string") { + return formatString(val); + } + if (type === "date") { + if (isNaN(val.getTime())) { + throw new TypeError("cannot serialize invalid date"); + } + return val.toISOString(); + } + if (type === "object") { + return stringifyInlineTable(val, depth); + } + if (type === "array") { + return stringifyArray(val, depth); + } +} +function stringifyInlineTable(obj, depth) { + let keys = Object.keys(obj); + if (keys.length === 0) + return "{}"; + let res = "{ "; + for (let i = 0; i < keys.length; i++) { + let k = keys[i]; + if (i) + res += ", "; + res += BARE_KEY.test(k) ? k : formatString(k); + res += " = "; + res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1); + } + return res + " }"; +} +function stringifyArray(array, depth) { + if (array.length === 0) + return "[]"; + let res = "[ "; + for (let i = 0; i < array.length; i++) { + if (i) + res += ", "; + if (array[i] === null || array[i] === void 0) { + throw new TypeError("arrays cannot contain null or undefined values"); + } + res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1); + } + return res + " ]"; +} +function stringifyArrayTable(array, key, depth) { + if (depth === 0) { + throw new Error("Could not stringify the object: maximum object depth exceeded"); + } + let res = ""; + for (let i = 0; i < array.length; i++) { + res += `[[${key}]] +`; + res += stringifyTable(array[i], key, depth); + res += "\n\n"; + } + return res; +} +function stringifyTable(obj, prefix, depth) { + if (depth === 0) { + throw new Error("Could not stringify the object: maximum object depth exceeded"); + } + let preamble = ""; + let tables = ""; + let keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + let k = keys[i]; + if (obj[k] !== null && obj[k] !== void 0) { + let type = extendedTypeOf(obj[k]); + if (type === "symbol" || type === "function") { + throw new TypeError(`cannot serialize values of type '${type}'`); + } + let key = BARE_KEY.test(k) ? k : formatString(k); + if (type === "array" && isArrayOfTables(obj[k])) { + tables += stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1); + } else if (type === "object") { + let tblKey = prefix ? `${prefix}.${key}` : key; + tables += `[${tblKey}] +`; + tables += stringifyTable(obj[k], tblKey, depth - 1); + tables += "\n\n"; + } else { + preamble += key; + preamble += " = "; + preamble += stringifyValue(obj[k], type, depth); + preamble += "\n"; + } + } + } + return `${preamble} +${tables}`.trim(); +} +function stringify(obj, opts) { + if (extendedTypeOf(obj) !== "object") { + throw new TypeError("stringify can only be called with an object"); + } + let maxDepth = opts?.maxDepth ?? 1e3; + return stringifyTable(obj, "", maxDepth); +} + +// dist/index.js +var dist_default = { parse, stringify, TomlDate, TomlError }; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); +/*! + * Copyright (c) Squirrel Chat et al., All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + /***/ }), /***/ 4012: diff --git a/dist/update-known-checksums/index.js b/dist/update-known-checksums/index.js index 743ec4a..92d2f32 100644 --- a/dist/update-known-checksums/index.js +++ b/dist/update-known-checksums/index.js @@ -34751,39 +34751,28 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.updateChecksums = updateChecksums; const node_fs_1 = __nccwpck_require__(3024); const tc = __importStar(__nccwpck_require__(3472)); const known_checksums_1 = __nccwpck_require__(2764); -function updateChecksums(filePath, downloadUrls) { - return __awaiter(this, void 0, void 0, function* () { - yield node_fs_1.promises.rm(filePath); - yield node_fs_1.promises.appendFile(filePath, "// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: { [key: string]: string } = {\n"); - let firstLine = true; - for (const downloadUrl of downloadUrls) { - const key = getKey(downloadUrl); - if (key === undefined) { - continue; - } - const checksum = yield getOrDownloadChecksum(key, downloadUrl); - if (!firstLine) { - yield node_fs_1.promises.appendFile(filePath, ",\n"); - } - yield node_fs_1.promises.appendFile(filePath, ` "${key}":\n "${checksum}"`); - firstLine = false; +async function updateChecksums(filePath, downloadUrls) { + await node_fs_1.promises.rm(filePath); + await node_fs_1.promises.appendFile(filePath, "// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: { [key: string]: string } = {\n"); + let firstLine = true; + for (const downloadUrl of downloadUrls) { + const key = getKey(downloadUrl); + if (key === undefined) { + continue; } - yield node_fs_1.promises.appendFile(filePath, ",\n};\n"); - }); + const checksum = await getOrDownloadChecksum(key, downloadUrl); + if (!firstLine) { + await node_fs_1.promises.appendFile(filePath, ",\n"); + } + await node_fs_1.promises.appendFile(filePath, ` "${key}":\n "${checksum}"`); + firstLine = false; + } + await node_fs_1.promises.appendFile(filePath, ",\n};\n"); } function getKey(downloadUrl) { // https://github.com/astral-sh/uv/releases/download/0.3.2/uv-aarch64-apple-darwin.tar.gz.sha256 @@ -34796,25 +34785,21 @@ function getKey(downloadUrl) { const version = parts[parts.length - 2]; return `${name}-${version}`; } -function getOrDownloadChecksum(key, downloadUrl) { - return __awaiter(this, void 0, void 0, function* () { - let checksum = ""; - if (key in known_checksums_1.KNOWN_CHECKSUMS) { - checksum = known_checksums_1.KNOWN_CHECKSUMS[key]; - } - else { - const content = yield downloadAssetContent(downloadUrl); - checksum = content.split(" ")[0].trim(); - } - return checksum; - }); +async function getOrDownloadChecksum(key, downloadUrl) { + let checksum = ""; + if (key in known_checksums_1.KNOWN_CHECKSUMS) { + checksum = known_checksums_1.KNOWN_CHECKSUMS[key]; + } + else { + const content = await downloadAssetContent(downloadUrl); + checksum = content.split(" ")[0].trim(); + } + return checksum; } -function downloadAssetContent(downloadUrl) { - return __awaiter(this, void 0, void 0, function* () { - const downloadPath = yield tc.downloadTool(downloadUrl); - const content = yield node_fs_1.promises.readFile(downloadPath, "utf8"); - return content; - }); +async function downloadAssetContent(downloadUrl) { + const downloadPath = await tc.downloadTool(downloadUrl); + const content = await node_fs_1.promises.readFile(downloadPath, "utf8"); + return content; } @@ -34858,39 +34843,28 @@ var __importStar = (this && this.__importStar) || (function () { 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()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); const github = __importStar(__nccwpck_require__(3228)); const core = __importStar(__nccwpck_require__(7484)); const constants_1 = __nccwpck_require__(6156); const semver = __importStar(__nccwpck_require__(9318)); const update_known_checksums_1 = __nccwpck_require__(6182); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const checksumFilePath = process.argv.slice(2)[0]; - const github_token = process.argv.slice(2)[1]; - const octokit = github.getOctokit(github_token, { baseUrl: constants_1.GITHUB_COM_API }); - const response = yield octokit.paginate(octokit.rest.repos.listReleases, { - owner: constants_1.OWNER, - repo: constants_1.REPO, - }); - const downloadUrls = response.flatMap((release) => release.assets - .filter((asset) => asset.name.endsWith(".sha256")) - .map((asset) => asset.browser_download_url)); - yield (0, update_known_checksums_1.updateChecksums)(checksumFilePath, downloadUrls); - const latestVersion = response - .map((release) => release.tag_name) - .sort(semver.rcompare)[0]; - core.setOutput("latest-version", latestVersion); +async function run() { + const checksumFilePath = process.argv.slice(2)[0]; + const github_token = process.argv.slice(2)[1]; + const octokit = github.getOctokit(github_token, { baseUrl: constants_1.GITHUB_COM_API }); + const response = await octokit.paginate(octokit.rest.repos.listReleases, { + owner: constants_1.OWNER, + repo: constants_1.REPO, }); + const downloadUrls = response.flatMap((release) => release.assets + .filter((asset) => asset.name.endsWith(".sha256")) + .map((asset) => asset.browser_download_url)); + await (0, update_known_checksums_1.updateChecksums)(checksumFilePath, downloadUrls); + const latestVersion = response + .map((release) => release.tag_name) + .sort(semver.rcompare)[0]; + core.setOutput("latest-version", latestVersion); } run(); diff --git a/package-lock.json b/package-lock.json index e080175..3fe0623 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,8 +16,8 @@ "@actions/glob": "^0.5.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.1", - "@iarna/toml": "^2.2.5", - "@octokit/rest": "^21.1.0" + "@octokit/rest": "^21.1.0", + "smol-toml": "^1.3.1" }, "devDependencies": { "@biomejs/biome": "1.9.4", @@ -1105,11 +1105,6 @@ "node": ">=14" } }, - "node_modules/@iarna/toml": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz", - "integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==" - }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -4577,6 +4572,17 @@ "node": ">=8" } }, + "node_modules/smol-toml": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.3.1.tgz", + "integrity": "sha512-tEYNll18pPKHroYSmLLrksq233j021G0giwW7P3D24jC54pQ5W5BXMsQ/Mvw1OJCmEYDgY+lrzT+3nNUtoNfXQ==", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -5940,11 +5946,6 @@ "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==" }, - "@iarna/toml": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz", - "integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==" - }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -8607,6 +8608,11 @@ "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true }, + "smol-toml": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.3.1.tgz", + "integrity": "sha512-tEYNll18pPKHroYSmLLrksq233j021G0giwW7P3D24jC54pQ5W5BXMsQ/Mvw1OJCmEYDgY+lrzT+3nNUtoNfXQ==" + }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", diff --git a/package.json b/package.json index b146b49..09f6bd2 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.1", "@octokit/rest": "^21.1.0", - "@iarna/toml": "^2.2.5" + "smol-toml": "^1.3.1" }, "devDependencies": { "@biomejs/biome": "1.9.4", diff --git a/src/utils/pyproject.ts b/src/utils/pyproject.ts index c727855..dca27e4 100644 --- a/src/utils/pyproject.ts +++ b/src/utils/pyproject.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; import * as core from "@actions/core"; -import * as toml from "@iarna/toml"; +import * as toml from "smol-toml"; export function getUvVersionFromConfigFile( filePath: string, diff --git a/tsconfig.json b/tsconfig.json index 4a6c661..d8d5291 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, + "target": "ES2022" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, "outDir": "./lib" /* Redirect output structure to the directory. */, "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,